How to build an automated scalping strategy using NinjaTrader 8

Automated Strategy, NinjaScript, NinjaTrader, price action, Scalping, Supply & Demand, Support & Resistance -

How to build an automated scalping strategy using NinjaTrader 8

1. Overview

Most traders are aware that support & resistance levels play an important role in todays financial markets. Time and time again we see the market respecting these levels and price coming back to (re)test these levels.

It therefore makes sense for traders to look for trades around these important levels.  In this article i'll explain how you can create a simple automated strategy for NinjaTrader 8 which scalps these important support & resistance levels.

We'll use our own Suport & Resistance indicator as a base for our strategy. It will detect all the important support/and resistance levels for us and it exposes a couple of plots we can use in our strategy. From there we'll add our entries & exits and finally use the strategy analyzer for backtesting.

 

2. The scalping strategy

In this article we'll be using a 5-min chart of NQ, The strategy itself should work on any market & timeframe but note that the stoplosses and targets we present in this article are based on the 5-min NQ charts. For other markets and timeframes you will need to adjust those accordingly.

2.1 Rules for short trades 

We open a short trade when 

  • Price touches or peeks through a resistance level
  • AND price then snaps back below the resistance level
  • And the resistance level has 2 or more touches
  • Our stoploss is the (current) high of the candle plus a few extra ticks
  • Our target is 20 ticks

Its important to note that we want to see price respecting the level. Its ok if it goes through the level a few ticks, but when it does that, we want to see price coming back below the resistance level before we open a short trade.

2.2 Rules for long trades 

We open a long trade when 

  • Price touches or peeks through a support level
  • AND price then snaps back above the support level
  • And the support level has 2 or more touches
  • Our stoploss is the (current) low of the candle minus a few extra ticks
  • Our target is 20 ticks

Again its important to note that we want to see price respecting the level. Its ok if it goes through the level a few ticks, but when it does that, we want to see price coming back above the support level before we open a long trade.

2.3 Other rules

  • We take only 1 trade each bar
  • We only trade a support/resistance level once. So if price is (re)testing the support/resistance level in multiple bars, we only trade it once.

3. Coding the strategy in NinjaScript

We will be building our strategy using NinjaScript. The complete source code can be downloaded here

Please note that

  • This code is for educational purposes only and not meant for live trading
  • You need to have our Support/Resistance indicator installed in order to be able to run this automated strategy
  • You need to be able to code and understand ninjascript. The code is meant for people who understand coding & ninjascript. We will not give support or answer questions on questions like how to install or run it
  • We don't provide any support for this code. Its meant as an example which you can use to built upon 

3.1 A skeleton strategy

We start with a skeleton strategy and build up on that. In the first part we just initialize our strategy to use OnEachTick as calculation mode since we want to be able to react on every price change. You could also choose OnPriceChange probably.

Next we add a 1-tick dataseries in the Configure state which we'll use to place our orders on. NinjaTrader requires you to place your orders on a specific dataseries. If we used the default 5min dataseries then our trades would open on the next 5-min bar instead of on the next tick. By adding a 1-tick dataseries we can place our orders on that and ensure that our orders get opened as quick as possible.

Finally in the DataLoaded state we create the TDUSupportResistance indicator which we will use later to detect our support & resistance levels and initialize its properties. Next.. we are going to look at the OnBarUpdate() method. In here we'll place all our order entry logic

Skeleton for our automated scalping strategy

3.2 Adding logic for long trades

Now we'll add the code we need for our long entries. First we need to check if we are in the default data series , or in the added extra 1-tick data series, Since we're interested in the S&R levels of the 5-min chart we only want to get OnBarUpdates() for the default 5-min dataseries. This is done by the first line which checks if BarsInProgress equals 0. If not, then we simply return

The next line is a standard line and just checks if we have enough bars to trade . When the strategy starts it only has a couple of bars and we want to wait with trading until enough bars (and S&R levels) are available.

Next we look at our market position. We only want to open trades when we're flat and no other trades are running. 

Finally we can now check the rules for the long setup. We check if the low of the current bar is at or below the current support level, and whether the current price is back above the support level. If thats the case we can continue checking the number of touches the support level has. If that also meets our criteria a long trade gets opened

You can see that the take profit is set to the number of ticks specified. The stoploss is set a few ticks below the low of the current candle. We added an extra step to make sure that the stoploss is at least 4 ticks to prevent it getting hit straight away in the case the stoploss might be very small 

Adding code for the long entries of the automated strategy

3.2 Adding code for short trades

The code for the short trade is basically the same as the long trades. But instead of looking at support levels, we look at the resistance levels.

We check if the high of the current candle is at or above the resistance level and if the current price of the current candle is back below the resistance level

If so we check if the resistance level has the number of touches we want and when that is the case we open a new short trade.

The target is again set to the number of ticks we want, and the stoploss is placed a few ticks above the high of the candle. 

Code for short trades for the automated scalping strategy

3.3. Adding code for the other rules

Remember that we don't want to open more then 1 trade per bar , and we don't want to open more then 1 trade per support/resistance level.

Here's how we do this. The first rule is pretty simple. We just remember at which bar we opened the last trade. We store this bar number in the _lastBar variable when we open a trade. Then next time we come into the OnBarUpdate() and the bar is still the same, we simply return. That way we never enter more then 1 trade / bar

For the other rule we need to remember the support/resistance level we last traded. We store the support/resistance in the _lastLevel variable when we open a trade. Then next time we want to open a new trade we simply check if the current support/resistance level is different then the previous one mentioned in the _lastLevel variable. Ifso then we can open the trade

Code to limit the amount of trades per bar and level

4. Backtest results

We backtested the strategy in the strategy analyzer for the august 2021 on a 5-min NQ chart. We used the following settings in the strategy analyzer.

  • NQ - 5min, trading hours: <use instrument settings>
  • Start date : 01/08/2021
  • End date: 27/08/2021
  • Enable tickreplay : on
  • Enable commissions : on
  • slippage : 2
  • Exit on session close : off

 

!!!PLEASE NOTE THAT ITS IMPORTANT TO HAVE TICKREPLAY ENABLED!!!

If you dont see tick replay or cant turn it on, then you might need to enable 'Show Tick Replay in tools->options first!

 

4.1 Backtest with 20 tick target

Let's change our profit target from 10 to 20 ticks and see what happens. We keep all the other settings the same and run a new backtest

Strategy settings:

  • Take profit : 20 ticks
  • Extra SL (ticks) : 2 ticks
  • Extra Retracement (ticks) : 2 ticks
  • Min. Touches: 1

The following screenshots show what happens with a target of 20 ticks. The winrate is 73.39% over 124 trades with a profit factor of 6.23 which is still excellent. Our average loser is -$44 and our average winner is $100. That gives us a nice reward to risk ratio 

Now these results look very good, perhaps TOO good. And to be honest, i wrote this strategy while i was on holiday, so it has not been tested in the live markets. So next weeks we'll deploy this in the live markets (on a Sim account) to see if we get the same results as the backtests

 

Equity curve for automated scalping strategy ninjatrader 8

Backtest summary for automated scalping strategy ninjatrader 8

5. Room for improvements

The strategy presented here looks very promising. More backtesting might be needed over longer periods to gain more insights in its performance though. 

Also the strategy as is is pretty simple, not only in functionality but also in stability. There's lots of room for improvements. For example it could be further improved by adding the following things:

  • Make the strategy error proof. For example sometimes stoploss or takeprofit orders will be rejected by NinjaTrader since price might already gone past it before we get a change to place these orders. Code for dealing with rejected orders would need to be added before even thinking about running this strategy on a live account
  • a time & day of the week filter which tells when the strategy is allowed to take trades
  • max loss / day filter which tells the strategy to stop trading for the day when it hits the max. loss for the day
  • max profit / day filter which tells the strategy to stop trading when it hits its max. profit for the day
  • Multiple profit targets via a scalp and  (multiple) runner(s)
  • Dynamic position sizing based on the account size and risk
  • Including the round numbers indicator to also take scalps of important round numbers
  • Including candle stick patterns to determine when to take a scalp or not
  • Including a new filters, e.g. with our news indicator to avoid taking trades during news events

 

6. Download the source code

The complete source code can be downloaded here

!!!PLEASE NOTE THAT ITS IMPORTANT TO HAVE TICKREPLAY ENABLED!!!

If you dont see tick replay or cant turn it on, then you might need to enable 'Show Tick Replay in tools->options first!

Please note that

  • This code is for educational purposes only and not meant for live trading
  • To keep this article simple, this code does not handle any errors like rejected orders. So don't run it on a live account
  • You need to have our Support/Resistance indicator installed in order to be able to run this automated strategy
  • You need to be able to code and understand ninjascript. The code is meant for people who understand coding & ninjascript. We will not give support or answer questions on topics like how to install or run it
  • We don't provide any support for this code. Its meant as an example which you can use to built upon 
  • If you are going to test this, please test it in a SIM account first
  • We didnt run this strategy in the live markets (yet). The results look very good, but perhaps a little too good. Therefore we will need to test this in the live markets first (in a sim account) to see if we get the same results as the backtest

 

Installing the strategy:

  • Make sure you have our support/resistance indicator installed and working. If not, get our 5-day free trial and install that first
  • Download the source code
  • Copy the SupportResistanceStrategy.cs you downloaded to the Documents\NinjaTrader 8\bin\custom\strategies folder  (see screenshot below)
  • Start NinjaTrader 8
  • Choose New->NinjaScript Editor
  • press compile (F5)
  • Now you can add the strategy to a NQ - 5 min chart. please don't forget to enable Tick Replay!

Folder where to install the strategy