Create a Custom Time Window in NinjaScript
How to create a user-defined time window in NinjaScript for use in automated trade systems and backtesting.
In the trading world, everything revolves around efficiency. Automated trade systems allow traders to trade strategies when they aren’t at the computer. This can save many hours of charting and research if done correctly. However, just because your strategy can trade during every hour of the session doesn’t mean it should.
When backtesting strategies, you will notice that some strategies perform better at different times of the day. In this article, we will create a time window feature for use in our NinjaScript trade strategies. The focus will be on simple and effective code use. We will also discuss a software development principle and how it can help us organize our code for more efficient use and testing in the future.
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 Review
There are three parts to this section. The first two parts will cover creating the time window feature inside the strategy, and the third part will discuss separating certain logic from the strategy and creating a custom class. The code can be used as is at any of the stages. Each section is designed to build on the previous one by applying some design principles to the code.
Attributes and Basic Usage
We first need to create our properties that allow the user to define the hours they wish the strategy to trade in. We will need hours and minutes for both a start and end time. We will use these inputs to define our private TimeSpan
variables that we will use for comparison operations.
We will use TimeSpan
objects in this code instead of DateTime
objects, as they are generally more efficient, less error-prone, and more logically fitting. There are a few reasons they are beneficial:
TimeSpan
objects avoid any date-related issues that could arise when comparingDateTime
objects. This is because they do not have a date component, only a time component.They are not affected by factors such as daylight saving time and time zones.
Mathematical operations (like adding and subtracting hours or minutes) are more intuitive and much easier to perform.
It aligns with financial practices that often focus on market hours, time slots, sessions, etc., which are inherently time-of-day based rather than date and time-specific.
The following code is the first step in this process, but it can technically be used as is.