Hi all,
I recently start with coding and I learned a lot with reading the articles on this forum and the code I found.
Now I’m working on the Trailing Stop code which I found on in this forum. The code is working (backtesting + Paper Trading) but I have a question:
When the trade starts, the ‘ stop’ is not immediately active, but after the entry candle has been closed and the conditions has been met, then the Trailing Stop will be active.
This means that I have a risk because when I enter my trade, there is no stop…….is that correct assumption? Or do I use the Trailing Stop code incorrect?
But when I enter a trade, I want to have immediately a stop to avoid the risk, how do I program that in the code?
Can you help?
Below a code (simple sample code) with the Trailing Stop which is working in Backtesting + Papertrading:
——————————————————————————————————————————
Defparam cumulateorders = false
//order launch (example) would be set to any other entry conditions
c1 = close>close[1]
c2 = close<close[1]
if c1 then
BUY 1 LOT AT MARKET
set target pprofit 30
endif
if c2 then
SELLSHORT 1 LOT AT MARKET
set target pprofit 30
endif
//************************************************************************
//trailing stop function
trailingstart = 2 //trailing will start @trailinstart points profit
trailingstep = 2 //trailing step to move the "stoploss"
//reset the stoploss value
IF NOT ONMARKET THEN
newSL=0
ENDIF
//manage long positions
IF LONGONMARKET THEN
//first move (breakeven)
IF newSL=0 AND close-tradeprice(1)>=trailingstart*pointsize THEN
newSL = tradeprice(1)+trailingstep*pointsize
ENDIF
//next moves
IF newSL>0 AND close-newSL>=trailingstep*pointsize THEN
newSL = newSL+trailingstep*pointsize
ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
//first move (breakeven)
IF newSL=0 AND tradeprice(1)-close>=trailingstart*pointsize THEN
newSL = tradeprice(1)-trailingstep*pointsize
ENDIF
//next moves
IF newSL>0 AND newSL-close>=trailingstep*pointsize THEN
newSL = newSL-trailingstep*pointsize
ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
SELL AT newSL STOP
EXITSHORT AT newSL STOP
ENDIF
——————————————————————————————————————–
Thanks in advance!
Richard
Just add a SET STOP PLOSS just below, or before, SET TARGET PPROFIT, so you’ll have a stop loss from the very start.