Hello!
I have a question regarding an ATR stop loss/profit code snippet. Here is two different codes, that produce very different backtest results. I would expect it to be the same. Why does the backtest differ when I have the stop loss and target profit outside of the “if”-statement? I guess its probably obvious for someone with more coding experience than me. Thanks in advance!
Code 1:
// Definition of code parameters
DEFPARAM CumulateOrders = False // Cumulating positions deactivated
// Conditions to enter long positions
indicator1 = Average[20](close)
indicator2 = Average[50](close)
c1 = (indicator1 CROSSES OVER indicator2)
IF c1 THEN
BUY 1 CONTRACT AT MARKET
//Variables
NATR = 12 //ATR Period
SATR = 15 // ATR Multiplier for Stop
PATR = 15// ATR Multiplier for Profit
//Stop and Target
SET STOP LOSS SATR*AverageTrueRange[NATR](close)
SET TARGET PROFIT PATR*AverageTrueRange[NATR](close)
ENDIF
Code 2:
// Definition of code parameters
DEFPARAM CumulateOrders = False // Cumulating positions deactivated
// Conditions to enter long positions
indicator1 = Average[20](close)
indicator2 = Average[50](close)
c1 = (indicator1 CROSSES OVER indicator2)
IF c1 THEN
BUY 1 CONTRACT AT MARKET
ENDIF
//Variables
NATR = 12 //ATR Period
SATR = 15 // ATR Multiplier for Stop
PATR = 15// ATR Multiplier for Profit
//Stop and Target
SET STOP LOSS SATR*AverageTrueRange[NATR](close)
SET TARGET PROFIT PATR*AverageTrueRange[NATR](close)
JSParticipant
Senior
Hi,
When you put the SL and the TP in the “IF” statement, they are only placed once, but when you put them outside the “IF” statement, they are placed every time while “ATR” values change…
As a result, the two codes work with different “ATR” values, hence the difference…
Thanks so much JS! To me it sounds more “correct” to then place it outside of the “IF” statement then? Or would you say none is more correct than the other?
JSParticipant
Senior
Hi,
Personally, I would always put the SL and TP within the “IF” statement because it follows the logic of your system…
Logic “Under certain conditions, you want to enter into a transaction and then place an SL and TP…”
(Outside the “IF” statement it is “out of control”)