Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Position.MarketPosition

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

    Position.MarketPosition

    When you first start a strategy, and it's historical calculations show that it's supposed to be short, for example. when you enable it, the Position.MarketPosition returns MarketPosition.Short, even though no real position has actually been placed yet (and you are actually flat in reality).

    How do I get the actual true market position?

    Jeremy
    Jeremytang
    NinjaTrader Ecosystem Vendor - Shark Indicators

    #2
    Hi,

    Don't mind me too much because I'm just guessing here. I wonder if you were to turn off the setting that has your strategy run historical bars, and run only forward from the time it's enabled. Maybe in that case it would not assume a historical MarketPosition.Long and check to see what the true MarketPosition is. I hope this is right because I'm going to need this too.

    Comment


      #3
      Hello Jeremytang,

      A Strategy Position is going to be a virtual position different from the account position so if it is processing it historically the strategy will think that it is short. Here is a thread that you may read that will go over the difference between Account Position and Strategy Position.


      Not running your Strategy Historically would be one way to do this as well.


      You can also sync your account position with your strategy if you like by following the different methods shown in our Help Guide below.
      JCNinjaTrader Customer Service

      Comment


        #4
        Hi Jeremytang,

        I'm about to post the solution I just came up with a few minutes ago, but I have to say first that this kind of coding isn't supported by the NT moderators and should be used at own risk. Also, I can't verify 100% that the things I'm saying are true but I have been testing them for the past 3 hours and they seem to add up.

        So I have found (with the help of someone else) that you can in fact find out the true account position and I'll include the code below. But first, to make a distinction: The true account position that pre-existed before the strategy was run can be checked and put to use by the strategy, but if you then make a closing trade based on that account position, the STRATEGY position, Position.MarketPosition will now consider itself to be MarketPosition.Short even though the account is truly flat, because it will consider having done a sell order from flat to short.

        For that reason, I have made all my code and orders to evaluate market position based on true market position, and not strategy market position. This is further complicated by having historical bars, so I have also set my strategy to not process OnBarUpdate() if bars are historical.

        So without further ado, here are three methods I made up that you can call to find out true account info, even of positions that exist before the strategy was started:

        Code:
                private int GetAccountPositionQuantity()
                {
                    if(Account.Positions != null)
                       {
                        PositionCollection positions = Account.Positions;
                           foreach (Position pos in positions)
                           {
                            if(pos.Instrument.MasterInstrument.Name == Instrument.MasterInstrument.Name)
                            {
                                return (pos.Quantity);
                            }
                            
                        }
                       }
                    
                    return (0);  //if it doesn't find that there's a position in the accout matching this symbol, it returns 0 as the current position quantity
                }
        
                
                private double GetAccountPositionAvgPrice()
                {
                    if(Account.Positions != null)
                       {
                        PositionCollection positions = Account.Positions;
                           foreach (Position pos in positions)
                           {
                            if(pos.Instrument.MasterInstrument.Name == Instrument.MasterInstrument.Name)
                            {
                                return (pos.AvgPrice);
                            }
                            
                        }
                       }
                    
                    return (0);  //if it doesn't find that there's a position in the accout matching this symbol, it returns 0 as the current position AvgPrice
                }
                
                private [B]MarketPosition[/B] GetAccountPositionDirection()
                {
                    if(Account.Positions != null)
                       {
                        PositionCollection positions = Account.Positions;
                           foreach (Position pos in positions)
                           {
                            if(pos.Instrument.MasterInstrument.Name == Instrument.MasterInstrument.Name)
                            {
                                return (pos.MarketPosition);
                            }
                            
                        }
                       }
                    
                    return (MarketPosition.Flat);  //if it doesn't find that there's a position in the accout matching this symbol, it returns 0 as the current position direction
                }
        You would put these methods in your code, and then they can be called in this way:

        For example, in OnStartUp(), you want to first of all check if there were any open positions prior to starting the strategy. You could do this:

        if(GetAccountPositionDirection() != MarketPosition.Flat)
        {
        Print("THERE IS A PRE-EXISTING POSITION ON THIS INSTRUMENT OF " + GetAccountPositionQuantity() + " SHARES");

        //Set a live emergency stop at entry price - 5% to cover this position based on whatever its entry price was
        SubmitOrder(0, OrderAction.Sell, OrderType.Stop, GetAccountPositionQuantity(), 0, (GetAccountPositionAvgPrice() * 0.95), "", "Pre-existing position's emergency stop");

        }


        My code may have errors, but you can see that the Account.Positions collection code shown above will draw from the true account details rather than the strategy's Position.MarketPosition details. I hope this helps.

        And I hope this isn't against the forum rules to post this kind of stuff. If it is, may the moderators please remove it.

        Anyway, for me it has been a great breakthrough as now I truly have a strategy that I can run 24 hours a day, five days a week in automatic trading on forex, and if I get a disconnetion, I don't have to worry anymore about the strategy being thrown off. I can just reconnect, reload the strategy, and it will pick up where it left off which changes everything for me.

        Comment


          #5
          is there an easy way to say if 1 bar ago i was long or short

          Comment


            #6
            Hello hifreq,

            The easiest way to find this out inside of a strategy would be to add a DataSeries and track your position this way. For Example:

            Code:
            public DataSeries PositionSeries = null;
            
            protected override void Initialize()
            {			
            	PositionSeries = new DataSeries(this);
            }
            
            protected override void OnBarUpdate()
            {
            	if(Position.MarketPosition == MarketPosition.Long)
            		PositionSeries.Set(1);
            	else if(Position.MarketPosition == MarketPosition.Short)
            		PositionSeries.Set(-1);
            	else
            		PositionSeries.Set(0);
            
                     //Rest of Code
            }
            This way if you check "PositionSeries" it will be 1 for Long, 0 for Flat, and -1 for short and you may use the BarsAgo method to check.
            JCNinjaTrader Customer Service

            Comment


              #7
              ah, great - thx

              Comment


                #8
                i inserted the code and it compiled fine but when i went to backtest it it said it could not be deserialised. the output window related something about my use of setstoploss. it does not seem to like having setstoploss and the positionseries together under the protected override void Initialize() part of the code - what am i missing here?

                Comment


                  #9
                  Hello hifreq,

                  Could you provide me with the full "Deserialization" error so that I may further assist you?
                  JCNinjaTrader Customer Service

                  Comment


                    #10
                    it reads "Strategy "ninjaTrader. strategy........ could not be deserialized: There was an errorreflecting type 'NinjaTrader'. Strategy.........

                    Comment


                      #11
                      Hello hifreq,

                      Sounds like there is a variables that is being used in without using its public/private version usually something inside of the Properties section of a strategy.

                      If you comment out the new DataSeries object that you created do you still get this message?
                      JCNinjaTrader Customer Service

                      Comment


                        #12
                        I cant comment out only a portion but if i comment out the code you gave - then no i dont get that error

                        Comment


                          #13
                          Hello hifreq,

                          Could you post the code that you commented out so that I may take a look at it?
                          JCNinjaTrader Customer Service

                          Comment


                            #14
                            Here I am just posting the whole first part code and yes I have a lot of things commented out - thanks very much for your help!

                            #region Using declarations
                            using System;
                            using System.ComponentModel;
                            using System.Diagnostics;
                            using System.Drawing;
                            using System.Drawing.Drawing2D;
                            using System.Xml.Serialization;
                            using NinjaTrader.Cbi;
                            using NinjaTrader.Data;
                            using NinjaTrader.Indicator;
                            using NinjaTrader.Gui.Chart;
                            using NinjaTrader.Strategy;
                            #endregion

                            // This namespace holds all strategies and is required. Do not change it.
                            namespace NinjaTrader.Strategy
                            {
                            /// <summary>
                            /// Enter the description of your strategy here
                            /// </summary>
                            [Description("Enter the description of your strategy here")]
                            public class AUGTESTER: Strategy
                            {
                            #region Variables
                            // Wizard generated variables
                            int positionSize = 1;
                            // User defined variables (add any user defined variables below)

                            // presets
                            int tbip = 1;
                            //private BoolSeries signalDirection;

                            //public DataSeries PositionSeries = null;

                            #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(PeriodType.Tick,1); // the high granularity dataseries

                            //PositionSeries = new DataSeries(this);

                            RealtimeErrorHandling = RealtimeErrorHandling.TakeNoAction;

                            SetStopLoss("", CalculationMode.Ticks,30, true);


                            //signalDirection = new BoolSeries(this);


                            //SetStopLoss("L2 RT", CalculationMode.Ticks, 26, true);
                            //SetStopLoss("L3 RT", CalculationMode.Ticks, 26, true);
                            //SetStopLoss("S RT", CalculationMode.Ticks, 26, true);
                            //SetStopLoss("S2 RT", CalculationMode.Ticks, 26, true);
                            //SetStopLoss("S3 RT", CalculationMode.Ticks, 26, true);
                            CalculateOnBarClose = true;
                            TraceOrders = true;
                            //signalDirection = new BoolSeries(this);

                            //if (TCTrendingTSF(3, 50).SignalDirection[0] == true)
                            //{
                            //EnterLong();
                            //}
                            //if (TCTrendingTSF(3, 50).SignalDirection[0] == false)
                            //{
                            //EnterShort();
                            //}

                            // SetProfitTarget("L3", CalculationMode.Ticks, 26);
                            // SetProfitTarget("L2", CalculationMode.Ticks, 45);
                            // SetProfitTarget("S2", CalculationMode.Ticks, 45);
                            // SetProfitTarget("S3", CalculationMode.Ticks, 26);
                            }



                            protected override void OnTermination()
                            {
                            SendMail("","", "STR G OFF", "Disabled");


                            }

                            protected override void OnStartUp()
                            {
                            for (int a = 0; a< BarsArray.Length; a++)
                            Print(this.Name+" Bars data ["+a+"] contains "+BarsPeriods[a].ToString()+" of "+BarsArray[a].Count+" bars, commencing at "+BarsArray[a].Get(0).Time);
                            }



                            /// <summary>
                            /// Called on each bar update event (incoming tick)
                            /// </summary>
                            protected override void OnBarUpdate()
                            {
                            //if(Position.MarketPosition == MarketPosition.Long)
                            // PositionSeries.Set(1);
                            // else if(Position.MarketPosition == MarketPosition.Short)
                            // PositionSeries.Set(-1);
                            // else
                            // PositionSeries.Set(0);
                            // SetProfitTarget("", CalculationMode.Ticks, 75);


                            if (BarsInProgress > 0 || CurrentBar < BarsRequired)
                            return; // don't process anything directly on the high granularity timeframe, or early in the chart's data

                            // Condition set 1

                            Comment


                              #15
                              Hello hifreq,

                              I am not able to reproduce this but I do not have your full code or an Indicator that you are calling (TCTrendingTSF) but I am not sure why you are having an Enter signal inside of Initialize() as this would not work.

                              If you would to send me the entire script so that I can take a look at it you may sent it to "support [at] ninjatrader [dot] com".

                              You may Export it as a Source File using the step from our Help Guide at the link below. Please make sure to uncomment out the lines so that you get this deserialization error in the Strategy Analyzer so that I am able to produce this error on my side.
                              JCNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              668 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              377 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              110 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              575 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              580 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X