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

AutomationID issue

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

    AutomationID issue

    I am having issues that I don't understand.
    I have followed the examples given by NT using AutomationID to grab the account name and any changes therein using
    ChartTrader - it works fine but I get the odd InvokeTarget error and my Print to output only works for one account??
    This is the account i set here

    Code:
    if (State == State.SetDefaults)
                {
                   currentAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");​
    }
    In Data Loaded I find my UIElements as such AND load up account item handlers
    Code:
    else if (State == State.DataLoaded)
                {
    
                FindAssignUIElementsByAutomationID();
    if ( currentAccount != null)
                    {
    
                      currentAccount.AccountItemUpdate += OnAccountItemUpdate;
                    currentAccount.PositionUpdate += OnPositionUpdate;    
                    currentAccount.ExecutionUpdate += OnExecutionUpdate;        
                    }​
    
    
    }   ​
    Here is my code for finding UIElements

    Code:
            private void FindAssignUIElementsByAutomationID()
            {
                if (ChartControl != null)
                {
                    // chart controls run on the UI thread. Dispatcher Invoke is used to access the thread.
                    // Typically, the InvokeAsync() is used access the UI thread asynchronously when it is ready. However, if this information is needed immediately, use Invoke so that this blocks the NinjaScript thread from continuing until this operation is complete.
                    // Beware that using Invoke improperly can result in deadlocks.
                    // This example uses Invoke so that the UI control values are available as the historical data is processing
    
                    ChartControl.Dispatcher.Invoke((Action)(() =>
                    {
                        // the window of the chart
                        Window chartWindow = Window.GetWindow(ChartControl.Parent);
    
                        // find the ChartTrader account selector by AutomationID
                        accountSelector        = chartWindow.FindFirst("ChartTraderControlAccountSelector") as AccountSelector;
                        if (accountSelector != null)
                        {
                            accountSelector.SelectionChanged        += AccountSelector_SelectionChanged;
                            currentAccount                            = accountSelector.SelectedAccount;
                            Print("ďn Find "+currentAccount);
                        }
    
                        // find the ChartTrader atmStrategy selector by AutomationID
                        atmStrategySelector    = chartWindow.FindFirst("ChartTraderControlATMStrategySelector") as Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
                        if (atmStrategySelector != null)
                        {
                            atmStrategySelector.SelectionChanged    += AtmStrategySelector_SelectionChanged;
                            currentAtmStrategy                        = atmStrategySelector.SelectedAtmStrategy;
                        }
    
    
                    }));
                }
            }
    
    ​
    And here is my code to monitor and update for account changes
    Code:
            private void AccountSelector_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
                if (currentAccount != null)
                    currentAccount.OrderUpdate -= CurrentAccount_OrderUpdate;
    
                currentAccount        = accountSelector.SelectedAccount;
                if (currentAccount != null)
                    Print("ChartTraderControlAccountSelector SelectedAccount: '" + currentAccount.DisplayName + "' assigned to local variable");
                else
                    Print("ChartTraderControlAccountSelector null");
            }    ​
    All works lovely EXCEPT for when I change account my execution string no longer outputs to Print. If I go back to Sim101 it all works fine so somehow the event handlers are not being transferred over.


    I have spent hours and numerous iterations to sort this and I can't do it.
    If I remove the line in set Defaults ( where I set account to Sim101) the handlers are not initiated. So I definitely need to set the account object to something but why does it 'stick'.
    Can anyone assist and tell me where I am going wrong?
    Last edited by Mindset; 11-23-2022, 09:27 PM.

    #2
    Mindset It seems you have four separate matters here:
    1. Determine the Account the strategy is currently running within
    2. Determine the currently selected Account in a ChartTrader and notify when that Account selection changes
    3. Determine the currently selected ATM Strategy in a ChartTrader and notify when that ATM Strategy selection changes
    4. Monitor changes to various things such as Orders, AccountItems, Executions, etc during strategy execution
    These four matters are largely unrelated and can be managed separately.
    1. The Account variable in a strategy is always the Account the strategy is running in -- no need to use a query to get it; just refer to Account and you're there!
    2. For determining the selected Account in a ChartTrader and updating when it changes, you already have the relevant code, by and large:
      Find the ChartTrader AccountSelector using the AutomationID, then establish an event handler for the SelectionChanged event. That event handler merely needs to update the variable holding the currently selected ChartTrader Account from the SelectionChangedEventArgs. You do not need to set anything else from an Account-specific context.
    3. For the ATM Strategy, the approach is virtually identical to the Account selection in ChartTrader.
    4. The methods OnOrderUpdate, OnAccountItemUpdate, OnExecutionUpdate, etc are "standalone" in nature. Simply declare these methods if you want to use them, in the same manner as the documentation on the method, and then do whatever you want within the body of the method. You do not need to "attach" them to an Account as event handlers, since the strategy will only ever be running within the one Account. Note that these methods are invoked automatically by NinjaTrader, and they provide data (via the method parameters) that allows the Account to be known for the update. For example, OnOrderUpdate includes the Order, OnAccountItemUpdate includes the Account itself, and OnExecutionUpdate has an Execution object that contains the Account. Refer to those objects and you have the Account, and lots more besides.
    You will find all this information (and more) in the individual sections within the NT8 Help for Strategy.​ Like many things, we often try to make them more complicated than they really are, and this is such a case, I think. Always a good idea to go to the Help. It's not perfect, but it is almost always very useful. For things like the update methods, it's authoritative.

    Hope that helps.

    Thanks.
    Multi-Dimensional Managed Trading
    jeronymite
    NinjaTrader Ecosystem Vendor - Mizpah Software

    Comment


      #3
      Thanks jeronymite.Indeed we can get all caught up in the complexity of something that is simple but the fact remains I still can't get this to work how I want.
      I can change the account and it registers but I cannot get my print to work.
      Ive used NT for over 10 years and it's been frustrating because I am only a self taught coder - so my knowledge is limited really.
      I now have a situation where sometimes the whole position disappears off the chart - literally no line, no flag no pnl - but the position is there.
      So I can't use it real time with that potential behaviour. And I can't pin what causes that other than it is to do with changing accounts.
      But it happens sporadically.
      And that is frustrating - perhaps NT support can shine some light on what I am doing incorrectly. I am at the end of my tether.

      ps should add that this is an indicator not a strategy
      Last edited by Mindset; 11-24-2022, 07:55 AM.

      Comment


        #4
        Hello Mindset

        The code you are using is incomplete and won't work to resubscribe or correctly unsubscribe from the first account. I would suggest looking at the addon sample basic file and how it makes use of the account selector.



        See how the updateAccountHandlers action is used to update the account when the account selection is changed.



        JesseNinjaTrader Customer Service

        Comment


          #5
          Hi Jesse
          Maybe I can go through my logic and if anything is awry you can set me straight.
          First declare an account and an accountSelector
          Code:
          private NinjaTrader.Gui.Tools.AccountSelector account selector;
          private NinjaTrader.Cbi.Account currentAccount;
          then In State == State.Downloaded

          Code:
          else if State = State.Downloaded
          {
          FindAssignUIElementsByAutomationID();
          }
          Which ascertains the elements of Automation.it seems to work currently.
          Code:
          private void FindAssignUIElementsByAutomationID()
          {
          if (ChartControl != null)
          {
          ChartControl.Dispatcher.Invoke((Action)(() =>
          {
          // the window of the chart
          Window chartWindow = Window.GetWindow(ChartControl.Parent);
          
          // find the ChartTrader account selector by AutomationID
          accountSelector = chartWindow.FindFirst("ChartTraderControlAccountSe lector") as AccountSelector;
          if (accountSelector != null)
          {
          accountSelector.SelectionChanged += AccountSelector_SelectionChanged;
          currentAccount = accountSelector.SelectedAccount;
          }
          
          // find the ChartTrader atmStrategy selector by AutomationID
          atmStrategySelector = chartWindow.FindFirst("ChartTraderControlATMStrate gySelector") as Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
          if (atmStrategySelector != null)
          {
          atmStrategySelector.SelectionChanged += AtmStrategySelector_SelectionChanged;
          currentAtmStrategy = atmStrategySelector.SelectedAtmStrategy;
          }
          }));
          }
          }
          and this is the SelectionChanged handler
          Code:
          private void AccountSelector_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
          {
          if (currentAccount != null)
          currentAccount.OrderUpdate -= CurrentAccount_OrderUpdate;
          currentAccount = accountSelector.SelectedAccount;
          }
          ​
          Does this seem complete? - other than disposing of everything on termination obviously.
          ​​

          Comment


            #6
            Hello Mindset,

            You are still missing what the addon sample demonstrates. In what you provided here you are subscribing to a single account in DataLoaded and then later unsubscribing when the account is changed. I don't see that you are re subscribing to the new account at all.

            If you are going to work with the account selector your code is going to end up looking almost identical to the code in the addon sample in regard to subscribing and unsubscribing from the accounts. In that sample you can see the code being used starting at line 319. That code would be the suggested way to work with account selection and subscription. You could copy that code exactly as it is to use in your own script, the only parts that need changed is finding the account selector and adding dispatchers to work with UI controls.




            JesseNinjaTrader Customer Service

            Comment


              #7
              Jesse
              Thought I would revisit this as I have half solved the issue.
              I get what you are saying about unsubscribing and resubscribing.

              And I can get my code to work now when I change accounts.
              However on opening NT I get an Object ref not set to an instance of an object error.

              I feel this is because upon opening my NT does not connect to a data source of any sort and therefore the Chart Trader account is empty(null i guess).
              How would it be best to cope with this ?
              Once I connect to a data source this error disappears.

              Comment


                #8
                Hello Mindset,

                The error you are getting means something is null, to find out the specific problem you need to re run the script in that use case and use prints to identify which part is having a problem. It may be that you are not connected depending on where you tried to execute the code and what code is having a problem.
                JesseNinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by rtwave, 04-12-2024, 09:30 AM
                2 responses
                19 views
                0 likes
                Last Post rtwave
                by rtwave
                 
                Started by tsantospinto, 04-12-2024, 07:04 PM
                5 responses
                67 views
                0 likes
                Last Post tsantospinto  
                Started by cre8able, Today, 03:20 PM
                0 responses
                6 views
                0 likes
                Last Post cre8able  
                Started by Fran888, 02-16-2024, 10:48 AM
                3 responses
                49 views
                0 likes
                Last Post Sam2515
                by Sam2515
                 
                Started by martin70, 03-24-2023, 04:58 AM
                15 responses
                115 views
                0 likes
                Last Post NinjaTrader_Jesse  
                Working...
                X