Topics
Replies
michaelgriffiths00
14 Aug 2023, 05:30
( Updated at: 14 Aug 2023, 05:31 )
RE: Close onBar order execution too late
PanagiotisChar said:
Hi there,
What you see is correct. OnBar is executed on the opening of the next bar, so on bar 3 the conditions are valid and the trade is entered.
Need help? Join us on Telegram
Hi,Yeah, the current code is acting as it should according to the logic of the API, but if I wanted to enter the order at the close of the candle, that registers simultaneuously at the open of the current, my code as it is fails. Just wondering if there is a better way of getting the order to execute on the candle (candle 2) prior to the current execution candle rather than to rely on timing
@michaelgriffiths00
michaelgriffiths00
13 Aug 2023, 11:05
RE: Close onBar order execution too late
firemyst said:
Your requirements are tricky because unless you're keeping track of time yourself and have a timer-method to check the time when a bar should be closing, there's no way to tell if a bar has closed or not until the next tick comes in.
For instance, a tick could come in on the current M1 candle at 12:59:55pm; the next tick might not come in until 1:00:05pm - difference of ten seconds. And regardless of time, that next tick could jump up down by several pips from the last value depending on what's happening in the market.
If you had a separate event method being called on say, every second, then your bot should execute the method at 1:00:00pm, in which can you can make the judgment call in your code to open a position.
Another alternative is once your threshold is crossed, you can wait to open a position once price is a pip, 2 pips, or x-pips above the threshold before waiting for the candle to close and next candle to open.
Many thanks for the reply firemyst. I have tried the following
protected override void OnTick()
{
// Handle price updates here
// Put your core logic here
if (IncludeTrailingStop)
{
SetTrailingStop();
}
DateTime currentTickTime = Server.Time;
DateTime lastCandleCloseTime = Bars.OpenTimes.Last(1).AddMinutes(5);
TimeSpan timeDifference = currentTickTime - lastCandleCloseTime;
double millisecondsDifference = timeDifference.TotalMilliseconds;
double tolerance = 50; // Define a tolerance in milliseconds
if (Math.Abs(millisecondsDifference - 300000) <= tolerance)
{
// This tick is likely the first tick after the close of the previous candle
// You can use this information for your logic
ManagePositions();
}
Print("The number of ms's is {0}", millisecondsDifference);
}
However, as the number of milliseconds for each candle is not always exactly 300,000, it's very difficult to gauge what the close price of the candle will be
@michaelgriffiths00
michaelgriffiths00
14 Aug 2023, 06:50
RE: RE: RE: Close onBar order execution too late
firemyst said:
@michaelgriffiths00