Implementing Separate Money Management for Long and Short Positions in Trading Strategies

10 Dec 2022
0 comment
0 attachment

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:

  • The code starts by initializing variables to track profits for long and short positions separately.
  • It calculates the change in strategy profit and updates the respective profit variables based on whether the market was long or short at the previous bar.
  • Money management settings are defined, including minimum and maximum position sizes, and multipliers based on drawdowns to calculate the capital for long and short positions.
  • Position sizes for buying and selling are dynamically adjusted based on the equity, which includes accrued profits and the initial capital adjusted for drawdowns.
  • Trading signals are generated based on the crossover of the closing price with a simple moving average. Trades are executed only if there is no current position in the market.
  • Stop loss and take profit levels are set for each trade.
  • Debugging data is graphed to visualize the combined profit from long and short positions and the overall strategy profit.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/money-management-discussion/#post-201804

Visit Link
What is a Snippet? A snippet is a small, reusable chunk of code designed to solve specific tasks quickly. Think of it as a shortcut that helps you achieve your coding goals without reinventing the wheel. How to Use: Simply copy the snippet and paste it into your project where needed. Don't forget to tweak it to fit your context. Snippets are not just time-savers; they're also learning tools to help you become a more efficient coder.
robertogozzi Master
Roberto https://www.ots-onlinetradingsoftware.com
Author’s Profile

Comments

Search Snippets

Showing some results...
Sorry, no result found!

Snippets Categories

global
35
indicator
133
strategy
171

Recent Snippets

How to Create a Simple MTF Trend Dashboard with EMA and SMA
indicator
This indicator builds a compact multi-timeframe (MTF) dashboard that shows whether price is trading above or below a [...]
How to Display Per-Bar Volume Accumulation in Real Time (Intrabar Updates)
global
This snippet tracks and displays the current bar’s accumulated volume while the bar is still forming, instead of only [...]
Ticks Counter: Count Tick Updates Per Bar on Tick or Time Charts
global
This snippet counts how many tick updates have occurred for the current bar by incrementing a per-bar counter on each [...]
How to Build a Step-Based Trailing Stop That Moves to Break-Even First
strategy
This snippet implements a step trailing stop that advances in fixed increments once price reaches predefined profit [...]
Utilizing Arrays to Track and Compare Indicator Values Within the Same Bar in ProBuilder
indicator
This ProBuilder code snippet demonstrates how to use arrays to compare the values of an indicator (RSI in this case) [...]
Logo Logo
Loading...