Python Script to Identify Doji Candlestick Patterns
A Doji candlestick is a special type of candlestick pattern in the stock market that shows indecision between buyers and sellers. When doji candlestick forms, it indicates that the market opens and closes at the same price. This means there is equality and indecision between buyers and sellers, with no one controlling the market

How a Doji Candle Looks
- Very small or no body (because open ≈ close)
- Long wicks (shadows) may appear on the top or bottom
from kiteconnect import KiteConnect
import pandas as pd
import datetime as dt
import os
import numpy as np
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
access_token = open("access_token.txt",'r').read()
key_secret = open("api_key.txt",'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
kite.set_access_token(access_token)
instrument_dump = kite.instruments("NSE")
instrument_df = pd.DataFrame(instrument_dump)
def instrumentLookup(instrument_df,symbol):
try:
return instrument_df[instrument_df.tradingsymbol==symbol].instrument_token.values[0]
except:
return -1
def fetchOHLC(ticker,interval,duration):
instrument = instrumentLookup(instrument_df,ticker)
data = pd.DataFrame(kite.historical_data(instrument,dt.date.today()-dt.timedelta(duration), dt.date.today(),interval))
data.set_index("date",inplace=True)
return data
def doji(ohlc_df):
"""returns dataframe with doji candle column"""
df = ohlc_df.copy()
avg_candle_size = abs(df["close"] - df["open"]).median()
df["doji"] = abs(df["close"] - df["open"]) <= (0.05 * avg_candle_size)
return df
ohlc = fetchOHLC("TATAMOTORS","5minute",5)
doji_df = doji(ohlc)
Line-by-Line Explanation
1. Importing Libraries
from kiteconnect import KiteConnect
import pandas as pd
import datetime as dt
import os
import numpy as np
- KiteConnect → Used to connect with Zerodha Kite API.
- pandas → Used to create dataframes and handle market data.
- datetime → Used to calculate date ranges for historical data.
- os → Used for file/folder path settings.
- numpy → Used for numeric operations (optional here).
2. Change Current Working Directory
cwd = os.chdir("D:\GenAi\python\python basic\Strategy")
- Changes the working folder to your strategy directory.
- So Python will look for files (access_token.txt, api_key.txt) inside this folder.
3. Generate Trading Session
access_token = open("access_token.txt",'r').read()
Opens the file access_token.txt and reads the access token (used for authenticated API calls).
key_secret = open("api_key.txt",'r').read().split()
Reads API key & secret from api_key.txt and splits into a list.
Example: ["your_api_key", "your_api_secret"]
kite = KiteConnect(api_key=key_secret[0])
Creates a KiteConnect object with your API key.
kite.set_access_token(access_token)
Sets the access token so you can call private API endpoints.
4.Get all NSE instruments
instrument_dump = kite.instruments("NSE")
- Fetches all tradable instruments from NSE exchange.
- Zerodha returns a big list of dictionaries, including instrument names, tokens, etc.
instrument_df = pd.DataFrame(instrument_dump)
- Converts that list into a pandas DataFrame for easy lookup.
5. instrument Lookup()
def instrumentLookup(instrument_df,symbol):
try:
return instrument_df[instrument_df.tradingsymbol==symbol].instrument_token.values[0]
except:
return -1
- Searches for the trading instrument by symbol (e.g., “TCS”, “INFY”).
- Returns its instrument_token, which is required for historical API.
- If symbol not found → returns -1.
6. fetchOHLC()
def fetchOHLC(ticker,interval,duration):
instrument = instrumentLookup(instrument_df,ticker)
- Gets the instrument token for the ticker.
data = pd.DataFrame(kite.historical_data(
instrument,
dt.date.today()-dt.timedelta(duration),
dt.date.today(),
interval))
- Fetches historical OHLC data using:
- instrument token
- start date (today – duration days)
- end date (today)
- interval (e.g., “5minute”, “day”)
data.set_index("date", inplace=True)
- Makes the date column the index of the DataFrame.
return data
- Returns the complete OHLC dataset.
7.doji() — Identify Doji Candlestick
def doji(ohlc_df):
df = ohlc_df.copy()
- Creates a copy of the input OHLC DataFrame.
avg_candle_size = abs(df["close"] - df["open"]).median()
- Calculates median body size of all candles.
- A doji has a very small body.
df["doji"] = abs(df["close"] - df["open"]) <= (0.05 * avg_candle_size)
return df
- Marks a candle as doji when body ≤ 5% of median candle size.
- Creates a new column
"doji"with True/False. - Returns DataFrame with doji information.
8.Execute the program and Identify Doji candles
ohlc = fetchOHLC("TATAMOTARS","5minute",5)
doji_df = doji(ohlc)
Doodle Floral Printed Dress for Girls
Amazon
-44% ₹899
- Doodle Floral Printed Dress for Girls | Breathable Kids Frock & Dresses Frocks with Waist Tie & Back Zip | Cap Sleeves & Knee Length (Pink & Navy Option | Age - 4 to 12 Years)
- CUTE PRINTED DESIGN: The dress features a cute printed design that is perfect for little girls. The prints are available in blue and pink colors / Knee-length frock design: The knee-length frock design of the dress is perfect for active little girls. It allows them to move around freely without any restrictions
We earn a commission if you make a purchase, at no additional cost to you.