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

MySharedMethodsAddonExample

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

    MySharedMethodsAddonExample

    I have been working with static variables as shown by the MySharedAddonExample that was posted by NT Support. Then I got the idea to create an event when a variable was change. Unfortunately I am struggling and am hoping some one could shed a little light on this. I have tried many things including INotifyPropertyChanged (appears it does not not work with static variables). Here are the latest two attempts. I have no preference, just trying to get anything to work which will alert when when a static variables value has changed.`

    Trigger a method call from the set property in the Addon. I am stuck in static and can't get out. Suggestions?
    PHP Code:
    namespace NinjaTrader.NinjaScript.AddOns
    {
        public 
    partial class MyTestAddon NinjaTrader.NinjaScript.AddOnBase
        
    {
            public static 
    DateTime zoneLastUpdateTime;
            public static 
    DateTime ZoneLastUpdateTime
            
    {
                
    get
                
    {
                    return 
    zoneLastUpdateTime;
                }
                
    set
                
    {
                    
    zoneLastUpdateTime value;
             
    NinjaTrader.NinjaScript.Indicators.MyTestAddonUpdate.Indicator_DateChanged();
                }
            }
        }
    }

    namespace 
    NinjaTrader.NinjaScript.Indicators
    {
        public class 
    MyTestAddonUpdate Indicator
        
    {
            protected 
    override void OnStateChange()
            {
                if (
    State == State.SetDefaults)
                {
                    
    Description                                    = @"Enter the description for your new custom Indicator here.";
                    
    Name                                        "MyTestAddonUpdate";
                    
    Calculate                                    Calculate.OnBarClose;
                    
    IsOverlay                                    false;
                    
    DisplayInDataBox                            true;
                    
    DrawOnPricePanel                            true;
                    
    DrawHorizontalGridLines                        true;
                    
    DrawVerticalGridLines                        true;
                    
    PaintPriceMarkers                            true;
                    
    ScaleJustification                            NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    
    //Disable this property if your indicator requires custom values that cumulate with each new market data event. 
                    //See Help Guide for additional information.
                    
    IsSuspendedWhileInactive                    true;
                }
                else if (
    State == State.Configure)
                {
                    
                }
            }

            
    internal static void Indicator_DateChanged()
            {
                
    //  How to get out of static?  Dispatcher?  Create new instance?

                
    NinjaTrader.Code.Output.Process("Indicator_DateChanged()"PrintTo.OutputTab1);
            }
            } 
    And then I tried to create an event. The EventHandler ZoneHasBeenUpdated is always null which suggests that the caller is not wired up correctly. Suggestions on how to fix.

    PHP Code:
    namespace NinjaTrader.NinjaScript.AddOns
    {
        public 
    partial class MyTestAddon NinjaTrader.NinjaScript.AddOnBase
        
    {
            public static 
    DateTime zoneLastUpdateTime;
            public static 
    DateTime ZoneLastUpdateTime
            
    {
                
    get
                
    {
                    return 
    zoneLastUpdateTime;
                }
                
    set
                
    {
                    
    zoneLastUpdateTime value;
                    
    //    This is in a new class.  Can only call a static method in a class
                    
    NinjaTrader.NinjaScript.Indicators.ClassStep1.Method1();
                }
            }
        }
    }

    namespace 
    NinjaTrader.NinjaScript.Indicators
    {
        public class 
    MyTestAddonUpdate Indicator
        
    {
            protected 
    override void OnStateChange()
            {
                if (
    State == State.SetDefaults)
                {
                    
    Description                                    = @"Enter the description for your new custom Indicator here.";
                    
    Name                                        "MyTestAddonUpdate";
                    
    Calculate                                    Calculate.OnBarClose;
                    
    IsOverlay                                    false;
                    
    DisplayInDataBox                            true;
                    
    DrawOnPricePanel                            true;
                    
    DrawHorizontalGridLines                        true;
                    
    DrawVerticalGridLines                        true;
                    
    PaintPriceMarkers                            true;
                    
    ScaleJustification                            NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    
    //Disable this property if your indicator requires custom values that cumulate with each new market data event. 
                    //See Help Guide for additional information.
                    
    IsSuspendedWhileInactive                    true;
                }
                else if (
    State == State.Configure)
                {
                    
    NinjaTrader.NinjaScript.Indicators.ClassStep2 objectToSubscribeTo = new NinjaTrader.NinjaScript.Indicators.ClassStep2();
                    
    objectToSubscribeTo.ZoneHasBeenUpdated += TestAlert;
                }
            }

            
            protected 
    void TestAlert(object senderEventArgs e)
            {
                Print(
    "TestAlert  static variable has been updated");
            }
            
            protected 
    override void OnBarUpdate()
            {
                
    NinjaTrader.NinjaScript.AddOns.MyTestAddon.ZoneLastUpdateTime Time[0];
            }
        }
        
        
        
        
    partial class ClassStep1
        
    {
            public static 
    void Method1()
            {
                
    ClassStep1 classStep1 = new ClassStep1();
                
    classStep1.Method2();
            }
            public 
    void Method2()
            {
                
    ClassStep2 classStep2 = new ClassStep2();
                
    classStep2.CreateEvent(EventArgs.Empty);
            }
        }
        
        public class 
    ClassStep2
        
    {
            public 
    event EventHandler ZoneHasBeenUpdated ;
            
            public 
    void CreateEventEventArgs e)
            {
                
    NinjaTrader.Code.Output.Process("ClassStep2:  CreateEvent()"PrintTo.OutputTab1);
                if(
    ZoneHasBeenUpdated != null)
                {
                    
    ZoneHasBeenUpdated(thisnull);
                }
                else
                    
    NinjaTrader.Code.Output.Process("   IS NULL"PrintTo.OutputTab1);
            }
        } 
    Many thanks to anyone that can offer up a fix.

    #2
    Hello TAJTrades,

    Thanks for the post.

    So all you need to do is implement a static event handler in the static class. You can then create an event method in your indicator to subscribe to changes to that variable.

    TestShareData:

    Code:
    namespace NinjaTrader.NinjaScript.AddOns
    {
    
    	public static class SharedData {
    		
    		public static event EventHandler PropChanged;
    		
    		private static double _testDouble;
    		public static double TestDouble { 
    			get{ return _testDouble; } 
    			set{
    				if(value != _testDouble){
    					
    					_testDouble = value;
    					
    					if(PropChanged != null){
    						PropChanged(null, EventArgs.Empty);
    						
    					}
    				}
    			} 
    		}
    	}
    	
    }
    Then add this to your indicator/strategy:

    Code:
    else if (State == State.Configure)
    			{
    				NinjaTrader.NinjaScript.AddOns.SharedData.PropChanged += OnPropChanged;
    			}
    
    
    void OnPropChanged(object o, EventArgs e){
    			 Print("Prop changed");
    		 }
    
    protected override void OnBarUpdate()
    		{
    		        NinjaTrader.NinjaScript.AddOns.SharedData.TestDouble = 100;
                            //Flip flop values to activate the event function.
    			NinjaTrader.NinjaScript.AddOns.SharedData.TestDouble = 200;			
    		}
    You will then be subscribed to changes in this property.

    Be sure to unsubscribe from the event in State.Terminated:

    Code:
    else if (State == State.Terminated)
        {
            NinjaTrader.NinjaScript.AddOns.SharedData.PropChanged -= OnPropChanged;
        }
    Please let us know if we may be of any further assistance.
    Last edited by NinjaTrader_ChrisL; 11-08-2017, 10:42 AM.
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Many thanks Chris.
      Off all the different routines I tried I never thought about a static event handler. I have never had a need for a static event in all the C# projects I have written. Learn something new everyday. Hopefully I can get this working and starting sending some trading business to Ninja

      Comment


        #4
        ChrisL, Works like a champ, exactly what I have been searching for.

        For those playing along, if you get a Thread Error calling a method within the Indicator like I did you may need an InvokeAsync to get back into the correct thread.

        if(ChartControl != null)
        ChartControl.Dispatcher.InvokeAsync((Action)(() => {MethodName()})));

        I have now created a dynamic toolbar for customized DrawingTools that enables a Selectable Global Draw Object. http://www.screencast.com/t/krSRj7LdART

        Many thanks again. Getting closer to opening a Ninja Broker Account.
        Last edited by TAJTrades; 11-08-2017, 04:03 PM.

        Comment


          #5

          Old thread but still relevant. Thanks to the original poster! The code is cleaned up a bit below and will return the value in the event parms.

          I trigger this from within an addon to broadcast information to all subscribing indicators.


          Addon code:
          Code:
           
          
          namespace NinjaTrader.NinjaScript.AddOns
          public static class EventClass 
              {
                  public static event EventHandler PropChanged;
                  private static double TestDoubleValue;
          
                  public static double TestDoubleEvent 
                  { 
                      get{ return TestDoubleValue; } 
                      set{
                              TestDoubleValue = value;
                              NinjaTrader.Code.Output.Process("Value in superdom event handler " + value, PrintTo.OutputTab1);
                              if(PropChanged != null){PropChanged(value, EventArgs.Empty);
                          }
                      } 
                  }
              }
          
          } // End namespace


          Indicator initialization

          Code:
              protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                      }
                      else if (State == State.Configure)
                      {
          
                          Print("subscribe to event");
                          EventClass.PropChanged += OnPropChanged; 
          
                      }
                      else if (State == State.Terminated)
                      {
          
                         //Unsubscribe from addon events 
                         EventClass.PropChanged -= OnPropChanged;
          
                      }
                  }


          Indicator event code

          Code:
              void OnPropChanged(object sender, EventArgs e){
                  EventValue = (double)sender;
                  Print("Event fired from within chart indicator. Prop changed to " + EventValue.ToString()   );
               }



          To trigger the event in all subscribing indicators execute this code in the addon (or from another indicator or wherever)

          Code:
          EventClass.TestDoubleEvent = 122;





          Comment


            #6
            Thanks, that's very useful code.

            Just be aware that when you recompile anything in NT it could lead to having two instances of the EventHandler and indicator instances before the compilation will not be able to communicate with indicators created after the compilation.

            https://ninjatrader.com/support/foru...lass-recompile

            I haven't tested it with a static class but when using a factory for singletons it caused issues.

            Comment


              #7
              Originally posted by Bidder View Post
              Old thread but still relevant. Thanks to the original poster! The code is cleaned up a bit below and will return the value in the event parms.
              You might want to add this, or a bool check, into your Termination

              Code:
              else if (State == State.Terminated)
              {
                   if(ChartControl == null) return;
                   //Unsubscribe from addon events
                   EventClass.PropChanged -= OnPropChanged;
              }
              State.Terminated is triggered multiple times thru a scripts lifecycle
              https://ninjatrader.com/support/help...fecycle_of.htm



              -=Edge=-
              NinjaTrader Ecosystem Vendor - High Tech Trading Analysis

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by sidlercom80, 10-28-2023, 08:49 AM
              171 responses
              2,275 views
              0 likes
              Last Post QuantKey_Bruce  
              Started by Irukandji, Yesterday, 02:53 AM
              2 responses
              17 views
              0 likes
              Last Post Irukandji  
              Started by adeelshahzad, Today, 03:54 AM
              0 responses
              3 views
              0 likes
              Last Post adeelshahzad  
              Started by CortexZenUSA, Today, 12:53 AM
              0 responses
              3 views
              0 likes
              Last Post CortexZenUSA  
              Started by CortexZenUSA, Today, 12:46 AM
              0 responses
              1 view
              0 likes
              Last Post CortexZenUSA  
              Working...
              X