This ProBuilder code snippet demonstrates how to calculate and track profits separately for long and short trading positions within a trading strategy. The code identifies the type of trade (long or short) and updates the respective profit variables accordingly.
NOT TESTED:
ONCE LongStrategyProfit = 0
ONCE ShortStrategyProfit = 0
IF StrategyProfit <> StrategyProfit[1] THEN
EntryPrice = TradePrice[2]
ExitPrice = TradePrice[2]
Difference = StrategyProfit - StrategyProfit[1]
IF LongOnMarket[1] THEN
//LONG trades
LongStrategyProfit = LongStrategyProfit[1] + Difference
ELSIF ShortOnmarket[1] THEN
//SHORT trades
ShortStrategyProfit = ShortStrategyProfit[1] + Difference
ELSE
//UNDEFINED trades for which both the Difference and the Entry and Exit prices need to be compared to determine the direction
IF Difference > 0 THEN
IF ExitPrice > EntryPrice THEN
LongStrategyProfit = LongStrategyProfit[1] + Difference //when it's a PROFIT, a higher EXIT price implies a LONG trade
ELSE
ShortStrategyProfit = ShortStrategyProfit[1] + Difference //when it's a PROFIT, a lower EXIT price implies a SHORT trade
ENDIF
ELSE
IF ExitPrice < EntryPrice THEN
LongStrategyProfit = LongStrategyProfit[1] + Difference //when it's a LOSS, a lower EXIT price implies a LONG trade
ELSE
ShortStrategyProfit = ShortStrategyProfit[1] + Difference //when it's a LOSS, a higher EXIT price implies a SHORT trade
ENDIF
ENDIF
ENDIF
ENDIF
graph LongStrategyProfit coloured("Green")
graph ShortStrategyProfit coloured("Red")
graph LongStrategyProfit + ShortStrategyProfit
Explanation of the Code:
This snippet is useful for traders and developers looking to analyze the performance of trading strategies by distinguishing between profits made on long and short positions.
Check out this related content for more information:
https://www.prorealcode.com/topic/strategy-profit-splitted-for-long-and-short/#post-216388
Visit Link