Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

OnPositionUpdate not updating?

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

    OnPositionUpdate not updating?

    Hi,
    I created a simple indicator and I want it to only take trades when there are no open positions.
    Given the code below,I subscribed to position updates, the indicator uses atm to manage the trades. Until the first trade is taken, it shows mw that the marketposition is flat. When the first order is submitted, it shows that i am in a trade, but when either stop loss or profit target gets hit, and the position is flat, it still shows that i am in a trade. What did i do wrong?

    Thank you

    Code:
    #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.DrawingTools;
    #endregion
    
    //This namespace holds Indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public class TraderIndicator : Indicator
        {
        
            
            
            
            private string  atmStrategyId            = string.Empty;
            private string  orderId                    = string.Empty;
            private bool    isAtmStrategyCreated    = false;
            
            private bool intrade = false;
            
            private int contr;
            
            private Account myAccount;
            private Account myAcc;
            
            private Order stopOrder = null;
             Order xOrder = null;
            
            NinjaTrader.Gui.Tools.AccountSelector xAlselector;
            
            
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Indicator here.";
                    Name                                        = "TraderIndicator";
                    Calculate                                    = Calculate.OnEachTick;
                    IsOverlay                                    = true;
                    DisplayInDataBox                            = true;
                    DrawOnPricePanel                            = true;
                    DrawHorizontalGridLines                        = true;
                    DrawVerticalGridLines                        = true;
                    PaintPriceMarkers                            = true;
                    ScaleJustification                            = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
                    //See Help Guide for additional information.
                    IsSuspendedWhileInactive                    = true;
                    AddPlot(Brushes.Transparent, "Val");
                    
                    
                     lock (Account.All)
                  myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");
     
          
                    myAcc = myAccount;
                    
                       if (myAccount != null)
                            {
                
                  Print(string.Format("Account Name: {0} Connection Name: {1} Cash Value {2}",
                      myAccount.Name,
                      myAccount.Connection.Options.Name,
                      myAccount.Get(AccountItem.CashValue, Currency.UsDollar)
                      ));
     
                            
                    myAccount.PositionUpdate += OnPositionUpdate;                        
                            
                  // Print the prices of the executions on our account
                  lock (myAccount.Executions)
                      foreach (Execution execution in myAccount.Executions)
                            Print("Price: " + execution.Price);
     
              
                        }
                    
                    
                }
                else if (State == State.Configure)
                {
                }
            
                
            }
    
            protected override void OnBarUpdate()
            {
            
                
            //====================================================================================================================================        
            //   TRADING FUNCTIONS
            //====================================================================================================================================
                    
                    
                    if ( State != State.Historical )
                {
                    if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 10)
                    return;
                
              //   getting the atm strategy from chart trader
    
                    ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                {
                                xAlselector = Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlAccountSelector") as NinjaTrader.Gui.Tools.AccountSelector;
                                  NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector selector = Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlATMStrategySelector") as
                                 NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
                        
                    myAccount = xAlselector.SelectedAccount;
                }));
    
               //  getting the contract size from chart trader
                
                ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                                                {
                                                    NinjaTrader.Gui.Tools.QuantityUpDown quantitySelector = (Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlQuantitySelector") as
                                   NinjaTrader.Gui.Tools.QuantityUpDown);
    
                                                    contr = quantitySelector.Value ;        
                                                }));
              // update and subscribe to events in case account has been changed from the chart trader
        
            if (myAcc != myAccount)
            {
                 myAcc = myAccount;
                myAccount.PositionUpdate += OnPositionUpdate;    
                
            }    
                    
                    Print ( intrade);
            
              //------------------------------
              //   long entry
            
                if ( IsFirstTickOfBar
                    && !intrade
                    && Close[1]>Open[1]
                    
                    )
                    {
                                            
                                                  xOrder = myAccount.CreateOrder(Instrument, OrderAction.Buy, OrderType.Market, OrderEntry.Automated, TimeInForce.Gtc, contr, 0, 0, "", "Entry",
                                                                   Core.Globals.MaxDate, null);
                                                ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                                            {
                                                NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector selector =
                                                Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlATMStrategySelector") as NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
                                                NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy(selector.SelectedAtmStrategy, xOrder);
                                            }));
                    }
                    
             //----------------------------------------------
             // short entry                
    
                    if ( IsFirstTickOfBar
                    && !intrade
                    && Close[1]<Open[1]
                  
                    )
                    {
                                            
                                                  xOrder = myAccount.CreateOrder(Instrument, OrderAction.Sell, OrderType.Market, OrderEntry.Automated, TimeInForce.Gtc, contr, 0, 0, "", "Entry",
                                                                  Core.Globals.MaxDate, null);
                                                ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                                            {
                                                NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector selector =
                                                Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlATMStrategySelector") as NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
                                                NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy(selector.SelectedAtmStrategy, xOrder);
                                            }));
                    }
                    
                    
            
                }
                
                
                //---------------------------------------------------------------------------------------------------------------------------------------
                    
                    
                        
            }
            
             private void OnPositionUpdate(object sender, PositionEventArgs e)
        {
           if ( e.Position.MarketPosition == MarketPosition.Flat )
                   intrade = false;
           else intrade = true;
          
              NinjaTrader.Code.Output.Process(string.Format("Instrument: {0} MarketPosition: {1} AveragePrice: {2} Quantity: {3}",
                  e.Position.Instrument.FullName, e.MarketPosition, e.AveragePrice, e.Quantity), PrintTo.OutputTab1);
          
        }
     
      
      
        }
    }
    
    ​
    Last edited by gyilaoliver; 11-06-2024, 07:30 AM.

    #2
    Hello gyilaoliver,

    You likely should be using the position collection for this instead, the indicator could loop over that collection at any time to check if positions exists, you don't have to wait for events that way.

    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