Let user select Candles/Bars

Created at 02 Feb 2022, 01:26
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
SE

seankiaa

Joined 02.02.2022

Let user select Candles/Bars
02 Feb 2022, 01:26


Hi, 

I am trying to create a cBot, that allows the user to pick two candles and let the bot store all the candles between those two in a file. 
I am thinking of letting the user draw a rectangle and find all the candles inside that rectangle. But I was wondering if there is an easier way? like somehow capture the clicked candle? because I am not sure how easy would be to find all the candles within a rectangle. 

Any suggestions are welcome! 
Thank you


@seankiaa
Replies

amusleh
02 Feb 2022, 08:33

Hi,

There are different ways to select bars, one is by mouse click event that you can use when user click on one bar and then on another bar, you can get the mouse click bar index.

You can also use Rectangle which is much better way than using mouse click event, use Chart object events like chart object added, check the rectangle Time1 and Time2 properties and change it to bar index.

Here is an example with rectangle:

using cAlgo.API;
using System.Linq;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class CandlesSelectionWithRectangle : Indicator
    {
        protected override void Initialize()
        {
            Chart.ObjectsAdded += Chart_ObjectsAdded;
        }

        private void Chart_ObjectsAdded(ChartObjectsAddedEventArgs obj)
        {
            var chartRectangleObject = obj.ChartObjects.FirstOrDefault(chartObject => chartObject.ObjectType == ChartObjectType.Rectangle);

            if (chartRectangleObject == null) return;

            var rectangle = chartRectangleObject as ChartRectangle;

            var startTime = rectangle.Time1 < rectangle.Time2 ? rectangle.Time1 : rectangle.Time2;
            var endTime = rectangle.Time1 < rectangle.Time2 ? rectangle.Time2 : rectangle.Time1;

            var startBarIndex = Bars.OpenTimes.GetIndexByTime(startTime);
            var endBarIndex = Bars.OpenTimes.GetIndexByTime(endTime);

            Print("startBarIndex: {0} | endBarIndex: {1}", startBarIndex, endBarIndex);

            for (int barIndex = startBarIndex; barIndex <= endBarIndex; barIndex++)
            {
                var bar = Bars[barIndex];

                // do anythign you want to with the bars here
            }
        }

        public override void Calculate(int index)
        {
        }
    }
}

Create an instance of indicator on cTrader automate, draw a rectangle on your chart, check the logs tab.


@amusleh