Tracking High and Low CBot

Created at 19 Oct 2022, 14:36
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!
JO

johnwithers12

Joined 19.10.2022

Tracking High and Low CBot
19 Oct 2022, 14:36


Hi Guys,

Apologies for what I'm sure is a simple question as my coding skills are pretty basic.  I'm trying to replicate a basic pinescript code I wrote.  It simply tracks the highest high and lowest low over a set duration based on a start and finish time.  The pinescript version works fine in Teamviewer but my attempt to replicate it in CAlgo doesn't work.  It appears that on each bar the "hi and "lo" variables reset back to their initialization values rather than keeping the ongoing highest high or lowest low.  Can someone please suggest an alternate method?

Pinescript Original

CAlgo Conversion Attempt

Thanks in advance guys

John


@johnwithers12
Replies

pick
20 Oct 2022, 12:29

All of your variables there are localised to the scope of the OnBar method. You want the values to persist between method calls; therefore they need to be defined outside of the method. I won't edit your logic, but this should get you closer to where you want to be:

double hi = double.MinValue;
double lo = double.MaxValue;

var tradingStarts = System.TimeSpan.ParseExect(SessionStart, "hh\\:mm", null);
var tradingStops = System.TimeSpan.ParseExect(SessionEnd, "hh\\:mm", null);

protected override void OnBar()
{
	double srcHi = Bars.HighPrices.Last(1);
	double srcLo = Bars.LowPrices.Last(1);
	
	if (Server.Time.TimeOfDay >= tradingStarts && Server.Time.TimeOfDay < tradingStops)
	{
		hi = Math.Max(srcHi, hi);
		lo = Math.Min(srcLo, lo);
	}
		
	Print(hi);
	Print(lo);
}

 


@pick

johnwithers12
20 Oct 2022, 14:06

Thanks very much Pick!  I knew it would be something basic.  I've just tested it out and that small change fixed it though I still don't think my code is very efficient.  Time to do a C# course I think.

 

Cheers,

 

John


@johnwithers12