This code snippet demonstrates how to implement a trading strategy in ProBuilder that utilizes Z-Score for decision making and includes a trailing stop mechanism for managing open positions. The strategy skips trades based on the Z-Score and manages exits with dynamic stop-loss adjustments.
//*********************************************************************************
// Z-Score management
ONCE SkipOneTrade = 0
ONCE SkipFlag = 0
ONCE MinTrades = 51 //30 or 51
DirectionSwitch = (ShortOnMarket AND LongOnMarket[1]) OR (ShortOnMarket[1] AND LongOnMarket)
IF Zpos THEN
IF (CurTrade = 1) AND SkipFlag = 0 AND ((Not Onmarket) OR DirectionSwitch) THEN
IF N >= MinTrades THEN
SkipOneTrade = 1
SkipFlag = 1
ENDIF
ENDIF
ELSIF Zneg THEN
IF (CurTrade = -1) AND SkipFlag = 0 AND ((Not Onmarket) OR DirectionSwitch) THEN
IF N >= MinTrades THEN
SkipOneTrade = 1
SkipFlag = 1
ENDIF
ENDIF
ENDIF
//*********************************************************************************
ONCE MA = 100 //100
ONCE T = 1 //1=ema
IF close CROSSES OVER average[MA,T] AND Not OnMarket THEN
IF SkipOneTrade THEN
SkipOneTrade = 0
ELSE
BUY AT Market
SkipFlag = 0
ENDIF
ELSIF close CROSSES UNDER average[MA,T] AND Not OnMarket THEN
IF SkipOneTrade THEN
SkipOneTrade = 0
ELSE
SELLSHORT AT Market
SkipFlag = 0
ENDIF
ENDIF
set stop ploss 500 //500
set target pprofit 5000 //5000
//
//*********************************************************************************
//trailing stop function
trailingstart = 50 //50
trailingstep = 5 //5
//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*pipsize THEN
newSL = tradeprice(1)+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 tradeprice(1)-close>=trailingstart*pipsize THEN
newSL = tradeprice(1)-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
//*********************************************************************************
// graph Zscore coloured(255,0,0,255)
graph TotalWin
graph TotalLose
Explanation of the Code:
This snippet provides a practical example of combining various trading strategy components like Z-Score filtering, entry/exit rules, and dynamic risk management in the ProBuilder language.
Check out this related content for more information:
https://www.prorealcode.com/topic/z-score-to-improve-strategies/#post-174413
Visit Link