NinjaTrader Ninjascript, C# & Algo Trading

NinjaTrader is a great trading platform. Previously NinjaTrader was not available freely. Sometimes back the NinjaTrader people decided to make the platform free. This is a great decision which will help retail traders alot who are interested in developing powerful algo trading system. NinjaTrader uses Ninjascript for indicator and strategy development. Ninjascript is C#. C# is a powerful modern object oriented programming language that is owned by Microsoft. C# is being heavily used in game development and mobile app development. So learning C# will open many avenues for you including developing indicators and strategies on NinjaTrader. I plan to write a series of post on C# and NinjaTrader. C# is a very versatile programming language that has been open sources by Microsoft recently. You can take a look at my course C# for Traders. Learning C# is not easy of course as compared to R and Python. Below is the 60 minute Point and Figure Chart:

Kagi Chart

If you have been trading on MT4/MT5 and ignoring Ninja Trader, you should take a look at Ninja Trader 8 platform. It is great. I am also new to Ninja Trader but I have decided to explore it more, learn it and start using it.MT4 has very limited options available. We cannot go below 1 minute timeframe. If we want to go below 1 minute timeframe we need to use the tick data and construct the charts which is not easy for most traders who have no programming experience. Now on NinjaTrader we can have Tick Charts, Volume Charts, Range Charts, Kagi Charts, Candlestick Charts as well as Point and Figure charts. So you can see we have a lot more options as compared to MT4. Did you read the post on the economic indicators that move financial markets? Below is the 60 minute Kagi Chart:

Kagi Chart

In this post we will try to develop a simple trading indicator on Ninja Trader. Ninja Trader indicator development requires NinjaScript which is a subset of C#. C# is a powerful modern object oriented programming language. Learning C# will help you develop cross platform apps as well as a lot of other things. So the effort you put in learning C# for developing Ninja Trader indicators will provide you with skills that you can use on other areas as well.

using Deedle;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program1
{
    class Program
    {
        //this is where the program starts
        static void Main(string[] args)
        {

            //Console.SetWindowSize(100, 50);

            // Read in the raw dataset
            // TODO: change the path to point to your data directory
            string dataDirPath = @"D:/Shared/MarketData/";

            // Load the data into a dataframe
            string rawDataPath = Path.Combine(dataDirPath, "GBPUSD#60.csv");
            Console.WriteLine("Loading {0}\n", rawDataPath);
            var ohlc = Frame.ReadCsv(
                rawDataPath,
                hasHeaders: false,
                schema: "String,String,float,float,float,float,int",
                inferTypes: false
            );
            // Print the data
            Console.WriteLine("-- OHLCV Data --");
            ohlc.Print();

            //Rename Columns
            var ohlcv=ohlc.IndexColumnsWith(new[] { "Date", "Time", "Open",
                           "High", "Low", "Close", "Volume" });
            Console.WriteLine("-- After Naming Columns --");
            ohlcv.Print();
            // Compute Daily Returns
            ohlcv.AddColumn(
                "DailyReturn",
                ohlcv["Close"].Diff(1) / ohlcv["Close"] * 100.0);

            // Encode Target Variable - Predict Next Daily Return
           ohlcv.AddColumn(
                "Target",
                ohlcv["DailyReturn"].Shift(-1)
            );

            ohlcv.Print();
            /*
            // Save OHLC data
            string ohlcDataPath = Path.Combine(dataDirPath, "GBPUSD.csv");
            Console.WriteLine("\nSaving OHLC data to {0}\n", rawDataPath);
            rawDF.SaveCsv(ohlcDataPath);

            Console.WriteLine("DONE!!");
            */
            Console.ReadKey();
        }
    }
}

Above is my attempt to read a historical OHLCV price data file downloaded from MT4 history center into C#. When it comes to data science R and Python are great. C# may not be that good at data science. I am new to C# so I can be wrong as well. This is the problem that I have been facing. The first column is the date column and the second column is the time column. I used Deedle a C# package for dealing with dataframes. Pandas is great when it comes to dealing with dataframes. R also have great libraries for dealing with dataframes. I am unable to find a method that can take the first two columns and merge them into one so that I can convert that column into DateTime index. This is very easy to do in R and Python. Deedle is not as powerful as compared to Pandas. Now don’t worry at all. We can embed R and Python code in C#. More on that in future posts. Do we really need to read a csv file? Not really. It was just for educational purposes. So let’s move on. Read the post on are high frequency price returns normally distributed. This is what we can easily do. We can develop R and Python scripts and call them from within Ninjascript code which is infact C#. Let’s develop an R indicator.

How to Develop NinjaTrader Indicators?

The code is divided into regions. We can collapse and uncollapse the regions. Most of the time we will collapse them. The namespace NinjaTrader.NinjaScript.Indicators is specific to Ninjascript. We will always use this namepace if we want to develop indicators. How do you develop NinjaTrader indicators. We can use the Wizard. Open the NinjaTrader. Then click on New menu. Then click on NinjaScript Editor. On the right panel there are many folders that we will discuss one by one. One is Indicators. Right click on it and then click on New Indicator. We will use New Indicator Wizard to develop new indicators. NinjaScript Editor will automatically code the indicator basic C# code. We will then use that basic code to further develop our indicator. At the end there is #region NinjaScript generated code. Neither change nor remove. This code we don’t touch and change. This code is generated by NinjaScript Editor for its internal use and we don’t need to touch and change it. Did you read the post on Random Walk with GBPUSD? Below is the basic C# code that has been generated by NinjaScript Editor.

#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion

//This namespace holds Indicators in this folder and is required. Do not change it. 
namespace NinjaTrader.NinjaScript.Indicators
{
	public class RInd1 : Indicator
	{
		protected override void OnStateChange()
		{
			if (State == State.SetDefaults)
			{
			Description		= @"R Indicator";
			Name			= "RInd1";
			Calculate		= Calculate.OnBarClose;
			IsOverlay		= false;
			DisplayInDataBox	= false;
			DrawOnPricePanel        = false;
			DrawHorizontalGridLines	= false;
			DrawVerticalGridLines	= false;
			PaintPriceMarkers	= false;
			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)
			{
			}
		}

		protected override void OnBarUpdate()
		{
            //Add your custom indicator logic here.
            //define window length
            int length = 100;
            Double[] closeCopy = new Double[length];
            for (int k = 0; k <= length; k++)
            {
                closeCopy[k] = Close[k];
            }
            
            Array.Reverse(closeCopy);
            Print(closeCopy[10]);

        }
	}
}

#region NinjaScript generated code. Neither change nor remove.

namespace NinjaTrader.NinjaScript.Indicators
{
	public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
	{
		private RInd1[] cacheRInd1;
		public RInd1 RInd1()
		{
			return RInd1(Input);
		}

		public RInd1 RInd1(ISeries input)
		{
			if (cacheRInd1 != null)
				for (int idx = 0; idx < cacheRInd1.Length; idx++)
				if (cacheRInd1[idx] != null &&  cacheRInd1[idx].EqualsInput(input))
						return cacheRInd1[idx];
			return CacheIndicator(new RInd1(), input, ref cacheRInd1);
		}
	}
}

namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
	public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
	{
		public Indicators.RInd1 RInd1()
		{
			return indicator.RInd1(Input);
		}

		public Indicators.RInd1 RInd1(ISeries input )
		{
			return indicator.RInd1(input);
		}
	}
}

namespace NinjaTrader.NinjaScript.Strategies
{
	public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
	{
		public Indicators.RInd1 RInd1()
		{
			return indicator.RInd1(Input);
		}

		public Indicators.RInd1 RInd1(ISeries input )
		{
			return indicator.RInd1(input);
		}
	}
}

#endregion

As you can see Ninjascript which is infact C# code looks quite daunting and complicated. Coding a NinjaTrader indicator requires a lot of experience as compared to coding a MT4 indicator. But these things should not daunt as with practice we will be able to improve our skill level. At the top we have the declarations region which tell the compiler the namespaces we will be using. Namespace is just like a library in Python. Namespace is a collection of related classes that we bundle together so that we can use them. For example System is an important namespace that is used a lot in C# as it contains a lot of basic classes that we need like the System.IO. Did you take a look at my course C# Machine Learning for Traders.

Published
Categorized as Forex