Topics

Forum Topics not found

Replies

thanhbachle2766
16 Aug 2023, 04:44

RE: RE: RE: RE: Close onBar order execution too late sda

michaelgriffiths00 said: 

firemyst said: 

michaelgriffiths00 said: 

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

 

 

Not what I meant. :-)

The way I'm suggesting, you don't use your onTick or OnBar methods.

You create your own SEPARATE event handler method that's called every 5 minutes once you start the timer ticking.

It's in that new event method you will perform your logic, as you know it will reliably happen close to every 5 minutes.

Example:

using System;
using System.Timers;

//First, set up your timer
Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    //You'll have to figure out the logic to start it exactly when you want
    t.Start();
// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    ManagePositions(); 
}

That's using the native C# timers, but hopefully you get my point.

cAlgo has it's own timer example, but make sure to read the notes they put in at the top of the code : MyBKExperience

https://help.ctrader.com/ctrader-automate/references/Timer/Timer/#namespace

 

Thanks firemyst, I'll give this a whirl today

 

This information is really helpful for who really needs this. I hope you will many more write post like this.. 


@thanhbachle2766