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

Cannot get strategy to behave as it does in real-time

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

    #16
    Hi Rob, Unfortunately, I will not be able to spend time debugging custom scripts. I would have to guess its coming from the use of BarsSinceEntryExecution, possibly this is preventing an initial trade. This is why using Print will be useful, so you can see the data your script is processing so you can see why you are getting unexpected results.
    Chris L.NinjaTrader Customer Service

    Comment


      #17
      ChrisL,

      Absolutely, sorry to ask too much of you. I sure do appreciate the help. As soon as I posted that reply I realized some errors and added some logic that would base the entry off barssinceexit and included language to allow for entry when no exits have been made. I spent the morning debugging and continually got the result of entries being made for the "exitonsessionclose" and then the entry submission closing the trade. I decided to take the test indicator you sent me and modify it so instead of drawing a dot, it enters a trade. I cannot for the life of me figure out what's wrong in my logic, and I assume it could be a setting on the chart I have wrong. I have tick replay enabled. Your indicator places dots at the beginning of bars, but I cannot get it to enter trades at the beginning of bars. Thanks.

      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 Indicators in this folder and is required. Do not change it.
      
      namespace NinjaTrader.NinjaScript.Strategies
      
      {
      
      public class testisfirsttickbartest : Strategy
      
      {
      
      
      
      
      protected override void OnStateChange()
      
      {
      
      if (State == State.SetDefaults)
      
      {
      
      Description = @"Enter the description for your new custom Indicator here.";
      
      Name = "testisfirsttickbartest";
      
      Calculate = Calculate.OnEachTick;
      
      ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
      
      //Disable this property if your indicator requires custom values that cumulate with each new market data event.
      
      //See Help Guide for additional information.
      
      }
      
      else if (State == State.Configure)
      
      {
      
      
      
      
      }
      
      else if (State == State.DataLoaded)
      
      {
      
      
      
      
      }
      
      }
      
      
      
      
      protected override void OnBarUpdate()
      
      {
      
      
      
      if(BarsInProgress == 0 && IsFirstTickOfBar)
      
      {
      
      EnterLong(1,"");
      
      }
      
      
      
      }
      
      }
      
      }
      
      
      
      
      
      
      
      
      
      
      
      
      ​

      Comment


        #18
        Hi Rob, This strategy is only submitting a long order with no stop or target, or exit signal. Check the very beginning of the chart to see if there is an entry there. You can also check to see if there are any trades by right-clicking the chart>Strategy Performance>Historical Trades.
        Chris L.NinjaTrader Customer Service

        Comment


          #19
          ChrisL,

          The first entry is "exit on session close" and is then closed by what what supposed to be the entry. That happens at the end of ever day it runs on historical data. It also submits an entry as soon as initiated on a chart, right in the middle of the current bar. Thanks.

          Rob

          Comment


            #20
            Hi Rob, The Exit on session close signal is an Exit signal, it should not be an entry in any circumstances. If you want to turn this off, there is an option for "Exit On Session Close" in the strategy's properties. The key to getting proper IsFirstTickOfBar logic to work is to activate Tick Replay on the chart.
            Chris L.NinjaTrader Customer Service

            Comment


              #21
              ChrisL,

              I figured that "Exit on Session Close" bit playing with your indicator. Even though I didn't have that language in the strategy I made from you indicator, it was still entering (which makes no sense to me) on every session close. So I just added the language to set it to false and changed a few other designations making sure I was pointing things to the correct data stream and I think the entries are working exactly as they should, now. I added langauage to exit the position at a certain time instead of relying on "exit on session close," and with a little finaggling it appears to be functioning properly. The rest of the exits, on the other hand, I cannot figure out. I've debugged extensively using different combinations of language, but I think the root of the problem is it's not recognizing a change in marketposition until bar close. I've done a lot of reading, and I'm not sure how to solve that one. Unless there is something I'm overlooking with the condition logic, but no matter what I change it doesn't print (or execute) until the end of the bar.

              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 AAAobviog04132 : Strategy
              
              {
              
              private double Stop;
              
              private double Profit;
              
              
              
              
              
              
              private OBV OBV1;
              
              private ATR ATR1;
              
              private Series<double> profit1;
              
              private Series<double> stop1;
              
              
              
              
              protected override void OnStateChange()
              
              {
              
              if (State == State.SetDefaults)
              
              {
              
              Description = @"Enter the description for your new custom Strategy here.";
              
              Name = "AAAobviog04132";
              
              Calculate = Calculate.OnEachTick;
              
              EntriesPerDirection = 1;
              
              EntryHandling = EntryHandling.AllEntries;
              
              IsExitOnSessionCloseStrategy = false;
              
              ExitOnSessionCloseSeconds = 30;
              
              IsFillLimitOnTouch = false;
              
              MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
              
              OrderFillResolution = OrderFillResolution.Standard;
              
              Slippage = 0;
              
              StartBehavior = StartBehavior.AdoptAccountPosition;
              
              TimeInForce = TimeInForce.Day;
              
              TraceOrders = true;
              
              RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
              
              StopTargetHandling = StopTargetHandling.PerEntryExecution;
              
              BarsRequiredToTrade = 20;
              
              // Disable this property for performance gains in Strategy Analyzer optimizations
              
              // See the Help Guide for additional information
              
              IsInstantiatedOnEachOptimizationIteration = true;
              
              Profitmultiply = 2;
              
              Shortprofitmultiply = 2;
              
              Stop = 1;
              
              Profit = 1;
              
              
              
                if (State == State.SetDefaults)
              
                  {
              
                      IsAdoptAccountPositionAware = true;
              
                  }
              
              }
              
              else if (State == State.Configure)
              
              {
              
              AddDataSeries(Data.BarsPeriodType.Tick, 1);
              
              }
              
              else if (State == State.DataLoaded)
              
              {
              
              profit1 = new Series<double>(this);
              
              stop1 = new Series<double>(this);
              
              OBV1 = OBV(Close);
              
              ATR1 = ATR(Close, 14);
              
              }
              
              }
              
              
              
              
              protected override void OnBarUpdate()
              
              {
              
              
              
              
              
              
              if (CurrentBars[0] < 2
              
              || CurrentBars[1] < 0)
              
              return;
              
              
              
              
              // Set 1
              
              if (Close[0] != Close[1])
              
              {
              
              profit1[0] = (ATR(Close, 14)[1] * Profitmultiply) ;
              
              }
              
              
              
              // Set 2
              
              if ((Times[0][0].TimeOfDay >= new TimeSpan(6, 0, 0))
              
              && (Times[0][0].TimeOfDay <= new TimeSpan(13, 0, 0))
              
              && (OBV1[1] > OBV1[2])
              
              && (IsFirstTickOfBar == true)
              
              && (BarsInProgress == 0))
              
              
              
              {
              
              EnterLong(1, Convert.ToInt32(DefaultQuantity), "long");
              
              Print(Convert.ToString(IsFirstTickOfBar) + " " + Convert.ToString(Position.Quantity) + " " + Convert.ToString(Times[0][0].TimeOfDay));
              
              }
              
              
              
                // Set 3
              
              if (Times[1][0].TimeOfDay > new TimeSpan(12, 55, 0))
              
              {
              
              ExitShort(1, Convert.ToInt32(Position.Quantity), "time", "");
              
              ExitLong(1, Convert.ToInt32(Position.Quantity), "time", "");
              
              }
              
              
              
              // Set 4
              
              if ((Position.MarketPosition == MarketPosition.Long)
              
              && (Bars.GetClose(1) < (Position.AveragePrice + ((profit1[0] * 0.3) )) ))
              
              {
              
              ExitLongStopMarket(1, true,  Convert.ToInt32(Position.Quantity), (Position.AveragePrice - ((ATR1[1] * 0.5) )) , @"SLlong", "");
              
              Print(Convert.ToString(Times[0][0].TimeOfDay));
              
              }
              
              
              
              // Set 5
              
              if ((Position.MarketPosition == MarketPosition.Long)
              
              && (Bars.GetClose(1) < (Position.AveragePrice + ((profit1[0] * 0.5) )) )
              
              && (Bars.GetClose(1) > (Position.AveragePrice + ((profit1[0] * 0.3) )) ))
              
              {
              
              ExitLongStopMarket(1,true, Convert.ToInt32(Position.Quantity), Position.AveragePrice, @"SLeven", "");
              
              }
              
              
              
              // Set 6
              
              if ((Position.MarketPosition == MarketPosition.Long)
              
              && (Bars.GetClose(1) > (Position.AveragePrice + ((profit1[0] * 0.5) )) )
              
              && (Bars.GetClose(1) < (Position.AveragePrice + ((profit1[0] * 0.8) )) ))
              
              {
              
              ExitLongStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice + ((profit1[0] * 0.25) )) , @"SL50", "");
              
              }
              
              
              
              // Set 7
              
              if ((Position.MarketPosition == MarketPosition.Long)
              
              && (Bars.GetClose(1) > (Position.AveragePrice + ((profit1[0] * 0.8) )) )
              
              && (Bars.GetClose(1) < (Position.AveragePrice + ((profit1[0] * 0.9) )) ))
              
              {
              
              ExitLongStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice + ((profit1[0] * 0.64) )) , @"SL80", "");
              
              }
              
              
              
              // Set 8
              
              if ((Position.MarketPosition == MarketPosition.Long)
              
              && (Bars.GetClose(1) > (Position.AveragePrice + ((profit1[0] * 0.9) )) ))
              
              {
              
              ExitLongStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice + ((profit1[0] * 0.81) )) , @"SL90", "");
              
              }
              
              
              
              // Set 9
              
              if ((Times[0][0].TimeOfDay >= new TimeSpan(6, 0, 0))
              
              && (Times[0][0].TimeOfDay <= new TimeSpan(13, 0, 0))
              
              && (OBV1[1] < OBV1[2])
              
              && (IsFirstTickOfBar == true)
              
              && (BarsInProgress == 0))
              
              {
              
              EnterShort(1, Convert.ToInt32(DefaultQuantity), "");
              
              Print(Convert.ToString(IsFirstTickOfBar) + " " + Convert.ToString(Position.Quantity) + " " + Convert.ToString(Times[0][0].TimeOfDay));
              
              }
              
              
              
              // Set 10
              
              if ((Position.MarketPosition == MarketPosition.Short)
              
              && (Bars.GetClose(1) > (Position.AveragePrice - ((profit1[0] * 0.3) )) ))
              
              {
              
              ExitShortStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice + ((ATR1[1] * 0.5) )) , @"SLstop", "");
              
              Print(Convert.ToString(Times[0][0].TimeOfDay));
              
              }
              
              
              
              // Set 11
              
              if ((Position.MarketPosition == MarketPosition.Short)
              
              && (Bars.GetClose(1) > (Position.AveragePrice - ((profit1[0] * 0.5) )) )
              
              && (Bars.GetClose(1) < (Position.AveragePrice - ((profit1[0] * 0.3) )) ))
              
              {
              
              ExitShortStopMarket(1,true, Convert.ToInt32(Position.Quantity), Position.AveragePrice, @"SLeven", "");
              
              }
              
              
              
              // Set 12
              
              if ((Position.MarketPosition == MarketPosition.Short)
              
              && (Bars.GetClose(1) < (Position.AveragePrice - ((profit1[0] * 0.5) )) )
              
              && (Bars.GetClose(1) > (Position.AveragePrice - ((profit1[0] * 0.8) )) ))
              
              {
              
              ExitShortStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice - ((profit1[0] * 0.25) )) , @"SL50", "");
              
              }
              
              
              
              // Set 13
              
              if ((Position.MarketPosition == MarketPosition.Short)
              
              && (Bars.GetClose(1) < (Position.AveragePrice - ((profit1[0] * 0.8) )) )
              
              && (Bars.GetClose(1) > (Position.AveragePrice - ((profit1[0] * 0.9) )) ))
              
              {
              
              ExitShortStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice - ((profit1[0] * 0.64) )) , @"SL80", "");
              
              }
              
              
              
              // Set 14
              
              if ((Position.MarketPosition == MarketPosition.Short)
              
              && (Bars.GetClose(1) < (Position.AveragePrice - ((profit1[0] * 0.9) )) ))
              
              {
              
              ExitShortStopMarket(1,true, Convert.ToInt32(Position.Quantity), (Position.AveragePrice - ((profit1[0] * 0.81) )) , @"SL90", "");
              
              }
              
              
              
              }
              
              
              
              
              #region Properties
              
              [NinjaScriptProperty]
              
              [Range(0.25, double.MaxValue)]
              
              [Display(Name="Profitmultiply", Order=1, GroupName="Parameters")]
              
              public double Profitmultiply
              
              { get; set; }
              
              
              
              
              [NinjaScriptProperty]
              
              [Range(0.25, double.MaxValue)]
              
              [Display(Name="Shortprofitmultiply", Order=2, GroupName="Parameters")]
              
              public double Shortprofitmultiply
              
              { get; set; }
              
              #endregion
              
              
              
              
              }
              
              }
              ​

              Comment


                #22
                Hi Rob, If some of your exit signals are not exiting when expected it is an issue with the code. You will need to add prints to each of your exit conditions to see if they are being reached, if they are being reached in code but not executing, turn on Trace Orders to see if they are being ignored for any of the reasons below:

                https://ninjatrader.com/support/help...antedPositions - order handling rules
                https://ninjatrader.com/support/help...aceorders2.htm - TraceOrders, these will show up under New>NinjaScript Output window
                Chris L.NinjaTrader Customer Service

                Comment


                  #23
                  ChrisL,
                  I don't get much printed before I get a "maximum threshold reached" message in the output window. I thought that if I changed some of my logic to crossover instead of more or less it would reduce the number of triggers, but when I try to switch (Bars.GetClose(1) < (Position.AveragePrice + ((profit1[0] * 0.3) )) ) to (cross above((Bars.GetClose(1), (Position.AveragePrice + ((profit1[0] * 0.3) )), 0 ) I get an error about doubles that I cannot overcome. I did notice before I started down that road that many of the exit order messages said if was ignored because "no position exists". Thanks for the help.

                  Rob

                  Comment


                    #24
                    ChrisL,

                    After much debugging, I think I've got it working correctly. I do get an alert in the Log page of the control center each time it's instantiated that says an indicator is "expecting calculate on tick or bar close." But I have calculate.OnEachTick coded into my defaults. Any thoughts on how to remedy this or is it not a problem? Again, thanks for all the help. You gave me the tools to work through this, and I appreciate it.

                    Rob

                    Comment


                      #25
                      One of the indicators you are using (OBV maybe?) is only coded to work correctly for OnBarClose so whatever indicator it is in question is warning you that its operation won't be as expected since you are forcing it to run OnEachTick. You could test this by putting OBV on the chart (and all the others you are using) and setting them to OnEachTick individually to see if they make the message.
                      Bruce DeVault
                      QuantKey Trading Vendor Services
                      NinjaTrader Ecosystem Vendor - QuantKey

                      Comment


                        #26
                        Bruce,

                        Thank you, that solved it.

                        Rob

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by AaronKoRn, Yesterday, 09:49 PM
                        0 responses
                        11 views
                        0 likes
                        Last Post AaronKoRn  
                        Started by carnitron, Yesterday, 08:42 PM
                        0 responses
                        10 views
                        0 likes
                        Last Post carnitron  
                        Started by strategist007, Yesterday, 07:51 PM
                        0 responses
                        11 views
                        0 likes
                        Last Post strategist007  
                        Started by StockTrader88, 03-06-2021, 08:58 AM
                        44 responses
                        3,980 views
                        3 likes
                        Last Post jhudas88  
                        Started by rbeckmann05, Yesterday, 06:48 PM
                        0 responses
                        9 views
                        0 likes
                        Last Post rbeckmann05  
                        Working...
                        X