Coding Double Narrow Range 4 (Double NR4) Scanner Using Python and Zerodha

A Double NR4 Bar is a specific candlestick pattern in technical analysis that consists of two consecutive NR4 bars. An NR4 bar is a candlestick with the narrowest range among the previous four days, meaning it has the smallest difference between its high and low prices in the last four days.

Double Narrow Range 4 (NR4) Bar

In the context of a Double NR4 Bar, it means that there are two days in a row where the daily price range is exceptionally narrow compared to the previous four days. This pattern often indicates a period of low volatility and a potential upcoming price breakout or significant move.

Double NR4 Bar is also NR5 by Definition:

  • By definition, a Double NR4 Bar consists of two consecutive NR4 bars.
  • Since an NR4 bar implies a narrow range compared to the previous four days, two consecutive NR4 bars indicate an even narrower range for two consecutive days, making it a Narrow Range 5 (NR5) pattern.

Prerequisite

To go ahead with this tutorial, One must complete the pre-requsite tutorial which shows how to scan the stocks having Narrow Range 4 (NR4) Bar Pattern.

The Double Narrow Range 4 (NR4) Bar Scanner Using Zerodha KiteConnect API

To detect and print the last date each stock had a “Double Narrow Range 4 (NR4) Bar” pattern within the specified date range, you can modify the code from the last chapter as follows. The logic for a “Double Narrow Range 4 (NR4) Bar” is that there should be two consecutive Narrow Range 4 (NR4) Bars:

				
					from datetime import datetime, timedelta

# Define the date range
start_date = datetime.strptime('2023-08-01', '%Y-%m-%d')
end_date = datetime.strptime('2023-09-01', '%Y-%m-%d')

# Define the interval (in minutes)
interval = 'day'

# Iterate through the list of stock symbols
for symbol in symbol_list:
    # Fetch instrument data for the current stock symbol
    instruments = kite.ltp([symbol])

    # Check if the stock symbol is in the instruments dictionary
    if symbol in instruments:
        instrument_token = instruments[symbol]['instrument_token']

        if instrument_token:
            # Fetch historical data for the stock
            historical_data = kite.historical_data(instrument_token, start_date, end_date, interval='day')

            # Initialize variables to track NR4 candles
            nr4_candles = []
            consecutive_nr4_candles = 0  # Initialize a counter for consecutive NR4 candles

            # Iterate through historical data to detect NR4 candles
            for i in range(3, len(historical_data)):
                current_candle = historical_data[i]

                # Calculate the trading range for the previous three candles
                previous_candles = historical_data[i - 3:i]
                trading_ranges = [candle['high'] - candle['low'] for candle in previous_candles]

                # Check if the current candle has the narrowest range among the previous three (NR4)
                if min(trading_ranges) == trading_ranges[-1]:
                    nr4_candles.append(current_candle)
                    consecutive_nr4_candles += 1
                else:
                    consecutive_nr4_candles = 0  # Reset the counter if no NR4 candle

                # Check if there were two consecutive NR4 candles
                if consecutive_nr4_candles == 2:
                    print(f"Double NR4 Candle detected for {symbol} on {current_candle['date']}")
                    consecutive_nr4_candles = 0  # Reset the counter after detection

        else:
            print(f"Instrument token not found for {symbol}")
    else:
        print(f"{symbol} not found in instruments")

				
			

The output looks like – 

				
					Double NR4 Candle detected for NSE:NIFTY BANK on 2023-08-08 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY BANK on 2023-08-17 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY BANK on 2023-08-21 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY BANK on 2023-08-23 00:00:00+05:30
...
...
...
...
Double NR4 Candle detected for NSE:TATACONSUM on 2023-08-23 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-08 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-21 00:00:00+05:30
Double NR4 Candle detected for NSE:NIFTY FIN SERVICE on 2023-08-29 00:00:00+05:30
				
			

Changes from NR4 Bar Code to Double NR4 Bar Code:

  1. Introduction of ‘consecutive_nr4_candles’ Counter:
    1. A new variable called ‘consecutive_nr4_candles‘ has been introduced to track consecutive NR4 candles.
    2. This counter helps identify when there are two consecutive NR4 bars, which is the criterion for detecting a ‘Double NR4 Bar’ pattern.
  2. Additional Condition for Detection:
    1. Within the loop that iterates through historical data, logic has been added to determine if the current candle is an NR4 bar and increment the ‘consecutive_nr4_candles‘ counter accordingly.
    2. If the current candle does not meet the NR4 criteria, the ‘consecutive_nr4_candles‘ counter is reset to zero. This ensures that only consecutive NR4 bars are counted.
  3. Output Message for Double NR4 Bar:
    1. After detecting two consecutive NR4 bars (when ‘consecutive_nr4_candles‘ reaches 2), a message is printed indicating that a ‘Double NR4 Bar’ pattern has been detected for the current stock on the date of the second NR4 bar candle.
    2. Subsequently, the ‘consecutive_nr4_candles‘ counter is reset to zero to continue searching for other patterns.

These changes in the code enable it to specifically search for the ‘Double NR4 Bar’ pattern, defined by the presence of two consecutive NR4 bars, and report the date on which this pattern occurs for each stock in the symbol_list.

Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close