Iterating Bars object between two datetime's.

Created at 20 Apr 2021, 11:28
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!
DA

DAXTrader

Joined 25.01.2021

Iterating Bars object between two datetime's.
20 Apr 2021, 11:28


I hope you can help me.  I’ve not done any cAlgo before, but I have done a lot of c# and MT4.

How can I loop between two datetime’s to get the Highest ClosePrice?

For example, on a 1Min Backtest I want to say "get the Highest Bar ClosePrice between 6am today and 10am today". 

I can see I need to the use Bars object, and I can see I am may be able to fashion something using Bars.OpenTimes.  But what is the best way?


@DAXTrader
Replies

amusleh
20 Apr 2021, 16:49

Hi,

There are lots of ways to do what you are after, one simple option is to use Linq:

using cAlgo.API;
using System;
using System.Globalization;
using System.Linq;

namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class TodayHighestClose : Indicator
    {
        private TimeSpan _startTime, _endTime;

        [Parameter("Start Time", DefaultValue = "06:00:00")]
        public string StartTime { get; set; }

        [Parameter("End Time", DefaultValue = "10:00:00")]
        public string EndTime { get; set; }

        protected override void Initialize()
        {
            if (!TimeSpan.TryParse(StartTime, CultureInfo.InvariantCulture, out _startTime))
            {
                Print("Invalid Start Time");
            }

            if (!TimeSpan.TryParse(EndTime, CultureInfo.InvariantCulture, out _endTime))
            {
                Print("Invalid End Time");
            }

            var highestClosePriceOfToday = Bars.Where(iBar => iBar.OpenTime.Date == Server.Time.Date && iBar.OpenTime.TimeOfDay >= _startTime && iBar.OpenTime.TimeOfDay <= _endTime).Max(iBar => iBar.Close);

            Print(highestClosePriceOfToday);
        }

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

 


@amusleh