Skip to main content

Fyers trading APIs.

Project description

The Fyers API Python client - v2.1

The official Python client for communicating with the Fyers API

Documentation

Requirements

  • Python v3

Installation

Install via pip

pip install fyers-apiv2@latest

Breaking changes - v2.1

v2.1 is a breaking major release with multiple internal modification to improve user experience.

Below are the breaking changes:

  • list of changes

Getting started with access token generation

import webbrowser
from fyerstest.fyers_api import SessionModel


def getauthToken(client_id, redirect_uri, response_type, scope, state, nonce):
    """
            The variable `generateTokenUrl` will have a url like
            https://uat-api.fyers.in/api/dev/generate-authcode?appId=B8PWLVH8T6&redirectUrl=https%3A%2F%2Fgoogle.com
             1. This function open this url in the browser.
             2. This will ask you to login and will ask you to approve the app if it is not approved already.

             3. Once that is done, it will redirect to a url (added while app creation) with the auth_code. The url will look like
                https://www.google.com/?auth_code=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTM1ODY2NzEsInN1YiI6ImF1dGhDb2RlIiwiYXBwX2lkIjoiQjhQV0xWSDhUNiIsImlzcyI6ImFwaS5sb2dpbi5meWVycy5pbiIsImF1ZCI6WyJ4OjAiLCJ4OjEiLCJ4OjIiXSwidXVpZCI6ImZhOGNhYjE3ZWU4OTQzMGRhZjA1YWUxNDI2YWVkYzI4IiwiaXBBZGRyIjoiMjIzLjIzMy40Mi40NiIsImRpc3BsYXlfbmFtZSI6IkRQMDA0MDQiLCJpYXQiOjE1OTM1ODYzNzEsIm5iZiI6MTU5MzU4NjM3MX0.IMJHzQGHQgyXt_XN0AgDrMN1keR4qolFFKO6cyXTnTg&user_id=DP00404
             4. You have to take the auth_code from the url and use that token in your generate_access_token function.

    """
    appSession = SessionModel(client_id=client_id, redirect_uri=redirect_uri,
                              response_type=response_type, scope=scope, state=state, nonce=nonce)
    generateTokenUrl = appSession.generate_authcode()
    print((generateTokenUrl))
    webbrowser.open(generateTokenUrl, new=1)


def generate_access_token(auth_code, client_id, redirect_uri, secret_key, grant_type):
    """
    :param auth_code: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTM1ODY2NzEsInN1YiI6ImF1dGhDb2RlIiwiYXBwX2lkIjoiQjhQV0xWSDhUNiIsImlzcyI6ImFwaS5sb2dpbi5meWVycy5pbiIsImF1ZCI6WyJ4OjAiLCJ4OjEiLCJ4OjIiXSwidXVpZCI6ImZhOGNhYjE3ZWU4OTQzMGRhZjA1YWUxNDI2YWVkYzI4IiwiaXBBZGRyIjoiMjIzLjIzMy40Mi40NiIsImRpc3BsYXlfbmFtZSI6IkRQMDA0MDQiLCJpYXQiOjE1OTM1ODYzNzEsIm5iZiI6MTU5MzU4NjM3MX0.IMJHzQGHQgyXt_XN0AgDrMN1keR4qolFFKO6cyXTnTg"
    :param app_id: "B8PWLVH8T6"
    :param secret_key: "575XQDKGN0"
    :param redirect_url: "https://google.com"
    :return: access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1OTM1ODgzNzMsIm5iZiI6MTU5MzU4ODM3MywiZXhwIjoxNTkzNjQ5ODEzLCJpc3MiOiJhcGkuZnllcnMuaW4iLCJzdWIiOiJhY2Nlc3MiLCJhdWQiOiJ4OjAseDoxLHg6MiIsImF0X2hhc2giOiJnQUFBQUFCZV9EcVZIZExMMTAzTVpVN1NYSkZfR2p5R3hidzMtTVVhb0VEMGI0QUVvNjFsR24tREY2OFU5cXhuNzd0UXVoOVVJalYtNm9MVXhINVFfWE1WTEJfRXpROGV2clJmUzlNUXB0Y2J5c2ltN1drWllZTT0iLCJkaXNwbGF5X25hbWUiOiJQSVlVU0ggUkFKRU5EUkEgS0FQU0UiLCJmeV9pZCI6IkRQMDA0MDQifQ.cAfrj2TxAyb8A_9DfiCb1hLIZg_mH-xvP3Ybnj3a4AE"

    1.this function takes the param and return the access_token
    2.the access_token created will be used further .(in fyersModel)]
    3. one can get the auth_code from the url generated by getauthToken function (from auth_code= ..... &user_Id=xxxxxx before &)
    """
    # import ipdb;
    # ipdb.set_trace()
    appSession = SessionModel(client_id=client_id, redirect_uri=redirect_uri,
                              secret_key=secret_key, grant_type=grant_type)
    appSession.set_token(auth_code)
    access_token = appSession.generate_token()
    return access_token

def main():

    # Define the required parameters
    redirect_uri = "https://trade.fyers.in/api-login/redirect-uri/index.html"
    client_id = "XC4XXX67IM-100"
    secret_key = "5OXXX3DM8"
    grant_type = "authorization_code"
    response_type = "code"
    state = "sample_state"
    nonce = "baka"
    scope = "openid"

    # Step 1: Get authorization token
    getauthToken(client_id, redirect_uri, response_type, scope, state, nonce)
    
    # Step 2: Obtain authorization code
    # Add the obtained authorization code here
    auth_code = "XXXxxx"
    
    # Step 3: Generate access token
    generate_access_token(auth_code, client_id, redirect_uri, secret_key, grant_type)


if __name__ == '__main__':
    main()
    

Getting started wih API

from fyerstest.fyers_api import FyersModelv3


def api_call(access_token, clientId, log_path):
    functionName = "api_call"
    """
        :param access_token: "https://XXXXXX.com"
        :param app_id: "XXXXXXXXXXX"
        :param log_path: "home/gfxcgv/vgghvb/xxxx"
    """

    # If you want to make asynchronous API calls then assign the below variable as True and then pass it in the functions, by default its value is False
    is_async = False

    # Creating an instance of fyers model in order to call the apis
    fyers = FyersModelv3(token=access_token, is_async=is_async, log_path=log_path, client_id=clientId)

    # Setting the AccessToken
    fyers.token = access_token

    ## uncomment the any of the following requests to send a particular request and get the required data
    # print(fyers.get_profile())
    
    # print(fyers.tradebook())
    
    # print(fyers.positions())
    
    # print(fyers.holdings())
    
    # print(fyers.funds())
    
    # print(fyers.orderbook())

    # print(fyers.cancel_order({'id':'8080582117761'}))
    # data = {
    #     "productType":"INTRADAY",
    #     "side":1,
    #     "symbol":"NSE:DEEPAKNTR-EQ",
    #     "qty":1,
    #     "disclosedQty":0,
    #     "type":2,
    #     "validity":"DAY",
    #     "filledQty":0,
    #     "limitPrice":0,
    #     "stopPrice":0,
    #     "offlineOrder":False
    # } 
    # print(fyers.place_order(data))

    # print(fyers.modify_order({"id":"808058117761", "qty":"0","type":"1","limitPrice":"71100","stopPrice":"0"})) #modify instead of update

    # print(fyers.convert_position({"symbol":"MCX:SILVERMIC20AUGFUT","positionSide":"1","convertQty":"1","convertFrom":"MARGIN","convertTo":"INTRADAY"}))

    # print(fyers.get_orders({'id':'808078094451'}))

    # print(fyers.market_status())

    # print(fyers.exit_positions({"id":"MCX:SILVERMIC20AUGFUT-MARGIN"}))

    # print(fyers.generate_data_token({"vendorApp":"0KMS0EZVXI"}))

    # print(fyers.cancel_basket_orders([{"id":"120080780536"},{"id":"120080777069"}]))

    # print(fyers.place_basket_orders([{
    #     "productType":"INTRADAY",
    #     "side":1,
    #     "symbol":"NSE:DEEPAKNTR-EQ",
    #     "qty":1,
    #     "disclosedQty":0,
    #     "type":2,
    #     "validity":"DAY",
    #     "filledQty":0,
    #     "limitPrice":0,
    #     "stopPrice":0,
    #     "offlineOrder":False
    # } ,{
    #     "productType":"INTRADAY",
    #     "side":1,
    #     "symbol":"NSE:SBIN-EQ",
    #     "qty":1,
    #     "disclosedQty":0,
    #     "type":2,
    #     "validity":"DAY",
    #     "filledQty":0,
    #     "limitPrice":0,
    #     "stopPrice":0,
    #     "offlineOrder":False
    # } ]))

    # print(fyers.modify_basket_orders([{"id":"120080780536", "type":1, "limitPrice": 190, "stopPrice":0},{"id":"120080777069", "type":1, "limitPrice": 190}]))
    
    # print(fyers.quotes(data={"symbols":"NSE:TCS-EQ"}))
    
    # print(fyers.depth(data={"symbol":"NSE:TCS-EQ,NSE:SBIN-EQ","ohlcv_flag":"1"}))
    
    # data = {"symbol":"NSE:SBIN-EQ","resolution":"10","date_format":"0","range_from":"1686481206","range_to":"1686567665","cont_flag":"1"}
    # print(fyers.history(data))


if __name__ == '__main__':
    # the access token returned fro generate_access_token(x,x,x,x) function from getAccessToken.py module
    access_token = "eyJ0eXAiOiJieDoxIiwieDoyIiwiZDoxIiwiZDoyIiwieDoxIiwieDowIl0sInN1YiI6ImFjY2Vzc190b2tlbiIsImF0X2hhc2giOiJnQUFBQUFCa25ucldKVEhfWXRpREcyVnlldUJTN2Z6NzE0YzBlTUpaa3BUcGRHWURQR2daT0t5RTZ5SmVPa3N0WTVyNExBX2NpTUZtQ0d1d0xuamp5VWhPckVJTzNjZHNqM1laNHJQMzc0dHdXeVRPQlJpVEUxbz0iLCJkaXNwbGF5X25hbWUiOiJWSU5BWSBLVU1BUiBNQVVSWUEiLCJvbXMiOiJLMSIsImZ5X2lkIjoiWFYyMDk4NiIsImFwcFR5cGUiOjEwMCwicG9hX2ZsYWciOiJOIn0.yWShR1T8DHIZYqZgt3GE8xaSYLMfcFpHMLSGenE92lA"

    # The app id we get after creating the app
    clientId = "XCXXXXXIM-100"

    # The system path where we want to store the logs e.g-c:\user\vvvv\xxxx\nnnn
    log_path = None
    ## uncomment any of the function in the api_call to get the required output
    api_call(access_token, appId, log_path)

Getting started with Data Socket

import threading
from fyerstest.data_ws import FyersDataSocket
import time

# Specify your access token
access_token = "XCXXXXXIM-100:eyJ0eXAiOiJKV1QtbVHrlbEGK-jsWCcUf9dFW1cRQRJg3vEc5Y"

# Specify the data type and symbols you want to subscribe to
data_type = "SymbolUpdate"

# Create an instance of FyersDataSocket
fyData = FyersDataSocket(access_token=access_token, log_path=None, litemode=False)


# Subscribe to the specified symbols and data type
symbols = ['NSE:NIFTY50-INDEX', "NSE:HDFC-EQ"]
fyData.subscribe(symbols=symbols, data_type=data_type)

# Unsubscribe from the specified symbols and data type
time.sleep(6)
symbols = ["NSE:NIFTY50-INDEX"]
fyData.unsubscribe(symbols=symbols, data_type=data_type)

time.sleep(6)
symbols = ['NSE:SBIN-EQ','NSE:ADANIENT-EQ']
fyData.subscribe(symbols=symbols, data_type="DepthUpdate")

# Keep the socket running to receive real-time data
fyData.keep_running()

Getting started with Order Socket

import time
from fyerstest.order_ws import FyersOrderSocket

# Specify your access token
access_token = "XCXXXXX7IM-100:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiIsImFwcFR5cGUiOjEwMCwicG9hX2ZsYWciOiJOIn0.fED040uRtbVHrlbEGK-jsWCcUf9dFW1cRQRJg3vEc5Y"

# Create an instance of FyersDataSocket
fyOrder = FyersOrderSocket(access_token=access_token, log_path=None)

# Subscribe to the specified data type
data_type = "OnOrders,OnTrades"
fyOrder.subscribe(data_type=data_type)

# Unsubscribe to the specified data type7
time.sleep(10)
data_type = "OnTrades"
fyOrder.unsubscribe(data_type=data_type)

# Keep the socket running to receive real-time data
fyOrder.keep_running()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fyers_apiv3-3.0.0.tar.gz (30.1 kB view hashes)

Uploaded Source

Built Distribution

fyers_apiv3-3.0.0-py3-none-any.whl (28.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page