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

Building my first strategy...it doesn't execute orders, help!

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

    Building my first strategy...it doesn't execute orders, help!

    I'm teaching myself to code strategies in the Strategy Builder. I've built my first application, and it compiles correctly. But when I run the backtester, it never takes a trade! I know the backtester is configured correctly because I can run other strategies successfully.

    This is an opening range strategy, so there's a condition met nearly every day. I'm sure I did something wrong, but I can't tell what. I need a fresh set of eyes.

    The code is supposed to look at the first 30 minutes of market open, and establish a range. After the first 30min, if the range is broken it takes a trade with a target of 1/2 the range and a stop loss of 1/2 the range. It's designed to take either one long or one short trade each day, and it resets at 2PM.

    Here's the code, can anyone help me spot what I've missed?

    region Using declarations

    using System.Linq;

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.ComponentModel.DataAnnotations;

    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;

    using NinjaTrader.NinjaScript.Strategies;

    #endregion

    class CrudeOilOpeningRangeBreakoutStrategy : Strategy

    {

    private DateTime lastTradeTime = DateTime.MinValue;

    private double stopLoss;

    private double profitTarget;

    private int Quantity = 1;

    private bool longPositionOpened = false;

    private bool shortPositionOpened = false;

    private double openingRangeHigh;

    private double openingRangeLow;

    protected override void OnStateChange()

    {

    if (State == State.SetDefaults)

    {

    Description = "Crude Oil Opening Range Breakout Strategy";

    Name = "CrudeOilOpeningRangeBreakoutStrategy";

    Calculate = Calculate.OnEachTick;

    }

    else if (State == State.Realtime)

    {

    }
    base.OnStateChange();

    }
    protected override void OnMarketData(MarketDataEventArgs marketDataUpdate)

    {

    // Check if it's outside the allowed trading time

    if (Time[0].Hour < 8 || Time[0].Hour >= 14) return;

    if (Time[0].Hour == 8 && Time[0].Minute < 30) return;

    if (Time[0].Hour == 14 && Time[0].Minute >= 0) return;

    // Set opening range high and low

    if (Time[0].Hour == 8 && Time[0].Minute == 30)

    {

    double highValue = High[1];

    double lowValue = Low[1];

    openingRangeHigh = Math.Max(highValue, openingRangeHigh);

    openingRangeLow = Math.Min(lowValue, openingRangeLow);

    stopLoss = openingRangeLow - (openingRangeHigh - openingRangeLow) * 0.5;

    profitTarget = openingRangeHigh + (openingRangeHigh - openingRangeLow) * 0.5;

    }

    // Reset trade flags and range at 2PM

    if (Time[0].Hour == 14)

    {

    longPositionOpened = false;

    shortPositionOpened = false;

    openingRangeHigh = 0;

    openingRangeLow = 0;

    stopLoss = 0;

    profitTarget = 0;
    }
    // Place a long trade if price rises above the opening range high and no long trade has been placed

    if (Close[0] > openingRangeHigh && !longPositionOpened)

    {

    longPositionOpened = true;

    EnterLong(Quantity, "Long");

    lastTradeTime = Time[0];

    }

    // Place a short trade if price falls below the opening range low and no short trade has been placed

    if (Close[0] < openingRangeLow && !shortPositionOpened)

    {

    shortPositionOpened = true;

    EnterShort(Quantity, "Short");

    lastTradeTime = Time[0];

    }

    }}

    #2
    Just a quick comment; I would use the "HighestBar" & "LowestBar" functions to set your "openingRangeHigh" & "openingRangeLow" values...

    Comment


      #3
      Add a "print" statement to check the values of your variables.

      Comment


        #4
        Hello mattlaguardia,

        Thank you for your post and welcome to the NinjaTrader forums! Thank you waltFX and KonstantinosNT for your input as well.

        For anyone getting started with NinjaScript, I like to share the following post that has a lot of helpful resources listed in one place:
        In this case, I do agree that you should add print statements to check the values of your variables. If the openingRangeHigh and openingRangeLow values are not what you expect, you could also look into using HighestBar and LowestBar as suggested. We have more information about using prints to debug a script, as well as a video showing how to add prints in the Strategy Builder, at the following link:Please don't hesitate to reach out with any additional questions or concerns.
        Emily C.NinjaTrader Customer Service

        Comment


          #5
          Thank you so much guys! I will try these suggestions tonight and report back.

          Comment


            #6
            OK, I've added print statements to the code, and changed to HighestBar/LowestBar.

            I also watched the video...something very interesting I discovered is that I can't attach this strategy to a chart. It doesn't show up in the strategies when I right click and bring up the menu.

            I can load it into the backtester and run it, but there is no output in the terminal even with the print statements added.

            Comment


              #7
              Hello mattlaguardia,

              If the strategy is applied to a chart, is there data with new bars appearing on the chart the Strategy is applied to?

              Is the strategy showing as enabled on the Strategies tab of the Control Center?

              Importantly, are there errors appearing on the Log tab of the Control Center?

              It doesn't show up in the strategies when I right click and bring up the menu.
              This would indicate there is an error in OnStateChange(). This error would be appearing on the Log tab of the Control Center.

              From a strategy still locked for editing with the Strategy Builder, this is typically due to using series information (like indicators or prices) with stops and targets
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Hello Chelsea, thanks so much for the reply.

                If the strategy is applied to a chart, is there data with new bars appearing on the chart the Strategy is applied to?​
                I'm unable to apply it to a chart because it doesn't show up in the list of available strategies when I right click on the chart.

                This would indicate there is an error in OnStateChange(). This error would be appearing on the Log tab of the Control Center.

                From a strategy still locked for editing with the Strategy Builder, this is typically due to using series information (like indicators or prices) with stops and targets​
                That's very strange--the strategy isn't locked within the Strategy Builder. It compiles with no errors. I can run it in the Backtester, but it won't take trades.

                Is it possible there's an issue in the OnStateChange() section that's causing this odd behavior?

                Comment


                  #9
                  Hello mattlaguardia,

                  Is it possible there's an issue in the OnStateChange() section that's causing this odd behavior?
                  Yes, it is possible there is an issue in OnStateChange().

                  Please provide the information requested in post # 7.

                  "Importantly, are there errors appearing on the Log tab of the Control Center?"


                  Regarding the strategy not placing orders, print the time of the bar, and all values used in the condition that submits the entry order. Include labels for each value and comparison operator. Save the output to a text file. Include the text file with your reply and we will be happy to assist with analyzing the output. Post # 4 includes a link to a forum post with directions on using prints to understand behavior and includes a video.
                  Last edited by NinjaTrader_ChelseaB; 02-02-2023, 09:04 AM.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    If the strategy is applied to a chart, is there data with new bars appearing on the chart the Strategy is applied to?

                    Is the strategy showing as enabled on the Strategies tab of the Control Center?

                    Importantly, are there errors appearing on the Log tab of the Control Center?​
                    I am not able to apply the strategy to any chart. It does not show up in the list of available strategies when I right click and select 'add new strategy'.

                    Nothing shows up in the strategies tab of the control center.

                    There are no errors that show up in the log tab of the control center.

                    Comment


                      #11
                      Hello, thanks for the follow up. If you can not see the strategy in the Strategies menu, this typically means there is an initialization error with the strategy, an error message should pop up in the Log tab of the Control Center if this happens. If there is no message about the strategy, then the file may be in the wrong location. Check to make sure the strategy .cs file is within the following directory:

                      Documents\NinjaTrader 8\bin\Custom\Strategies

                      Also, double check the "Name" parameter of the strategy to confirm the name that will be seen in the Strategy menu.
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        The name follows the correct format, and the strategy shows up in the correct folder.

                        I think the issue is that I haven't correctly defined the data condition used for entry? The code says to look at a bar close, but never defines the bar period. Instead it should be looking at individual tick data.

                        Any thoughts there?​

                        Comment


                          #13
                          Hello mattlaguardia,

                          You said in the message #10
                          "I am not able to apply the strategy to any chart. It does not show up in the list of available strategies when I right click and select 'add new strategy'."

                          It's unlikely that this problem has anything to do with possibly wrong entry conditions in your strategy.
                          It seems like your strategies are not yet compiled.
                          Check that possibility.

                          Comment


                            #14
                            Thank you for the reply.

                            It seems like your strategies are not yet compiled.
                            I click the compile button inside the NinjaScript Editor, and they compile with no errors. Isn't that the process I need to go through? Am I missing a step?

                            Also, there is another person who just posted here with the same issue:
                            Last edited by mattlaguardia; 02-05-2023, 07:46 AM. Reason: Add information.

                            Comment


                              #15
                              Hello again mattlaguardia,

                              The code in your first message must be a part of your script and not the full script, because I don't see any stop loss orders.

                              Something I have noticed is that there is no "OnBarUpdate()" method anywhere in your script. ​
                              You are only using OnMarketUpdate(), but in the NT Help it is clearly stated that:

                              " The OnMarketData() method is expected to be called after OnBarUpdate()​ "

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by DJ888, 04-16-2024, 06:09 PM
                              6 responses
                              18 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by Jon17, Today, 04:33 PM
                              0 responses
                              1 view
                              0 likes
                              Last Post Jon17
                              by Jon17
                               
                              Started by Javierw.ok, Today, 04:12 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post Javierw.ok  
                              Started by timmbbo, Today, 08:59 AM
                              2 responses
                              10 views
                              0 likes
                              Last Post bltdavid  
                              Started by alifarahani, Today, 09:40 AM
                              6 responses
                              41 views
                              0 likes
                              Last Post alifarahani  
                              Working...
                              X