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

Get drawn Object's color - Error on calling 'OnBarUpdate' method on bar 0

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

    Get drawn Object's color - Error on calling 'OnBarUpdate' method on bar 0

    Good evening,
    I need help. I am looking to get the color on the previous candle's drawn object color:

    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 MyCustomStrategy : Strategy
        {
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "MyCustomStrategy";
                    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;
                }
                else if (State == State.Configure)
                {
                }
            }
    
            protected override void OnBarUpdate()
            {
                //Add your custom strategy logic here.
                
                if(Plots[1].Brush == Brushes.Lime)
                {
                    Print("Its green!");
                    
                }
                
                if(Plots[1].Brush == Brushes.Red)
                {
                    Print("Its red!");
                    
                }
            
            }
        }
    }
    ​
    and I keep getting this same error. Basically, in like MQL4, I could look up the objects that were drawn on the chart and get their information. but I cant seem to find a way to get the previous candle's object's color information other than:

    Code:
            protected override void OnBarUpdate()
            {
                //Add your custom strategy logic here.
                
                if(Plots[1].Brush == Brushes.Lime)
                {
                    Print("Its green!");
                    
                }
                
                if(Plots[1].Brush == Brushes.Red)
                {
                    Print("Its red!");
                    
                }​


    Click image for larger version

Name:	image.png
Views:	64
Size:	3.0 KB
ID:	1294771
    (get the color of these arrows.. which I I think are really text.. but any drawing really)

    however, the Ninja says no...

    Strategy 'MyCustomStrategy': Error on calling 'OnBarUpdate' method on bar 0: Index was outside the bounds of the array.
    Please advise.
    Thank you!

    #2
    Hello Lele2k24,

    Thank you for your post.

    Are you trying to check the color for a drawing object that is drawn by another script?

    This is likely why you are getting an index error, since this strategy can't access plots drawn from another script. The Plots[] collection is empty, so there is no Plots[1] or Plots[0] value.

    I also recommend you check out this forum post on how to check the color of a plot:



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

    Comment


      #3
      Is there a way then to access plots from this indicator by a strategies? Thank you.

      Comment


        #4
        Hello Lele2k24,

        If the indicator's code has these plots exposed, it is possible to access the plot's values.

        Can you clarify, are you trying to access Plot values or draw objects drawn by an indicator (like the arrows in your screenshot)? Or something else?

        I look forward to your response.
        Gaby V.NinjaTrader Customer Service

        Comment


          #5
          That is correct. The plots should be exposed.. I would like to get the color of these triangles that the indicator prints to open and close positions on a strategy. Thanks again

          Comment


            #6
            The indicator plots these drawings

            Comment


              #7
              Hello Lele2k24,

              Do you have access to the code of this indicator? You can try printing the indicator's plot values and see what it is exposing for data. If one of the plots is a signal they're using for coloring, you can use that in your own strategy.

              If these are drawing objects (which it looks like) and not plots, you can loop through the collection of drawing objects and detect if there is an TriangleUp or TriangleDown. These look like TriangleUp and TriangleDown drawing objects.

              The Help Guide link has a code snippet demonstrating looping through the collection of drawing objects.



              MyIndicator myindy;

              myindy = MyIndicator();

              foreach (DrawingTool draw in myindy.DrawObjects.ToList())

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

              Comment


                #8
                Thank you. Is there a way to just look at the last entry in myindy.DrawObjects.ToList()) the once a bar closes?

                Or to access the number of objects that are on tge list so i can see when it chanes (a new object was drawn on the chart)

                MyIndicator myindy
                WHat doesnthis mean? Do i have to change this to my indicator name info?




                thanks again!!
                Last edited by Lele2k24; 03-09-2024, 08:04 AM.

                Comment


                  #9
                  Hello Lelesk24,

                  You can get the number of the draw objects drawn on the chart. There is a code snippet demonstrating in the previous link I shared.

                  Code:
                  protected override void OnBarUpdate()
                  {
                  if (DrawObjects.Count == 3)
                  {
                  // Do something
                  }
                  }



                  Code:
                  MyIndicator myindy
                  This is just example code, instead of this you would use whichever indicator you are counting the drawing objects from.

                  For example, if you were using the SMA:

                  SMA mySMA;

                  mySMA = SMA(14);

                  foreach (DrawingTool draw in mySMA.DrawObjects.ToList())​
                  Gaby V.NinjaTrader Customer Service

                  Comment


                    #10
                    Good morning.

                    I have tried the following:

                    Code:
                        foreach (DrawingTool draw in DrawObjects.ToList())
                                    {
                                    
                                    Print("number of drawings " + DrawObjects.Count);    
                                    if (draw is DrawingTools.TriangleUp)
                                    {
                                    Print ("Tag name: "+draw.Tag);
                                    DrawingTools.TriangleUp temp = draw as DrawingTools.TriangleUp;
                                        
                                    // check to see if it's the rectangle the indicator drew for the current date
                                    if (temp.Anchor.Time.Date == Time[1].Date)
                                    {
                                                    
                                        EnterLong(Convert.ToInt32(DefaultQuantity), @"OptimusBuy");
                                    }
                                    }//end of check for buy
                                                        
                                        
                                    else if (draw is DrawingTools.TriangleDown)
                                    {
                                    Print ("Tag name: "+draw.Tag);
                                    DrawingTools.TriangleDown temp = draw as DrawingTools.TriangleDown;
                                        
                                    // check to see if it's the rectangle the indicator drew for the current date
                                    if (temp.Anchor.Time.Date == Time[1].Date)
                                    {
                                                    
                                        EnterShort(Convert.ToInt32(DefaultQuantity), @"OptimusSell");
                                    }
                                    }//end of check for sell​

                    It prints out the number of objects.. but doesn't print out Print ("Tag name: "+draw.Tag); nor enter trades.. is there something that I am missing?

                    number of drawings 457
                    number of drawings 482
                    number of drawings 485
                    I have confirmed that the indicator draws the TriangleUp/TriangleDown. They are also tagged:"BuySig" and "SellSig"

                    Code:
                    Draw.TriangleUp(this, "BuySig", true, 0, Low[0] - TickSize, Brushes.Lime);
                    Code:
                    Draw.TriangleDown(this, "SellSig", true, 0, High[0] + TickSize, Brushes.Red);
                    and since they use the same tag, they move along the charts when a new triangle is down..so the time changes.. and that's what I want to check,,
                    I want to check if the triangle is an up triangle and if the time of the anchor matches the previous candle's time ( bar[1] ) since they are printed at the close of the candles

                    thank you!
                    Last edited by Lele2k24; 03-11-2024, 08:14 AM.

                    Comment


                      #11
                      Hello Lele2k24,

                      Thank you for your response.

                      The code to identify if the drawing object is an up triangle or a down triangle looks correct.

                      If you know the tag name, you could also identify it this way:

                      Code:
                      if (DrawObjects["BuySig"] != null && DrawObjects["someTag"] is DrawingTools.TriangleUp)
                      {
                      // Do something with the drawing tool line
                      }



                      Can you clarify what you mean by the anchor matching the time? You can see a list of all the IDrawingTool properties you can access in the following Help Guide link:





                      To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects 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


                        #12
                        thanks again! It looks like I had to close the chart and re-add it and its now doing everything I wanted. I do have a final question.

                        Code:
                                            if(Position.MarketPosition == MarketPosition.Flat)            
                                            EnterLong(Convert.ToInt32(DefaultQuantity), @"OptimusBuy");
                                            
                                            if(Position.MarketPosition == MarketPosition.Short)
                                              {
                                            ExitShort(Convert.ToInt32(DefaultQuantity), @"OptimusCloseSell", @"OptimusSell");
                                            EnterLong(Convert.ToInt32(DefaultQuantity), @"OptimusBuy");
                                            Print("long arrow on short trade " +DateTime.Now.ToString());
                                               }​

                        I have another strategy running on the same instrument, is there a way to check if only the trades entered by this strategy are counted? like if the position is flat for only this strategy?

                        thanks again!

                        Comment


                          #13
                          Hello Lele2k24,

                          When checking MarketPosition like how you are in the sample code, this is getting the market position for that strategy instance only. So you are only if Market Position is flat for this strategy only. Even if you have another strategy added to the chart, this is only returning the market position for this strategy instance.



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

                          Comment


                            #14
                            aslo,
                            I have a question..

                            why does this not work:



                            Code:
                            protected override void OnBarUpdate()
                                    {​
                                      int OldCount = 0;
                            .......

                            Code:
                            if(OldCount != DrawObjects.Count)
                            {
                            OldCount = DrawObjects.Count;
                            ​.....

                            i get:
                            Click image for larger version

Name:	image.png
Views:	17
Size:	4.2 KB
ID:	1295193
                            Click image for larger version

Name:	image.png
Views:	19
Size:	5.2 KB
ID:	1295192

                            thanks again!

                            Comment


                              #15
                              Hello,

                              Where is oldCount defined in relation to where this if statement is? If OldCount is defined locally and you are trying to access it from outside it's scope, you may receive this error.
                              Gaby V.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by poplagelu, Today, 05:00 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post poplagelu  
                              Started by fx.practic, 10-15-2013, 12:53 AM
                              5 responses
                              5,407 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  
                              Working...
                              X