Python Backtrader : Mark Doji CandleSticks - Example Indicator

Python Backtrader: Mark Doji CandleSticks - Example Indicator

Below is the script in python using the backtrader package for marking Doji CandleSticks on the chart. Ideally, a doji is a candlestick pattern where the open price is exactly the same as the close price. However, since such ideal conditions seldom exist, in the script, I have used a tolerance of 0.05% between the open and close price for identifying and marking doji.

import backtrader as bt
# Create a Stratey
class DojiTest(bt.Indicator):

alias = ('DD',)
lines = ('doji',)
params = (
('tolerence', 0.05), # tolerence
)

plotinfo = dict(
subplot=False,
plotlinelabels=True,
)
plotlines = dict(
doji=dict(marker='^', markersize=8.0, color='blue', fillstyle='full', ls='',
),
)

def next(self):
# red doji
if ((self.datas[0].close[0] * (1 + (self.p.tolerence/100))) > self.datas[0].open[0]) and (self.datas[0].close[0]<self.datas[0].open[0]):
self.lines.doji[0]= self.datas[0].high[0]

# green doji
if ((self.datas[0].open[0] * (1 + (self.p.tolerence/100))) > self.datas[0].close[0]) and (self.datas[0].close[0]>self.datas[0].open[0]):
self.lines.doji[0]= self.datas[0].high[0]


class MyStrategy(bt.Strategy):
def __init__(self):
# self.BB = bt.ind.BBands(self.data,period=20,devfactor=1.5)
self.doji = DojiTest(self.data)

if __name__ == '__main__':
cerebro = bt.Cerebro(stdstats=False)
data = bt.feeds.YahooFinanceCSVData(dataname='AAPL.csv')
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)
cerebro.run()
cerebro.plot(style='candlestick')

The script is using Cerebro engine of backtrader for plotting of custom indicators created in backtrader. A new indicator class named DojiTest has been written and implemented.

Resources

Highest Rated Udemy Course on PineScript - Grab your Seat Now 

Udemy Discount Coupon Code : UDEMY-JAN23 (Valid upto 30th Nov 2023)

Learn more about coding on tradingview in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book200+ pages book


Point and Figure Charts : A Time-Tested Tool for Technical Analysis

In the dynamic world of financial markets, investors and traders constantly seek tools that can provide valuable insights into market trends...