Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Orders created programatically (EnterLong) not showing up in the application

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

    Orders created programatically (EnterLong) not showing up in the application

    Hello,

    I created a rather simple strategy which is aiming to submit a Long (or Short, doesn't matter) sample order on an arbitrary instrument, and follow its execution.

    I tried to follow the programming guidelines (managed approach) and the samples from the forum and came up with something like:

    -------------------------------

    protected override void OnBarUpdate()
    {
    EnterLong("aTest");

    Print(isOrderFilled ? "Order is filled" : "Order is NOT filled");

    if (entryOrder != null){
    Print("NotNull:" + entryOrder.ToString());
    } else {
    Print("Null:");
    }

    Print("");
    }


    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
    if (execution.Order.Name == "aTest")
    {
    Print("Order is BEING FILED ...");
    Print(execution.ToString());

    Print("... instrument -> " + execution.Instrument);
    Print("... quantity -> " + execution.Quantity);
    Print("... position -> " + execution.Position);

    entryOrder = execution.Order;
    isOrderFilled = true;
    }
    }

    private Order entryOrder = null;
    private bool isOrderFilled;

    --------------------------------------------

    In the log I see the following lines.

    -------------------------------------------
    Strategy 'MyCustomStrategy/197652248': An order placed at '3/31/2020 2:06:00 PM' has been ignored since the order was submitted before the strategy property BarsRequiredToTrade had been met.
    Order is NOT filled
    Null:

    Order is NOT filled
    Null:

    Order is NOT filled
    Null:

    Order is BEING FILED ...
    execution='NT-00000-389' instrument='GBPJPY' account='Sim101' exchange=Default price=133.638 quantity=1 marketPosition=Long orderId='NT-00000-389' time='2020-03-31 14:12:00' sod=False statementDate='0001-01-01'
    ... instrument -> GBPJPY Default
    ... quantity -> 1
    ... position -> 0
    Order is filled
    NotNullrderId='NT-00000-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=133.638 onBehalfOf='' id=-1 time='2020-03-31 14:09:00' gtd='2099-12-01' statementDate='2020-04-06'

    Order is filled
    NotNullrderId='NT-00000-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=133.638 onBehalfOf='' id=-1 time='2020-03-31 14:09:00' gtd='2099-12-01' statementDate='2020-04-06'

    Order is filled
    NotNullrderId='NT-00000-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=133.638 onBehalfOf='' id=-1 time='2020-03-31 14:09:00' gtd='2099-12-01' statementDate='2020-04-06'

    [...]

    Order is filled
    NotNullrderId='NT-00006-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=132.579 onBehalfOf='' id=-1 time='2020-04-05 14:04:00' gtd='2099-12-01' statementDate='2020-04-06'

    Enabling NinjaScript strategy 'MyCustomStrategy/197652248' : On starting a real-time strategy - StartBehavior=WaitUntilFlat Position=GBPJPY 1L EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
    Order is filled
    NotNullrderId='NT-00006-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=132.579 onBehalfOf='' id=-1 time='2020-04-05 14:04:00' gtd='2099-12-01' statementDate='2020-04-06'

    Order is filled
    NotNullrderId='NT-00006-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=132.579 onBehalfOf='' id=-1 time='2020-04-05 14:04:00' gtd='2099-12-01' statementDate='2020-04-06'

    Order is filled
    NotNullrderId='NT-00006-389' account='Sim101' name='aTest' orderState=Filled instrument='GBPJPY' orderAction=Buy orderType='Market' limitPrice=0 stopPrice=0 quantity=1 tif=Gtc oco='' filled=1 averageFillPrice=132.579 onBehalfOf='' id=-1 time='2020-04-05 14:04:00' gtd='2099-12-01' statementDate='2020-04-06'

    -----------------------------------------

    Looking at the log I would say the code works as intended, and the order is created and executed as planned. However I don't see it anywhere in the application (Orders, Executions, Positions.. anything)

    Could anyone please let me know if you have any ideas what I might be doing wrong?...

    Thanks in advance,
    Sorin

    #2
    Hello smf2005,

    Thank you for your post.

    The only orders I would expect to show in the orders/positions/executions tabs would be the orders that occur after the strategy goes to real time. Most likely, since you don't have an associated exit order/stop loss/profit target is that the strategy, when started, is already in a historical position that wouldn't be closed out until the end of the session if you have Exit on Session Close enabled.

    I suspect the strategy, when you look at it on the Strategies tab, has its name in yellow there. When a strategy is yellow in the Strategies tab of the Control Center, this means that the strategy entered a historical (theoretical) position in the historical data that has been loaded.

    It also means that you have "Wait until flat" selected for the 'Start behavior' option in the strategy parameters.

    This means that once the strategy has finished processing the historical data and has transitioned to real-time, it will wait until there is a real-time order submission that will cause the strategy to become flat. This also includes changing from a long position to a short position or vice versa as the position would pass through flat.

    Below is a link to the help guide on the strategy parameters.

    http://ninjatrader.com/support/helpG...tegyProperties

    As well as a link to the start behavior options.

    http://ninjatrader.com/support/helpG..._positions.htm

    And a link to a forum post with videos that demonstrate the start behavior options.

    https://ninjatrader.com/support/forum/forum/ninjatrader-8/platform-technical-support-aa/104242-how-to-reset-sim-on-ninjatrader-8-can-t-close-open-position?p=811541#post811541

    To change the behavior here, you have a couple of options.

    You can change the start behavior to "Immediately submit" in the parameters of the strategy. This means that if in the historical data the strategy submitted an order to enter a long position, once the strategy has transitioned to processing real-time data it will use this long position as the live position (and will not wait to become flat first). Any working orders that are still in a working state when the strategy transitions from historical to live (such as protective stop losses and profit targets) it will submit as live orders when the strategy is started.

    http://ninjatrader.com/support/helpG...ediatelySubmit

    The start behavior can also be set in the State.SetDefaults of the script to default to a particular selection.

    http://ninjatrader.com/support/helpG...rtbehavior.htm

    You could also modify your script so that it only places orders if the data is real-time data. To do this you will need to edit the code of your script directly, as the Historical public variable is not available to the Strategy Builder.

    The code needed would be some thing like:

    if (State != State.Realtime)
    return;

    This condition checks to see if the script is not processing real-time data (meaning it is processing historical data) and if true will stop any code appearing after it in the same method from evaluating.

    This can also be written as:

    if (State == State.Historical)
    return;

    This checks to see if the script is processing historical data and will stop processing if true (which is the same condition and action as above).

    If this logic is placed at the beginning of OnBarUpdate, the strategy will not process until it reaches real-time data and will not calculate historically.

    If this is placed in the conditions for making an order, it will prevent the order from being placed until the strategy reaches real-time data.

    You could also optionally trigger any open position to exit with an exit market order on the last historical bar.

    To find the last historical bar:

    if (State == State.Historical && CurrentBar == Count — 2)

    Below is a link to the help guide on the 'State' NinjaScript property.
    http://ninjatrader.com/support/helpG...n-us/state.htm

    Please let me know if this does not resolve your inquiry.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      OnBarUpdate runs completely and in its entirety, it is not interrupted to execute OnExecutonUpdate
      during the middle of its own processing -- that's not what "event-driven" means.

      When EnterLong() is called, it starts a chain of send/receive events that the internal framework
      performs on your behalf, such as the order submission sent to the order feed and the order fill or
      partial fills received from the order feed. But, EnterLong() returns asynchronously, meaning after
      it sends the entry order to the order feed (aka, your broker 'order routing' connection, such as
      Continuum, Rithmic, Interactive Brokers, etc) it immediately returns -- it does not wait for the
      order fill or order partial fill -- that event will be received asynchronously..

      Since EnterLong returns without waiting, this allows OnBarUpdate to finish its own execution and
      it, too, returns. Naturally, since OnExecutionUpdate hasn't run yet (it may be waiting to run) the
      variable 'isOrderFilled' is still false, so this invocation of OnBarUpdate won't know anything about
      the fill.

      Ok, so who does OnBarUpdate() return to?
      To where it was called from, which is the internal NinjaTrader framework code.

      Ok, so now what?
      The internal framework is always busy on behalf of your strategy -- it's been queue'ing up events
      that need to be 'sent' to you -- and if the order fill has occurred , the internal framework now calls
      OnExecutionUpdate() to let you know. Only then is the variable 'isOrderFilled' set to true.

      In other words, isOrderFilled will be true on the next call to OnBarUpdate, but only after the call to
      OnExecutionUpdate sets it to true.

      The code looks correct -- but it also looks incomplete.
      Where is the code to exit the position?

      Comment


        #4
        Hello Kate / David,

        Thank you both for the quick replies! You were both correct:
        - adding the check against State.Realtime does the trick (and the strategy was in yellow/historical data processing state, as you said);
        - the code is incomplete, that's true - I didn't write the exit position part, I was trying to get the order sending part working and didn't have too much luck until posting the issue here.

        Thanks also for the detailed explanations and documentation links.

        Regards,
        Sorin

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by Renorail, Today, 01:38 PM
        1 response
        3 views
        0 likes
        Last Post Renorail  
        Started by BrianARice, Today, 01:16 PM
        0 responses
        5 views
        0 likes
        Last Post BrianARice  
        Started by Ousher, Today, 09:08 AM
        0 responses
        6 views
        0 likes
        Last Post Ousher
        by Ousher
         
        Started by Unsuitable, Today, 08:41 AM
        0 responses
        14 views
        0 likes
        Last Post Unsuitable  
        Started by newdill, Today, 07:54 AM
        0 responses
        7 views
        0 likes
        Last Post newdill
        by newdill
         
        Working...
        X