NinjaScript Best Practices

View as Markdown

There are some best practices to be aware of when developing NinjaScript classes. The following tables present a non-exhaustive list of considerations to keep in mind when designing and implementing your code.

  • NinjaTrader is multi-threaded and event driven. Always assume that any of the methods you implement in NinjaScript could be called from another thread.

State management practices

Managing Resources

  • The OnStateChange() method is called anytime there has been a change of State and can be used to help you setup, manage, and destroy several types of resources. Where these values are setup is highly dependent on the kind of resource you are using. The section below will cover how to manage various resources throughout different states.

Setting Default UI Property Grid values

  • Reserve State.SetDefaults for defaulting any public properties you wish to have exposed on the UI property grid. You should also use this State for setting default desired NinjaScript property behavior which can be overridden from the property grid (e.g. Calculate, IsOverlay, etc.). For Plots and Lines you wish to configure, AddPlot(), AddLine() should also have their default values set during this State.

  • Why


  • Public values of the NinjaScript object in SetDefaults are pushed to the UI property grid for an opportunity to change settings of your object.
1// Best practice
2protected override void OnStateChange()
3{
4 // these are the values that show up as default on the UI
5 if (State == State.SetDefaults)
6 {
7 Calculate = Calculate.OnPriceChange;
8 IsOverlay = false;
9
10 Period = 50;
11
12 AddPlot(Brushes.Blue, "Plot Value");
13 AddLine(Brushes.Gray, 100, "Threshold");
14 }

For public properties you do NOT wish exposed to the UI property grid, set the Browsable attribute to false:

1// Best practice
2[Browsable(false)] // prevents from showing up on the UI property grid
3public int Communicator { get; set;

On indicators, properties you wish to set from other objects, set the NinjaScriptPropertyAttribute:

1// Best practice
2[NinjaScriptProperty] // can now call **MyIndicator**(20) from another object
3public int Period { get; set; }

The default behavior is to serialize any public properties and fields to a Workspace or Template file when saving. However, not all objects can be serialized - or you may wish to exclude a property from being saved and restored. For these scenarios, set the XmlIgnore attribute to the property:

1// Best practice
2[XmlIgnore] // removes from serialization
3public Brush DownBrush
4{ get; set; }

As a best practice as well, your NinjaScript should not have any public fields, since those would get serialized as well - which means their state would be persisted, which in turn could lead to unexpected outcomes.

  • See the Working with Brushes section of the Help Guide for information on properly serializing brushes.

Calculating run-time object values

Do not attempt to do advanced calculations or try to access object references in State.SetDefaults. This State should be kept as lean as possible, and any calculation logic should be delayed until at least State.Configure.

  • Why

1// Practice to avoid
2protected override void OnStateChange()
3{
4 if (State == State.SetDefaults)
5 {
6 // logic could take longer than desired as the list of indicator names is populated
7 for (int i = 0; i <= array.length; i++)
8 DoWork(i);
9
10 // possible null reference exception since **TickSize** is not set yet
11 Period = 5 * TickSize;
12 }
1// Best practice
2protected override void OnStateChange()
3{
4 // Complex operations should be delayed to >= State.Configure
5 if (State == State.Configure)
6 {
7 for (int i = 0; i <= array.length; i++)
8 DoWork(i);
9 }
10
11 // information related to market data is not available until at least State.DataLoaded
12 else if (State == State.DataLoaded)
13 {
14 Period = 5 * TickSize;
15 }
16}

Setting class level variables

Do not set variables at the class level unless they are constant. You should delay setting or resetting variables until the State has reached State.Configure. You can use const keyword to differentiate values which do not change from variables which do change.

  • Why

  • Waiting to set up and define resources until the object has been configured ensures that values not set up and declared prematurely.
1// Best practice
2// value is always 5, it can be made constant and declared at the class level
3private const int multiplier = 5;
4
5// these values can change, may be better to delay setting until State.Configure
6private int counter;
7private List<int> myList;
8
9protected override void OnStateChange()
10{
11 if (State == State.Configure)
12 {
13 counter = 0;
14 myList = new List<int>();
15 }

Resetting class level variables for Strategy Analyzer Optimization

To take advantage of performance optimizations, developers may need to reset class level variables in the strategy otherwise unexpected results can occur.

  • Why

  • When optimizing a strategy, instances may or may not be recycled depending on the strategy IsInstantiatedOnEachOptimizationIteration setting.
1// Best practice
2// examples of fields which need to be reset
3private double myDouble;
4private bool myBool;
5private DateTime myDateTime;
6private Order myOrderObject;
7private Brush myBrushObject;
8private Array myIntArray;
9private List<object> myList;
10private SMA mySMAIndicator;
11private Series<double> mySeries;
12
13protected override void OnStateChange()
14{
15 if (State == State.SetDefaults)
16 {
17 // disabled to take advantage of performance gains
18 // However any strategy state that would be mutable after State.SetDefaults needed to be reset for the next run.
19 IsInstantiatedOnEachOptimizationIteration = false;
20 }
21 else if (State == State.Configure)
22 {
23 // Since these values are not dependent on bars, they can be reset as early as State.Configure
24 myDouble = double.MinValue;
25 myBool = false;
26 myDateTime = DateTime.MinValue;
27 myOrderObject = null;
28 myBrushObject = null;
29
30 if (myIntArray != null)
31 Array.Clear(myIntArray, 0, myIntArray.Length);
32 else
33 myIntArray = new int[20];
34
35 if (myList != null)
36 myList.Clear();
37 else
38 myList = new List<object>();
39 }
40
41 else if (State == State.DataLoaded)
42 {
43 // Since these values do are dependent on bars, they should only reset during State.DataLoaded
44 mySMAIndicator = SMA(14);
45 mySeries = new Series<double>(this);
46 }

Do not attempt to access objects related to instrument market data until the State has reached State.DataLoaded.

  • Why

  • Waiting to access objects that depend on market data until DataLoaded prevents access errors in all scenarios.
1// Best practice
2protected override void OnStateChange()
3{
4 if (State == State.DataLoaded)
5 {
6 // these objects and their related members are not available until State.DataLoaded
7 Print(Bars.Count);
8 Print(Instrument.FullName);
9 Print(BarsPeriod.BarsPeriodType);
10 Print(TradingHours.TimeZon;
11 Print(Input);
12 }
13}
  • All additional data series must be added in State.Configure (this includes series that any hosted script potentially needs as well - more info). Since objects such as Instrument, BarsPeriod, TradingHours, etc. are NOT guaranteed to be available until State.DataLoaded, you cannot reliably use the primary instrument properties as arguments in AddDataSeries(). Attempting to add a data series dynamically is NOT guaranteed and therefore should be avoided. In some cases, you may be able to use a BarsRequest() to obtain market data for other instruments and intervals.

Setting up resources that rely on market data

For objects which depend on market data, delay their construction until the State has reached State.DataLoaded.

  • Why

  • Waiting to construct objects that depend on market data until DataLoaded ensures that their underlying input contains significant values in all scenarios.
1// Best practice
2// these resources depend on bars, wait until State.DataLoaded to instantiated
3private EMA myEMA;
4private Series<double> mySeries;
5private SessionIterator mySessionIterator;
6
7protected override void OnStateChange()
8{
9 if (State == State.DataLoaded)
10 {
11 myEMA = EMA(20);
12 mySeries = new Series<double>(this);
13 mySessionIterator = new SessionIterator(Bars);
14 }

Accessing element on the UI

For objects which exist on the UI (e.g., ChartControl, ChartPanel, ChartBars, NTWindow, etc.) wait until the State has reached State.Historical. This practice is correct for both reading properties or should you wish to add custom elements to the existing UI.

  • Why

  • NinjaTrader UI related objects are not guaranteed to be available until historical data processing has started.
1// Best practice
2protected override void OnStateChange()
3{
4 // wait until at least State.Historical
5 if (State == State.Historical)
6 {
7 // and double check UI object is not null before accessing
8 if (ChartControl != null)
9 {
10 Print(ChartControl.Properties.ChartBackground);
11 }
12 }
13}

Transitioning order references from historical to real-time

When dealing with strategy based orders which have transitioned from historical to real-time, you will need to ensure that locally stored order references are also updated.

  • Why

1// Best practice
2private Order entryOrder = null;
3
4protected override void OnBarUpdate()
5{
6 if (entryOrder == null && Close[0] > Open[0])
7 entryOrder = EnterLongLimit("myEntryOrder", Low[0]);
8}
9
10protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
11{
12 // One time only, as we transition from historical
13 // Convert any old historical order object references to the live order submitted to the real-time account
14 if (entryOrder != null && entryOrder.IsBacktestOrder && State == State.Realtime)
15 entryOrder = GetRealtimeOrder(entryOrder);
16
17 // Null entryOrder if filled or cancelled. We do not use the Order objects after the order is filled, so we can null it here
18 if (entryOrder != null && entryOrder == order)
19 {
20 if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
21 entryOrder = null;
22 if (order.OrderState == OrderState.Filled)
23 entryOrder = null;
24 }

Terminating custom resources

Use a flag to track when resources have been set up properly before attempting to destroy them.

  • Why

1// Best practice
2protected override void OnStateChange()
3{
4 if (State == State.Configure)
5 {
6 myObject = new object();
7 // set a flag to indicator object has been configured
8 configured = true;
9 }
10
11 else if (State == State.Terminated)
12 {
13 // only dispose of object if it has been configured
14 if (configured)
15 {
16 myObject.Dispose();
17 }
18 }
19}

Error handling practices

Safely accessing reference objects

Although there are documented States where objects are available, the implementation could change. If you are accessing a reference object, please do so by first checking that the object is not null.

1// Best practice
2
3// checking to ensure chart control is available in all situations
4// will help to ensure this logic below does not generate errors at a later time
5if(ChartControl != null)
6{
7 myBackgroundBrush = ChartControl.Properties.ChartBackground;
8}

Accessing objects which terminate

To protect against race conditions and access errors, you should temporarily check for reference errors any time you attempt to do something with an object.

  • Why

  • OnStateChange() runs asynchronous to other NinjaScript events. You can run into scenarios where you State.Terminated logic is called in the middle of OnBarUpdate(), OnRender() etc.
1// Best practice
2
3protected override void OnStateChange()
4{
5 // this logic runs asynchronously to other events
6 if (State == State.Terminated)
7 {
8 myObject = null;
9 }
10}
11protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
12{
13 if (myObject == null)
14 return;
15
16 // for safety, always check for null references before attempting to access an object
17 // even if you have once checked for null references earlier run-time
18 if (myObject != null)
19 myObject.DoSomething();
20}

Proving instructions for non-ninjascript properties

Do not attempt to modify existing UI “Properties” to meet your specific needs. These features are exposed to allow you to read the environment state and make decisions to alter how your code executes, but should not be relied on to modify settings on behalf of the user. While these objects from these classes have setters for technical reasons, you should not attempt to amend the values through code. Instead, you should issue warnings or log errors instructing users to modify settings when required:

  • Why

  • NinjaTrader makes no guarantee that the requested changes will take effect, and user settings always take precedences. This includes the user defined ChartControl.Properties, ChartBars.Properties, and ChartPanel.Properties. Furthermore, two different user scripts could be installed which also attempt to modify properties you are relying which could introduce conflicts.
1// Best practice
2if (State == State.Historical)
3{
4 if (ChartControl.Properties.EquidistantBarSpacing == true)
5 {
6 Draw.TextFixed(this, "error", "This indicator works best with Equidistant BarSpacing set to false.", TextPosition.BottomRight);
7 }
8}

Modifying UI elements and multi-threading

When interacting with UI objects, such as obtaining UI information, or modifying the existing layout, always use the NinjaScript’s Dispatcher asynchronously.

Value
Improper thread handling from a NinjaScript object is a common cause of application deadlocks. Please be sure to read more information on Multi-Threading Consideration for NinjaScript.
1// Best practice
2// using a Dispatcher will ensure that the corresponding action executes on the associated thread
3this.Dispatcher.InvokeAsync(() =>
4{
5 UserControlCollection.Add(new System.Windows.Controls.TextBlock
6 {
7 Text = "\nAdded by the ChartControl Dispatcher."
8 });
9});

Properly implementing try/catch blocks

Unless you are specifically debugging a method, the use of a try-catch block should be scoped to a particular area of logic. Do NOT try to handle all of your execution logic under one giant try-catch block.

  • Why

  • Larger try-catch blocks can not only be harder to debug, but can introduce performance issues at run-time.
1// Practice to avoid
2protected override void OnBarUpdate()
3{
4 try
5 {
6 // encapsulates entire OnBarUpdate logic
7 }
8 catch (Exception ex)
9 {
10 // attempt to handle all errors in one catch
11 }
12}

Using WPF brushes

Try to use a static predefined Brush if possible. If you need to customize a new brush object, make sure to .Freeze() the brush before using it.

  • Why

  • The pre-defined brushes are thread safe and do not require any special handling. Custom defined brushes, on the other hand, are NOT thread-safe and must be frozen otherwise cross-thread exceptions can occur.
1// Best practice
2// predefined brush
3BackBrush = Brushes.Blue;
4
5// if you are using a custom brush to e.g., modify the opacity
6SolidColorBrush opaqueBlue = new SolidColorBrush(Colors.Blue) {Opacity = .25f};
7
8// or just using at custom color not available in pre-defined brushes class
9SolidColorBrush coolGreen = new SolidColorBrush(Color.FromRgb(30, 255, 128));
10
11// you must freeze these brushes after they are constructed!
12opaqueBlue.Freeze();
13coolGreen.Freeze();

barsAgo indexer vs. absolute bar Index

As you probably know, you can quickly look up the bar value on the chart by calling a PriceSeries<t> barsAgo indexer, e.g., Close[0].

However, the internal indexer and pointers about the barsAgo value are only guaranteed to be correctly synced and updated during a market data event. As a result, you should favor using the absolute GetValueAt() methods during events which are not driven by price.

  • Why

  • Attempting to call the barsAgo indexer in an event method that is not driven by market data can yield unexpected results.
1// Best practice
2// OnRender is not a market data event; barsAgo pointers are not guaranteed to be in sync
3protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
4{
5 Print(mySMA.GetValueAt(CurrentBar));
6}
7
8// same is true for you custom events
9private void myCustomClickHandler(object sender, MouseButtonEventArgs e)
10{
11 Print(Close.GetValueAt(CurrentBar));
12}
Tip
If you have programming requirements which rely on a PriceSeries indexer, you can use the TriggerCustomEvent() delegate which will update the internal pointers and indexes before executing the logic you specify.

Casting safely

Avoid type casting and type conversion as much as possible. Casting from a mixed collection of types is also prone to exceptions especially in situations that may not occur when you originally test your code.

  • Why

  • The practice to avoid code below could work in some scenarios but would generate errors if other types were added to that collection that you were not anticipating.
1// Practice to avoid
2// This would run without errors if there were ONLY type HorizontalLine on the chart
3// But you risk a likely 'System.InvalidCastException' when other draw types are in that collection
4foreach (HorizontalLine hLine in DrawObjects)
5{
6}

If you must cast, do so safely and avoid implicit casts to types which may not be guaranteed to succeeded.

1// Best practice
2// Use the base IDrawingTool type and then cast to the desired type within the for loop
3foreach (IDrawingTool hLine in DrawObjects)
4{
5 // Note: to prevent further errors, your type casting should be done using the "as" keyword
6 // Opposed to a direct cast:
7 // HorizontalLine myLine = (HorizontalLine) hLine;
8
9 HorizontalLine myLine = hLine as HorizontalLine;
10
11 // This will allow you to ensure the cast actually occurred
12 if (myLine != null)
13 {
14 Print(myLine.StartAnchor.Price);
15 }

Performance practices

Referencing indicator methods

In general, when calling an Indicator return method, there is some internal caching which occurs by design to help reduce memory consumption.

  • Why

  • While the designed indicator caching improves general memory performance, there is an implied cost of actually looking up the cached indicator.
1// Practice to avoid
2// each time you call the SMA() return method there is a small performance cost
3// implied from the time it takes to look up the cached instance
4if (Close[0] > SMA(20)[0])
5{
6 Print(SMA(20)[0]);
7 EnterLongLimit(SMA(20)[0]);
8 Draw.Dot(this, Time[0].ToString(), false, 0, SMA(20)[0], Brushes.DarkGreen);

Indicator caching ONLY occurs when an indicator is recalled with the same EXACT parameters and input from the SAME calling script. (i.e. when a previously called indicator is called a second time with new parameters in the same script, a second instance will be created / cached).

If you are reusing an indicator several times through your code (especially indicators with many parameters), you can take further steps to refine performance by storing a reference to the indicator instance yourself (although it is by no means a requirement, and this suggestion does not need to be followed strictly).

1// Best practice
2
3private SMA mySma;
4
5protected override void OnStateChange()
6{
7 // when the indicator begins processing
8 // save an instance of the SMA indicator with the desired input
9 if (State == State.Historical)
10 {
11 mySma = SMA(20);
12 }
13}
14
15protected override void OnBarUpdate()
16{
17 // use the referenced mySMA throughout the lifetime of the script
18 if (Close[0] > mySma[0])
19 {
20 Print(mySma[0]);
21 EnterLongLimit(mySma[0]);
22 Draw.Dot(this, Time[0].ToString(), false, 0, mySma[0], Brushes.DarkGreen);
23 }

Marking object references for garbage collection

While it is not always necessary to set objects to null, doing so will mark them for garbage collection sooner and help prevent unnecessary memory resources from being utilized.

  • Why

  • In general you should be diligent to set stored memory objects to null when you are done using them, especially in situations where a NinjaScript object may be running for an extended period.
1// Best practice
2protected override void OnBarUpdate()
3{
4 // saving "myDot" creates an additional reference in memory
5 Dot myDot = Draw.Dot(this, "myDot" + CurrentBar, false, Time[0], Close[0], Brushes.Blue);
6
7 if (conditionToRemove)
8 {
9 // remove draw object will remove the object from the chart
10 RemoveDrawObject("myDot");
11
12 // but your local object "myDot" is still stored in memory.
13 // Explicitly setting to null will ensure object is marked for garbage collection
14 myDot = null;
15 }
16}

The example above demonstrates using a draw object, but the practice can be extended to any object you store in memory (e.g., orders, brushes, custom objects, etc).

Disposing of custom resources

Dispose of objects that inherit from IDisposable or put into a Using statement.

  • Why

  • NinjaTrader is not guaranteed to dispose of objects for you. To avoid unnecessary memory consumption, always manage your resources by creating a variable and dispose of the object.
1// Best practice
2// example of object instantiated which need to be disposed
3StreamWriter writer = new StreamWriter("some_file.txt");
4
5// use the object
6writer.WriteLine("Some text");
7
8// implements IDisposbile, make sure to call .Dispose() when finished
9writer.Dispose();
10
11// or put in "using" statement which implicitly calls .Dispose() when finished
12using (StreamWriter writer2 = new StreamWriter("some_file.txt"))
13{
14 writer2.WriteLine("Some text");
15}

Tip: This is most commonly applicable when using SharpDX resources for custom rendering. Please be sure to review the information on Best Practices for SharpDX Resources.

Avoiding duplicate calculations

Be mindful where and when your potentially complex calculations would be recalculated and thus run the risk of being calculated redundantly. For example, you may have logic which only needs to calculate, e.g., once per instance, once per session, once per bar, etc.

1// Best practice
2
3// get GetPreviousTradingDayEnd() is expensive to look up
4// but value only needs to be looked up once a day -> only calculate on first bar of session
5if (Bar.IsFirstBarOfSession)
6{
7 TradingHours.GetPreviousTradingDayEnd(Time[0]);
8}

The same considerations would apply to variables or function calls that would not change their output value for the currently processed bar on Calculate.OnEachTick or .OnPriceChange, thus there would be no need handling them outside of IsFirstTickOfBar.

1// Best practice
2// dedicated logic to cache the prior sum on each tick of bar
3// While it is a good practice, this can cause problems for bar types which may remove last bar (see below)
4if (IsFirstTickOfBar)
5 priorSum = sum;
6
7sum = priorSum + Input[0] - (CurrentBar >= Period ? Input[Period] : 0);
8Value[0] = sum / (CurrentBar < Period ? CurrentBar + 1 : Period);

Caching values on bars which remove last bar

Building on the previous example, be careful when caching values on the first tick of bar if using bars types which are IsRemoveLastBarSupported. To see how to handle these situations best, take a look at the default SMA indicator which has an additional logic branch which disables caching on those bar types:

1// Best practice
2 // logic below disables first tick of bar caching only on bar types which remove last bar
3if (BarsArray[0].BarsType.IsRemoveLastBarSupported)
4{
5 if (CurrentBar == 0)
6 Value[0] = Input[0];
7 else
8 {
9 double last = Value[1] * Math.Min(CurrentBar, Period);
10
11 if (CurrentBar >= Period)
12 Value[0] = (last + Input[0] - Input[Period]) / Math.Min(CurrentBar, Period);
13 else
14 Value[0] = ((last + Input[0]) / (Math.Min(CurrentBar, Period) + 1));
15 }

Precomputing values instead of calculating in OnRender()

To preserve good performance, always err on the side of caution if you are using OnRender for any calculation logic.

  • Why

  • OnRender() is called frequently as you interact with the Chart, which can cause calculations to occur much more often than the related market data events and can cause unnecessary spikes in CPU consumption.
1// Practice to avoid
2protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
3{
4 // continually recalling the same value methods is unnecessary in this situation
5 double myValue = Bars.GetClose(CurrentBar) + Bars.GetOpen(CurrentBar);
6
7 // render myValue
8}
1// Best practice
2private double myValue;
3
4protected override void OnBarUpdate()
5{
6 // myValue only needs to update when OnBarUpdate() is called
7 // and then can be passed to OnRender() for chart rendering purposes
8 myValue = Close[0] + Open[0];
9}
10
11protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
12{
13 // if needed, you can always check that myValue has actually been set
14 if (myValue > double.MinValue)
15 {
16 // render myValue
17 }
18}

Restricting OnRender() calculations to visible ChartBars

Use the ChartBars.FromIndex and ChartBars.ToIndex to limit calculations to only what is visible on the chart.

  • Why

  • Rendering should be reserved for rendering on what is visible on the Chart. Performing calculations on bar index which are not visible can cause random spikes in CPU consumption.
1// Best practice
2protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
3{
4 // restricting this loop to only the ChartBars.From/ToIndex limits the loop to only what is visible on the chart
5 for (int barIndex = ChartBars.FromIndex; barIndex <= ChartBars.ToIndex; barIndex++)
6 {
7 Print(ChartControl.GetSlotIndexByX(barIndex));
8 }
9}

Using DrawObjects vs custom graphics in OnRender()

When using Draw methods, a new instance of the Draw object is created including its custom rendering and calculation logic. These methods are convenient in many situations, but can quickly introduce performance issues if used too liberally. In some situations, you may see better performance for rendering via SharpDX in OnRender().

  • Why

  • Each draw object instance will see its own OnRender() called to render values. If you instead implement custom rendering in the your object, you would only see a single OnRender() call for your custom created graphics.
1// Practice to avoid
2protected override void OnBarUpdate()
3{
4 // this would draw a dot on every bar on the chart
5 // each instance would need to call its own OnRender() method
6 // not a very efficient use a draw method
7 Draw.Dot(this, "everyDot" + CurrentBar, false, 0, Close[0], Brushes.Blue);
8}

With just a little extra code (much less than what is in the Draw methods) custom SharpDX rendering greatly reduces CPU and Memory consumption. Please ensure a Direct2D1 factory would only be instantiated from OnRender() or OnRenderTargetChanged() (which run in the UI thread), as access from other threads outside those methods could cause a degradation in performance.

1// Best practice
2protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
3{
4 // achieves the same effect of drawing a dot on every bar
5 // but only needs to call your object's OnRender()
6 for (int index = ChartBars.FromIndex; index <= ChartBars.ToIndex; index++)
7 {
8 float price = chartScale.GetYByValue(Close.GetValueAt(index));
9 float bar = chartControl.GetXByBarIndex(ChartBars, index);
10 float radius = (float) chartControl.BarWidth;
11
12 SharpDX.Direct2D1.Ellipse dot = new SharpDX.Direct2D1.Ellipse(new SharpDX.Vector2(bar, price), radius, radius);
13
14 using (SharpDX.Direct2D1.SolidColorBrush brush = new SharpDX.Direct2D1.SolidColorBrush(RenderTarget, SharpDX.Color.Blue))
15 {
16 RenderTarget.FillEllipse(dot, brush);
17 }
18 }
19}

One of the advantages of using a Draw.Method is the returned Draw Objects contains metadata which could be used later (such as for obtain the bar index or price value of the dot later on). If you would use this metadata later on, using a Draw method would be in your best interests. However, if you are solely looking to render figures on a chart, favoring your custom SharpDX methods can drastically improve performance.

Responding to user events

Do NOT use OnRender() for purposes other than rendering. If you need events to hook into user interactions, consider adding your own event handler. The example below shows registering the ChartPanel MouseDown event and registering a custom WPF control.

  • Why

  • OnRender() may call more or less frequently than you anticipated. Using your own custom event handlers allows you control and isolate user event logic you are looking to capture.
1// Best practice
2protected override void OnStateChange()
3{
4 if (State == State.Historical)
5 {
6 // subscribe to chart panel mouse down event
7 if (ChartPanel != null) ChartPanel.MouseDown += DoUserClickedChartPanelEvent;
8
9 // subscribe to a custom UI element mouse down event
10 if (myWPFControl != null) myWPFControl.MouseDown += DoCustomWPFControlClickEvent;
11 }
12
13 else if (State == State.Terminated)
14 {
15 // remember to unsubscribe when finished
16 if (ChartPanel != null) ChartPanel.MouseDown -= DoUserClickedChartPanelEvent;
17 if (myWPFControl != null) myWPFControl.MouseDown -= DoCustomWPFControlClickEvent;
18 }
19}
20
21private void DoUserClickedChartPanelEvent(object sender, MouseButtonEventArgs e)
22{
23 Print("User clicked on the ChartPanel, executing custom mouse down logic...");
24}
25
26private void DoCustomWPFControlClickEvent(object sender, MouseButtonEventArgs e)
27{
28 Print("User clicked on my button, executing button logic...");
29}

Delaying logic for a particular time interval

Do NOT call Thread.Sleep() as it will lock the Instrument thread executing your NinjaScript object.

  • Why

  • Market data events exposed to NinjaScript run on the underlying Instrument thread pool shared by all Instruments. Sleeping the underlying thread of your object will cause the entire Instrument thread to sleep, adversely affecting other features using that same Instrument.
1// Practice to avoid
2protected override void OnBarUpdate()
3{
4 if (IsFirstTickOfBar && State == State.Realtime)
5 {
6 Print("Run some logic before:: " + DateTime.Now);
7 Thread.Sleep(5000); // sleeping the Instrument thread will have adverse effects on elements outside of your script!
8 Print("Run some logic after: " + DateTime.Now);
9 }
10}

Instead, try using a Timer object if you need to delay logic execution.

1// Best practice
2protected override void OnBarUpdate()
3{
4 if (IsFirstTickOfBar && State == State.Realtime)
5 {
6 // Instead of Thread.Sleep for, create a timer that runs at the desired interval
7 System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer {Interval = 5000};
8
9 // queue the "after" logic to run when the timer elapses
10 timer.Tick += delegate
11 {
12 timer.Stop(); // make sure to stop the timer to only fire ones (if desired)
13 Print("Run some logic after: " + DateTime.Now);
14 timer.Dispose(); // make sure to dispose of the timer
15 };
16
17 Print("Run some logic before: " + DateTime.Now);
18
19 timer.Start(); // start the timer immediately following the "before" logic
20 }

Miscellaneous practices

Floating-point comparison

Be aware of floating-point precision problems. It can sometimes be more reliable to check within a certain degree of tolerance, such as the TickSize.

  • Why

1// Practice to avoid
2
3// depending on how Value[0] was calculated, it could be off by a degree of floating points
4// where this logic below would never be true
5// e.g., 2050.2499999 vs 2050.50
6if (Value[0] == Close[0])
7{
8 // do something
9}
1// Best practice
2
3// you can avoid these precision issues by rewriting the comparison to evaluate within a certain tolerance.
4if (Math.Abs(Value[0] - Close[0]) < TickSize)
5{
6 // do something
7}
8
9// You will also see NinjaTrader developed objects use a custom Extension Method
10// double.ApproxCompare() which Returns an int based on a Epsilon value:
11if (Close[0].ApproxCompare(Value[0]) == 0)
12{
13 // do something
14}

Creating user defined parameter types / enums

When creating enums for your NinjaScript objects, it is strongly suggested to define those outside the class and in a custom namespace. A reference sample providing all details could be found here.

Efficiently debugging

Extremely liberal use of Log() and Print() methods can represent a performance hit on your PC as it takes memory and time to process each one of those method calls. When running custom NinjaScript, especially when using Calculate = Calculate.OnEachTick, please be mindful of how often Log() and Print() methods are processed as it can quickly consume PC resources.

  • Log() method should not be used except for critical messages as each log entry makes it to the Control Center log which stays active till the end of the day. Excessive logging can result in huge amounts of memory being allocated just to display all the log messages which would mean less memory for NinjaTrader to do other tasks.
  • Print() method can be used more liberally than the Log() method, but can still represent a performance hit if used with extremely high frequency. Consider decreasing the printing from your script if you experience slowdowns when running the script.

Debug Mode

The debug mode should only be used if you are actively debugging a script and attached to a debugger.

Why
Debug Mode will compile all of the files in the custom project as a “Debug” build, which omits certain optimizations which occur in the C# compilation process. It is more efficient to use your custom objects in the default “Release” build if you are using your scripts during production.

To disable Debug Mode:

  • Right mouse click in any NinjaScript Editor
  • Ensure the “Debug Mode” menu item is unchecked
  • Press F5 to recompile your scripts
  • Your scripts will be re-built using “Release” mode

Known NinjaScript Wrappers limitations

  • The NinjaScript editor detects code changes in external editors, and will compile on code changes, however code will only be automatically generated by the NinjaScript editor if it’s edited within the NinjaScript editor itself (or Visual Studio).
  • Wrappers cannot be generated automatically for partial and abstract classes.
  • Code in the Properties region of the NinjaScript object cannot be commented out with the /**/ style commenting, as it will cause issues with the wrapper generation. Code must be commented out with the // style.
  • Subclassing would not allow for wrappers to be generated.