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

How to find all DrawObjects. Not always working.

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

    How to find all DrawObjects. Not always working.

    Hello everyone!

    I want to find all the "ExtendedLine" lines on the chart and use this code:

    Code:
                    
                    int        size    = s.DrawObjects.Count;
    
                    Print("size: "+size.ToString());
                    if (size > 0){
                        foreach (DrawingTool draw in s.DrawObjects.ToList()){
                            if (draw is DrawingTools.ExtendedLine){
                                Print ("Tag name: "+draw.Tag);
    
                                DrawingTools.ExtendedLine temp = draw as DrawingTools.ExtendedLine;
    
                                Print("startY: " + temp.StartAnchor.Price);
                                Print("startX: " + temp.StartAnchor.Time);
    
                                Print("endY: " + temp.EndAnchor.Price);
                                Print("endX: " + temp.EndAnchor.Time);
    
                            }
                        }
                    }
    This code does not find all lines on the chart. For example, the size is 2, but it did not define these two lines, which were added before I added the strategy. Take a look please at the screenshot below:
    Click image for larger version  Name:	Obj1.jpg Views:	0 Size:	155.3 KB ID:	1102033

    Next, I add another the same line - and the code already defines this line. As you can see, the size is already 3, but only the last line is defined as "DrawingTools.ExtendedLine":
    Click image for larger version  Name:	Obj2.jpg Views:	0 Size:	185.3 KB ID:	1102034

    Next, I go into the settings of one of the lines, add a new character to Tag, delete this new character (so that the Apply button becomes active). I click apply. Now the code sees and distinguishes all three lines:
    Click image for larger version  Name:	Obj3.jpg Views:	0 Size:	258.9 KB ID:	1102035

    Comment:
    The strategy always sees these lines, but not always a successful check:
    Code:
    if (draw is DrawingTools.ExtendedLine)

    Question:
    What is it and why?
    How can I achieve stable operation of this function without additional obscure actions?
    Last edited by webus; 05-27-2020, 02:15 PM.

    #2
    Hello webus,

    If you are specifically seeing this fail at the cast to ExtendedLine that may relate to how drawing tools work in different contexts. Generally you will need to use dynamic type rather than casting here. We have a small example on this topic in the following link, I would suggest giving this a try and see if that works for this use case. If not can you post a small sample of the code you used and steps to see the problem so I can try it?

    Take note in the sample how a string is used rather than a cast to tell if the object IS a type. Later you never cast to the type, you just use dynamic which has "any" property.

    JesseNinjaTrader Customer Service

    Comment


      #3
      Hi NinjaTrader_Jesse,

      Originally posted by NinjaTrader_Jesse View Post
      Hello webus,

      If you are specifically seeing this fail at the cast to ExtendedLine that may relate to how drawing tools work in different contexts. Generally you will need to use dynamic type rather than casting here. We have a small example on this topic in the following link, I would suggest giving this a try and see if that works for this use case.
      Take note in the sample how a string is used rather than a cast to tell if the object IS a type. Later you never cast to the type, you just use dynamic which has "any" property.
      https://ninjatrader.com/support/help...htsub=consider
      I found a way to check by .Name, but this is not a convenient way. I will try what you describe a little later.

      Originally posted by NinjaTrader_Jesse View Post
      Hello webus,
      If not can you post a small sample of the code you used and steps to see the problem so I can try it?
      But I have already described the code that I use. I took it on the forum, it was provided by a member of your team.
      You need to insert it into OnBarUpdate (or please use JesseLinesSample.zip) and follow the steps that I described in the last letter.
      In brief again:
      1. First add lines to the fast chart (so that logging would happen often).
      2. Run the strategy with my code. You will see that the size corresponds to the number of lines, which means that the Strategy sees these lines. But the check "if (draw is DrawingTools.ExtendedLine)" does not pass. Although these lines are ExtendedLine.
      3. While the Strategy is working, add another line and you will see that the Strategy recognized a new same line, and the previous ones still do not recognize it as ExtendedLine.
      4. Open the settings of one of the lines and just click "OK" - you will see that now the strategy recognizes all lines as ExtendedLine.

      My question is:
      Why is this happening and what are these not logical results?

      Attached Files
      Last edited by webus; 05-28-2020, 02:17 AM.

      Comment


        #4
        Hi NinjaTrader_Jesse,

        Originally posted by NinjaTrader_Jesse View Post
        Hello webus,

        Take note in the sample how a string is used rather than a cast to tell if the object IS a type. Later you never cast to the type, you just use dynamic which has "any" property.

        https://ninjatrader.com/support/help...htsub=consider
        Ok, I tried using your method. Here is the code:

        Code:
                protected override void OnBarUpdate()
                {
        
                    if (
                        CurrentBars[0] < 1 ||
                        State == State.Historical
                        ) return;
        
        
                    int        size    = DrawObjects.Count;
        
                    Print("size: "+size.ToString());
                      foreach(ExtendedLine line in DrawObjects){
                      // Print the tag of each ExtendedLine on the chart
                        Print(String.Format("ExtendedLine{0} found.", line.Tag));
                      }
                }
        I still draw the lines first, and only then run the strategy.
        Now I get a new error, which is described in russian:
        HTML Code:
        Enabling NinjaScript strategy 'JesseLines/201594692' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
        size: 2
        Strategy 'JesseLines': Error on calling 'OnBarUpdate' method on bar 27314: Невозможно выполнить приведение [A]NinjaTrader.NinjaScript.DrawingTools.ExtendedLine к [B]NinjaTrader.NinjaScript.DrawingTools.ExtendedLine. Источником типа A является "f364c88032624bf0af2937a45907451f, Version=8.0.22.0, Culture=neutral, PublicKeyToken=null" в контексте "LoadFrom" в расположении "C:\Users\Lenovo\Documents\NinjaTrader 8\tmp\f364c88032624bf0af2937a45907451f.dll". Источником типа B является "adbc5887342742219f69e85e47b18b18, Version=8.0.22.0, Culture=neutral, PublicKeyToken=null" в контексте "LoadFrom" в расположении "C:\Users\Lenovo\Documents\NinjaTrader 8\tmp\adbc5887342742219f69e85e47b18b18.dll".
        Disabling NinjaScript strategy 'JesseLines/201594692'
        Questions:
        1. Did you mean this example?
        2. What does "Cannot cast [A] NinjaTrader.NinjaScript.DrawingTools.ExtendedLine to [B] NinjaTrader.NinjaScript.DrawingTools.ExtendedLine" mean?

        Comment


          #5
          Hello

          Ok, I tried using your method. Here is the code:
          This is the example of what not to use. The following is what would be used with dynamic type:

          Code:
          foreach (dynamic line in DrawObjects.ToList())
          {
            // Use ToString().Equals() to detect the object's Type
            if (line.ToString().Equals("NinjaTrader.NinjaScript.DrawingTools.ExtendedLine"))
            {
                // Access the object by assuming that it is the Type we expect
                Print(String.Format("ExtendedLine Line {0} detected!", line.Tag));
            }
          }

          Please try this in your test and see if using the type as a string will allow for the objects to be used. I tried the sample however I can only see the correct count and other prints when it runs the first realtime bar after adding the strategy.

          In general this collection is not expected to be in sync with your script as this is the charts drawing object collection so there can be some odd situations around this collections use. This will happen when using exported assemblies and also happens with using third party objects, in this situation with the standard tool and as source code the cast generally should work however if it is not you can instead use dynamic.

          What does "Cannot cast [A] NinjaTrader.NinjaScript.DrawingTools.ExtendedLine to [B] NinjaTrader.NinjaScript.DrawingTools.ExtendedLine" mean?
          This is a situation where dynamic is needed, you would see this if you tried to use your sample as an exported assembly.

          JesseNinjaTrader Customer Service

          Comment


            #6
            Hi NinjaTrader_Jesse,

            Originally posted by NinjaTrader_Jesse View Post
            The following is what would be used with dynamic type:

            Code:
            foreach (dynamic line in DrawObjects.ToList())
            {
            // Use ToString().Equals() to detect the object's Type
            if (line.ToString().Equals("NinjaTrader.NinjaScript.DrawingTools.ExtendedLine"))
            {
            // Access the object by assuming that it is the Type we expect
            Print(String.Format("ExtendedLine Line {0} detected!", line.Tag));
            }
            }
            Please try this in your test and see if using the type as a string will allow for the objects to be used.
            This method works. But can I, for example, change the color for the line found in this way?


            Originally posted by NinjaTrader_Jesse View Post

            I tried the sample however I can only see the correct count and other prints when it runs the first realtime bar after adding the strategy.
            I wanted to record a video for you how I get this error, but I can no longer get it using the same code. I don’t know what is the reason, and this bothers me the most, since it seems that the terminal is not stable and lives its own life. I can’t be sure that code that works stably today will not produce critical errors tomorrow.


            Originally posted by NinjaTrader_Jesse View Post
            In general this collection is not expected to be in sync with your script as this is the charts drawing object collection so there can be some odd situations around this collections use. This will happen when using exported assemblies and also happens with using third party objects, in this situation with the standard tool and as source code the cast generally should work however if it is not you can instead use dynamic.

            This is a situation where dynamic is needed, you would see this if you tried to use your sample as an exported assembly.
            When I get this error - the strategy can recognize these lines only as DrawingTools. I can not change color, etc.

            Comment


              #7
              Hello webus,

              This method works. But can I, for example, change the color for the line found in this way?
              Yes, you can access any properties of the object. You can read about Dynamic here: https://docs.microsoft.com/en-us/dot...g-type-dynamic

              I wanted to record a video for you how I get this error, but I can no longer get it using the same code. I don’t know what is the reason, and this bothers me the most, since it seems that the terminal is not stable and lives its own life. I can’t be sure that code that works stably today will not produce critical errors tomorrow.
              I couldnt really say what may have been happening without more details here. If you run into the situation again try and collect the steps you used to see that happen and we can explore why. There are situations where type casting is expected to not work so its possible you had run into that. Using dynamic is the suggested way to access objects in the multi assembly context.


              When I get this error - the strategy can recognize these lines only as DrawingTools. I can not change color, etc.
              Right, if you use type casts that will fail because its not the same type. If you have MyDrawingToolType in assembly A but it also exists in assembly B, they are not the same type and cannot be cast to that type. You can use a string representation of the type to compare it in that case and dynamic to access properties without a firm type.
              JesseNinjaTrader Customer Service

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by algospoke, Yesterday, 06:40 PM
              2 responses
              18 views
              0 likes
              Last Post algospoke  
              Started by ghoul, Today, 06:02 PM
              3 responses
              14 views
              0 likes
              Last Post NinjaTrader_Manfred  
              Started by jeronymite, 04-12-2024, 04:26 PM
              3 responses
              44 views
              0 likes
              Last Post jeronymite  
              Started by Barry Milan, Yesterday, 10:35 PM
              7 responses
              20 views
              0 likes
              Last Post NinjaTrader_Manfred  
              Started by AttiM, 02-14-2024, 05:20 PM
              10 responses
              180 views
              0 likes
              Last Post jeronymite  
              Working...
              X