This code snippet demonstrates how to implement a trailing stop strategy for cumulative positions in trading using the ProBuilder language. A trailing stop is a type of stop-loss order that moves with the market price and is designed to protect gains by enabling a trade to remain open and continue to profit as long as the price is moving in the investor’s favor. The code specifically handles the complexity of adjusting the stop-loss level when additional positions are cumulated.
//*********************************************************************************
// https://www.prorealcode.com/blog/trading/complete-trailing-stop-code-function/
//
// trailing stop function
//-------------------------------------------------------------
//reset the stoploss value
IF NOT ONMARKET THEN
NewSL = 0
MyPositionPrice = 0
ENDIF
//-------------------------------------------------------------
// Update locked in profit, if any, after comulating positions
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
//-------------------------------------------------------------
trailingstart = 20 //trailing will start @trailinstart points profit
trailingstep = 5 //trailing step to move the "stoploss"
//manage long positions
IF LONGONMARKET THEN
//first move (breakeven)
IF newSL=0 AND close-PositionPrice>=trailingstart*pipsize THEN
newSL = PositionPrice+trailingstep*pipsize
ENDIF
//next moves
IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
newSL = newSL+trailingstep*pipsize
ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
//first move (breakeven)
IF newSL=0 AND PositionPrice-close>=trailingstart*pipsize THEN
newSL = PositionPrice-trailingstep*pipsize
ENDIF
//next moves
IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
newSL = newSL-trailingstep*pipsize
ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
SELL AT newSL STOP
EXITSHORT AT newSL STOP
ENDIF
MyPositionPrice = PositionPrice
//*********************************************************************************
Explanation of the Code:
This code is a practical example of how to manage and adjust trailing stops dynamically in a trading environment, particularly useful for strategies involving cumulative positions.
Check out this related content for more information:
https://www.prorealcode.com/topic/trailing-stop-with-cumulative-orders/#post-146951
Visit Link