Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Please Help/ I cannot for some reason draw arrows on my chart!!!

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

    Please Help/ I cannot for some reason draw arrows on my chart!!!

    I have tried so many different ways to do this but yet they all fail. I want an arrow to show when the crossover occurs and the buy/sell trade begins. Here is my code. Please help me fix this issue.

    ```

    // Add these using declarations at the top if they are not already present
    using NinjaTrader.Cbi;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.Gui;
    using System;

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class EMACross : Strategy
    {
    private EMA fastEma;
    private EMA slowEma;
    private double trailingStopValue;

    // Marker series to plot markers on the chart
    private Series<double> sidewaysMarkerSeries;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    // Your existing settings...
    trailingStopValue = 6.0; // Set your desired trailing stop value (in points or ticks)
    Calculate = Calculate.OnEachTick;

    // Add a new series for markers
    sidewaysMarkerSeries = new Series<double>(this);
    }
    else if (State == State.Configure)
    {
    // Do nothing here or add additional configuration
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    // Check if EMA indicators are not yet initialized
    if (fastEma == null || slowEma == null)
    {
    // Initialize EMA indicators
    fastEma = EMA(Close, 10);
    slowEma = EMA(Close, 20);
    return;
    }

    // Continue with your existing strategy logic

    // Check trading hours
    if (!IsRegularMarketHours())
    {
    // Avoid trading outside regular market hours
    return;
    }

    // Check for EMA crossover
    if (CrossAbove(fastEma, slowEma, 1))
    {
    // Enter long position logic
    EnterLong("TradeLong");
    Draw.ArrowUp(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red);

    // Set take profit for the long position
    // SetProfitTarget("EMACrossLong", CalculationMode.Ticks, 3);

    // Set trailing stop for the long position
    //SetTrailStop("TradeLong", CalculationMode.Ticks, 16, false); // 'false' indicates a non-simulated stop

    // Set stop-loss for the long position (adjust the value as needed)
    //SetStopLoss("TradeLong", CalculationMode.Ticks, 10, false);
    }
    else if (CrossBelow(fastEma, slowEma, 1))
    {
    // Enter short position logic
    EnterShort("TradeShort");
    Draw.ArrowUp(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red);

    // Set take profit for the short position
    // SetProfitTarget("EMACrossShort", CalculationMode.Ticks, 3);

    // Set trailing stop for the short position
    //SetTrailStop("TradeShort", CalculationMode.Ticks, 16, false); // 'false' indicates a non-simulated stop

    // Set stop-loss for the short position (adjust the value as needed)
    //SetStopLoss("TradeShort", CalculationMode.Ticks, 10, false);
    }
    }

    private bool IsRegularMarketHours()
    {
    TimeSpan currentTime = Time[0].TimeOfDay;
    return currentTime >= new TimeSpan(9, 0, 0) && currentTime <= new TimeSpan(19, 0, 0);
    }
    }
    }​

    ```

    #2
    Hello LiamTwine,

    Thank you for your post.

    What are the results when you test this script? Are you seeing any entries? Are there any errors on the Log tab of the Control Center?
    Since you are trying to draw arrows, what do you see after a crossover has occurred and you open the Drawing Tools window from the chart - do you see any objects with "tag1" in that window?

    I suggest adding Print() statements for debugging purposes. You can add a print both before and after an arrow should be drawn, and you could include the price the arrow is supposed to be drawn at as well as which bar it should be drawn on. Then, you would need to keep the NinjaScript Output window open while testing your script and see if those prints appear or not. If they do, it means that the logic was hit so the Draw() method should have been called. If not, the logic to enter and draw arrows is not being hit. For more information about using prints for debugging:


    If you are unsure about the meaning of your output, please right-click the NinjaScript Output window and select Save As to save it to a text file that may be attached to your reply.

    As a side note, I see you are calling SetProfitTarget(), SetTrailingStop(), and SetStopLoss() after calling EnterLong() / EnterShort(). The Set() methods are submitted upon receiving an execution, so they should be called prior to submitting the entry order. In your case, they do not appear to be using dynamic values so you could even call them in OnStateChange() when State == State.Configure to use a static offset, such as 3 ticks or 10 ticks. Another thing; you may not use SetStopLoss() and SetTrailStop() together for the same position. If you call both, the SetStopLoss() always takes precedence and SetTrailStop() will be ignored. These items are all noted in the help guide on the following pages:I look forward to assisting you further.

    Comment


      #3
      Hi Thank you for your response. Yes, here are the errors im getting:

      NinjaScript File Error Code Line Column EMACross.cs The name 'Draw' does not exist in the current context CS0103 76 5
      NinjaScript File Error Code Line Column EMACross.cs The name 'Brushes' does not exist in the current context CS0103 76 60


      Comment


        #4
        Hello LiamTwine,

        Thank you for your reply.

        Based on those messages, it seems as though you are missing the following using declarations at the top of your script:
        using NinjaTrader.NinjaScript.DrawingTools;
        using System.Windows.Media;

        These statements are included by default, so I suspect that you have potentially pasted code into the editor that resulted in removing the code that is already generated by the NinjaScript Wizard. I suggest generating a new strategy from the wizard and then pasting in the relevant parts of your code to ensure that all necessary using statements and system-generated code is included in the strategy. You can do this by clicking the '+' plus sign in the bottom of the NinjaScript Editor and selecting New Strategy. Follow the prompts in the wizard then finally generate the script. Copy/paste over the relevant pieces of logic in your strategy and then try to compile again. You can right-click the old script in the NinjaScript Explorer on the right-hand side and exclude it from compilation if you'd like. For more information about the NinjaScript Wizard and NinjaScript Explorer:



        Please let us know if we may be of further assistance.

        Comment


          #5
          Perfect. I added them back and problem solved. I really appreciate it. How do i make the arrows bigger? also i wanted to add code to automatically draw lines at set levels for example support and resistance. how do i do that

          Comment


            #6
            Originally posted by LiamTwine View Post
            Perfect. I added them back and problem solved. I really appreciate it. How do i make the arrows bigger? also i wanted to add code to automatically draw lines at set levels for example support and resistance. how do i do that
            Changing the size of the arrows is not an option with the ArrowUp and ArrowDown objects that come with NinjaTrader.

            With that said, this custom script is publicly available on our NinjaTrader Ecosystem website and it includes NinjaScript methods for DrawPlus.<object name here>() that allow you to draw the custom markers instead:
            Here is a basic guideline of how to import NinjaScript add-ons in NinjaTrader 8:

            Note — To import NinjaScripts you will need the original .zip file.

            To Import:
            1. Download the NinjaScripts to your desktop, keep them in the compressed .zip file.
            2. From the Control Center window select the menu Tools > Import > NinjaScript Add-on...
            3. Select the downloaded .zip file
            4. NinjaTrader will then confirm if the import has been successful.

            Critical - Specifically for some NinjaScripts, it will prompt that you are running newer versions of @SMA, @EMA, etc. and ask if you want to replace, press 'No'

            Once installed, you may add the indicator to a chart by:
            • Right-click your chart > Indicators... > Select the Indicator from the 'Available' list on the left > Add > OK

            Here is a short video demonstration of the import process:
            "also i wanted to add code to automatically draw lines at set levels for example support and resistance"
            If you want horizontal lines at set levels, you could call AddLine():


            Otherwise, you could draw Line objects with the Draw.Line() method:


            Please let me know if I can be of further assistance.

            The NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The add-ons listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.

            Comment


              #7
              Thanks for the reply. If i install https://ninjatraderecosystem.com/use...rtmarkersplus/ , how do i then integrate that with my own strategy? as this seems to be valid only within its own context as an indicator? also how do i have lines drawn at levels such as when a price hits a level at least twice then creates a line to plot that as supp/res etc

              Comment


                #8
                Originally posted by LiamTwine View Post
                Thanks for the reply. If i install https://ninjatraderecosystem.com/use...rtmarkersplus/ , how do i then integrate that with my own strategy? as this seems to be valid only within its own context as an indicator? also how do i have lines drawn at levels such as when a price hits a level at least twice then creates a line to plot that as supp/res etc
                Thanks for your reply.

                This is why I mentioned "it includes NinjaScript methods for DrawPlus.<object name here>() that allow you to draw the custom markers instead"
                Please see the screenshot of the notes I am referring to for the NinjaScript methods available when this script has been imported to the platform:
                World's leading screen capture + recorder from Snagit + Screencast by Techsmith. Capture, edit and share professional-quality content seamlessly.


                You can start the method then use the intelliprompt to guide you through completing the method:


                "also how do i have lines drawn at levels such as when a price hits a level at least twice then creates a line to plot that as supp/res etc"
                You would have to code the desired logic into your conditions. If you want the price to hit a level at least twice, you could have one condition that checks for the first time it hits that level then toggle a bool to true, then your second condition could check if the bool is true (meaning the price hit it once) then when it is hit a second time you could trigger the desired action. This is similar to the concept demonstrated in the following Strategy Builder example that toggles bools:
                Hi, To improve a strategy, I would like the condition to enter a trade to be triggered only after a second crossing happens. Meaning, for instance we have a sthocastics crossing, but the strategy would only trigger when a crossing between 2 emas happen. Would the looking back N bars work? Can it be done within the builder


                Please let us know if we may be of further assistance.

                Comment


                  #9
                  thank you for your help. i have been able to plot lines etc. but trying to get lines plotted at set points that have been touched to build support and rsistance. here is the code. whats wrong with it as now it plots nothing.:

                  ```

                  // Add these using declarations at the top if they are not already present
                  using NinjaTrader.Cbi;
                  using NinjaTrader.NinjaScript.Indicators;
                  using NinjaTrader.Gui;
                  using NinjaTrader.NinjaScript.DrawingTools;
                  using System.Windows.Media;
                  using System;

                  namespace NinjaTrader.NinjaScript.Strategies
                  {
                  public class EMACross : Strategy
                  {
                  private EMA fastEma;
                  private EMA slowEma;
                  private double trailingStopValue;

                  // Marker series to plot markers on the chart
                  private Series<double> sidewaysMarkerSeries;

                  // Declare variables for support and resistance feature
                  private double prevPrice; // Previous price level
                  private int hitCount; // Number of times the price hits the same level

                  protected override void OnStateChange()
                  {
                  if (State == State.SetDefaults)
                  {
                  // Your existing settings...
                  trailingStopValue = 6.0; // Set your desired trailing stop value (in points or ticks)
                  Calculate = Calculate.OnEachTick;

                  // Add a new series for markers
                  sidewaysMarkerSeries = new Series<double>(this);

                  // Initialize variables for support and resistance feature
                  prevPrice = 0.0;
                  hitCount = 0;
                  }
                  else if (State == State.Configure)
                  {
                  // Do nothing here or add additional configuration
                  }
                  }

                  protected override void OnBarUpdate()
                  {
                  if (BarsInProgress != 0)
                  return;

                  // Check if EMA indicators are not yet initialized
                  if (fastEma == null || slowEma == null)
                  {
                  // Initialize EMA indicators
                  fastEma = EMA(Close, 10);
                  slowEma = EMA(Close, 20);
                  return;
                  }

                  // Continue with your existing strategy logic

                  // Check trading hours
                  if (!IsRegularMarketHours())
                  {
                  // Avoid trading outside regular market hours
                  return;
                  }

                  // Check for EMA crossover
                  if (CrossAbove(fastEma, slowEma, 1))
                  {
                  // Enter long position logic
                  EnterLong("TradeLong");
                  Draw.ArrowUp(this, "BUY", true, 0, Low[0] - TickSize, Brushes.Green);

                  // Set take profit for the long position
                  // SetProfitTarget("EMACrossLong", CalculationMode.Ticks, 3);

                  // Set trailing stop for the long position
                  // SetTrailStop("TradeLong", CalculationMode.Ticks, 16, false); // 'false' indicates a non-simulated stop

                  // Set stop-loss for the long position (adjust the value as needed)
                  // SetStopLoss("TradeLong", CalculationMode.Ticks, 10, false);
                  }
                  else if (CrossBelow(fastEma, slowEma, 1))
                  {
                  // Enter short position logic
                  EnterShort("TradeShort");
                  Draw.ArrowDown(this, "SELL", true, 0, High[0] - TickSize, Brushes.Red);

                  // Set take profit for the short position
                  // SetProfitTarget("EMACrossShort", CalculationMode.Ticks, 3);

                  // Set trailing stop for the short position
                  // SetTrailStop("TradeShort", CalculationMode.Ticks, 16, false); // 'false' indicates a non-simulated stop

                  // Set stop-loss for the short position (adjust the value as needed)
                  // SetStopLoss("TradeShort", CalculationMode.Ticks, 10, false);
                  }

                  // Define a threshold value for price touches
                  double threshold = 0.5;

                  // Define an array to store the price levels
                  double[] levels = new double[100];

                  // Define a variable to keep track of the number of levels
                  int levelCount = 0;

                  // Add support and resistance feature logic
                  // Get the current price level
                  double currPrice = Close[0];

                  // Loop through the array of levels
                  int i;
                  for (i = 0; i < levelCount; i++)
                  {
                  // Check if the current price is within the threshold of a level
                  if (Math.Abs(currPrice - levels[i]) <= threshold)
                  {
                  // Increment the counter for that level
                  hitCount++;

                  // Break out of the loop
                  break;
                  }
                  }

                  // Check if the current price is not within the threshold of any level
                  if (i == levelCount)
                  {
                  // Add the current price to the array of levels
                  levels[levelCount] = currPrice;

                  // Set the counter for that level to one
                  hitCount = 1;

                  // Increment the number of levels
                  levelCount++;
                  }

                  // Loop through the array of levels again
                  for (i = 0; i < levelCount; i++)
                  {
                  // Check if the counter for a level is two or more
                  if (hitCount >= 2)
                  {
                  // Draw a horizontal line at that level
                  Draw.Line(this, "SRLine" + i, false, -10, levels[i], 0, levels[i], Brushes.Yellow, DashStyleHelper.Solid, 2);

                  // Optionally, you can also add some logic to remove the line when the price breaks through it, or to extend the line as new bars are added
                  }
                  }
                  }

                  private bool IsRegularMarketHours()
                  {
                  TimeSpan currentTime = Time[0].TimeOfDay;
                  return currentTime >= new TimeSpan(9, 0, 0) && currentTime <= new TimeSpan(19, 0, 0);
                  }
                  }
                  }


                  ```

                  Comment


                    #10
                    Hello LiamTwine,

                    Thank you for your reply.

                    Do you see any errors on the Log tab of the Control Center when you expect to see lines drawn? I see you are using a negative bar index for the startBarsAgo value:
                    Draw.Line(this, "SRLine" + i, false, -10, levels[i], 0, levels[i], Brushes.Yellow, DashStyleHelper.Solid, 2);

                    Using a negative index is not supported. Extending drawing tools into the future is not supported and using a negative barsAgo index could result in unexpected behavior from the platform. Where on your chart are you wanting the lines to be drawn?

                    What are the results after adding debugging prints? If you print the values of the levels, are those the expected price levels or something different?

                    I look forward to your reply.

                    Comment


                      #11
                      Thanks for your reply. I have attached a SS so you can see what's happening. I just want a support and resistance line plotted at prev swing highs and lows. for the current data series (about 5 days). For the lines to be plotted if they have been touched at least twice and then plot a line

                      Click image for larger version

Name:	Screenshot 2024-02-27 155908.png
Views:	454
Size:	33.5 KB
ID:	1293342

                      Comment


                        #12
                        Originally posted by LiamTwine View Post
                        Thanks for your reply. I have attached a SS so you can see what's happening. I just want a support and resistance line plotted at prev swing highs and lows. for the current data series (about 5 days). For the lines to be plotted if they have been touched at least twice and then plot a line

                        Click image for larger version  Name:	Screenshot 2024-02-27 155908.png Views:	0 Size:	33.5 KB ID:	1293342
                        Thanks for your reply with the screenshot. If the script is not behaving how you'd like it to or how you expect it to, you will need to debug the behavior. That is why I have suggested adding debugging prints. What are the results after adding debugging prints? For more info on using prints to debug:


                        Unfortunately, in the support department at NinjaTrader it is against our policy to create, debug, or modify, code or logic for our clients. Further, we do not provide C# programming education services or one-on-one educational support in our NinjaScript Support department. This is so that we can maintain a high level of service for all of our clients as well as our associates.

                        That said, through email or on the forum we are happy to answer any questions you may have about NinjaScript if you decide to code this yourself. We are also happy to assist with finding resources in our help guide as well as simple examples, and we are happy to assist with guiding you through the debugging process to assist you with understanding unexpected behavior.

                        You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our NinjaTrader Ecosystem team to follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request or provide one-on-one educational services.

                        Thank you for your time and patience.​

                        Comment


                          #13
                          Thank you for all your help. I will do some more digging. I just want to figure out how to create support and resistance for my strategy.

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by NullPointStrategies, Today, 05:17 AM
                          0 responses
                          44 views
                          0 likes
                          Last Post NullPointStrategies  
                          Started by argusthome, 03-08-2026, 10:06 AM
                          0 responses
                          125 views
                          0 likes
                          Last Post argusthome  
                          Started by NabilKhattabi, 03-06-2026, 11:18 AM
                          0 responses
                          65 views
                          0 likes
                          Last Post NabilKhattabi  
                          Started by Deep42, 03-06-2026, 12:28 AM
                          0 responses
                          42 views
                          0 likes
                          Last Post Deep42
                          by Deep42
                           
                          Started by TheRealMorford, 03-05-2026, 06:15 PM
                          0 responses
                          46 views
                          0 likes
                          Last Post TheRealMorford  
                          Working...
                          X