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

Strategy Builder creates a strategy that doesn't want to trade!

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

    Strategy Builder creates a strategy that doesn't want to trade!

    Hi, I am trying to create a simple crossover strategy. However although I managed to use the strategy builder to create it, after attaching it to the chart it doesn't seem to get anything done (in terms of trade), doesn't throw any errors either. Including here my script found from "View Code". Can anyone please point me to the faults I have created or things that I have overlooked in it. I'd appreciate it very much.
    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 DEMASMAtest001 : Strategy
        {
            private bool TradeOn;
    
            private DEMA DEMA1;
            private SMA SMA1;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "DEMASMAtest001";
                    Calculate                                    = Calculate.OnBarClose;
                    EntriesPerDirection                            = 1;
                    EntryHandling                                = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy                = true;
                    ExitOnSessionCloseSeconds                    = 30;
                    IsFillLimitOnTouch                            = false;
                    MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution                            = OrderFillResolution.Standard;
                    Slippage                                    = 0;
                    StartBehavior                                = StartBehavior.WaitUntilFlat;
                    TimeInForce                                    = TimeInForce.Gtc;
                    TraceOrders                                    = false;
                    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;
                    TradeOn                    = false;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    DEMA1                = DEMA(Close, 14);
                    SMA1                = SMA(Close, 10);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if ((Position.MarketPosition == MarketPosition.Flat)
                     && (CurrentBars[0] > 20)
                     && (TradeOn == false))
                {
                    TradeOn = true;
                }
                
                 // Set 2
                if ((TradeOn == true)
                     && (CrossAbove(DEMA1, SMA1, 1)))
                {
                    EnterLong(Convert.ToInt32(DefaultQuantity), "");
                    TradeOn = false;
                    BackBrush = Brushes.CornflowerBlue;
                }
                
                 // Set 3
                if ((TradeOn == true)
                     && (CrossBelow(DEMA1, SMA1, 1)))
                {
                    EnterShort(Convert.ToInt32(DefaultQuantity), "");
                    TradeOn = false;
                    BackBrush = Brushes.Brown;
                }
                
            }
        }
    }​
    Any idea ?

    #2
    Hello SnailHorn,

    Thank you for your post.

    It looks like your TradeOn variable may be preventing the strategy from taking further trades. Once TradeOn is set to false by either entering long or entering short, it cannot be set back to true until the strategy's market position is flat. However the strategy's position will never be flat since you are only ever either entering long or entering short. The strategy's position will only be flat when you first enable it then afterwards will always be in a long or short position.

    You will need to adjust your logic/conditions for flipping the TradeOn variable to true or false.

    Please let me know if you have any further questions.
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Gaby View Post
      Hello SnailHorn,

      Thank you for your post.

      It looks like your TradeOn variable may be preventing the strategy from taking further trades. Once TradeOn is set to false by either entering long or entering short, it cannot be set back to true until the strategy's market position is flat. However, the strategy's position will never be flat since you are only ever either entering long or entering short. The strategy's position will only be flat when you first enable it then afterwards will always be in a long or short position.

      You will need to adjust your logic/conditions for flipping the TradeOn variable to true or false.

      Please let me know if you have any further questions.
      Thanks, Gaby
      You are right. The variable "TradeOn" is meant to be the one to stop the strategy from opening any further trade after opening the first one! But unfortunately, it doesn't even open the first one!. I need it to open the first one, which it doesn't. Presently the logic should allow it to open the first one at least and at best -- which is necessarily my intention too.

      To my understanding at the 'Strategy launch'-time the TradeOn is set to false(default value). Hence, as the market is(should be) 'flat' at the right bar(the current bar being at BarsRequiredToTrade) the strategy should allow me to set the TradeOn to true. Practically, TradeOn just 'flags' me to trade either 'Long' or 'Short' (the next two 'Sets') when the setup is right(i.e. TradeOn is true). But would prevent me from trading otherwise.

      To my understanding, it should allow me to trade at least once when the setup is right. But it is not doing so. I think I am not getting my logic either :-( I was taking the idea from one of the forum posts, I'll have to find it to let you know.

      Comment


        #4
        Hello SnailHorn,

        Currently, it seems that it should only allow you to enter once either long or short. oneTrade will be set to true when your Set 1 conditions are true, then either allow you to enter long or enter short once before it is set back to false.

        However, if the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true and the order is not being submitted, or the order is being ignored for other reasons, or the order is being cancelled.

        To understand why the script is behaving as it is, such as placing orders or not placing orders when expected, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

        In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

        The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

        Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

        Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

        I am happy to assist you with analyzing the output from the output window.

        Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

        Below is a link to a forum post that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.



        Please let me know if I may further assist with analyzing the output or if you need any assistance creating a print or enabling TraceOrders.
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          Hello NinjaTrader_Gaby, surprise surprise, after introducing the prints in the strategy I really have found out something that I would never even think about, myself!! Thanks to you for pointing me out in the proper direction! Please see the output first then my revised routine below, & then my question afterwards:
          Code:
          17/03/2024 18:38:01 | Market condition (Position.MarketPosition == MarketPosition.Flat) is = True
          _____________________ | Position.MarketPosition <Flat> == MarketPosition.Flat <Flat>
          _____________________ | TradeOn = <False> is True
          _____________________ | BarsSinceExitExecution() <-1>
          
          _____________________ | longSetup <False>
          _____________________ | shortSetUp <True>
          17/03/2024 18:38:01 Strategy 'DEMASMAtest001Unlocked/321671092': Entered internal SubmitOrderManaged() method at 17/03/2024 18:38:01: BarsInProgress=0 Action=SellShort OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
          
          17/03/2024 18:40:11 | Market condition (Position.MarketPosition == MarketPosition.Flat) is =False
          _____________________ | Position.MarketPosition <Short> == MarketPosition.Flat <Flat>
          _____________________ | TradeOn = <False> is True
          _____________________ | BarsSinceExitExecution() <-1>
          
          _____________________ | longSetup <True>
          _____________________ | shortSetUp <False>
          
          17/03/2024 18:45:38 | Market condition (Position.MarketPosition == MarketPosition.Flat) is = False
          _____________________ | Position.MarketPosition <Short> == MarketPosition.Flat <Flat>
          _____________________ | TradeOn = <False> is True
          _____________________ | BarsSinceExitExecution() <-1>
          
          _____________________ | longSetup <False>
          _____________________ | shortSetUp <False>
          
          17/03/2024 18:51:58 | Market condition (Position.MarketPosition == MarketPosition.Flat) is = False
          _____________________ | Position.MarketPosition <Short> == MarketPosition.Flat <Flat>
          _____________________ | TradeOn = <False> is True
          _____________________ | BarsSinceExitExecution() <-1>
          
          _____________________ | longSetup <False>
          _____________________ | shortSetUp <False>
          
          17/03/2024 18:53:35 | Market condition (Position.MarketPosition == MarketPosition.Flat) is = False
          _____________________ | Position.MarketPosition <Short> == MarketPosition.Flat <Flat>
          _____________________ | TradeOn = <False> is True
          _____________________ | BarsSinceExitExecution() <-1>
          
          _____________________ | longSetup <False>
          _____________________ | shortSetUp <True>​
          
          .... snip ...
          Look at the 1st (18:38:01) market flatness test at the top and the second(18:40:11) one! See any differences? which is obvious!

          In the meantime, my strategy has Entered internal SubmitOrderManaged() method at 17/03/2024 18:38:01, which is not successful but screwed up everything else..

          Here is my revised Strategy code before this out put:
          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.MyStrategies
          {
              public class DEMASMAtest001Unlocked : Strategy
              {
                  private bool TradeOn;    /// Toggles trading feature : allows when holds true
                  private bool deBug;
          
                  private DEMA DEMA14;    /// Going to use  DEMA for 14 period
                  private SMA SMA10;        /// Going to use  SMA for 10 period
          
                  protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                          Description                                    = @"Enter the description for your new custom Strategy here.";
                          Name                                        = "DEMASMAtest001Unlocked";
                          Calculate                                    = Calculate.OnBarClose;
                          EntriesPerDirection                            = 1;
                          EntryHandling                                = EntryHandling.AllEntries;
                          IsExitOnSessionCloseStrategy                = true;
                          ExitOnSessionCloseSeconds                    = 30;
                          IsFillLimitOnTouch                            = false;
                          MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                          OrderFillResolution                            = OrderFillResolution.Standard;
                          Slippage                                    = 0;
                          StartBehavior                                = StartBehavior.WaitUntilFlat;
                          TimeInForce                                    = TimeInForce.Gtc;
                          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;
                          TradeOn                    = false;
                          deBug                    = true;        /// Manual tweek!!
                      }
                      else if (State == State.Configure)
                      {
                          ClearOutputWindow();
                      }
                      else if (State == State.DataLoaded)
                      {                
                          DEMA14                = DEMA(Close, 14);
                          SMA10                = SMA(Close, 10);
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if (BarsInProgress != 0)
                          return;
          
                      if (CurrentBars[0] < BarsRequiredToTrade)
                          return;
                      
                      if (!IsFirstTickOfBar)
                          return;                // reduces number of output for now!
                      
                      /// Check market condittions
                      bool marketConditionOK = (Position.MarketPosition == MarketPosition.Flat)    // No trade is on
                                                  && (TradeOn == false)                            // No trade is allowed yet
                                                  // At least 1 bar is passed after the last trade exit OR no trade was done ever!
                                                  && (BarsSinceExitExecution() > 1 || BarsSinceExitExecution() == -1)
                                                   ;
                      /// Check Entry setups
                      bool longSetup     = (CrossAbove(DEMA14, SMA10, 1));
                      bool shortSetUp = (CrossBelow(DEMA14, SMA10, 1));
                      
                      #region debug Prints
                      if (deBug)
                      {
                          Print(string.Format("\n{0} | Market condition (Position.MarketPosition == MarketPosition.Flat) is = {1}",Time[0], (Position.MarketPosition == MarketPosition.Flat)));
                          Print(string.Format("_____________________ | Position.MarketPosition <{0}> == MarketPosition.Flat <{1}>", Position.MarketPosition, MarketPosition.Flat ));
                          Print(string.Format("_____________________ | TradeOn = <{0}> is {1}", (TradeOn), (TradeOn == false) ));
                          Print(string.Format("_____________________ | BarsSinceExitExecution() <{0}>", BarsSinceExitExecution() ));
                          Print(string.Format("\n_____________________ | longSetup <{0}>", (CrossAbove(DEMA14, SMA10, 1)) ));
                          Print(string.Format("_____________________ | shortSetUp <{0}>", (CrossBelow(DEMA14, SMA10, 1)) ));
                      }
                      else Print("Strategy Debugging is halted manully");
                      #endregion
                      
                      // Set 1            
                      if (marketConditionOK) TradeOn = true; // Allowing to trade from now on
                      
                       // Set 2
                      if (TradeOn && longSetup )
                      {
                          EnterLong(Convert.ToInt32(DefaultQuantity), "");
                          TradeOn = false; // revoking trade allowance after entry
                      }
                      
                       // Set 3
                      if (TradeOn && shortSetUp )
                      {
                          EnterShort(Convert.ToInt32(DefaultQuantity), "");
                          TradeOn = false; // revoking trade allowance after entry
                      }
                      
                  }
              }
          }
          ​

          My question is: How can I revise my strategy now to get rid of this unwanted execution of trade that doesn't get its completion or fruition? OR any other way of having a better situation?

          Cheers!!

          Comment


            #6
            Hello SnailHorn,

            The strategy is only submitting the orders because the conditions for entry were true on that bar. If you would like to avoid it submitting this unwanted entry, you would need to adjust the logic in your script to prevent this entry from happening.

            Please let us know if you have any further questions.
            Gaby V.NinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by fx.practic, 10-15-2013, 12:53 AM
            5 responses
            5,406 views
            0 likes
            Last Post Bidder
            by Bidder
             
            Started by Shai Samuel, 07-02-2022, 02:46 PM
            4 responses
            98 views
            0 likes
            Last Post Bidder
            by Bidder
             
            Started by DJ888, Yesterday, 10:57 PM
            0 responses
            8 views
            0 likes
            Last Post DJ888
            by DJ888
             
            Started by MacDad, 02-25-2024, 11:48 PM
            7 responses
            160 views
            0 likes
            Last Post loganjarosz123  
            Started by Belfortbucks, Yesterday, 09:29 PM
            0 responses
            9 views
            0 likes
            Last Post Belfortbucks  
            Working...
            X