Amibroker: Coding a Time Stop

Long-time reader Thanit P. (name used with permission) sent me a code snippet in AFL with a question about coding a time stop, that is, an exit after a certain amount of time if another exit order hasn’t executed.

(I won’t include the entire AFL code to keep Thanit’s strategy logic private, but I’ll share the logic in question in my response.)


Thanit P.

It would be great if you could give some suggestions on my following code as it has failed to give any signal in live trading (a topic I have never talked about with you before but would be eager to). However, it gave normal backtesting results. 

The reason is that I think you may be able to help is that your demo code involves the use of a loop, which is something I didn’t think of before about AFL. However, after trying to code “exit on X bars”, ChatGPT gave me this loop. At first, I thought it would be OK as the backtest was fine. I suspect the function “barcount” may work differently in a live environment?


Dave:

The AFL code in question is this:

for( i = 1; i < BarCount; i++ )
{
    // ... other code here

    if (i - entryBar >= ExitBars)
    {
        Sell[i] = 1;
        Position = 0;
    }
    
    // ... other code here
}

First of all, ChatGPT is notoriously poor at AFL.

Hopefully, it will improve, but I end up fixing a lot of bad AFL code for traders who generate it with ChatGPT.

In theory, this code should work, but there are edge cases where it won’t.

For example, this won’t work if there are bars where the symbol doesn’t trade. That is, if you’re expecting to exit in 30 minutes and the symbol doesn’t have trades for half of those bars, then this logic won’t exit until 60 minutes!

For time stops, it’s always a good idea to use minutes since the market open and/or minutes until the market close as a reference.

It’s easier to follow the logic, and it’s extensible. For example, you could integrate half-day support and your logic wouldn’t change.

Real-time versus backtesting in Amibroker is a big topic.

There are major differences that come into play in real-time trading that you don’t have to think about in backtesting.

More on that later.

Thanks for the question, Thanit P.

-Dave