Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Dynamic Position Sizing

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

    Dynamic Position Sizing

    I'm attempting to build in my strategies a boiler plate of the number of shares to buy, given some user variables. I have the following variables:

    #region Variables
    // Wizard generated variables
    private int accountValue = 50000; // Default setting for AccountValue
    private double riskTolerance = 0.015; // Default setting for RiskTolerance
    private double stopLoss = 0.04; // Default setting for StopLoss
    // User defined variables (add any user defined variables below)
    #endregion

    I then have the following Method, which should yield a round 100 lot:

    public double ShareQuantity()
    {
    double x = Math.Round(((((1/stopLoss)*(accountValue*riskTolerance))/GetCurrentAsk())/100),0);
    return x * 100;
    }
    I have various conditions, then the execution line:

    EnterLong(ShareQuantity,"");

    For some reason, it does not seem to be working. I greatly appreciate any help anyone can provide.

    Thank you.

    #2
    Hi SRemains, welcome to our support forums!

    Have you tried adding Print statments to check your calculations? http://www.ninjatrader-support2.com/...ead.php?t=3418

    Which quantity is bought?

    How do you have set the 'SetOrderQuantity' when starting your NinjaScript strategy? - http://www.ninjatrader-support.com/H...romAChart.html

    Comment


      #3
      Hi Betrand, and thank you for taking a look. Clearly, I should have originally given more information. I use 'ByStrategy' in the 'SetOrderQuantity'. I have only run it using Ninja's simulated data feed, which buys a quantity of 1.

      I will see about trying the print window. Although I have some VBA experience, this is my first attempt at programming in C#, so I thought it might have been a simple error in my code. By your reply, I assume there are no glaring errors.

      I was wondering if the location of the method ShareQuantity() needs to be in a different location in the code.

      Comment


        #4
        SRemains,

        I would not think putting it there would be a problem. Normally I put it after the OnBarUpdate() method. I would, however, suggest you use it as a private instead of public if this is method is for internal calculation purposes only.

        In your code you do this: EnterLong(ShareQuantity,"");

        To get the ShareQuantity method to trigger you need to be calling the method name with ().

        Try: EnterLong(ShareQuantity(), "");

        A final note as well, GetCurrentAsk() is for use in real-time only. If used historically it will just give you the closing price of the bar.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          There must be other bugs at work. It doesn't seem to calculate at all, still buying only 1 share. I'm not sure where to go from here.

          Thank you

          Comment


            #6
            Make sure you are running your strategy with an Order Handling option of "ByStrategy".
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Yes, I'm doing that too, so I am stumped.

              Comment


                #8
                SRemains,

                Please post up complete code so we can evaluate it. Thank you.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Josh,

                  I really appreciate your help and evaluation. Here is the complete code. Please take a look. For example, let's assume the price of the stock at the buypoint1 is $7.38, the ShareQuantity method should buy 2500 shares.

                  I look forward to any help and input you may have. This is my first attempt at C# Ninja Script, so it may have all kinds of problems.

                  SRemains

                  namespace NinjaTrader.Strategy
                  {
                  /// <summary>
                  /// Enter the description of your strategy here
                  /// </summary>
                  [Description("Enter the description of your strategy here")]
                  public class EMA8Momentum : Strategy
                  {
                  #region Variables
                  // Wizard generated variables
                  private int accountValue = 50000; // Default setting for AccountValue
                  private double riskTolerance = 0.015; // Default setting for RiskTolerance
                  private double stopLoss = 0.04; // Default setting for StopLoss
                  // User defined variables (add any user defined variables below)
                  #endregion

                  /// <summary>
                  /// This method is used to configure the strategy and is called once before any strategy method is called.
                  /// </summary>
                  protected override void Initialize()
                  {
                  Add(EMA(8));
                  Add(EMA(21));
                  Add(MAX(5));
                  SetTrailStop("BuyPoint1", CalculationMode.Percent, StopLoss, true);

                  CalculateOnBarClose = false;
                  }

                  /// <summary>
                  /// Called on each bar update event (incoming tick)
                  /// </summary>
                  /// ShareQuantity will calculate the number of shares to buy based the overall risk one wants to take per trade
                  /// by calculating that dollar amount, and varying the share quantity to match the initial stop loss percent
                  public double ShareQuantity()
                  {
                  double x = Math.Round(((((1/stopLoss)*(accountValue*riskTolerance))/GetCurrentAsk())/100),0);
                  return x * 100;
                  }
                  protected override void OnBarUpdate()
                  {
                  // Condition set 1
                  if (EMA(8)[0] > EMA(21)[0]
                  && GetCurrentAsk() + 2 * TickSize == EMA(8)[0])
                  {
                  EnterLong(ShareQuantity(), "BuyPoint1");
                  DrawTriangleUp("My triangle up" + CurrentBar, false, 0, 0, Color.Lime);
                  }

                  // Condition set 2
                  if (Position.MarketPosition == MarketPosition.Long
                  && GetCurrentBid() < Position.AvgPrice + StopLoss * TickSize)
                  {
                  DrawTriangleDown("My triangle down" + CurrentBar, false, 0, 0, Color.Red);
                  ExitLong("", "BuyPoint1");
                  }

                  // Condition set 3
                  if (Position.MarketPosition == MarketPosition.Long
                  && GetCurrentBid() < EMA(8)[0])
                  {
                  ExitLong("", "BuyPoint1");
                  }

                  // Condition set 4
                  if (Position.MarketPosition == MarketPosition.Flat
                  && GetCurrentBid() + 2 * TickSize >= EMA(8)[0]
                  && GetCurrentBid() + 2 * TickSize > MAX(5)[1])
                  {
                  EnterLong(ShareQuantity(), "BuyPoint2");
                  }

                  // Condition set 5
                  if (Position.MarketPosition == MarketPosition.Long
                  && GetCurrentBid() + -2 * TickSize < EMA(8)[0])
                  {
                  ExitLong("", "BuyPoint2");
                  }
                  }

                  #region Properties
                  [Description("Day's Beginning Account Value")]
                  [Category("Parameters")]
                  public int AccountValue
                  {
                  get { return accountValue; }
                  set { accountValue = Math.Max(25000, value); }
                  }

                  [Description("Used to calculate MaxLoss on trade")]
                  [Category("Parameters")]
                  public double RiskTolerance
                  {
                  get { return riskTolerance; }
                  set { riskTolerance = Math.Max(0.01, value); }
                  }

                  [Description("Initial Stop Loss")]
                  [Category("Parameters")]
                  public double StopLoss
                  {
                  get { return stopLoss; }
                  set { stopLoss = Math.Max(0.01, value); }
                  }
                  #endregion
                  }
                  }

                  Comment


                    #10
                    Before your EnterLong(ShareQuantity(), "BuyPoint2"); line. Print out the value of ShareQuantity() so you know what you are submitting at. Also, why is this function a double function? Shares would be whole numbers for the most part.
                    Josh P.NinjaTrader Customer Service

                    Comment


                      #11
                      I put it in as a 'double' method because the initial value of the Round function works on is a decimal, but perhaps it should be a 'int'.

                      In order to Print the ShareQuantity, is is Print(ShareQuantity())?

                      Comment


                        #12
                        Print(ShareQuantity().ToString());
                        Josh P.NinjaTrader Customer Service

                        Comment


                          #13
                          I believe that the problem has to do with explicit conversion of a double to an int. Thanks again for your help.

                          Comment


                            #14
                            Glad you got it isolated.
                            Josh P.NinjaTrader Customer Service

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                            0 responses
                            558 views
                            0 likes
                            Last Post Geovanny Suaza  
                            Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                            0 responses
                            324 views
                            1 like
                            Last Post Geovanny Suaza  
                            Started by Mindset, 02-09-2026, 11:44 AM
                            0 responses
                            101 views
                            0 likes
                            Last Post Mindset
                            by Mindset
                             
                            Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                            0 responses
                            545 views
                            1 like
                            Last Post Geovanny Suaza  
                            Started by RFrosty, 01-28-2026, 06:49 PM
                            0 responses
                            547 views
                            1 like
                            Last Post RFrosty
                            by RFrosty
                             
                            Working...
                            X