Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

why don't I get orders executed on each OnBarUpdate in super simple case?

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

    why don't I get orders executed on each OnBarUpdate in super simple case?

    I am experimenting with writing strategies using backtesting on Nasdaq data. Well, so in a real strategy I will only place long and short limit orders in a small minority of cases, based on relevant trading logic. However, first I would like to establish a baseline of sorts to make sure that I fully understand what is happening in the system. So, as a baseline, I am trying to write the code that would just stupidly place a long order on each and every OnBarUpdte(). Unfortunately, I don't seem to observe this expected behavior. Please see code below.

    Now, the key points in it, (based on my possibly faulty understanding) are as follows:
    - I did SetStopLoss() as 100% and SetProfitTarget() as 0%. This means, (I think, correct me if I am wrong), that I am willing to suffer any level of loss and obtain any profit however minimal. In other words, an order should be placed successfully in any situation regardless of market conditions.
    - I set the BuyOffset (a local variable in my code, search for it) to be negative, which means that I am willing to buy at price higher than current ask. This again, as far as the mental model in my head goes, means that each long order that I place should get executed instantly.

    Well, so that's the theory. In practice, as you can see, I am doing a bunch of write to log file actions using LogWrite() method, and in the log I can see clearly that whereas OnBarUpdate() happens every minute (and hence the line with EnterLongLimit() gets executed) the OnExecution event runs fairly rarely. Moreover, I simply don't understand what is it that triggers it. And why doesn't it run on each OnBarUpdate() as I think it should?

    #region Using declarations
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Collections;
    using System.Drawing.Drawing2D;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Data;
    using NinjaTrader.Indicator;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Strategy;
    #endregion

    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class MyCustomStrategy3 : Strategy
    {
    #region Variables
    // Wizard generated variables

    private int p = 30; // Default setting for P
    private int l = 10; // Default setting for L
    // User defined variables (add any user defined variables below)
    #endregion

    /// <summary>
    /// This method is used to configure the strategy and is called once before any strategy method is called.
    /// </summary>
    protected override void Initialize()
    {
    LogInitialize(STR_FOLDER_DESKTOP + "logNinja3.txt");
    LogWrite("BEGIN 1 time=" + DateTime.Now);

    SetProfitTarget("", CalculationMode.Percent, 0);
    SetStopLoss("", CalculationMode.Percent, 100, false);

    this.AccountSize = 10000;


    CalculateOnBarClose = true;
    }
    const int WIDTH_MOVING_WINDOW = 5;

    IOrder order;

    protected override void OnExecution(IExecution execution)
    {
    LogWrite("exec=" + execution);

    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    RunStrategy();
    }

    void RunStrategy()
    {
    double ask = GetCurrentAsk();
    double bid = GetCurrentBid();
    LogWrite("RS time=" + this.Time + " bid=" + bid);
    double buyPrice = bid - BuyOffset; //this is nonsense, still not sure about strategy logic
    int numToBuy = 10;
    this.order = EnterLongLimit(0, true, numToBuy, buyPrice, "long");

    }

    const double BuyOffset = -1; const double SellOffset = -1;


    public static readonly String STR_FOLDER_DESKTOP = Environment.GetFolderPath(Environment.SpecialFolde r.Desktop) + @"\";

    static StreamWriter writerLog;
    static int counterLog = 0;
    public static void LogInitialize(String strFilename)
    {
    if(writerLog != null)
    writerLog.Close();
    writerLog = new StreamWriter(strFilename);

    counterLog = 1;
    } //end LogInitialize()

    public static void LogWrite(String str)
    {
    String strNumberPrefix = counterLog + ") ";
    counterLog++;

    writerLog.WriteLine("");
    writerLog.WriteLine(strNumberPrefix + str);
    writerLog.Flush();
    } //end LogWriteWithFlush()

    #region Properties
    [Description("P")]
    [Category("Parameters")]
    public int P
    {
    get { return p; }
    set { p = Math.Max(1, value); }
    }

    [Description("L")]
    [Category("Parameters")]
    public int L
    {
    get { return l; }
    set { l = Math.Max(1, value); }
    }
    #endregion
    }
    }

    #2
    Hello,

    Did you try changing this to false:
    CalculateOnBarClose = true;
    DenNinjaTrader Customer Service

    Comment


      #3
      just tried this - it does not work

      I just ran a test with CalculateOnBarClose = false and that made no difference. The order still executes very rarely in a seemingly random fashion. Well, you can try it yourself with my code and see for yourself.

      Originally posted by NinjaTrader_Ben View Post
      Hello,

      Did you try changing this to false:
      CalculateOnBarClose = true;

      Comment


        #4
        watcher,

        Please bump up your number of EntriesPerDirection if you wish to hold more than one position at a time.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          that seems to have worked; but can you explain more about the original case?

          Josh,

          yes, after I set EntriesPerDirection to 100 it seems that initially I do get the long orders filled on every OnBarUpdate. Thanks a lot!

          Now, going back to my original question, can you explain the randomness aspect of the order execution? Based on what you said, it would seem that I only should have seen a single order executed, the first one, to create the one and only allowed position. But, in practice, I have seen orders eventually short-liquidated and new ones filled for no apparent reason as to why this should happen at time t1 and not at some t0. This is all the more unclear to me because, like I said, I set the profit target and stop loss to be maximally permissible. So why weren't my orders short-liquidated and replaced with new ones on every OnBarUpdate?

          So what was I doing wrong here? Do I misunderstand something about the ProfitTarget/StopLoss mechanism? Or what was the problem?

          Originally posted by NinjaTrader_Josh View Post
          watcher,

          Please bump up your number of EntriesPerDirection if you wish to hold more than one position at a time.

          Comment


            #6
            Putting a 0% target could very well be a rejected order. Price could be moving up as you are getting filled and by the time the target gets placed in, it is below the market and is now invalid.

            Likewise, 100 for the stop does not mean 100%. For 100% use 1, but that type of stop doesn't make sense either. If you want to do that simply just don't place a stop.
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Josh,

              sorry about being pesky, but I am a programmer, and I am trying to get a working "mental model" of the situation here. After all, how else can I risk serious money if I don't even have decent understanding of the basic logic?

              Anyway, so you say, "for 100% use 1". Do you mean to say that for percentage based SetStopLoss() 1 means 100% loss allowed? Well, how about for 40% loss allowed? If I clearly indicate that this value should be interpreted as percentage, then are you saying that it still isn't? So how is it interpreted?

              I also don't quite understand your explanation about 0% target. Like I said, I always posted buy prices much higher than what is on the market. And, I said that I don't care about profit (is 0% profit target the right way to do it? or is there another way?). So what was the logic that prevented the closing of the position and opening of another? And why did it sometimes did happen?

              Originally posted by NinjaTrader_Josh View Post
              Putting a 0% target could very well be a rejected order. Price could be moving up as you are getting filled and by the time the target gets placed in, it is below the market and is now invalid.

              Likewise, 100 for the stop does not mean 100%. For 100% use 1, but that type of stop doesn't make sense either. If you want to do that simply just don't place a stop.

              Comment


                #8
                40%=use 0.4
                100%=use 1

                0% target results in orders that may or may not be rejected. If your price is constantly moving higher by the time the order is received at the brokerage/exchange it would be at an invalid price. You cannot place target orders below the market which is what could happen with 0% target which essentially means submit a target order at the entry price to exit immediately.

                If you don't care about the target just don't call SetProfitTarget(). There is no reason you should be calling any of these if you simply don't want the orders.

                I suggest you use TraceOrders = true to see what your orders are doing. http://www.ninjatrader-support2.com/...ead.php?t=3627
                Josh P.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                83 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                47 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                29 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                32 views
                0 likes
                Last Post TheRealMorford  
                Started by Mindset, 02-28-2026, 06:16 AM
                0 responses
                66 views
                0 likes
                Last Post Mindset
                by Mindset
                 
                Working...
                X