Creating a Signal Library for Automated Trade Systems in NinjaScript
Learn how to create a custom class in C#/NinjaScript to define your trade strategy’s logic by building an EMA breakout strategy. Build a library of signals to streamline development and research.
Today, we will cover how to turn our individual strategy logic into a custom class for use inside a NinjaScript trading strategy. Why would you want to do this? There are several reasons, and if you have been reading any of the recent posts, you already know what I am going to say.
Creating a custom class to encapsulate our strategy logic helps us create a modular piece of code that can be reused easily. It enforces organization and improves testing and debugging capabilities. It’s inherently scalable and allows us to use multiple signals without having all our code live in a single strategy file. If that wasn’t enough, it also encourages best code development practices and makes collaboration and version control easier.
For the example, I will create a simple EMA breakout strategy. The strategy logic is: - Enter long/short when the previous bar closes over/under the EMA. - Exit long/short when the previous bar closes under/over the EMA.
We will break this logic up into 4 different signals. That allows us flexibility when we code the actual strategy. We can use the exit signals for trading or implement any of the previous exit strategies we discussed in HGT.
This strategy will use the custom evaluator methods we created in the previous post.
Disclaimer: the following post is an organized representation of my research and project notes. It doesn’t represent any type of advice, financial or otherwise. Its purpose is to be informative and educational. Backtest results are based on historical data, not real-time data. There is no guarantee that these hypothetical results will continue in the future. Day trading is extremely risky, and I do not suggest running any of these strategies live.
Code
Unlike the evaluator class we created, this one will not be static. That means we will need to create a constructor method and ensure it is instantiated correctly in the strategy. I use this method so we can use the signal to hold the names for strategies entry and exit signals. Further removing clutter from the strategy’s main file.
Besides the constructor, we must create four different functions for our strategy logic. This strategy assumes that you run calculations on bar close. If you run it on each tick, it may hold up, but I still need to test this.