SplashAlgo

Powered by TheCodingView

SplashAlgoPowered by TheCodingView

Angel Broking Smart API Python Setup: Step-by-Step Guide for Financial OHLC Data Download

Published on: 24th Aug 2024

title image

Angel One is a leading retail full-service broking house in India, offering various innovative financial services. With cutting-edge tools such as basket orders, GTT (Good Till Triggered) orders, SmartAPI, and advanced charts, AngelOne empowers investors and traders to navigate capital markets like professionals. From online and algorithmic trading to smart orders, Angel One provides powerful platforms to help us achieve our financial goals. Focused on technology and customer satisfaction, AngelOne remains a trusted name in the industry.

You can find the complete code at the end of this blog, with explanations provided in the middle.

How Much Data Can I Download?

With the default API plan, we can make 3 requests per second using the getCandleData function for OHLC data. This allows us to download data consistently, giving us flexibility based on our needs. The Rate limit is calculated based on the client code. If the requests are more than 3 per second, the limit-exceeding requests will fail and return 403 Access denied because of exceeding the rate limit.

Initial Requirements

To be able to download data from SmartAPI (Angel One), We need to import the following libraries:

import pandas as pd
from SmartAPI import SmartConnect
from logzero import logger

If we do not have these libraries, we can install them via pip. Open your terminal window and enter the following commands:

pip install smartapi-python
pip install logzero
pip install pandas

If the above commands do not work properly, it will produce errors like this

pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Then try like this

python -m pip install smartapi-python

Method: How to use SmartAPI to download data

1. Create a Variable to Input credentials

api_key = '<put your api key here>'
username = '<your AngelOne ClientID>'
pin = '<your AngelOne mpin>'
# REQUIRED TO GENERATE OTP FOR LOGIN
totp= "<your TOTP from AngelOne>" 

2. Input Token and Check If the Token is Correct or not

if __name__ == "__main__":
    # CREATE ANGELONE SMARTCONNECT INSTANCE
    smartApi = SmartConnect(api_key) 
    otp = pyotp.TOTP(totp).now()
    smartApi.generateSession(username, pin, otp)

if the token is not correct, “Invalid Token: The provided token is not valid.” will appear.

3. Create a Function to Download Data from smartApi

Here is the historical_data function that renders the stock data in pandas data frame format.

import datetime
df_columns = ["Datetime", "Open", 'High', 'Low', 'Close', 'Volume']
def getData(exchange, token, interval, historicalDays):
  
    currentTime = datetime.datetime.now()
    threeDayBackDate = currentTime - datetime.timedelta(days = historicalDays)
    threeDayBackDate = threeDayBackDate.strftime("%Y-%m-%d") + " 09:15"
    currentTime = currentTime.strftime("%Y-%m-%d %H:%M")

    historicParam = {
        "exchange": exchange,
        "symboltoken": token,
        "interval": interval,
        "fromdate": threeDayBackDate,
        "todate": currentTime
    }
    try:
        df = smartApi.getCandleData(historicParam)['data']
        df = pd.DataFrame(df, columns=df_columns)
        df['Datetime'] = pd.to_datetime(df['Datetime'])
        
        # df['Datetime'] = df['Datetime'] + pd.Timedelta(minutes=15)
        df['Datetime'] = df['Datetime'].dt.strftime('%Y-%m-%d %H:%M')
        df["Datetime"] = pd.to_datetime(df["Datetime"])

        # print(df)
        return df
    except Exception as e:
        print(e)

4. Call The Function To Download the data

The function requires four input parameters. Below are the details of all the parameters:

a. Exchange Parameter: This parameter specifies the exchange symbol based on the type of instrument data we want to download. For example, if we want to download stock data, we should use "NSE" it as the exchange symbol. Refer to the table below for the appropriate exchange symbols for different instruments:

Exchange Lists Angelone

b. Token Parameter: We also need to input the token for the specific symbol we wish to download data. Tokens can be obtained from the following link: https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json

c. Timeframe Parameter: We need to specify the timeframe of the data we want to download. The table below lists the available timeframes and their corresponding input values. For example, to download data with a 1-minute interval, we should input "ONE_MINUTE".

Interval List

d. Maximum Days in One Request

The broker imposes limits on the amount of historical data we can download based on the selected timeframe. For example, we can download up to 30 days of data for a 1-minute timeframe. The table below shows the data limits for different timeframes:

rate limit

We can now call the function according to our requirements. Here’s an example:

Output:

Data Output Angelone

Here is the full code:

# ──────────────────────────────────────────────────────
import pyotp
import datetime
import pandas as pd
from SmartAPI import SmartConnect
from logzero import logger
import requests
# pip install smartapi-python logzero pyotp


# ──────────────────────────────────────────────────────
api_key = '<put your api key here>'
username = '<your AngelOne ClientID>'
pin = '<your AngelOne mpin>'
# REQUIRED TO GENERATE OTP FOR LOGIN
totp= "<your TOTP from AngelOne>" 

# ─────────────────────────────────────────────────────
df_columns = ["Datetime", "Open", 'High', 'Low', 'Close', 'Volume']
def getIntradayData(exchange, token, interval, historicalDays):
  
    currentTime = datetime.datetime.now()
    threeDayBackDate = currentTime - datetime.timedelta(
                            days = historicalDays)
    threeDayBackDate = threeDayBackDate.strftime("%Y-%m-%d") + " 09:15"
    currentTime = currentTime.strftime("%Y-%m-%d %H:%M")

    historicParam = {
        "exchange": exchange,
        "symboltoken": token,
        "interval": interval,
        "fromdate": threeDayBackDate,
        "todate": currentTime
    }
    try:
        df = smartApi.getCandleData(historicParam)['data']
        df = pd.DataFrame(df, columns=df_columns)
        df['Datetime'] = pd.to_datetime(df['Datetime'])
        
        # df['Datetime'] = df['Datetime'] + pd.Timedelta(minutes=15)
        df['Datetime'] = df['Datetime'].dt.strftime('%Y-%m-%d %H:%M')
        df["Datetime"] = pd.to_datetime(df["Datetime"])

        # print(df)
        return df
    except Exception as e:
        print(e)


# ────────────── LOGIN ──────────────────────────
if __name__ == "__main__":
    #CREATE ANGELONE SMARTCONNECT INSTANCE
    smartApi = SmartConnect(api_key) 
    otp = pyotp.TOTP(totp).now()
    smartApi.generateSession(username, pin, otp)

    token = 13611

    data = getIntradayData(
            "NSE", token, "ONE_DAY", 
             historicalDays=100
           )
    print(data)

Here you have it. In the next blog we will look into how we can fetch real-time data via web sockets using Angelone's SmartWebSocketV2.

*Note: The logo used in the title image of this blog is a property of AngelOne Broking, we do not own the registered trademark.

SplashAlgo

Powered by TheCodingView

SplashAlgo offer trading signals, indicators and execution engines to help improve your trading strategies. Our tools provide real-time market insights to help you make informed decisions. Join us to enhance your trading experience!

PRODUCTS

Indicators

Flickerr Signals

Screeners

USEFUL LINKS

Your account

Become an affiliate

FAQ


2024 Copyright | SplashAlgo

About Us

Disclaimer

Terms of Service

Privacy Policy