The Fyers API Python client - v3
The official Python client for communicating with the Fyers API
Documentation
Requirements
Installation
Install via pip
pip install fyers-apiv3
Breaking changes - v3
v3
is a breaking major release with multiple internal modification to improve user experience.
New Data Socket:
- Improved tick update speed, ensuring swift and efficient market data updates.
- Introducing Lite mode for targeted last traded price (LTP) change updates.
- SymbolUpdate: Real-time symbol-specific updates for instant parameter changes.
- DepthUpdate: Real-time market depth changes for selected symbols.
- Increased subscription capacity, accommodating tracking of 200 symbols.
- Strengthened error handling callbacks for seamless issue resolution.
New Order Socket:
- Real-time updates for orders.
- Real-time updates for positions.
- Real-time updates for trades.
- Real-time updates for eDIS.
- Real-time updates for price alerts.
- Improved error handling callbacks.
Getting started wih API
from fyers_apiv3 import fyersModel
import webbrowser
"""
In order to get started with Fyers API we would like you to do the following things first.
1. Checkout our API docs : https://myapi.fyers.in/docsv3
2. Create an APP using our API dashboard : https://myapi.fyers.in/dashboard/
Once you have created an APP you can start using the below SDK
"""
"""
1. Input parameters
"""
redirect_uri= "APP REDIRECT URI"
client_id = "XCXXXXXxxM-100"
secret_key = "MH*****TJ5"
grant_type = "authorization_code"
response_type = "code"
state = "sample"
appSession = fyersModel.SessionModel(client_id = client_id, redirect_uri = redirect_uri,response_type=response_type,state=state,secret_key=secret_key,grant_type=grant_type)
generateTokenUrl = appSession.generate_authcode()
"""There are two method to get the Login url if you are not automating the login flow
1. Just by printing the variable name
2. There is a library named as webbrowser which will then open the url for you without the hasel of copy pasting
both the methods are mentioned below"""
print((generateTokenUrl))
webbrowser.open(generateTokenUrl,new=1)
"""
run the code firstly upto this after you generate the auth_code comment the above code and start executing the below code """
auth_code = "Paste the auth_code generated from the first request"
appSession.set_token(auth_code)
response = appSession.generate_token()
try:
access_token = response["access_token"]
except Exception as e:
print(e,response)
"""
fyerModel object takes following values as arguments
1. accessToken : this is the one which you received from above
2. client_id : this is basically the app_id for the particular app you logged into
"""
fyers = fyersModel.FyersModel(token=access_token,is_async=False,client_id=client_id,log_path="")
"""
1. User Apis : This includes (Profile,Funds,Holdings)
"""
print(fyers.get_profile())
print(fyers.funds())
print(fyers.holdings())
"""
2. Transaction Apis : This includes (Tradebook,Orderbook,Positions)
"""
print(fyers.tradebook())
print(fyers.orderbook())
print(fyers.positions())
"""
3. Order Placement : This Apis helps to place order.
There are two ways to place order
a. single order : wherein you can fire one order at a time
b. multi order : this is used to place a basket of order but the basket size can max be 10 symbols
c. multileg order : this is used to place a multileg order but the legs size minimum is 2 and maximum is 3
"""
data = {
"symbol":"NSE:ONGC-EQ",
"qty":1,
"type":1,
"side":1,
"productType":"INTRADAY",
"limitPrice":0,
"stopPrice":0,
"validity":"DAY",
"disclosedQty":0,
"offlineOrder":False,
"stopLoss":0,
"takeProfit":0
}
print(fyers.place_order(data))
data = [{ "symbol":"NSE:SBIN-EQ",
"qty":1,
"type":1,
"side":1,
"productType":"INTRADAY",
"limitPrice":61050,
"stopPrice":0 ,
"disclosedQty":0,
"validity":"DAY",
"offlineOrder":False,
"stopLoss":0,
"takeProfit":0
},
{
"symbol":"NSE:HDFC-EQ",
"qty":1,
"type":2,
"side":1,
"productType":"INTRADAY",
"limitPrice":0,
"stopPrice":0 ,
"disclosedQty":0,
"validity":"DAY",
"offlineOrder":False,
"stopLoss":0,
"takeProfit":0
}]
print(fyers.place_basket_orders(data))
data = {
"orderTag": "tag1",
"productType": "MARGIN",
"offlineOrder": False,
"orderType": "3L",
"validity": "IOC",
"legs": {
"leg1": {
"symbol": "NSE:SBIN24JUNFUT",
"qty": 750,
"side": 1,
"type": 1,
"limitPrice": 800
},
"leg2": {
"symbol": "NSE:SBIN24JULFUT",
"qty": 750,
"side": 1,
"type": 1,
"limitPrice": 800
},
"leg3": {
"symbol": "NSE:SBIN24JUN900CE",
"qty": 750,
"side": 1,
"type": 1,
"limitPrice": 3
}
}
}
print(fyers.place_multileg_order(data))
"""
4. Other Transaction : This includes (modify_order,exit_position,cancel_order,convert_positions)
"""
data = {
"id":"7574657627567",
"type":1,
"limitPrice": 61049,
"qty":1
}
print(fyers.modify_order(data))
data = [
{ "id":"8102710298291",
"type":1,
"limitPrice": 61049,
"qty":0
},
{
"id":"8102710298292",
"type":1,
"limitPrice": 61049,
"qty":1
}]
print(fyers.modify_basket_orders(data))
data = {"id":'808058117761'}
print(fyers.cancel_order(data))
data = [
{
"id":'808058117761'
},
{
"id":'808058117762'
}]
print(fyers.cancel_basket_orders(data))
data = {
"id":"NSE:SBIN-EQ-INTRADAY"
}
print(fyers.exit_positions(data))
data = {
"symbol":"MCX:SILVERMIC20NOVFUT",
"positionSide":1,
"convertQty":1,
"convertFrom":"INTRADAY",
"convertTo":"CNC"
}
print(fyers.convert_position(data))
"""
DATA APIS : This includes following Apis(History,Quotes,MarketDepth)
"""
data = {"symbol":"NSE:SBIN-EQ","resolution":"D","date_format":"0","range_from":"1622097600","range_to":"1622097685","cont_flag":"1"}
print(fyers.history(data))
data = {"symbols":"NSE:SBIN-EQ"}
print(fyers.quotes(data))
data = {"symbol":"NSE:SBIN-EQ","ohlcv_flag":"1"}
print(fyers.depth(data))
Getting started with Data Socket
from fyers_apiv3.FyersWebsocket import data_ws
def onmessage(message):
"""
Callback function to handle incoming messages from the FyersDataSocket WebSocket.
Parameters:
message (dict): The received message from the WebSocket.
"""
print("Response:", message)
def onerror(message):
"""
Callback function to handle WebSocket errors.
Parameters:
message (dict): The error message received from the WebSocket.
"""
print("Error:", message)
def onclose(message):
"""
Callback function to handle WebSocket connection close events.
"""
print("Connection closed:", message)
def onopen():
"""
Callback function to subscribe to data type and symbols upon WebSocket connection.
"""
data_type = "SymbolUpdate"
symbols = ['NSE:SBIN-EQ', 'NSE:ADANIENT-EQ']
fyers.subscribe(symbols=symbols, data_type=data_type)
fyers.keep_running()
access_token = "XCXXXXXXM-100:eyJ0tHfZNSBoLo"
fyers = data_ws.FyersDataSocket(
access_token=access_token,
log_path="",
litemode=False,
write_to_file=False,
reconnect=True,
on_connect=onopen,
on_close=onclose,
on_error=onerror,
on_message=onmessage
)
fyers.connect()
Getting started with Order Socket
from fyers_apiv3.FyersWebsocket import order_ws
def onTrade(message):
"""
Callback function to handle incoming messages from the FyersDataSocket WebSocket.
Parameters:
message (dict): The received message from the WebSocket.
"""
print("Trade Response:", message)
def onOrder(message):
"""
Callback function to handle incoming messages from the FyersDataSocket WebSocket.
Parameters:
message (dict): The received message from the WebSocket.
"""
print("Order Response:", message)
def onPosition(message):
"""
Callback function to handle incoming messages from the FyersDataSocket WebSocket.
Parameters:
message (dict): The received message from the WebSocket.
"""
print("Position Response:", message)
def onGeneral(message):
"""
Callback function to handle incoming messages from the FyersDataSocket WebSocket.
Parameters:
message (dict): The received message from the WebSocket.
"""
print("General Response:", message)
def onerror(message):
"""
Callback function to handle WebSocket errors.
Parameters:
message (dict): The error message received from the WebSocket.
"""
print("Error:", message)
def onclose(message):
"""
Callback function to handle WebSocket connection close events.
"""
print("Connection closed:", message)
def onopen():
"""
Callback function to subscribe to data type and symbols upon WebSocket connection.
"""
data_type = "OnOrders,OnTrades,OnPositions,OnGeneral"
fyers.subscribe(data_type=data_type)
fyers.keep_running()
access_token = "XCXXXXXXM-100:eyJ0tHfZNSBoLo"
fyers = order_ws.FyersOrderSocket(
access_token=access_token,
write_to_file=False,
log_path="",
on_connect=onopen,
on_close=onclose,
on_error=onerror,
on_general=onGeneral,
on_orders=onOrder,
on_positions=onPosition,
on_trades=onTrade
)
fyers.connect()