Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

How to calculate new position size based on account balance

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

    How to calculate new position size based on account balance

    I am trying to modify a simple strategy I created using the strategy builder to make it increase the position size as the account balance increases. I have searched everywhere in the NT8 forums and I can't find a way to make it happens.

    This is the code I am having difficulty with:

    // Calculates new position size based on the account balance
    // ContractsPerPosition = Convert.ToInt32(Math.Floor(Account.Get(AccountItem .CashValue, Currency.UsDollar) / MinBalancePerContract));
    // ContractsPerPosition = (int) (Math.Floor(Account.Get(AccountItem.BuyingPower, Currency.UsDollar) / MinBalancePerContract));
    ContractsPerPosition = Convert.ToInt32(Math.Floor(Account.Get(AccountItem .BuyingPower, Currency.UsDollar) / MinBalancePerContract));

    As you can see I have already tried several approaches. Nothing appears to work.

    Any help will be greatly appreciated.

    Also, if you know of any book, Youtube video or tutorial for NinjaScript 8 beginners, I will appreciate that too. I am a seasoned MQL4 programmer but I know nothing about NinjaScript 8. I found a couple of books on NinjaScript 7 but I know how dramatic the changes from 7 to 8 are so I don't want to learn what is already obsolete.

    This is the program I am trying to modify:

    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion

    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class BarColorTraderv02 : Strategy
    {
    private int ContractsPerPosition;


    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"On the open close we trade the bar color. This one has money management.";
    Name = "BarColorTraderv02";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 600;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 2;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    Target = 12;
    StopLoss = 15;
    MinBalancePerContract = 2000;
    TrailingSL = 10;
    ContractsPerPosition = 1;
    }
    else if (State == State.Configure)
    {
    SetStopLoss("", CalculationMode.Ticks, StopLoss, false);
    SetProfitTarget("", CalculationMode.Ticks, Target);
    SetTrailStop(@"TrailingSL. " + Convert.ToString(CurrentBars[0]), CalculationMode.Ticks, TrailingSL, false);
    }
    }

    protected override void OnBarUpdate()
    {

    // Calculates new position size based on account balance
    // ContractsPerPosition = Convert.ToInt32(Math.Floor(Account.Get(AccountItem .CashValue, Currency.UsDollar) / MinBalancePerContract));
    // ContractsPerPosition = (int) (Math.Floor(Account.Get(AccountItem.BuyingPower, Currency.UsDollar) / MinBalancePerContract));
    ContractsPerPosition = Convert.ToInt32(Math.Floor(Account.Get(AccountItem .BuyingPower, Currency.UsDollar) / MinBalancePerContract));

    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if ((Close[0] >= Open[0])
    && (Close[1] < Open[1]))
    {
    EnterLong(Convert.ToInt32(ContractsPerPosition), @"LongPos. " + Convert.ToString(CurrentBars[0]));
    Draw.ArrowUp(this, @"ArrowUP. " + Convert.ToString(CurrentBars[0]), false, 0, (Low[0] + (-4 * TickSize)) , Brushes.Lime);
    }

    // Set 2
    if ((Close[0] < Open[0])
    && (Close[1] >= Open[1]))
    {
    EnterShort(Convert.ToInt32(ContractsPerPosition), @"ShortPos. " + Convert.ToString(CurrentBars[0]));
    Draw.ArrowDown(this, @"ArrowDown. " + Convert.ToString(CurrentBars[0]), false, 0, (High[0] + (4 * TickSize)) , Brushes.Red);
    }

    }

    #region Properties
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="Target", Order=1, GroupName="Parameters")]
    public int Target
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="StopLoss", Order=2, GroupName="Parameters")]
    public int StopLoss
    { get; set; }

    [NinjaScriptProperty]
    [Range(500, double.MaxValue)]
    [Display(Name="MinBalancePerContract", Description="Minimum balance required to open 1 contract", Order=3, GroupName="Parameters")]
    public double MinBalancePerContract
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="TrailingSL", Description="Distance from price to Trailing Stop Loss", Order=4, GroupName="Parameters")]
    public int TrailingSL
    { get; set; }

    #endregion

    }
    }

    #2
    I've been trying to achieve the same with no luck, any thing worked on your side?

    Comment


      #3
      Hello bestmethod,

      Thanks for your post and welcome to the NinjaTrader Forums!

      If you are looking to do this in the Strategy Builder it would not be possible.

      You can unlock the code of the strategy builder and work on the strategy directly in Ninjascript where you can access the account methods that are needed.

      Please see this thread for further information: https://ninjatrader.com/support/foru...n-account-size
      Paul H.NinjaTrader Customer Service

      Comment


        #4
        Yes bestmethod, I ended up figuring it out mostly by myself.

        I am going to give you the key points so you can include them in your code.

        By the way, it can't be achieved via the Strategy Builder. You can generate the basic code using it, but then you have to unlock the code and use either the NinjaScript editor -horrible choice- or Visual Basic editor to modify your code so you can change the position size according to your needs.

        Here is how I do it:


        namespace NinjaTrader.NinjaScript.Strategies
        {
        public class NewLotSize : Strategy
        {
        private int LotSize;

        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        // This variable is an input defined using the Strategy Builder
        InitialLotSize = 1;
        }

        protected override void OnBarUpdate()
        {
        // I am going to illustrate only a Long entry, you will figure out the rest:
        if (Here you define the condition to change the Lot Size)
        {
        // Here you will calculate the new Lot Size based on InitialLotSize and any rules and variables you define
        // Let's say for example that I want it like this:
        LotSize = InitialLotSize + 1;
        EnterLong(Convert.ToInt32(LotSize));
        }
        }



        #region Properties
        // Just in case, this is what you need to have in the region Properties at the end of your code for it to work properly,
        // but I prefer to generate it using the Strategy Builder because it takes care of the Order and several other things:
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name = "Initial Lot Size", Order = 2, GroupName = "Parameters")]
        public int InitialLotSize
        { get; set; }
        #endregion
        }
        }


        Let me know if you have any trouble implementing it. I am another user like you but I think we should help each other.

        Comment


          #5
          Here there is a picture of the code with indentations so you can have a better view of it:



          Comment


            #6
            Hi ivangil - are you still active? wondering if I can send you a message/email regarding this indicator. its something along the lines Im trying to develop

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by wzgy0920, 04-20-2024, 06:09 PM
            2 responses
            26 views
            0 likes
            Last Post wzgy0920  
            Started by wzgy0920, 02-22-2024, 01:11 AM
            5 responses
            32 views
            0 likes
            Last Post wzgy0920  
            Started by wzgy0920, Yesterday, 09:53 PM
            2 responses
            49 views
            0 likes
            Last Post wzgy0920  
            Started by Kensonprib, 04-28-2021, 10:11 AM
            5 responses
            192 views
            0 likes
            Last Post Hasadafa  
            Started by GussJ, 03-04-2020, 03:11 PM
            11 responses
            3,234 views
            0 likes
            Last Post xiinteractive  
            Working...
            X