Fyers Reference¶
- class aio_trader.fyers.Fyers(client_id: str, token: str)¶
Bases:
AbstractBroker
Unofficial implementation of Fyers API using aiohttp for async requests
- Parameters:
client_id (str) – APP_ID of the created app.
token (Optional[str]) – Api login token from a previous login
All arguments are Optional
enctoken
oraccess_token
if available can be reused to login.- async authorize(**kwargs) None ¶
Not required can be skipped
- async cancel_basket_orders(data: dict) dict ¶
Cancels the orders with the provided IDs.
- Parameters:
data (dict) – A dictionary containing the order details.
data (dict):
order_ids (list): A list of order IDs to be cancelled.
- async cancel_gtt_order(data: dict) dict ¶
Cancel order.
- Parameters:
data (dict) – The data containing the order ID.
Data must contain the following keys: values:
id (str): Unique identifier for the order to be cancelled, e.g., “25010700000001”.
- async cancel_order(data: dict) dict ¶
Cancel order.
- Parameters:
data (dict) – The data containing the order ID.
Data must contain the following keys: values:
id (str, optional): ID of the position to close. If not provided, all open positions will be closed.
- async convert_position(data: dict) dict ¶
Converts positions from one product type to another based on the provided details.
- Parameters:
data (dict) – Dict containing details about the position.
Data must contain the following keys: values:
symbol (str): Symbol of the positions. Eg: “MCX:SILVERMIC20NOVFUT”.
positionSide (int): Side of the positions. 1 for open long positions, -1 for open short positions.
convertQty (int): Quantity to be converted. Should be in multiples of lot size for derivatives.
convertFrom (str): Existing product type of the positions. (CNC positions cannot be converted)
convertTo (str): The new product type to convert the positions to.
- async depth(data: dict) dict ¶
Fetches market depth data for a symbol.
- Parameters:
data (dict) – Dict containing symbol name
data: dict
symbol (str): Symbol of the product. Eg: ‘NSE:SBIN-EQ’.
ohlcv_flag (int): Flag to indicate whether to retrieve open, high, low, closing, and volume quantity. Set to 1 for yes.
- async exit_positions(data: dict | None = None) dict ¶
Closes open positions based on the provided ID or closes all open positions if ID is not passed.
- Parameters:
data (dict) – A dictionary containing the position id.
data (dict):
id (str, optional): ID of the position to close. If not provided, all open positions will be closed.
- async funds() dict ¶
Retrieves funds details.
- async get_orders(data: dict) dict ¶
Retrieves order details by ID.
- Parameters:
data (dict) – The data containing the order ID.
- async get_profile() dict ¶
Retrieves the user profile information.
- async gtt_orderbook(data: dict | None = None) dict ¶
Retrieves the gtt order information.
- Parameters:
data (Optional[dict]) – Default None.
- async history(data: dict) dict ¶
Fetches candle data based on the provided parameters.
- Parameters:
data (dict) – Dict containing details of symbol
Data dict must contain the below keys:
symbol (str): Symbol of the product. Eg:
NSE:SBIN-EQ
.resolution (str): The candle resolution. Possible values are:
Day
or1D
,1
,2
,3
,5
,10
,15
,20
,30
,60
,120
,240
.date_format (int): Date format flag. 0 to enter the epoch value, 1 to enter the date format as
yyyy-mm-dd
.range_from (str): Start date of the records. Accepts epoch value if date_format flag is set to 0, or
yyyy-mm-dd
format if date_format flag is set to 1.range_to (str): End date of the records. Accepts epoch value if
date_format
flag is set to 0, oryyyy-mm-dd
format ifdate_format
flag is set to 1.cont_flag (int): Flag indicating continuous data and future options. Set to 1 for continuous data.
- async holdings() dict ¶
Retrieves information about current holdings.
- async logout() dict ¶
Invalidates the access token.
- async market_status() dict ¶
Retrieves market status.
- async modify_basket_orders(orders: List[dict])¶
Modifies multiple pending orders based on the provided details.
- Parameters:
orders (List[dict]) – A list of dictionaries containing the order details.
orders (list):
A list of dictionaries containing the order details to be modified.
Each dictionary should have the following keys:
‘id’ (str): ID of the pending order to be modified.
‘limitPrice’ (float): New limit price for the order. Mandatory for Limit/Stoplimit orders.
‘stopPrice’ (float): New stop price for the order. Mandatory for Stop/Stoplimit orders.
‘qty’ (int): New quantity for the order.
‘type’ (int): New order type for the order.
- Returns:
The response JSON as a dictionary.
- async modify_gtt_order(data: dict) dict ¶
Modifies the parameters of a pending order based on the provided details.
- Parameters:
data (dict) – A dictionary containing the order details.
data (dict):
id (str): Unique identifier for the order to be modified, e.g., “25010700000001”
orderInfo* (object): Contains updated information about the GTT/OCO order legs.
orderInfo.leg1* (object): Details for GTT order leg. Mandatory for all modifications.
orderInfo.leg1.price* (number): Updated price at which the order should be placed.
orderInfo.leg1.triggerPrice* (number): Updated trigger price for the GTT order.
NOTE: for OCO order this leg trigger price should be always above LTP.
orderInfo.leg1.qty** (integer): Updated quantity for the GTT order leg.
orderInfo.leg2* (object): Details for OCO order leg. Required if the order is an OCO type.
orderInfo.leg2.triggerPrice* (number): Updated trigger price for the second leg of the OCO order.
NOTE: for OCO order this leg trigger price should be always below LTP.
orderInfo.leg2.qty* (integer): Updated quantity for the second leg of the OCO order.
- async modify_order(data: dict) dict ¶
Modifies the parameters of a pending order based on the provided details.
- Parameters:
data (dict) – A dictionary containing the order details.
data (dict):
id (str): ID of the pending order to be modified.
limitPrice (float, optional): New limit price for the order. Mandatory for Limit/Stoplimit orders.
stopPrice (float, optional): New stop price for the order. Mandatory for Stop/Stoplimit orders.
qty (int, optional): New quantity for the order.
type (int, optional): New order type for the order.
- async optionchain(data: dict) dict ¶
Fetches option chain data for a given symbol.
- Parameters:
data (dict) – Dict containing symbol name and strikecount
data: dict
symbol (str): The symbol of the product. For example, ‘NSE:NIFTY50-INDEX’.
timestamp (int): Expiry timestamp of the stock. Use empty for current expiry. Example: 1813831200.
strikecount (int): Number of strike price data points desired. For instance, setting it to 7 provides: 1 INDEX + 7 ITM + 1 ATM + 7 OTM = 1 INDEX and 15 STRIKE (15 CE + 15 PE).
- async orderbook(data: dict | None = None) dict ¶
Retrieves the order information.
- Parameters:
data (Optional[dict]) – Default None. The data containing the order ID.
- async place_basket_orders(orders: List[dict]) dict ¶
Places multiple orders based on the provided details.
- Parameters:
orders (List[dict]) – A list of dictionaries containing the order details.
orders (list):
Each dictionary should have the following keys:
‘symbol’ (str): Symbol of the product. Eg: ‘MCX:SILVERM20NOVFUT’.
‘qty’ (int): Quantity of the product.
‘type’ (int): Type of the order. 1 for Limit Order, 2 for Market Order, and so on.
‘side’ (int): Side of the order. 1 for Buy, -1 for Sell.
‘productType’ (str): Type of the product. Eg: ‘INTRADAY’, ‘CNC’, etc.
‘limitPrice’ (float): Valid price for Limit and Stoplimit orders.
‘stopPrice’ (float): Valid price for Stop and Stoplimit orders.
‘disclosedQty’ (int): Disclosed quantity. Allowed only for equity.
‘validity’ (str): Validity of the order. Eg: ‘DAY’, ‘IOC’, etc.
‘offlineOrder’ (bool): Specifies if the order is placed when the market is open (False) or as an AMO order (True).
‘stopLoss’ (float): Valid price for CO and BO orders.
‘takeProfit’ (float): Valid price for BO orders.
- async place_gtt_order(data: dict) dict ¶
Places an order based on the provided data.
- Parameters:
data (dict) – A dictionary containing the order details.
data (dict):
‘id*’ (str): Unique identifier for the order to be modified, e.g., “25010700000001”.
‘side’ (int): Indicates the side of the order: 1 for buy, -1 for sell.
‘symbol’ (str): The instrument’s unique identifier, e.g., “NSE:CHOLAFIN-EQ”
‘productType*’ (str): The product type for the order. Valid values: “CNC”, “MARGIN”, “MTF”.
‘orderInfo*’ (object): Contains information about the GTT/OCO order legs.
‘orderInfo.leg1*’ (object): Details for GTT order leg. Mandatory for all orders.
‘orderInfo.leg1.price*’ (number): Price at which the order.
‘orderInfo.leg1.triggerPrice’ (number): Trigger price for the GTT order. NOTE: for OCO order this leg trigger price should be always above LTP
‘orderInfo.leg1.qty*’ (int): Quantity for the GTT order leg.
‘orderInfo.leg2*’ (object): Details for OCO order leg. Optional and included only for OCO orders.
‘orderInfo.leg2.price*’ (number): Price at which the second leg of the OCO order should be placed.
‘orderInfo.leg2.triggerPrice*’ (number): Trigger price for the second leg of the OCO order.NOTE: for OCO order this leg trigger price should be always below LTP
‘orderInfo.leg2.qty*’ (integer): Quantity for the second leg of the OCO order.
- async place_multileg_order(data: dict) dict ¶
Places an multileg order based on the provided data.
- Parameters:
data (dict) – A dictionary containing the order details.
data (dict):
‘productType’ (str): Type of the product. Possible values: ‘INTRADAY’, ‘MARGIN’.
‘offlineOrder’ (bool): Specifies if the order is placed when the market is open (False) or as an AMO order (True).
‘orderType’ (str): Type of multileg. Possible values: ‘3L’ for 3 legs and ‘2L’ for 2 legs .
‘validity’ (str): Validity of the order. Possible values: ‘IOC’ (Immediate or Cancel).
legs (dict): A dictionary containing multiple legs order details.
‘symbol’ (str): Symbol of the product. Eg: ‘NSE:SBIN-EQ’.
‘qty’ (int): Quantity of the product. Should be in multiples of lot size for derivatives.
‘side’ (int): Side of the order. 1 for Buy, -1 for Sell.
‘type’ (int): Type of the order. Possible values: 1 for Limit Order.
‘limitPrice’ (float): Valid price for Limit and Stoplimit orders.
- async place_order(data: dict) dict ¶
Places an order based on the provided data.
- Parameters:
data (dict) – A dictionary containing the order details
Data dict must contain the following keys: values:
‘productType’ (str): Type of the product. Possible values: ‘CNC’, ‘INTRADAY’, ‘MARGIN’, ‘CO’, ‘BO’.
‘side’ (int): Side of the order. 1 for Buy, -1 for Sell.
‘symbol’ (str): Symbol of the product. Eg: ‘NSE:SBIN-EQ’.
‘qty’ (int): Quantity of the product. Should be in multiples of lot size for derivatives.
‘disclosedQty’ (int): Default: 0. Disclosed quantity. Allowed only for equity.
‘type’ (int): Type of the order. 1 for Limit Order, 2 for Market Order, 3 for Stop Order (SL-M), 4 for Stoplimit Order (SL-L).
‘validity’ (str): Validity of the order. Possible values: ‘IOC’ (Immediate or Cancel), ‘DAY’ (Valid till the end of the day).
‘filledQty’ (int): Filled quantity. Default: 0.
‘limitPrice’ (float): Default: 0. Valid price for Limit and Stoplimit orders.
‘stopPrice’ (float): Default: 0. Valid price for Stop and Stoplimit orders.
‘offlineOrder’ (bool): Specifies if the order is placed when the market is open (False) or as an AMO order (True).
- async positions() dict ¶
Retrieves information about current open positions.
- async quotes(data: str) dict ¶
Fetches quotes data for multiple symbols.
- Parameters:
symbols (str) – Comma-separated symbols of the products. Maximum symbol limit is 50. Eg: ‘NSE:SBIN-EQ,NSE:HDFC-EQ’.
- async tradebook() dict ¶
Retrieves daily trade details of the day.
- class aio_trader.fyers.FyersAuth(client_id: str, redirect_uri: str, secret_key: str, state: str | None = None, scope: str | None = None, nonce: str | None = None)¶
Bases:
object
Fyers class for generating access token
- Parameters:
client_id (str) – APP_ID of the created app.
redirect_uri (str) – URL provided when creating fyers app.
secret_key (str) – App secret key of the created app.
state (str) – A random string used to verify the request
scope (Optional[str]) – Default None.
nonce (Optional[str]) – Default None. A random string used to verify the auth token
import webbrowser from aio_trader.fyers import FyersAuth fyers_auth = FyersAuth( client_id="CLIENT_ID", redirect_uri="https://someurl.com", state="RANDOM_STRING", secret_key="SECRET_KEY", nonce="OTHER_RANDOM_STRING" ) auth_url = auth.generate_authcode() # After redirect auth_code is available in the redirect url params webbrowser.open(auth_url, new=1) auth_code = "Paste the auth_code generated from the first request" response = fyers_auth.generate_token(auth_code) if "access_token": access_token = response["access_token"] else: print("Failed requesting access_token")
- generate_authcode() str ¶
Returns a url to generate the auth token
- async generate_token(auth_code: str) dict ¶
Makes a request for an access token
- Parameters:
auth_code (str) – auth_code received after logging into fyers using generate_authcode().
- async refresh_token(refresh_token: str, pin: str) dict ¶
Refresh the access token using the refresh_token and user pin.
Refresh token is valid for 15 days.
- Parameters:
refresh_token (str) – refresh_token received from generate_token()
pin (str) – User login pin
- class aio_trader.fyers.FyersFeed(access_token: str, litemode=False, parse_data: bool = True, session: ClientSession | None = None)¶
Bases:
AbstractFeeder
Websocket class for Fyers
- property on_tick: Callable[[FyersFeed, Dict[str, Any], bool], None]¶
A user defined function called, when tick data is received. It receives the dictionary and a bool value indicating if the tick data is parsed.
def on_tick(feed: FyersFeed, tick: dict, binary=False) -> None
- property on_connect: Callable[[FyersFeed], None]¶
A user defined function called, when a websocket connection is established
def on_connect(feed: FyersFeed) -> None
- property on_error: Callable[[FyersFeed, error: Dict[str, Any]], None]¶
A user defined function called, when an error occurs
Error dictionary has the following key values:
code: int - Error code
message: str - The error message
def on_error(feed: FyersFeed, error: dict) -> None
- Parameters:
access_token (str) – Fyers access_token.
litemode (bool) – If true, only last traded price is updated in the feed. Default True.
parse_data (bool) – If true, on_tick handler receives raw binary/text data. Default True.
session (Optional[aiohttp.ClientSession].) – Client Session for making HTTP requests.
- channel_resume(channel: int) None ¶
Resumes the specified channel.
- Parameters:
channel (int) – The channel number to resume.
- async close()¶
Perform clean up operations to gracefully exit
- async connect(**kwargs) None ¶
Connect and start the Websocket connection
Uses the retry decorator to reconnect on error
@retry(max_retries=5, base_wait=2, max_wait=60)
- Parameters:
kwargs – Any keyword arguments to pass to aiohttp.ClientSession.ws_connect
- Type:
kwargs: Any
- async subscribe(symbols: List[str], data_type: Literal['SymbolUpdate', 'DepthUpdate'] = 'SymbolUpdate', channel: int = 11)¶
Subscribes to real-time data updates for the specified symbols.
symbols = [‘NSE:SBIN-EQ’, ‘NSE:ADANIENT-EQ’]
- Parameters:
symbols (List[str]) – A list of symbols to subscribe.
data_type (Literal['SymbolUpdate', "DepthUpdate"]) – Default “SymbolUpdate”. The type of data to subscribe.
channel (int) – Default 11. The channel to use for subscription.
- async unsubscribe(symbols: List[str], data_type: Literal['SymbolUpdate', 'DepthUpdate'] = 'SymbolUpdate', channel: int = 11)¶
Unsubscribes from real-time data updates for the specified symbols.
symbols = [‘NSE:SBIN-EQ’, ‘NSE:ADANIENT-EQ’]
- Parameters:
symbols (Literal["SymbolUpdate", "DepthUpdate"]) – A list of symbols to unsubscribe from.
data_type – Default “SymbolUpdate”. The type of data to unsubscribe from.
channel (int) – Default 11. The channel to use for unsubscription.
- class aio_trader.fyers.FyersOrder(access_token: str, session: ClientSession | None, parse_data: bool = True)¶
Bases:
AbstractFeeder
Websocket class for Fyers Order Websocket
- property on_tick: Callable[[FyersOrder, Dict[str, Any], bool], None]¶
A user defined function called, when an order notification is received. It receives the order dictionary and a bool value indicating if the order message is parsed.
def on_tick(feed: FyersOrder, order: dict, binary=False) -> None
- Parameters:
access_token (str) – Fyers access_token.
session (Optional[aiohttp.ClientSession].) – Client Session for making HTTP requests.
parse_data (bool) – If true, on_tick handler receives raw binary/text data. Default True.
- async close()¶
Perform clean up operations to gracefully exit
- async connect(**kwargs) None ¶
Connect and start the Websocket connection
- Parameters:
kwargs – Any keyword arguments to pass to aiohttp.ClientSession.ws_connect
- Type:
kwargs: Any
- async subscribe(data_type: str) None ¶
Subscribes to real-time updates of a specific data type.
await subscribe(data_type=”OnOrders”)
await subscribe(data_type=”OnOrders,OnTrades,OnPositions,OnGeneral”)
- Parameters:
data_type (str) – Can be one of OnOrders, OnTrades, OnPositions, or OnGeneral, or a comma separated list of values
- async unsubscribe(data_type: str) None ¶
Unsubscribes from real-time updates of a specific data type.
await unsubscribe(data_type=”OnOrders”)
await unsubscribe(data_type=”OnOrders,OnTrades,OnPositions,OnGeneral”)
- Parameters:
data_type (str) – Can be one of OnOrders, OnTrades, OnPositions, or OnGeneral, or a comma separated list of values