Exit entry by value of current PnL

This is the code I have for closing trade. It is supposed to activate once PnL is -500, but when back testing I am getting trades that close out with a $4000 loss. What is wrong with this coding or is it other coding in my strategy?

        dailyPnL = Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]);
        if (dailyPnL == -500 && Position.MarketPosition != MarketPosition.Flat)
        {
            ExitLong("DailyCap", "Long");
            ExitShort("DailyCap", "Short");
            return;
        }

Your condition only exits the trade if the position is exactly -500, it’s very possible that the price moves enough to go beyond 500 before your next OnBarUpdate is called. Try using “<=” instead of “==”. You may also want to qualify your exit calls so that only the correct one is executed given your position state (ie: only ExitLong when position is long, and vice versa).

Also, be aware there are inherit limitations in the basic backtest. Typically, without special considerations, your OnBarUpdate is only being called once per bar (at close). this may still result in trades far exceeding your 500 limit during a backtest.

These docs may help:
Realtime vs backtest discrepancies
Improving backtest order fill accuracy

2 Likes

The default way how backtesting works is far from accurate.
I do by backtesting in two different parts:

  1. The first part is to let it run till it comes close to fulfilling my signal generating “area”. I let it run fast to save time, it has no impact on my trading as I stop it when I am close to fulfilling my signal generating “area”.
  2. The second part is to let it run, from the time when I can have potentially a signal. This part I run in “tickmode”. So the conditions are checked each tick. This helps you to avoid the problem of condition checking at the close. For this you should put your checking at “on every tick”, so not on “at the close”.

“Condition checking at the close” can/will almost always give you a wrong price. Only if the conditions are exactly correct at the close then you will get a correct price. This will probably happen in less than 10% of the signals.
In very volatile markets you can indeed lose $4000 on a $500 stop signal. The smaller the timeframe, the smaller the risk as you will have more closes that will check your conditions.
1 minute timeframes give you 5 times more closes than a 5 minute timeframe.

1 Like