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

How to get the "Entry Price" of last order placed & "Total Quantity" of orders. (NT8)

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

  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode,

    The code where there order is assigned to a variable in OnOrderUpdate() was not included with this code you have provided.

    What order is the order in question?

    Where is the order assigned to a variable?

    This code:
    if (
    (entryOrder.AverageFillPrice >= Open[0])
    )
    EnterLong(Quantity,"EURUSD1");

    Will cause an error.

    Have you used prints to determine this is the line of code causing the error?

    You are printing that the order is null above, but you are not including a check for null in the condition that actually uses that variable. If that variable is called when it is null, you will get that error. I was suggesting that you write your logic, so that the variable is not used if it is null.

    Leave a comment:


  • johnnybegoode
    replied
    Using your example, the entry order object is still null

    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.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class LastEntryPrice : Strategy
        {
            private Order entryOrder;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "LastEntryPrice";
                    Calculate                                    = Calculate.OnEachTick;
                    EntriesPerDirection                            = 3;
                    EntryHandling                                = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy                = false;
                    ExitOnSessionCloseSeconds                    = 30;
                    IsFillLimitOnTouch                            = false;
                    MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution                            = OrderFillResolution.Standard;
                    Slippage                                    = 9999999999;
                    StartBehavior                                = StartBehavior.ImmediatelySubmit;
                    TimeInForce                                    = TimeInForce.Gtc;
                    TraceOrders                                    = false;
                    RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade                            = 0;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration    = true;            
                }
    
                else if (State == State.Configure)
                {
    
                }
    
                else if (State == State.DataLoaded)
                {        
    
                }
    
            }
    
    [COLOR=#FF0000][B] protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
    {    
        if (order.Name == "EURUSD1")
          entryOrder = order;
    }        [/B][/COLOR]
    
            protected override void OnBarUpdate()
            {        
                Account a = Account.All.First(t => t.Name == "Playback101"); // Account Display Name
                int Quantity = 10000;
    
                if (entryOrder != null && entryOrder.OrderState == OrderState.Filled)
                Print(entryOrder.AverageFillPrice);
    
                if (entryOrder == null)
                Print("1. entryOrder is null");    
    
                 // Set 1
                if (
                    (Open[0]-Close[0] >= 0)
                    )
                {
                    EnterLong(Quantity,"EURUSD1");
                }
    
    
                if (entryOrder != null && entryOrder.OrderState == OrderState.Filled)
                Print(entryOrder.AverageFillPrice);            
    
                if (entryOrder == null)
                Print("2. entryOrder is null");
    
                if (
                    (entryOrder.AverageFillPrice >=  Open[0])
                    )
                      EnterLong(Quantity,"EURUSD1");                        
            }                
        }
    }
    Last edited by johnnybegoode; 03-05-2019, 09:49 PM.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode,

    This was an example of how to ensure an object is not null. This was code to directly copy in your script.

    What is the object in your script that is null? Create a null check for that object using the example I have provided you.

    You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our business development follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request.

    Leave a comment:


  • johnnybegoode
    replied
    I placed

    Code:
    if (entry1 != null && entry1.OrderState == OrderState.Filled)
    Print(entry1.AverageFillPrice);
    In OnBarUpdate() before and after Condition 1
    I also still get "myObject is null" at the output.

    Same error:
    I can't enable strategy on a chart:
    Log: "Error on calling 'OnBarUpdate' method on bar 20: Object reference not set to an instance of an object"
    Last edited by johnnybegoode; 03-02-2019, 07:54 PM.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode ,

    You could write something like

    In #region Variables

    private Order entry1;

    In OnOrderUpdate():

    if (order.Name == "EURUSD1")
    entry1 == order;

    In OnBarUpdate() (or where you want the price of the order):

    if (entry1 != null && entry1.OrderState == OrderState.Filled)
    Print(entry1.AverageFillPrice);

    Leave a comment:


  • johnnybegoode
    replied
    Using

    Code:
    if (myObject == null)
    Print("myObject is null");
    "myObject is null" before and after condition1
    Code:
    if(condition1 == true)
    EnterLong(0,Quantity,"EURUSD1");

    Code:
    protected override void OnBarUpdate()
    {
    //...
    if(condition1 == true)
        EnterLong(0,Quantity,"EURUSD1");
    
    
    if (EURUSD1.AverageFillPrice >=  Open[0])  // Strategy could be enabled without the 2nd condition.
         EnterLong(0,Quantity,"EURUSD2");
    //...
    }
    What code can I execute before and after Condition 1
    I just want the "last entry price".
    Code:
    if (myObject != null)
    {
    // execute code
    }
    Last edited by johnnybegoode; 02-27-2019, 06:55 PM.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode,

    'Object reference not set to an instance of an object' means that you have used a variable that has a null value without checking that the value is not null first.

    For example:

    Code:
    if (myObject != null)
    {
    // execute code
    }
    Which line is the specific line of code causing the error?

    You can use prints on every other line to find the exact line causing the error by looking to see which print was the last to print before the error occurs.
    You can also use prints find which object is null on that line.
    if (myObject == null)
    Print("myObject is null");


    Below is the example from the help guide on saving an order object to an Order variable.
    Code:
    private Order entryOrder = null;
    
    protected override void OnBarUpdate()
    {
      if (entryOrder == null && Close[0] > Open[0])
          EnterLong("entryOrder");
    }
    
    protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTimetime, ErrorCode error, string nativeError)
    {
      // check if the current order matches the orderName passed in "EnterLong"()
      // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
      // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not guaranteed to be complete if it is referenced immediately after submitting
      if (order.Name == "entryOrder")
          entryOrder = order;
    
      // if entry order exists
      if (entryOrder != null && entryOrder == order)
      {
          Print(order.ToString());
          if (order.OrderState == OrderState.Cancelled)
          {
              // Do something here
              entryOrder = null;
          }
      }
    }

    Leave a comment:


  • johnnybegoode
    replied

    I can't enable strategy on a chart:
    Log: "Error on calling 'OnBarUpdate' method on bar 20: Object reference not set to an instance of an object"

    No error after compilation.

    I do the comparison under
    Code:
    protected override void OnBarUpdate()
    {
    //...
    if(condition1 == true)
        EnterLong(0,Quantity,"EURUSD1");
    
    
    if (EURUSD1.AverageFillPrice >=  Open[0])  // Strategy could be enabled without the 2nd condition.
         EnterLong(0,Quantity,"EURUSD2");
    //...
    }


    How I Save the order object from OnOrderUpdate to a variable
    Code:
            protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
    {
      if (order.Name == "EURUSD1")
          EURUSD1 = order;
    
      if (EURUSD1 != null && EURUSD1 == order)
      {
          Print(order.ToString());
          if (order.OrderState == OrderState.Filled)        
              EURUSD1 = null;
      }
    }
    Last edited by johnnybegoode; 02-26-2019, 03:57 AM.

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode,

    Save the order object from OnOrderUpdate to a variable.

    After the <order>.OrderState is OrderState.Filled, compare the <order>.AverageFillPrice to the Close[0] price in OnBarUpdate() or OnOrderUpdate() or wherever you would like.

    Saving an order object to a variable is demonstrated in the examples of both the Order and OnOrderUpdate() pages in the help guide I have linked in post #4.


    Or save all of the orders objects to a List<Order> collection.
    Use the last index (array count minus 1) for the last object added.

    Below is a public link to a 3rd party educational site on List.
    Create a new List, add elements to it, and loop over its elements with for and foreach.

    Leave a comment:


  • johnnybegoode
    replied

    1) How to get the "Entry Price" of last order placed at Time 2?

    i.e.
    I had already opened a Buy position of 10,000 EURUSD at Time 0 at 1.13488
    then
    I opened another Buy position of 10,000 EURUSD at Time 1 at 1.13477
    and then
    another Buy position of 10,000 EURUSD at Time 2 at 1.13472

    Basically, I would like to compare the "Last Position Entry Price" to the "Current Price"

    i.e.
    Code:
    protected override void OnBarUpdate()
    {
      if (LastPositionEntryPrice >=  Open[0])
          EnterLong(0,Quantity,"EURUSD");
    }
    That would be Time 3
    and would continue to open positions whenever the statement is true.

    How do I get the "LastPositionEntryPrice" of 1.13473?

    Thank you!

    Leave a comment:


  • NinjaTrader_ChelseaB
    replied
    Hello johnnybegoode,

    This information you would need to track with variables. As the last order updates, assign either the order object itself to an Order variable. Or save the information you are wanting to save such as the entry price or name etc to variables.

    Below is a link to the Order variable type page in the help guide.


    And a link to OnOrderUpdate().



    You can loop through all orders on an account, not just those of the strategy, using the Addon approach.



    The open positions quantity is provided with the Position property or Positions collection.

    Leave a comment:


  • johnnybegoode
    replied
    Using Ninja Script.

    Leave a comment:


  • afcmaff
    replied
    johnnybegoode

    1) Entry prices - you should be able to go to the control panel, select New > Trade Performance > Display - drop-down filter on 'Trades' and the specific account - then you can see the timestamp, quantity, etc of every trade executed for whatever time frame you'd like

    2) Total quantity of open positions should be available in the SuperDOM and on the chart you're using (on the chart at the top toolbar, you should see an icon that looks like a backwards 'F' <- this will allow you to toggle the DOM view on the right hand side of the chart.

    Hope this helps...

    Leave a comment:


  • How to get the "Entry Price" of last order placed & "Total Quantity" of orders. (NT8)

    i.e.
    I place Buy 10,000 EURUSD at Time 0
    then
    another Buy 10,000 EURUSD at Time 1
    then
    another Buy 10,000 EURUSD at Time 2

    1) How to get the "Entry Price" of last order placed at Time 2?

    2) How do I get the "Total Quantity" of all the open positions which is 30,000?

    Thank you!

Latest Posts

Collapse

Topics Statistics Last Post
Started by Max238, Today, 01:28 AM
5 responses
40 views
0 likes
Last Post Max238
by Max238
 
Started by giulyko00, Yesterday, 12:03 PM
3 responses
12 views
0 likes
Last Post NinjaTrader_BrandonH  
Started by habeebft, Today, 07:27 AM
1 response
14 views
0 likes
Last Post NinjaTrader_ChristopherS  
Started by AveryFlynn, Today, 04:57 AM
1 response
12 views
0 likes
Last Post NinjaTrader_Erick  
Started by r68cervera, Today, 05:29 AM
1 response
10 views
0 likes
Last Post NinjaTrader_ChelseaB  
Working...
X