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

Add Profit Target and Stop Loss

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

    #31
    Chelsea, I have tried what you posted:
    "Lock (Account.All)
    account = Account.All.FirstOrDefault(a => a.Name == account.Name);"

    The problem with this approach is that if account hasn't been assigned, the account.Name does not exist (creating an error message). And, if it has been assigned, we don't need this line.

    I have also tried:
    "accountSelector = Window.GetWindow(ChartControl.Parent).FindFirst("C hartTraderControlAccountSelector") as NinjaTrader.Gui.Tools.AccountSelector;"

    But this cannot be executed within DataLoaded. Trust me, I have done a lot of experimenting and research to find a solution, without success.

    So, if you advise that it be placed in the DataLoaded area and feel you have a solution, please share.

    Thanks.
    Last edited by ronhb107; 01-25-2018, 07:40 AM.

    Comment


      #32
      Hello ronhb107,

      The account.Name doesn't exist.

      You don't have an account assigned to account. So when attempting to use the linq expression to select an account where the a.name meaning the account name is equal to the account.Name variable, its being compared to a null object.

      Is trying to use the Account Selector account not working in DataLoaded after checking that the ChartControl is not null?

      In OnBarUpdate you get the account from the Chart Trader account selector. Why is this being done in OnBarUpdate? Why not do this in OnStateChange so that you have an account object assigned to the account variable to work with? Then it would be available anywhere you need to use in, and not just in OnBarUpdate..
      Attached Files
      Last edited by NinjaTrader_ChelseaB; 01-25-2018, 09:26 AM.
      Chelsea B.NinjaTrader Customer Service

      Comment


        #33
        Add Profit Target and Stop Loss

        Ok, Chelsea.

        I've implemented your code below, but it does not work because of two reasons. First, ChartControl is Null; and second, relying on DataLoaded does not capture changes in the Account (from Sim101 to Live-Account). This is why the need to check for Account in the OnBarUpdate().


        "else if (State == State.DataLoaded)
        {
        Print("\nState.DataLoaded");
        if (ChartControl != null)
        {
        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
        {
        account = (Window.GetWindow(ChartControl.Parent).FindFirst(" ChartTraderControlAccountSelector") as AccountSelector).SelectedAccount;

        Print(account.ToString());
        }));
        }
        }"
        Attached Files
        Last edited by ronhb107; 01-25-2018, 03:20 PM.

        Comment


          #34
          Hello ronhb107,

          I have tested the example script from my last post and I am finding this is printing the account selected in the account drop-down.

          May I confirm you have tested the example I have provided you?

          Below is a link to a video showing that the account does print as expected.


          May I confirm that if you take the same actions as in the video you are getting different behavior?

          If so, I would like to schedule a call so that I may test my script example on your end and observe the behavior.


          If you want to the script to update the account at a later time that is fine. I would not recommend doing this in OnBarUpdate. I would recommend attaching a method handler to the accountSelector.SelectionChanged event and updating the account any time the selection changes (after its already been found in OnStateChange when State is State.DataLoaded).

          However, I am trying to convey that you need an account object if you want to reference that account. Referencing a variable before it is set will cause an object reference error.
          Chelsea B.NinjaTrader Customer Service

          Comment


            #35
            Chelsea:

            I've changed the Print statement to capitalize: DATALOADED: <account name>. Notice (below) both an error message and that the DATALOADED occurs after the State.Terminated. This is strange!

            I will work on attaching a Method Handler (more research). Should I use: TriggerCustomEvent() ?

            Here is the output from the NinjaScript window when the Indicator is linked to the Chart...

            State.SetDefaults

            State.SetDefaults
            OnStateChange

            State.SetDefaults

            State.Terminated

            State.SetDefaults

            State.Terminated
            OnStateChange
            Indicator 'RBTestATMorders': Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.

            State.SetDefaults

            State.Terminated
            DIRECT False Multi Broker False License Type Regular DOM Credits 0

            State.Configure

            State.DataLoaded

            State.Terminated
            Bars Request Begin 1/18/2018 9:30:00 AM End 1/18/2018 4:15:00 PM Trading Hours CME Globex - Ron, TimeZone (UTC-05:00) Eastern Time (US & Canada)
            DATALOADED: Playback101|

            Subscribe
            Subscribe account: Playback101|

            ClearOrders Orders count: 0
            ES 03-18 Caler VP and Set startPrice: 1928.00 Tick Mult4 tickSize 0.25
            ES 03-18 Get Bars From 1/17/2018 4:30:00 PM To 1/18/2018 9:45:38 AM Bar Total 107017 None Process Bar 77373
            ES 03-18 Push VP to Grid 28 start price 2799.75 last price 2806.50
            Attached Files
            Last edited by ronhb107; 01-25-2018, 06:29 PM.

            Comment


              #36
              Add Profit Target and Stop Loss

              Chelsea:

              Here is the latest, which includes the Event Handler for accountSelector.SelectionChanged.

              This is all done within the DataLoaded.

              QUESTION: How do I deselect from accountSelector.SelectionChanged ?
              accountSelector.SelectionChanged -= ????
              Attached Files
              Last edited by ronhb107; 01-25-2018, 11:00 PM.

              Comment


                #37
                Hello,

                Thank you for the reply.

                Yes, that would be correct to use the -= but you are currently using a lambda expression instead of a method so I would suggest changing what you have to the method you have commented out. Here is a simple example:

                Code:
                accountSelector.SelectionChanged += AccountSelector_SelectionChanged; //subscribe
                accountSelector.SelectionChanged -= AccountSelector_SelectionChanged;  //unsubscribe
                
                private void AccountSelector_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {
                
                }

                Regarding TriggerCustomEvent, this would only be used to sync up NinjaScript pointers so this would not be needed unless you try to access a NinajScript inherited property like Close[0]. If you are storing the account that was selected to a variable from this selection changed event, that should not require the TriggerCustomEvent.

                As for the error in the last post, I am not seeing that on my end but the error Object reference not set to an instance of an object would mean something being used is null. You can likely add prints into the script to see where it stops, knowing where it stops you can print if the objects being used are null:

                Code:
                Print("someObject Is Null?: " + (someObject == null));
                JesseNinjaTrader Customer Service

                Comment


                  #38
                  Add Profit Target and Stop Loss

                  Thanks, Jesse; very helpful.

                  I have implemented your recommendations and then moved everything to a Strategy.

                  A couple of points. First, I am trying to access the text in Chart Trader for Current Position. This probably captures more quickly (vs. OnPositionUpdate) the position for real-trades. However, I am having difficulty getting the value of the text field (I'm looking for 'Flat' to tell me there are no current positions). I've tried the following code snippets:

                  NinjaTrader.Gui.Tools.PositionDisplay positionDisplay;
                  and
                  positionDisplay = Window.GetWindow(ChartControl.Parent).FindFirst("C hartTraderControlPositionQuantityText") as PositionDisplay;

                  And second, is there any way to maintain strategy 'Enabled' status (within the properties)? Each time I restart the Connection, I have to delete the Strategy from the Chart (Enabled checkbox is grayed out), then reattach and set the Enabled property to True.

                  One last point. Is there a way to easily track the account that has an open position so that when the account is changed in Chart Trader there is no cross over or confusion?

                  When you have a chance, please let me know if there are any steps I can take to improve the code.

                  Thanks,
                  Ron
                  Attached Files
                  Last edited by ronhb107; 01-29-2018, 08:17 AM.

                  Comment


                    #39
                    Hello,

                    Thank you for the questions.

                    First, I am trying to access the text in Chart Trader for Current Position. This probably captures more quickly (vs. OnPositionUpdate) the position for real-trades
                    I would disagree here, the OnPositionUpdate or any of the overrides in place are direct results of the actions happening in the platform. The overrides are guaranteed to process in the correct order where the GUI may be dispatching here and this could cause delays so this would not be a suggested way to access the position.

                    The strategy has its own Position Object which can be referenced, it also has a override of OnPositionUpdate or an Account position Object.

                    In advanced cases, you could use the Account object to access the subscriptions for the whole account as well.


                    And second, is there any way to maintain strategy 'Enabled' status (within the properties)? Each time I restart the Connection, I have to delete the Strategy from the Chart (Enabled checkbox is grayed out), then reattach and set the Enabled property to True.
                    When you say restart the connection, is this because of a disconnect or are you changing to a new connection that has different accounts? If the strategy cannot see the live or sim account where it was applied, that would be one reason this could happen.

                    One last point. Is there a way to easily track the account that has an open position so that when the account is changed in Chart Trader there is no crossover or confusion?
                    The OnPositionUpdate of the account would be suggested, you could see when the account you are subscribed to has a position update. As it has already been discussed in this thread, subscribing to the selection changed event for the account selector would let you know when the chart trader account changes specifically. If you want to know about the chart trader selection changed specifically, you would need to do this process.

                    If you want to know about all accounts all at once, you would need to use a loop and loop through all accounts one time and subscribe to all accounts OnPositionUpdate event. The position that is supplied to the OnPositionUpdate has the account information with it (position.Account), so you could define each position change.

                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment


                      #40
                      Add Profit Target and Stop Loss

                      Hi Jesse:

                      Good to know about OnPositionUpdate.

                      While testing the attached Strategy, I've noticed several anomalies.

                      First, the Chart used to display all positions that were filled then closed (exited); not anymore, despite that the Chart's properties is properly set to display trades. Does clearing the Orders collection (account.Orders.Clear() ) or cancelling the Instrument's orders (account.CancelAllOrders(instrument) ) causing this? Or is this a function of a Strategy; if so, how to correct?

                      Second, within the Trade Performance window for Trades, the data is off. The Control Center - Accounts has a different (more realistic) value than the Trade Performance - Trades data (in one instance, the entry was Stop1 and the exit was Entry). What could be causing this?

                      And third, if a position is entered while I'm actively moving the Entry price, the Entry is no longer displayed on the Chart (while the Target, Stop1 and stopTarget is displayed). When the exit is hit (and everything is cancelled), the Entry shows up and the Position shows an active entry. Again, is clearing the Orders collection involved, and why is the initial Entry not showing up?

                      Thanks,
                      Ron
                      Attached Files
                      Last edited by ronhb107; 01-29-2018, 10:05 AM.

                      Comment


                        #41
                        Hello,

                        Thank you for the reply.

                        First, you should never manage any of the collections in the platform directly, if you can manage a collection there will be NinjaScript methods for that like RemoveDrawObject(""); or CancelOrder(). I would suggest that you remove account.Orders.Clear(); as this is the C# collections Clear() method. The platform should remain in charge of managing the Orders collection based on the NinjaScript methods you use.

                        Second, within the Trade Performance window for Trades, the data is off. The Control Center - Accounts has a different (more realistic) value than the Trade Performance - Trades data (in one instance, the entry was Stop1 and the exit was Entry). What could be causing this?
                        If you are not including all trades in the TradePerformance window, that would be one cause to why the orders may not be matched up correctly. One example would be if a strategy ran overnight, and placed a trade at 11 pm, and then closed it at 12 am. If you do not select both days in the performance report, you would have 1 execution without a match which could skew the results. You may try to increase the lookback of the performance report to see if this is the case.

                        For the third item, I would likely suggest that you rethink the logic here as you are still using account.Orders.Clear(); in your overall logic. I would not suggest using this ever. What is the intended purpose of this logic in your code? Was this to hide old filled orders? I am not certain if this is the cause of what you explained in the third item, but because you are doing this to start with I would likely suggest to stop here and address this use and why you are using it.

                        I look forward to being of further assistance.
                        JesseNinjaTrader Customer Service

                        Comment


                          #42
                          Add Profit Target and Stop Loss

                          Ok.

                          I've attached the pic that includes the Trade Performance window and a portion of the Control Center (top right shows the current balance for Sim101).

                          As you can see, the Trades are properly checked and limited to today's activities. Note the last entry which shows Target1 as both the entry and exit (which is not possible).

                          Also, I have now removed the account.Orders.Clear(). We'll see how testing with this goes.

                          Still, there is NO display of trades on the Chart window with this strategy attached. Any ideas?

                          Thanks,
                          Ron
                          Attached Files

                          Comment


                            #43
                            Hello,

                            Thank you for the reply.

                            Was this report generated for an order when you were doing the account.Orders.Clear()?

                            I would likely suggest starting from zero at this point based on the prior tests you have shown. Because you were modifying the collection in the account, it may be in your interest to reset your database and clear all historical trades, and then retest to see if the same occurs. I cannot say what may have occurred from the image alone, but based on the history here it seems like you were doing some direct modifications to the account collections which would likely impact the overall reports in the platform.

                            Regarding the chart window showing trades, do you currently have the plot executions enabled in the charts data series window?

                            I look forward to being of further assistance.
                            JesseNinjaTrader Customer Service

                            Comment


                              #44
                              Plot executions is set to both Text and Markers.

                              Btw, how can I track orders related to the current Position when an entry is made till the entry is closed?

                              I've cleared the Sim101 account, saved everthing, then exited and reloaded NT8.

                              Let's see if this clears up the Chart problem showing trades.

                              Ron

                              UPDATE: the Chart still does NOT display the trades.
                              Last edited by ronhb107; 01-29-2018, 12:20 PM.

                              Comment


                                #45
                                Hello,

                                Thank you for the reply.

                                After further review of the most recent sample, you are using the Account to submit targets for what would appear to be an order the strategy finds using the account. These should not show up on the chart because the Strategy did not submit them, the Account did. If you are expecting to see the orders on the chart where the script is applied, you would need to not use a Strategy specifically as this hides other executions and isolates its virtual order view.

                                Strategies are not really intended to utilize the Account class like you are, this is really intended for you to create your own tools in new windows similar to a superdom as one example. A strategy does not know you want to take advantage of the advanced addon features so it can only work in the way strategies are designed to. Submitting an order from anywhere other than the Managed/Unmanaged/ATM methods in a strategy will result in a in untracked order. If you had the ChartTrader open, you could see active orders on the account but the executions would not be painted so long as the strategy is applied. After disabling the strategy, you would see the executions listed like they would be for any manual trade. Using the Account.Submit method is nearly identical to placing a manual trade in any manual tool so this type of order would be unable to be tracked using the standard strategies logic. You can paint your own execution markers using DrawinObjects from OnExecutionUpdate if you want to remain using a strategy for this use case.


                                Please let me know if I may be of further assistance.
                                JesseNinjaTrader Customer Service

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by cls71, Today, 04:45 AM
                                0 responses
                                1 view
                                0 likes
                                Last Post cls71
                                by cls71
                                 
                                Started by mjairg, 07-20-2023, 11:57 PM
                                3 responses
                                213 views
                                1 like
                                Last Post PaulMohn  
                                Started by TheWhiteDragon, 01-21-2019, 12:44 PM
                                4 responses
                                544 views
                                0 likes
                                Last Post PaulMohn  
                                Started by GLFX005, Today, 03:23 AM
                                0 responses
                                3 views
                                0 likes
                                Last Post GLFX005
                                by GLFX005
                                 
                                Started by XXtrader, Yesterday, 11:30 PM
                                2 responses
                                12 views
                                0 likes
                                Last Post XXtrader  
                                Working...
                                X