This code snippet demonstrates how to adjust a trading strategy in ProBuilder to move a stop loss to breakeven and partially close a position when a certain percentage of the take profit target is reached. This technique is commonly used in trading to protect gains and manage risk.
defparam cumulateorders=false
// --- settings
amount = 2 //amount of contract/lot/shares to open for each order
takeprofit = 30 //takeprofit in points
stoploss = 60 //stoploss in points
BreakevenAt = 25 //percent achieved of target to move stop to entry (breakeven)
PointsToKeep = 1 //how much pips/points to keep in profit above or below our entry price when the breakeven is activated (beware of spread)
Lot2Close = 1 //amount of contract/lot/shares quantity to close when breakeven occurs
// --- end of settings
upper = BollingerUp[20](close)
lower = BollingerDown[20](close)
//strategy
if high crosses over upper then
sellshort amount contract at market
endif
if low crosses under lower then
buy amount contract at market
endif
set target pprofit takeprofit
set stop ploss stoploss
//reset the breakevenLevel when no trade are on market
IF NOT ONMARKET THEN
breakevenLevel=0
ENDIF
startBreakeven = takeprofit*(BreakevenAt/100)//how much pips/points in gain to activate the breakeven function?
// --- BUY SIDE ---
//test if the price have moved favourably of "startBreakeven" points already
IF LONGONMARKET AND close-tradeprice(1)>=startBreakeven*pipsize THEN
//calculate the breakevenLevel
breakevenLevel = tradeprice(1)+PointsToKeep*pipsize
ENDIF
//place the new stop orders on market at breakevenLevel
IF LONGONMARKET AND breakevenLevel>0 THEN
SELL AT breakevenLevel STOP
if countoflongshares=amount then
sell Lot2Close contract at market
endif
ENDIF
// --- end of BUY SIDE ---
// --- SELL SIDE ---
//test if the price have moved favourably of "startBreakeven" points already
IF SHORTONMARKET AND tradeprice(1)-close>=startBreakeven*pipsize THEN
//calculate the breakevenLevel
breakevenLevel = tradeprice(1)-PointsToKeep*pipsize
ENDIF
//place the new stop orders on market at breakevenLevel
IF SHORTONMARKET AND breakevenLevel>0 THEN
EXITSHORT AT breakevenLevel STOP
if countofshortshares=amount then
exitshort Lot2Close contract at market
endif
ENDIF
// --- end of SELL SIDE ---
This code snippet is structured to handle both buy and sell orders within a trading strategy that uses Bollinger Bands as entry signals. Here’s a breakdown of its functionality:
This approach helps in managing ongoing trades by securing profits and reducing risk exposure as the market moves in favor of the open positions.
Check out this related content for more information:
https://www.prorealcode.com/topic/bollinger-band-coding-help-please/#post-80959
Visit Link