Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Fixed percentage account position

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Fixed percentage account position

    I'm trying to develop a simple strategy on which it always risk a percentage of the account on each position but I've been having some difficulties to code it and run a correct backtest that shows is positioning in this way.
    So, I have this global variable named accountBalance is declared and initialized to 0.0. This variable will be used to store the dynamic account balance:

    double accountBalance = 0.0;​

    Then I have the OnExecutionUpdate method that gets called whenever there is an execution (a filled order). It updates the accountBalance variable by retrieving the current account balance in USD using Account.Get method with AccountItem.CashValue as the parameter:

    protected override void OnExecutionUpdate(Cbi.Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
    // Update the dynamic account balance on each execution
    accountBalance = Account.Get(AccountItem.CashValue, Currency.UsDollar);
    }
    And finally, the OnBarUpdate method that gets called on each incoming bar. It checks if the script is running on the primary instrument (BarsInProgress != 0) and if there is at least one bar of historical data (CurrentBars[0] < 1). It calculates the remaining account balance by subtracting the total position size from the dynamic account balance. It calculates the dollar amount to risk per trade based on the remaining account balance and the desired risk percentage. It calculates the position size in contracts based on the calculated risk and the instrument's point value. It then defines conditions (longCondition and shortCondition) based on a simple trading logic using the Alligator indicator and the current bar's close price. If the conditions are met, it enters a long or short position with the calculated position size:

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Set your desired risk percentage
    double riskPerTradePercentage = 2.0;

    // Get all open positions
    Position[] openPositions = Positions.ToArray();

    // Get the total position size (sum of all open positions)
    double totalPositionSize = openPositions.Sum(position => position.Quantity * position.Instrument.MasterInstrument.PointValue);

    // Calculate the remaining account balance after considering open positions
    double remainingAccountBalance = accountBalance - totalPositionSize;

    // Calculate the dollar amount to risk per trade
    double riskPerTrade = remainingAccountBalance * (riskPerTradePercentage / 100.0);

    // Calculate the position size in contracts based on risk and Point Value
    double positionSize = riskPerTrade / Instrument.MasterInstrument.PointValue;

    // Set 1 - Long condition
    bool longCondition = WisemanAlligator1.Lips[0] >= WisemanAlligator1.Teeth[0] &&
    WisemanAlligator1.Teeth[0] >= WisemanAlligator1.Jaw[0] &&
    Close[0] >= WisemanAlligator1.Jaw[0];

    // Set 2 - Short condition
    bool shortCondition = WisemanAlligator1.Lips[0] <= WisemanAlligator1.Teeth[0] &&
    WisemanAlligator1.Teeth[0] <= WisemanAlligator1.Jaw[0] &&
    Close[0] <= WisemanAlligator1.Jaw[0];

    // Enter Long
    if (longCondition)
    {
    EnterLong((int)positionSize, "Long");
    }
    // Enter Short
    else if (shortCondition)
    {
    EnterShort((int)positionSize, "Short");
    }
    }

    My question is then, why when I run a backtest it always position sizes a different amount:Click image for larger version

Name:	sc nt.png
Views:	321
Size:	378.0 KB
ID:	1281033​​Could you kindly correct me in what I am doing wrong with this code and how to fix it?

    #2
    Hello jeremy83846,

    In a backtest in the strategy analyzer using Account.Get wont work because the backtest account has a non changing account value. On a chart using historical data the same problem will happen, you will reference the actual account value but that won't change for historical virtual trades. In order to accurately calculate a value historically you would need to add a second variable which is your account value that you wanted to use, when you have an order filled you could add or subtract the pnl from that value and reset the variable to update it. Using Account.Get would only be useful when running in realtime where realtime trades will have an effect on the actual account value.


    Comment


      #3
      Could you tell me on which method will be fine to calculate this variable?

      Comment


        #4
        Hello jeremy83846,

        Thanks for your notes.

        You could define the variable as a class-level variable in the script, such as private double accBalance; and assign a default value to the variable within OnStateChange() when the State == State.Defaults.

        The calculations for the variable could be done within OnBarUpdate().
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by NullPointStrategies, Yesterday, 05:17 AM
        0 responses
        62 views
        0 likes
        Last Post NullPointStrategies  
        Started by argusthome, 03-08-2026, 10:06 AM
        0 responses
        134 views
        0 likes
        Last Post argusthome  
        Started by NabilKhattabi, 03-06-2026, 11:18 AM
        0 responses
        75 views
        0 likes
        Last Post NabilKhattabi  
        Started by Deep42, 03-06-2026, 12:28 AM
        0 responses
        45 views
        0 likes
        Last Post Deep42
        by Deep42
         
        Started by TheRealMorford, 03-05-2026, 06:15 PM
        0 responses
        50 views
        0 likes
        Last Post TheRealMorford  
        Working...
        X