06.06.2020 15.42

Algorithmic Trading with NinjaTrader


Going through our code step by step I'm still not sure about  OnStateChange() part, what it actually is needed for:

        protected override void OnStateChange()


            if (State == State.SetDefaults) // ? what does it do ?





            else if (State == State.Configure)  // ? If user presses OK button of strategy property window ?


                _diPlus = DiPlus(DiPeriod);

                _diMinus = DiMinus(DiPeriod);





            else if (State == State.Terminated) // what does it do ?




  • Yuri Zolotarev
    06.06.2020 15:59

    OnStateChange method is called by NinjaTrader occasionally under certain circumstances:

    1) If the state of change is OnStateDefault then it is called when you open the UI where the indicator or the strategy is located. So it makes sense to put in your default settings here that you want to see once you actually click on the strategy or indicator in the list. If you don't create a name for your strategy here you simply won't see it. If you don't create the default parameters here your strategy will come up with everything set to zeros.

    2) State.Configures is called once you press apply or ok and is called only once. This is useful to call things like

    - clearing the output from the text that is not needed

    - resetting defaults to a new parameter value, so, for example, you have TraceOrders set to false by default but you want to get it to reset to a new value using your parameters once you initialize your strategy

    - checking parameter settings set by the user and making changes in the logic according to them eg. user sets trail on and forgets to set stop on that has to be on if trail is on so in this spot you can check for if trail is on and set stop on if its off programmatically

    3) State.DataLoaded - create all your indicators here to make sure they calculate on data that has been loaded

    4) State.Terminated - get used of all unwanted objects here like if you created any extra UI elements you would get rid of them here otherwise they won't get off the screen. Also, you can try and use this spot for crash instances although I am not sure if Ninja would call this State if it actually crashes or the strategy terminates in an unwanted way

    5) State.Realtime - do things here when state changes from historical to realtime

    So OnStateChange event provides the user with the ability to hook up to Ninja at point of change in state eg. we were historical and now we care realtime so in between is the OnStateChange process.

    Hope this helps!

  • Frank
    06.06.2020 17:49

    Yes now it's clear with your flow of events explanation :)

    B4 I read myself through the given info in Ninja help docs ... but it was kinda dry and didn't make click 4 me what the actual context is.

  • Yuri Zolotarev
    07.06.2020 17:31