The order of operations bug between my breakeven and trailing logic
I had two features in my EA, a breakeven move after a certain profit and a trailing stop that starts later. They looked fine separately and then I found trades where the stop did odd things, jumping back and forth.
It was an ordering problem. On each tick the EA ran the breakeven check first, which put the stop at entry, and then the trailing check, which had its own idea of where the stop should be and sometimes put it further back. Next tick, the breakeven logic saw the stop was not at entry and moved it again. They were fighting each other.
The fix was to make the stop only ever move in one direction. Before any modification, the code checks if the new stop is better than the current one, meaning closer to profit for the trade direction. If not, it does nothing. I also moved both features into a single function so there's one place that decides the stop each tick.
It's a simple principle but easy to overlook: one owner for each piece of state. Having two bits of logic both editing the same stop is asking for trouble.
The order of operations bug between my breakeven and trailing logic
Re: The order of operations bug between my breakeven and trailing logic
The one direction rule is the right fix. I had a similar problem and ended up writing a single function that receives every proposed stop from any feature, picks the best one for the trade direction, and only then sends the modification. Nothing else in the code is allowed to change the stop. That way I can add new stop features later without them fighting each other. It also cut the number of modification requests a lot, which some brokers do not like when there are too many.
It’s Fairman 
Re: The order of operations bug between my breakeven and trailing logic
Worth adding a minimum step for modifications too. If the trailing logic wants to move the stop by a fraction of a pip every tick, it sends a lot of requests that achieve almost nothing and can hit broker limits. I only modify if the new stop is better by at least a set amount. I also check the broker's stop level before sending, because a stop too close to the current price gets rejected and the EA should handle that cleanly.
It’s Fairman 
Re: The order of operations bug between my breakeven and trailing logic
Testing this kind of thing in the visual tester was what helped me find it. Watching the stop line move on each tick made the fight between the two features obvious in a way the trade log never showed. I now run a short visual test any time I change stop logic, just a few trades, before running the full backtest. It catches the silly ordering problems quickly, and it is much easier than trying to read hundreds of modification lines in the journal.
It’s Fairman 