Python Code : Auction failure and opportunity to trade

Introduction to Auction Theory and Auction Failure

As per the market auction theory, auction continues in one direction till the winner of the auction is decided. However, if auction fails to continue in one direction and re-starts on other direction abruptly, we term it as auction failure.

In the market profile theory, it is stated that the initial trading period of the session decides the direction for the day’s trade. You might have seen that the market in the opening first bar experiences gap ups and gap downs. Market in the first 15 mins is mostly clueless about the direction and may move in either direction to find buyer and sellers to support the trade. After about an hour, market sets its own direction and generally as per the auction theory the market should continue in this direction. If however, the market changes its direction, then it can be termed as market failure.

To make it more objective, consider the following rules :

  • The high low for the first hour should be marked
  • If the price moves above or below to this first hour high / low, this should be the direction of the market.
  • If market reverses after moving above / below to the high/low of first hour and closes in the first hour range or to the opposite side. The highest/lowest price point (the point of reversal) after the first hour trade can be termed as price point for the auction failure.
  • If the price re-visit this zone with in next 5-6 trading session , this price point is likely to provide reaction.

  • Graphical Representation of failed auction


    In the above example, failure happened at the lowest point of session-1 and the reaction was obtained in the session-3.



    The above is another example, here auction failure occurred at the lowest point of session-1 and retest happened on the session three , but from the below. Total reaction noted was about 2.5%.

    The lowest point of session -1 is outside the low of initial 1 hour price range (15 min of 4 bar = 1 hour). However, the close of the session is inside the initial range setup in the first hour. Thus the lowest point can be considered as auction failure. It may be noted that the reaction line has been drawn below the auction failure point at a distance of about 0.3%. This is because at this point of auction failure, we expect that there must be some more buyers/sellers below this point and the re-test will be done at this price level.

    Generally the reversal is of the range of 0.4% to 1.5%. It is suggested that the full or partial profit should be booked at 0.4% profit.

    The python code - Auction Failure Screening

    import datetime as datetime
    import pandas as pd
    from dateutil import parser
    import os

    def readData02(csvFileName):
      df = pd.read_csv(csvFileName,names=['Script','DateData','timeData','Open','High','Low','Close','Volume','OI'])
      df['Datetime'] = pd.to_datetime(df['DateData'].astype(str)+' '+df['timeData'].astype(str),format='%Y%m%d %H:%M')
      d = {'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', 'Volume': 'sum'}
      df = df.resample('5T', on='Datetime').agg(d)
      df = df[df['Open'].notna()]
      df = df[df['Volume'].notna()]
      df1 = df.reset_index()
      df1.to_csv("resultHDFC.csv")
      return df1 # return five minutes df

    l=os.listdir("..//..//Google Drive//oneminutedata//2022//FEB/22FEB//22FEB")
    print(l)
    l.remove("desktop.ini")
    for item in l:
      item1 = "..//..//Google Drive//oneminutedata//2022//FEB/22FEB//22FEB//" + item
      df = readData02(item1)

      fromDate = '2022-02-22'
      toDate = '2022-02-22'

      myDate0 = parser.parse(fromDate)
      myDate1 = parser.parse(toDate) + datetime.timedelta(days=1)

      i=0
      while(myDate0 + datetime.timedelta(days=i) < myDate1):
        df1 = df[df['Datetime'] < myDate0 + datetime.timedelta(days=i+1)][df[df['Datetime'] < myDate1]['Datetime'] > myDate0 + datetime.timedelta(days=i)]
        # print(df1)
        df2 = df1[df1['Datetime'] < myDate0 + datetime.timedelta(days=i, hours=10,minutes=20)]
        myDate = myDate0 + datetime.timedelta(days=i)
        ADHigh = df2['High'].max()
        ADLow = df2['Low'].min()
        df3 = df1[df1['Datetime'] < myDate0 + datetime.timedelta(days=i, hours=15,minutes=35)]
        df4 = df3[df3['Datetime'] > myDate0 + datetime.timedelta(days=i, hours=15,minutes=25)].reset_index(drop=True)
        myClose = df4['Close'].min()
        df5 = df1[df1['Datetime'] > myDate0 + datetime.timedelta(days=i, hours=10,minutes=15)]
        myHigh = df5['High'].max()
        myLow = df5['Low'].min()
        if myLow < ADLow and myClose > ADLow:
          print(item,myDate, myLow,"Auction Failure at Low")
        if myHigh > ADHigh and myClose < ADHigh:
          print(item,myDate, myHigh,"Auction Failure at High")
        i = i + 1

    The format of input File

    Mine file was not having any headers, it was a 1 min data. Code for reading the CSV file converts the 1 min data into 5 min data. Further, I have daily files in a single folder, so I have used OS module to list the files. desktop.ini is already there is each folder, so to remove that file , I have pop it out.


    The data looks like as under :
    DLF,20220222,09:08,331.00,331.00,331.00,331.00,29341,0
    DLF,20220222,09:16,332.95,333.95,331.60,332.35,209224,0

    wherein first col is Scrip name
    Second is date
    Third is time
    fourth - fifth -sixth -seventh are open/high/low /close
    eight is volume
    and the last one is IO, which is zero for equity

    PineScript Vs Backtrader : What to choose for backtesting ?

    Pinescript and Backtrader, both are used for backtesting of trading strategies on historical data. Pinescript is a script developed by tradingview platform. Pinescript can be used on tradingview platform for backtesting. While on the other hand "backtrader" is a python module developed by python community and is available for free on git hub for download. You can freely download the backtrader module and can use it with python for backtesting of trading strategies and development of technical indicators.

    Trading community in search of best backtesting software have often asked this question “pinescript or backtrader”. Both of them come with some advantage and some drawbacks.

    Pros for pinescript and crons for backtrader

  • Easy to learn and implement : No need to learn an entire programming lanaguage. Pinescript have simple, less coding rules and can therefore easy to learn and implement.
  • Lots of scripts available in the community library : The tradingview platform encourage users to put their scripts on community library for free download by other users. You can therefore have huge collections of scripts to refer from. 
  • Attractive, user-friendly charting software : The tradingview chart is an intractive chart. You can draw trendlines and mark candles or bars on the chart. At the same time, you can also use pinescript code to mark or highlight bars/candles by use of code.
  • No need for a separate data source : Tradingview supports almost all the modern exchanges, commodities, forex and thus their is no need for separate datasource for backtesting. You can use data provided by tradingview directly with pinescript. 
  • Crons for pinescript and pros for python

  • Cannot be used for complex algorithms : As explained earlier, the coding rules are simple and easy to understand, however, if you have a complex strategy, you will find it difficult or impossible to implement the same on pinescript. 
  • Cannot be used for Machine Learning, Deep learning , artificial integillence : Pinescript have no support for ML, deep learning or AI. However, in case you are using backtrader, you can use AI, ML modules of python for implementation in backtrader.
  • Slow in processing and calculation : Tradingview is a browser based trading / backtesting platform, the real execution takes place at the shared server therefore the execution of pinescript is slower compared to backtrader or other similar python based programme. 
  • The choice of using pinescript or python or backtrader will depend upon the requirement of user, his coding skills. If you are new to the coding and have a simple strategy to implement. You can safely use pinescript, its inbuilt functions. You can learn pinescript from various free sources on internet or you can buy book TradingView Pine Script Programming From Scratch available on amazon or you can also take buy Udemy course Creating trade strategies and backtesting using pinescript. Both the book and udemy course have been created for non-programmers cum traders willing to learn and leverage with coding skills.

    If you have complicated trading strategy or want to implement AI, ML , you should learn backtrader. If you are new to python or programming , the suggested book is Teach yourself python backtrader.

    Python Backtrader : Fibonacci Bollinger Bands - Example Indicator

    In the last post, I had discussed the Fibonacci Bollinger Bands and its implementation on the TradingView platform through pinescript. If you want to implement the indicator in python, you can use BackTrader module for backtesting and quick development and implementation of any indicator script in python. 

    Below is the code in Python for implementing the indicator Fibonacci Bollinger Bands through backtrader module.

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

        alias = ('FiboBB',)
        lines = ('mid', 't1','t2','t3','t4','t5','t6', 'b1','b2','b3','b4','b5','b6',)
        params = (
            ('period', 50), # Look Back Period
            ('devfactor', 3.0), # standard dev. for extreme lines
            ('movav', bt.ind.MovingAverageSimple),
                        )

        plotinfo = dict(
            subplot=False,
            plotlinelabels=False,
                                )

        plotlines = dict(
            mid=dict(ls='--'),
            t1=dict(_samecolor=True),
            t2=dict(_samecolor=True),
            t3=dict(_samecolor=True),
            t4=dict(_samecolor=True),
            t5=dict(_samecolor=True),
            t6=dict(_samecolor=True),
            b1=dict(_samecolor=True),
            b2=dict(_samecolor=True),
            b3=dict(_samecolor=True),
            b4=dict(_samecolor=True),
            b5=dict(_samecolor=True),
            b6=dict(_samecolor=True),
                                )

        def __init__(self):
            self.lines.mid = ma = self.p.movav(self.data, period=self.p.period)
            stddev = self.p.devfactor * bt.ind.StandardDeviation(self.data, ma, period=self.p.period,
    movav=self.p.movav)
            self.lines.t1 = ma + stddev
            self.lines.t2 = ma + stddev*.764
            self.lines.t3 = ma + stddev*.618
            self.lines.t4 = ma + stddev*.5
            self.lines.t5 = ma + stddev*.382
            self.lines.t6 = ma + stddev*.236
            self.lines.b1 = ma - stddev
            self.lines.b2 = ma - stddev*.764
            self.lines.b3 = ma - stddev*.618
            self.lines.b4 = ma - stddev*.5
            self.lines.b5 = ma - stddev*.382
            self.lines.b6 = ma - stddev*.236

            super(FiboBB, self).__init__()


    class MyStrategy(bt.Strategy):
        def __init__(self):
            self.FiboBBLines = FiboBB(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',bardown='black',barupfill = False,bartrans = 1.0,barup='black',volume=False)


    The resultant plot for Fibonacci Bollinger Band is shown below:


    If you are new to the backtrader module of python or have no prior experience of coding in python or any other programming language. I strongly suggest you consider the Backtrader book provided in the resource section. The book has been written for traders with no prior experience of coding or programming in any language.

    You can also download code from "backtraders/backtraderIndicators" on git hub

    Coding and using vortex indicator in PineScript

    Vortex Indicator

    Vortex indicator is used to identify the start, end or continuation of a trend. It consists of two lines which are generally red and green. Greenline measures the strength of the uptrend while the other measures for downtrends. When the two cross, trend change can be expected. 

    Vortex Indicator Calculation

    Vortex is calculated by subtracting the previous low/high from the current high/low. Please note, the low of the previous bar is substructed from the current high and the high of the previous bar is substructed from the current low of the present bar. 

    i.e. VM+ = high - low of previous bar and VM- = low-high of previous bar

    In the above, we are considering VM+ as positive vortex movement and VM- as negative vortex movement. A vortex movement is a scientific term associated with the flow of fluid or water. As you can notice the calculation above can be positive or negative depending on the values of high/low. For this reason, we calculate the absolute value (all negative are also considered as positive) of the same. The above therefore becomes :

    VM+ = absolute(high - low of previous bar) and VM- = absolute(low-high of previous bar)

    The calculation of VM+ and VM- is similar to the way we calculate TR i.e. true range. The VM can be considered as cross TR with previous bars. 

    Thus Vortex indicator can be considered as a comparison of cross TR with TR for a given period.

    Before we compare, VM with TR we have to calculate TR i.e. TR = high - low.

    Now we can compare these cross TR with actual TR. The comparison is done for a fixed lookback period. Generally, traders choose 14 or 21 days as a lookback period (because they are multiples of days in a week). If you are not working on the daily time frame, you may like to choose a different lookback period. 

    For comparison just sum up value of VM+ and VM- and TR for lookback period. 

    For calculation of Vortex Indicator Plus divide VM+ by TR summed up for lookback period.

    VIP = (sum of  VM+ for lookback period)/(sum of  TR for lookback period)

    VIM = (sum of  VM- for lookback period)/(sum of  TR for lookback period) 

    Implementing Vortex Indicator in Pinescript

    //@version=5
    indicator(title = "Vortex Indicator", shorttitle="VI")
    period = input.int(14, title="Length", minval=2)
    VMPlus = math.sum( math.abs( high - low[1]), period )
    VMMinus = math.sum( math.abs( low - high[1]), period )
    SumTR = math.sum( ta.tr, period)
    VIPlus = VMPlus / SumTR
    VIMinus = VMMinus / SumTR
    plot(VIPlus, title="VI +", color=#2962FF)
    plot(VIMinus, title="VI -", color=#E91E63)

    The above is code in pinescript for quick implementation of vortex indicator on trading view platform. 
    The VM+ and VM- is calculated by calculating cross TR as high - low[1] and low - high[1]. Here the [1] notation after high and low represent the value of high or low one bar back. 

    If you are new to pinescript or want to learn pinescript from scratch. Books and courses are recommended in the resource section. Even if you have no prior experience of coding or programming, you will be able to make code in pinescripts after going through the book or course.

    You are encouraged to copy and use the above code in your pinescript editor for results. 

    Vortex indicator best settings

    The common question that many traders often ask is what is the best setting for an indicator. What could be vortex indicator settings for intraday ? No one can give you the correct answer for such types of questions but I can provide you with some guidelines on the selection of the best setting for any indicator. 

    1.   Setting Shall depend on underlying asset and market timings. If the market works for  24X 7, its setting will always be different from other equity exchanges those work for 8 to 10 hours a day.

    2. Timeframe do have impact on settings of any indicator. Setting for one timeframe may not work for another. 

    Example : If you are using daily timeframe for an exchange that works for 5 days a week, a week is of 5 days , two weeks are of 10 days, month is of 20 days. I would suggest a setting of 15,20 for long term and 5 or 10 for short term. Your setting should be in line with higher time frame. 

    If you are using a 5 min chart, try using 60 min / 5 = 12 as setting or 30 min / 5 min = 6 as settings.

    In case of vortex, I am using 14 as setting which is equal to 2 weeks (7 X 7) or approx 3 weeks (5 X 3) if we consider 7 days or 5 days as days in a week. 

    Vortex Indicator Strategy

    VM being absolute number is always a positive number and being divided by TR, the Vortex Indicator for strength and weakness are always positive i.e. value greater than zero, however, as we had normalized the value of VM by TR, they are generally in a narrow range.

    Any value of VI above 1.1 can be considered as a strength and value below 0.90 can be considered as weakness. Some traders use crossover of VI+ and VI- as single for trend reversal. Some traders also use other indicators in combination with VI for signal filtering.




    vortex indicator screener

    vortex indicator vs dmi

    vortex indicator python

    vortex indicator afl

    vortex indicator accuracy

    vortex indicator adalah

    vortex angle indicator

    vortex indicator vs adx

    Fibonacci Bollinger Bands - PineScript Indicator Review

    Fibonacci Bollinger Bands is a community script developed by "Rashad" and is one of the popular community scripts in tradingview. The author of the script has not given an explanation to the script, however, the entire code is open for the community for study and development.

    Another script on the same is by "Shizaru". Shizaru has given an explanation of the indicator's construction but has not provided details about its uses.

    Both the script have different logics for the calculation of bands and Fibonacci bands inside the Bollinger band. In this blog post, I will be discussing both of these scripts. The differences are as under:


    Rashad

    Shizaru

    Uses standard deviation of 3 for calculation of upper and lower bands

    Uses ATR for calculation of the extreme upper and lower bands

    The 3 standard deviation is divided into Fibonacci ratios of 0.236, 0.382, 0.5, 0.618, 0.764, 1

    ATR ratio of 1.618,2.618,4.236 defines the three lines above mean and below mean.

    Seems more logical as Bollinger bands are based on standard deviations and the division of standard deviation with ratios is as per acceptable literature. 97% values should be under the bands.

    Shizaru has used descriptions provided on the internet for Bollinger Bands® Fibonacci Ratio.

    Fibonacci Bollinger Bands - by Rashad

    Below is the indicator on the SBIN from the National Stock Exchange of India. The Fibonacci lines are represented by L1,L2,L3,L4 and L5. The below daily chart is from May 2021 to Aug 2021.


    It may be observed from the above chart that price has received some reaction from the Fibonacci lines drawn inside Bollinger bands. During the period under examination, the price raised from below L2 to L4. No price reaction was observed when the first time price crossed/breached L2. However, on all occasions when price touched the Fibonacci level lines during rising or decline, they have to produce reactions as marked on the chart. 

    Out of the 6 events of crossing/touching of price with levels for the first time, 5 times it produces a reaction.

    Bollinger Bands Fibonacci ratios - by Shizaru

    We have now applied the script developed by Shizaru on the same scrip for the same period and timeframe. We can observe that the band lines in this one are less than the earlier one but the gap between the band lines is smaller.


    Due to the smaller gap between the band lines price has crossed/touched these lines many times during the same period. As compared to six events of band touching or crossing in the previous section as discussed above we can observe that there are nine such events in this script. Out of the nine such occasions, the price at E and H did not provide enough reaction. In fact, at E there was no reaction while at H there was a minor reaction. 

    For all practical purposes, both the scripts were able to provide points of reaction through the band lines. You can choose any one of them as per your requirement and volatility in the market. It is suggested that you back test them on the scrip, forex, commodity onto which you would like to apply. 

    Combining both Bollinger Bands and Fibonacci ratios




    To-Do /Suggestions

    For the script from Rashad - the colour scheme of the script makes it invisible in the lighter theme of the tradingview platform. To be able to use this script you have to be in the dark mode. In case you are more comfortable with the lighter theme of the trading view platform, you have to either change the theme or the colour scheme for better visualization.

    Also, try to use another indicator like RSI to improve upon signal generation and filtering. 

    Teach Yourself Python Backtrader: Step by Step backtesting implementation for non-programmers

     

    Backtrader is a python package for backtesting of strategies in python. The backtrader is in use by many traders for backtesting as well as for trading in live market. The book "Teach Yourself Python Backtrader" is for those who want to learn python backtrader for backtesting.


    Have you ever thought of a machine that could earn for you while you relax. There is no such machine but steps can be taken to build such a machine. It all depends on your skills and a winning strategy that can do trading on your behalf.



    Backtrader is python module used for creating custom indicators, trade alerts, creating strategies and back-testing them on historical and real data. After, gaining skill from this book you will be able to make your scripts for custom indicators and backtest strategies on historical data and real market. This book has been written in simple language so that readers with no prior background of python or computer programming are able to learn and build upon the basics. This book will also introduce you to basics of python programming need by the traders for coding on backtrader. Act now to have a copy of this book to test your strategies and build your skills.

    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...