This code snippet demonstrates how to implement a dynamic trailing stop strategy in a trading algorithm using the ProBuilder language. The trailing stop adjusts based on a percentage of the position price and incorporates sensitivity settings that determine the trigger based on different price points like close, high, low, or a typical price.
once trailingstoptype = 1
if trailingstoptype then
trailingpercentlong = tst
trailingpercentshort = tss
once acceleratorlong = a1
once acceleratorshort= a2
ts2sensitivity = 2
once steppercentlong = (trailingpercentlong/10)*acceleratorlong
once steppercentshort = (trailingpercentshort/10)*acceleratorshort
if onmarket then
trailingstartlong = positionprice*(trailingpercentlong/100)
trailingstartshort = positionprice*(trailingpercentshort/100)
trailingsteplong = positionprice*(steppercentlong/100)
trailingstepshort = positionprice*(steppercentshort/100)
endif
if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
newsl = 0
mypositionprice = 0
endif
positioncount = abs(countofposition)
if newsl > 0 then
if positioncount > positioncount[1] then
if longonmarket then
newsl = max(newsl,positionprice * newsl / mypositionprice)
else
newsl = min(newsl,positionprice * newsl / mypositionprice)
endif
endif
endif
if ts2sensitivity=1 then
ts2sensitivitylong=close
ts2sensitivityshort=close
elsif ts2sensitivity=2 then
ts2sensitivitylong=high
ts2sensitivityshort=low
elsif ts2sensitivity=3 then
ts2sensitivitylong=low
ts2sensitivityshort=high
elsif ts2sensitivity=4 then
ts2sensitivitylong=(typicalprice)
ts2sensitivityshort=(typicalprice)
endif
if longonmarket then
if newsl=0 and ts2sensitivitylong-positionprice>=trailingstartlong then
newsl = positionprice+trailingsteplong
endif
if newsl>0 and ts2sensitivitylong-newsl>=trailingsteplong then
newsl = newsl+trailingsteplong
endif
endif
if shortonmarket then
if newsl=0 and positionprice-ts2sensitivityshort>=trailingstartshort then
newsl = positionprice-trailingstepshort
endif
if newsl>0 and newsl-ts2sensitivityshort>=trailingstepshort then
newsl = newsl-trailingstepshort
endif
endif
if barindex-tradeindex>1 then
if longonmarket then
if newsl>0 then
sell at newsl stop
endif
if newsl>0 then
if low crosses under newsl then
sell at market
endif
endif
endif
if shortonmarket then
if newsl>0 then
exitshort at newsl stop
endif
if newsl>0 then
if high crosses over newsl then
exitshort at market
endif
endif
endif
endif
mypositionprice = positionprice
endif
The code snippet above is structured to manage a trailing stop loss in a trading system. Here’s a step-by-step explanation:
This example is useful for understanding how to implement complex trading strategies programmatically, focusing on dynamic and responsive stop loss mechanisms.
Check out this related content for more information:
https://www.prorealcode.com/topic/change-stop-loss-in-strategy/#post-179902
Visit Link