This code snippet demonstrates how to implement a trading strategy with trailing stop and breakeven functionalities using the ProBuilder language. The strategy is designed to execute trades based on moving average crossovers and manage risk with dynamic stop-loss adjustments.
// test trailingstop and breakeven on the dax
defparam cumulateorders = false
once enableSL = 1 // stop loss
once enablePT = 1 // profit target
once enableTS = 1 // trailing stop
once enableBE = 1 // breakeven stop
//once displaySL = 1 // stop loss
//once displayPT = 1 // profit target
//once displayTS = 1 // trailing stop
//once displayBE = 1 // breakeven stop
SL = 0.75 // % stop loss
PT = 1.00 // % profit target
TS = 0.35 // % trailing stop
BESG = 0.25 // % break even stop gain
BESL = 0.00 // % break even stop level
// reset at start
if intradaybarindex=0 then
longtradecounter=0
shorttradecounter=0
endif
pclong= longtradecounter<1
pcshort = shorttradecounter<1
shortma = average[25](close)
longma = average[50](close)
// conditions to enter long positions
l1 = (shortma crosses over longma)
// conditions to enter short
s1 = (shortma crosses under longma)
if pclong and l1 then
buy 1 contract at market
longtradecounter=longtradecounter+1
endif
if pcshort and s1 then
sellshort 1 contract at market
shorttradecounter=shorttradecounter+1
endif
// trailing stop
if enableTS then
trailingstop = (tradeprice/100)*TS
if not onmarket then
maxprice=0
minprice=close
priceexit=0
endif
if ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
maxprice=0
minprice=close
priceexit=0
endif
if longonmarket then
maxprice=max(maxprice,close)
if maxprice-tradeprice(1)>=trailingstop*pointsize then
priceexit=maxprice-trailingstop*pointsize
endif
endif
if shortonmarket then
minprice=min(minprice,close)
if tradeprice(1)-minprice>=trailingstop*pointsize then
priceexit=minprice+trailingstop*pointsize
endif
endif
if longonmarket and priceexit>0 then
sell at priceexit stop
endif
if shortonmarket and priceexit>0 then
exitshort at priceexit stop
endif
endif
// break even stop
if enableBE then
if not onmarket then
newsl=0
endif
if ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
newsl=0
endif
if longonmarket then
if close-tradeprice(1)>=((tradeprice/100)*BESG)*pipsize then
newsl=tradeprice(1)+((tradeprice/100)*BESL)*pipsize
endif
endif
if shortonmarket then
if tradeprice(1)-close>=((tradeprice/100)*BESG)*pipsize then
newsl=tradeprice(1)-((tradeprice/100)*BESL)*pipsize
endif
endif
if longonmarket and newsl>0 then
sell at newsl stop
endif
if shortonmarket and newsl>0 then
exitshort at newsl stop
endif
endif
// to set & display profittarget
if enablePT then
set target %profit PT
endif
// to set & display stoploss
if enableSL then
set stop %loss SL
endif
Explanation of the Code:
Check out this related content for more information:
https://www.prorealcode.com/topic/breakeven-and-trailing-stop-problem/#post-90466
Visit Link