This code snippet demonstrates how to manage money separately for long and short positions in a trading strategy using the ProBuilder language. It includes calculating profits for each type of trade, adjusting position sizes based on accrued profits, and executing trades based on simple moving average signals.
// Initialize variables for tracking profits
ONCE LongProfit = 0
ONCE ShortProfit = 0
// Calculate profit changes and update long or short profits
IF StrategyProfit <> StrategyProfit[1] AND BarIndex > 0 THEN
Profitto = StrategyProfit - StrategyProfit[1]
IF LongOnMarket[1] THEN
LongProfit = LongProfit + Profitto
ELSIF ShortOnMarket[1] THEN
ShortProfit = ShortProfit + Profitto
ELSE
p1 = 1
p2 = 2
IF OnMarket THEN
p1 = 2
p2 = 3
ENDIF
IF TradePrice(p1) > TradePrice(p2) THEN
IF Profitto > 0 THEN
LongProfit = LongProfit + Profitto
ELSE
ShortProfit = ShortProfit + Profitto
ENDIF
ELSIF TradePrice(p1) < TradePrice(p2) THEN
IF Profitto < 0 THEN
LongProfit = LongProfit + Profitto
ELSE
ShortProfit = ShortProfit + Profitto
ENDIF
ELSE
LongProfit = LongProfit + (Profitto / 2)
ShortProfit = ShortProfit + (Profitto / 2)
ENDIF
ENDIF
ENDIF
// Money management settings
ONCE MM = 1
ONCE PositionSizeLong = 1
ONCE PositionSizeShort = 1
ONCE MinSize = 0.5
ONCE MaxSize = 1150
ONCE ProfitAccrued = 0
ONCE DDlong = 2950
ONCE DDshort = 3000
ONCE Multiplier = 2
ONCE CapitalLong = DDlong * Multiplier
ONCE CapitalShort = DDshort * Multiplier
if MM then
EquityLong = CapitalLong + ProfitAccrued + LongProfit
EquityShort = CapitalShort + ProfitAccrued + ShortProfit
PositionSizeLong = Max(MinSize, EquityLong * (MinSize/CapitalLong))
PositionSizeLong = Round(PositionSizeLong*100)
PositionSizeLong = PositionSizeLong/100
PositionSizeLong = min(PositionSizeLong,MaxSize)
PositionSizeShort = Max(MinSize, EquityShort * (MinSize/CapitalShort))
PositionSizeShort = Round(PositionSizeShort*100)
PositionSizeShort = PositionSizeShort/100
PositionSizeShort = min(PositionSizeShort,MaxSize)
endif
// Trading signals based on simple moving average
// Sma = average[50,0](close)
IF close CROSSES OVER Sma AND Not LongOnMarket THEN
BUY PositionSizeLong contracts at Market
ELSIF close CROSSES UNDER Sma AND Not ShortOnMarket THEN
SELLSHORT PositionSizeShort contracts at Market
ENDIF
// Set stop loss and take profit
SET STOP pLOSS 100
SET TARGET pPROFIT 400
// Debugging data
graph LongProfit + ShortProfit AS "Strategy Profit" coloured(0,128,0,155)
graph strategyprofit
Explanation of the Code:
Check out this related content for more information:
https://www.prorealcode.com/topic/money-management-discussion/#post-201804
Visit Link