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.

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