Coding the “Doji” trading indicator in Python

Luiggi Trejo
2 min readDec 16, 2022
Python code for the Doji
Photo by Maxim Hopman on Unsplash

A Doji is a type of candlestick pattern that appears on a candlestick chart in technical analysis. It is characterized by a small body with the open and close prices being almost equal.

You may (or may not, my dear reader) already know that this way of charting prices was discovered and first used hundred of years ago by a Japanese rice trader, and -the story goes- he became the richest man in his country.

The Doji, in particular, is a signal that appears when a trend is about to hit a stop and reverse, hence its potentially enormous value. Now imagine a code that scans stock prices and/or currencies to detect when a Doji appears…

So, without further ado, lets begin our code:

# 2022 Luiggi.Trejo

def is_doji(candlestick):
open_price = candlestick[0]
close_price = candlestick[1]
# The body of a doji is considered small if the difference between
# the open and close prices is less than or equal to 5% of the open price
return abs(open_price - close_price) <= 0.05 * open_price

# Test the function
candlesticks = [[100, 99], [101, 102], [102, 101]]
for candlestick in candlesticks:
print(f"Candlestick {candlestick} is doji: {is_doji(candlestick)}")

This code defines a function is_doji that takes a candlestick as input (represented as a list with the open and close prices in that order) and returns True if it is a doji and False otherwise. The function first extracts the open and close prices from the candlestick and then calculates the difference between them. If this difference is less than or equal to 5% of the open price, the function returns True, indicating that the candlestick is a doji.

The code then tests the function by calling it on a list of candlesticks and printing the result for each one. The output of this code should be:

Candlestick [100, 99] is doji: True
Candlestick [101, 102] is doji: False
Candlestick [102, 101] is doji: True

We are already printing Dojis left and right!

Incoming articles will be written by yours truly on the matters of finding and extracting assets values, plotting them, and placing buy/sell orders.

Stay tuned!

Luiggi Trejo

I raise my (coffe) cup to you

Recommended from Medium