This code snippet demonstrates how to implement a dynamic trailing stop loss and take profit mechanism in a trading strategy using ProBuilder language. The trailing stop adjusts as the market price moves, ensuring that the stop loss and take profit levels adapt to changing market conditions.
sl = 20 //Stop loss distance
slmove = 3 //Price move needed to move stop loss
slminstop = 5 //Minimum stop loss distance allowed
tp = 20 //Take profit distance
tpmove = 3 //Price move needed to move take profit
tpminstop = 5 //Minimum take profit distance allowed
sl = max(sl, slminstop)
tp = max(tp, tpminstop)
if longonmarket and adj then
slprice = positionprice - sl
tpprice = positionprice + tp
adj = 0
endif
if shortonmarket and adj then
slprice = positionprice + sl
tpprice = positionprice - tp
adj = 0
endif
if not onmarket and (your long entry conditions) then
buy 1 contract at market
slprice = close - sl
tpprice = close + tp
adj = 1
endif
if not onmarket and (your short entry conditions) then
sellshort 1 contract at market
slprice = close + sl
tpprice = close - tp
adj = 1
endif
if longonmarket and high - sl > slprice + slmove then
slprice = min(high - sl, close - slminstop)
endif
if longonmarket and low + tp < tpprice - tpmove then
tpprice = max(low + tp, close + tpminstop)
endif
if shortonmarket and low + sl < slprice - slmove then
slprice = max(low + sl, close + slminstop)
endif
if shortonmarket and high - tp > tpprice + tpmove then
tpprice = min(high - tp, close - tpminstop)
endif
sell at slprice stop
exitshort at slprice stop
sell at tpprice limit
exitshort at tpprice limit
Explanation of the Code: