Average True Range - Algo Code

NikhilNikhil
1 min read

Learn full about ATR before using the below code

import kiteconnect
import time

# Authenticate with the KiteConnect API
kite = kiteconnect.KiteConnect(api_key="your_api_key")
kite.set_access_token("your_access_token")

# Define the symbol and interval for which you want to retrieve the live price ticks
symbol = "NSE/SYMBOL"
interval = "1minute"

# Function to calculate the ATR indicator
def calculate_atr(prices, n):
    """
    Calculates the Average True Range (ATR) for the given list of prices and the number of periods, n.
    """
    tr = [0] * len(prices)
    for i in range(1, len(prices)):
        tr[i] = max(prices[i] - prices[i-1], abs(prices[i-1] - prices[i-2]), abs(prices[i] - prices[i-2]))
    atr = [0] * len(prices)
    for i in range(n-1, len(prices)):
        atr[i] = sum(tr[i-n+1:i+1]) / n
    return atr
# Continuously check for the ATR indicator using live price ticks
while True:
    # Get the latest price data for the symbol
    data = kite.historical_data(symbol, interval, 1000)

    # Extract the close prices from the data
    prices = [row["close"] for row in data["data"]]

    # Calculate the ATR indicator
    atr = calculate_atr(prices, 14)

    # Get the latest ATR value
    latest_atr = atr[-1]

    # Use the latest ATR value to determine buy or sell signals
    if latest_atr > 0:
        # Buy signal
        print("Buy signal detected, ATR: ", latest_atr)
    else:
        # Sell signal
        print("Sell signal detected, ATR: ", latest_atr)

    # Sleep for a short period of time before checking the ATR again
    time.sleep(60)
0
Subscribe to my newsletter

Read articles from Nikhil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nikhil
Nikhil