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

Question about entering a trade with VWAP crossover strategy

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

    Question about entering a trade with VWAP crossover strategy

    Hi everyone, per the below screenshot, I have a strategy that enters a LONG position when the last bar close crossed above VWAP and goes short when it crossed below.
    However, my strategy is executing this with a delay of 1 bar for some reason, leading to a wrong "decision" in the screenshot, as the price retracts below VWAP, triggering the Short position. In other words in the screenshot, the trade opened short when the signal should have triggered a long position.

    The tricky part was that during that Green candle, I still had an open position that got stopped out with a profit. Could that be the reason no new trade was allowed to be entered after the bar closed?

    As I am not a developer, I just collected code to do what I want and thought it worked well... However, in this specific case I found that it works with a delay which causes the strategy to take the position for the wrong direction.

    Code:
     
    
            /// <summary>
            /// check if entry is allowed for actual bar
            /// </summary>
            /// <returns>true if entry is allowed</returns>
            private Boolean IsValidTime()
            {
                bool onBarClose = (State == State.Historical || Calculate == Calculate.OnBarClose);
                bool enabled = enabled = (tzsMON_THU.InSession(Time[0], onBarClose) == 0);
                DateTime timeTZ = tzsMON_THU.ActualBarTZ;
                switch( timeTZ.DayOfWeek )
                {
                    case DayOfWeek.Saturday:
                        break;
                    case DayOfWeek.Sunday:
                        break;
                    case DayOfWeek.Friday:
                        enabled = (tzsFRI.InSession(Time[0], onBarClose) == 0);
                        break;
                    default:
                        break;
                }
                if (!enabled)
                    Printf("Time filter timeTZ={0} {1}", timeTZ, timeTZ.DayOfWeek);
                return enabled;
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                try
                {
                    CheckEntry();
                }
                catch( Exception e)
                {
                    Printf(e.Message);
                    base.Print(e.StackTrace);
                    throw e;
                }
            }
    
            private void CheckEntry()
            {
                if (!trades.Update())
                {
                    lastTrade = null;
                }
    
    
                 // Set 1
                if (
                     // entry diretion
                       EntryDirection >= 0
                     // cross above VWAP
                     &&((Close[0] > VWAP81[0])
                     && trades.BarsSinceEntryExecution > 10      // check bars since last entry
                    {
                    if( lastTrade == null )
                    {
                        lastTrade = new StrategyTrade(this);
                        trades.Add(lastTrade);
                    }
                    lastTrade.EnterLongLimit( Close[0] - TickSize * Long_Negative_Offset_Arithmetic );
    
                }

    Thanks for your help in advance!

    #2
    ...just to add the below condition is met (the entry to the trade that closed was opened more than 20 bars before).
    BarsSinceEntryExecution > 10 // check bars since last entry

    Comment


      #3
      Hello Oracletrades, thanks for your post.

      If your strategy is running OnBarClose, the OnBarUpdate logic will run at the open of the next bar, so any order made will happen at the open of the next bar. You can prove what is happening by using the Print() method and printing the VWAP, Price (Close[0]) and Time[0] at the moment you make the trade. If you want the execution to happen at the very point of the cross, your strategy would need to run OnEachTick or OnPriceChanged, have you tested these calculate properties?

      I look forward to assisting.
      Chris L.NinjaTrader Customer Service

      Comment


        #4
        Thanks Chris. A few things here:
        • I have tried on each tick but the limit order "moves" on every tick, so it never gets filled. Looks funny, but the price is basically "chasing" the limit order without ever reaching it.
        • I don't think the problem is that I need to fill on the tick. I'm fine to set the order on bar close. I'd just like the limit order to be issued immediately on that bar close, not one bar later.

        The problem seems to be that the trigger event occurs, but yet another bar passes by before the strategy takes action... I wonder if the problem sits with this part:

        if (BarsInProgress != 0) return; if (CurrentBars[0] < 1) return;
        If I create a simple strategy that goes long when a fast SMA crosses a slow SMA, it does at it should: after the bar of that crossover closes, the trade is entered immediately on the following bar.. So maybe I need to get some professional help from a developer, as this snippet is only part of the overall strategy...

        Comment


          #5
          Hello Oracletrades, thanks for your reply.

          Is this happening in real-time, historical mode, or both? If this happens in historical mode, see this post #2 on adding intrabar granularity for better order fill estimation:
          https://ninjatrader.com/support/foru...-backtest-live

          Unfortunately, I can't tell what the problem is from the code snippet. We have this example that demonstrates placing resting orders (a protective stop and target). You can compare the results of this example to your strategy to see what you might be doing differently.

          I look forward to hearing from you.
          Last edited by NinjaTrader_ChrisL; 08-04-2020, 10:52 AM.
          Chris L.NinjaTrader Customer Service

          Comment


            #6
            This is happening real-time. I think I'll do another playback simulation to see where there is going wrong. The strategy does have what I believe you call a resting order, as the order stays "live" until it is filled, up to x bars after the signal was triggered... Let me get some help from a developer.. Thanks for now!

            Comment


              #7
              Hey Oracletrades,

              I know this post is a little old, but I was curious if you ever got this working? I have been messing with the code as well as referencing the Ninja Trader example for VWAP and am really struggling with this one. I thought it would be fun to see if I can get it working... ha! It has not been fun.

              Did you ever make any progress?

              Comment


                #8
                Hi paperblue46, thanks for posting.

                If you have a similar issue please make a new thread and the NinjaScript team will assist. Please detail your question as much as possible in a new post.

                Kind regards,
                -ChrisL
                Chris L.NinjaTrader Customer Service

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by algospoke, Yesterday, 06:40 PM
                2 responses
                19 views
                0 likes
                Last Post algospoke  
                Started by ghoul, Today, 06:02 PM
                3 responses
                14 views
                0 likes
                Last Post NinjaTrader_Manfred  
                Started by jeronymite, 04-12-2024, 04:26 PM
                3 responses
                45 views
                0 likes
                Last Post jeronymite  
                Started by Barry Milan, Yesterday, 10:35 PM
                7 responses
                20 views
                0 likes
                Last Post NinjaTrader_Manfred  
                Started by AttiM, 02-14-2024, 05:20 PM
                10 responses
                181 views
                0 likes
                Last Post jeronymite  
                Working...
                X