In the following discussion, ‘analysis technique initialized event’ and ‘analysis technique initialized event handler’ refer to the self.initialized Event.
For code you wish to run only once at startup, are there any important differences to keep in mind when using:
- Once begin
- method void AnalysisTechnique_Initialized( elsystem.Object sender, elsystem.InitializedEventArgs args ) begin
The “once” block and analysis technique initialized event handler are very similar and either one can be used to initialize objects. The important thing to note is that the analysis technique initialized event handler is not guaranteed to run before any other event handlers that have been setup. However, the analysis technique initialized event handler is guaranteed to run before the code outside of methods runs.
Shown below is a summary of the code run sequence when the analysis technique is enabled/turned on:
- Designer Generated Code (DGC) runs first, if there is any DGC. If you have assigned event handlers to the Analysis Technique or have used components from the ToolBox, DGC is created. If you do not want to have DGC, you can do your object setup in a “once” block and not use any components from the ToolBox.
- Any event handler assigned in the DGC (including the analysis technique initialized event handler, if assigned) can run now depending on when the events occur. There is no control at this point as to the order of the events – i.e., as events occur (including the analysis technique initialized event), the handlers will be called and the code in those handlers will run. Important to note is that the analysis technique initialized event is NOT guaranteed to run before any other event handler runs.
- Once the analysis technique initialized event is complete (if assigned), the code outside of methods can run on historical bars and/or when ticks arrive. This includes any code in the “once” block.
Based on the discussion above, you can see that it is important to assign event handlers at the proper time or problems may occur. For example, if an event handler is assigned prior to getting the object properly setup, an error can occur if the event occurs and the event handler is called. Also, other objects/events may depend on another object being properly set up. You will have to take into consideration when you want to assign event handlers.
An approach that may help to minimize potential problems due to event handler assignment is to assign the event handlers at the end of the code in the “once” block or at the end of the code in the analysis technique initialized event handler, whichever one you use for initialization. If you assign event handlers in your code, it is important that the event handler is NOT assigned in the Property Editor. If an event handler is assigned in the Property Editor, the event handler will be set up when the DGC code runs (which is first).