Skip to main content

The Fyers API Python client - v3.2.1

The official Python client for communicating with the Fyers API

Documentation

Requirements

  • Python v3

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.

Screeners API contract:

  • fyers.screeners_query(...) is replaced by fyers.screeners_standard(...) (/screeners/query -> /screeners/standard).
  • The screener request param is renamed to screener_id on the standard, technical and candlestick endpoints.
  • The config key screeners is renamed to screeners_standard, and timeframes now lists timeframe ids (t0_5min, c52_week, ...), not percentage-change columns.
  • dividend_per_share is renamed to yearly_dividend_per_share; the iw031 universe is gone.
  • Responses no longer carry is_editable, data.error, data.id or the allow_sort, is_sortable, is_formated_to_klcr, feed_type and criteria_label header fields.
  • The standard response reports the settings actually applied (data.universe, data.timeframe, data.expiry, data.option_type), which may be server defaults.

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

#### Generate an authcode and then make a request to generate an accessToken (Login Flow)

"""
1. Input parameters
"""
redirect_uri= "APP REDIRECT URI"  ## redircet_uri you entered while creating APP.
client_id = "XCXXXXXxxM-100"                       ## Client_id here refers to APP_ID of the created app
secret_key = "MH*****TJ5"                          ## app_secret key which you got after creating the app 
grant_type = "authorization_code"                  ## The grant_type always has to be "authorization_code"
response_type = "code"                             ## The response_type always has to be "code"
state = "sample"                                   ##  The state field here acts as a session manager. you will be sent with the state field after successfull generation of auth_code 


### Connect to the sessionModel object here with the required input parameters
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)

# ## Make  a request to generate_authcode object this will return a login url which you need to open in your browser from where you can get the generated auth_code 
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 """
##########################################################################################################################

### After succesfull login the user can copy the generated auth_code over here and make the request to generate the accessToken 
auth_code = "Paste the auth_code generated from the first request"
appSession.set_token(auth_code)
response = appSession.generate_token()

## There can be two cases over here you can successfully get the acccessToken over the request or you might get some error over here. so to avoid that have this in try except block
try: 
    access_token = response["access_token"]
except Exception as e:
    print(e,response)  ## This will help you in debugging then and there itself like what was the error and also you would be able to see the value you got in response variable. instead of getting key_error for unsuccessfull response.



## Once you have generated accessToken now we can call multiple trading related or data related apis after that in order to do so we need to first initialize the fyerModel object with all the requried params.
"""
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="")


## After this point you can call the relevant apis and get started with

####################################################################################################################
"""
1. User Apis : This includes (Profile,Funds,Holdings)
"""

print(fyers.get_profile())  ## This will provide us with the user related data 

print(fyers.funds())        ## This will provide us with the funds the user has 

print(fyers.holdings())    ## This will provide the available holdings the user has 


########################################################################################################################

"""
2. Transaction Apis : This includes (Tradebook,Orderbook,Positions)
"""

print(fyers.tradebook())   ## This will provide all the trade related information 

print(fyers.orderbook())   ## This will provide the user with all the order realted information 

print(fyers.positions())   ## This will provide the user with all the positions the user has on his end 


######################################################################################################################

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

NOTE: Prefer CNC / INTRADAY / MARGIN / MTF with optional takeProfit / stopLoss / legType.
takeProfit / stopLoss / legType may be omitted for a normal order.
When set, offsets are relative to entry price (legType=1 points, legType=2 percent).
"""

## SINGLE ORDER 

data =  {
      "symbol":"NSE:ONGC-EQ",
      "qty":1,
      "type":1,
      "side":1,
      "productType":"INTRADAY",
      "limitPrice":0,
      "stopPrice":0,
      "validity":"DAY",
      "disclosedQty":0,
      "offlineOrder":False,
      "isSliceOrder":False
    }                              ## This is a sample example to place a limit order you can make the further changes based on your requriements 

print(fyers.place_order(data))

## SINGLE ORDER with optional TP/SL overlay (fields may be omitted)

data =  {
      "symbol":"NSE:SBIN-EQ",
      "qty":10,
      "type":1,
      "side":1,
      "productType":"INTRADAY",
      "limitPrice":500.0,
      "stopPrice":0,
      "validity":"DAY",
      "disclosedQty":0,
      "offlineOrder":False,
      "takeProfit":10.5,
      "stopLoss":5.0,
      "legType":1
    }

print(fyers.place_order(data))

## MULTI ORDER 

data = [{ "symbol":"NSE:SBIN-EQ",
  "qty":1,
  "type":1,  
  "side":1, 
  "productType":"INTRADAY",   
  "limitPrice":61050,
  "stopPrice":0 ,
  "disclosedQty":0, 
  "validity":"DAY", 
  "offlineOrder":False
},
{
  "symbol":"NSE:HDFC-EQ",
  "qty":1,
  "type":2,  
  "side":1, 
  "productType":"INTRADAY",   
  "limitPrice":0,
  "stopPrice":0 ,
  "disclosedQty":0, 
  "validity":"DAY", 
  "offlineOrder":False
}]                                                ### This takes input as a list containing multiple single order data into it and the execution of the orders goes in the same format as mentioned.

print(fyers.place_basket_orders(data))

## MULTILEG ORDER

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
        }
    }
}               ### This is a sample data structure used to place an 3 leg order using multileg order api .you can make the further changes based on your requriements 

print(fyers.place_multileg_order(data))


###################################################################################################################

"""
4. Other Transaction : This includes (modify_order,exit_position,cancel_order,convert_positions,attach_position_legs)
"""

## Modify_order request (update TP, remove SL)
data = {
          "id":"7574657627567", 
          "type":1, 
          "limitPrice": 61049,
          "qty":1,
          "takeProfit":15.0,
          "stopLoss":None
      }

print(fyers.modify_order(data))

## Modify Multi Order 

data = [
    { "id":"8102710298291",
  "type":1,
  "limitPrice": 61049,
  "qty":0
},
{
  "id":"8102710298292",
  "type":1,
  "limitPrice": 61049,
  "qty":1 
}]

print(fyers.modify_basket_orders(data))


### Cancel_order
data = {"id":'808058117761'}
print(fyers.cancel_order(data))

### cancel_multi_order 
data  =  [
{ 
   "id":'808058117761'
 },
 {
   "id":'808058117762'
 }]
 
print(fyers.cancel_basket_orders(data))


### Exit Position 
data  = {
     "id":"NSE:SBIN-EQ-INTRADAY"
   }

print(fyers.exit_positions(data))


### Attach / update TP/SL on an open position
data = {
    "positionId": "NSE:SBIN-EQ-INTRADAY",
    "takeProfit": 2.5,
    "stopLoss": 1.5,
    "legType": 2
}

print(fyers.attach_position_legs(data))


### Convert Position

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)
"""

## Historical Data 

data = {"symbol":"NSE:SBIN-EQ","resolution":"D","date_format":"0","range_from":"1622097600","range_to":"1622097685","cont_flag":"1"}

print(fyers.history(data))

## Quotes 

data = {"symbols":"NSE:SBIN-EQ"}
print(fyers.quotes(data))

## Quotes APIv3 (POST)

data = {"symbols": ["NSE:SBIN-EQ"]}
print(fyers.quotes_v2(data))


## Market Depth 

data = {"symbol":"NSE:SBIN-EQ","ohlcv_flag":"1"}
print(fyers.depth(data))


## Futures Chain

data = {"symbol": "NSE:NIFTY50-INDEX"}
print(fyers.futures_chain(data))

## Expired F&O — Expiry Dates

data = {
    "symbol": "NSE:NIFTY50-INDEX",
    "range_from": "2024-01-01",
    "range_to": "2024-12-31",
    "date_format": "1"
}
response = fyers.expiry_dates(data)
print(response)
print(response["data"]["expiry_dates"]["futures"])
print(response["data"]["expiry_dates"]["options"])

## Expired F&O — Underlying Symbols

data = {
    "symbol": "NSE:NIFTY50-INDEX",
    "expiry_date": "2024-11-28"
}
response = fyers.history_underlying_symbols(data)
print(response)
print(response["data"]["contracts"]["futures"])
print(response["data"]["contracts"]["options"])

## Expired F&O — Historical Data

data = {
    "symbol": "NSE:NIFTY24NOV22500CE",
    "resolution": "5",
    "date_format": "1",
    "range_from": "2024-11-01",
    "range_to": "2024-11-28",
    "include_greeks": "1",
    "include_oi": "1"
}
response = fyers.fno_historical_data(data)
print(response)
print(response["candles"])


#################################################################################################################

"""
SCREENERS : This includes following APIs (screeners_config, screeners_standard, screeners_technical, screeners_candlestick)
"""

## Screeners Config
# Lists the screeners, columns, universes, groups, timeframes, option types,
# expiry types and the live expiries the other endpoints accept.
config = fyers.screeners_config()
print(config["data"]["screeners_standard"])
print(config["data"]["timeframes"])       # [{"id": "t0_5min", ...}, {"id": "c52_week", ...}]
print(config["data"]["expiries"])         # per universe: {"epoch": ..., "date": ..., "display": ...}

## Standard Screener
# The payload is sent to the API as given. The server applies the screener's own
# defaults for anything you omit and validates the rest.
data = {
    "screener_id": "top_gainers",
    "fields": "t0_close_ltp,t0_volume",
    "universe": "iw010",
    "order_by": "t0_change_per",
    "order": "desc",
    "timeframe": "t0_5min",
    # "expiry": 1793095800,
    # "option_type": "CE",
}
response = fyers.screeners_standard(data)
print(response["data"]["header"])
print(response["data"]["body"])
# The settings the server actually applied, defaults included:
print(response["data"]["universe"], response["data"]["timeframe"],
      response["data"]["expiry"], response["data"]["option_type"])

## Technical Screener
response = fyers.screeners_technical({"screener_id": "rsi_overbought"})
print(response["data"]["body"], response["data"]["total_count"])

## Candlestick Screener
response = fyers.screeners_candlestick({"screener_id": "bullish_engulfing"})
print(response["data"]["body"], response["data"]["total_count"])

#################################################################################################################

"""
PRICE ALERTS : This includes following APIs (create_alert, get_alert, update_alert, delete_alert, toggle_alert)
"""

## Create Price Alert
data = {
    "agent": "fyers-api",
    "alert-type": 1,
    "name": "gold alert",
    "symbol": "NSE:GOLDBEES-EQ",
    "comparisonType": "LTP",
    "condition": "GT",
    "value": "9888",
    "notes": " iji"
}

print(fyers.create_alert(data))

## Get Price Alerts
# Get all active alerts
print(fyers.get_alert())

# Get archived alerts
data = {"archive": "1"}
print(fyers.get_alert(data))

## Update Price Alert
data = {
    "alertId": "6249977",
    "agent": "fyers-api",
    "alert-type": 1,
    "name": "goldy bees",
    "symbol": "NSE:GOLDBEES-EQ",
    "comparisonType": "OPEN",
    "condition": "GT",
    "value": "10000.00676766767676676667"
}

print(fyers.update_alert(data))

## Delete Price Alert
data = {"alertId": "6131416", "agent": "fyers-api"}
print(fyers.delete_alert(data))

## Toggle Price Alert (Enable/Disable)
data = {"alertId": "3870991"}
print(fyers.toggle_alert(data))


#################################################################################################################

"""
SMART ORDERS : This includes following APIs (create, modify, cancel, pause, resume, orderbook)
Smart orders support different flow types: step, limit, trail, sip
"""

## Create Smart Order - Step
data = {
    "symbol": "NSE:SBIN-EQ",
    "qty": 10,
    "type": 1,
    "side": 1,
    "productType": "INTRADAY",
    "limitPrice": 600.00,
    "stopPrice": 0,
    "validity": "DAY",
    "disclosedQty": 0,
    "offlineOrder": False
}

print(fyers.create_smart_order_step(data))

## Create Smart Order - Limit
data = {
    "symbol": "NSE:SBIN-EQ",
    "qty": 10,
    "type": 1,
    "side": 1,
    "productType": "INTRADAY",
    "limitPrice": 600.00,
    "stopPrice": 0,
    "validity": "DAY",
    "disclosedQty": 0,
    "offlineOrder": False
}

print(fyers.create_smart_order_limit(data))

## Create Smart Order - Trail
data = {
    "symbol": "NSE:SBIN-EQ",
    "qty": 10,
    "type": 1,
    "side": 1,
    "productType": "INTRADAY",
    "limitPrice": 600.00,
    "stopPrice": 0,
    "validity": "DAY",
    "disclosedQty": 0,
    "offlineOrder": False
}

print(fyers.create_smart_order_trail(data))

## Create Smart Order - SIP
data = {
    "symbol": "NSE:SBIN-EQ",
    "qty": 10,
    "type": 1,
    "side": 1,
    "productType": "CNC",
    "limitPrice": 600.00,
    "stopPrice": 0,
    "validity": "DAY",
    "disclosedQty": 0,
    "offlineOrder": False
}

print(fyers.create_smart_order_sip(data))

## Modify Smart Order
data = {
    "flowId": "123456789",
    "limitPrice": 610.00,
    "qty": 15
}

print(fyers.modify_smart_order(data))

## Cancel Smart Order
data = {"flowId": "123456789"}
print(fyers.cancel_smart_order(data))

## Pause Smart Order
data = {"flowId": "123456789"}
print(fyers.pause_smart_order(data))

## Resume Smart Order
data = {"flowId": "123456789"}
print(fyers.resume_smart_order(data))

## Get Smart Order Book with Filter
# Get all smart orders
print(fyers.smart_orderbook_with_filter())

# Get filtered smart orders
# Filter by side (1 for Buy, -1 for Sell)
data = {"side": [1]}
print(fyers.smart_orderbook_with_filter(data))

# Filter by multiple parameters
data = {
    "exchange": ["NSE"],
    "side": [1, -1],
    "flowtype": [1, 2],
    "product": ["CNC", "INTRADAY"],
    "messageType": [1, 2],
    "search": "SBIN",
    "sort_by": "CreatedTime",
    "ord_by": 1,
    "page_no": 1,
    "page_size": 15
}
print(fyers.smart_orderbook_with_filter(data))


#################################################################################################################

"""
SMART EXIT TRIGGERS : This includes following APIs (create_smartexit_trigger,
get_smartexit_triggers, update_smartexit_trigger,
activate_deactivate_smartexit_trigger)
"""

## Create Smart Exit Trigger

# Type 1: Only Alert (notification only, no auto-exit)
data = {
    "name": "Alert Only Strategy",
    "type": 1,
    "profitRate": 5000,
    "lossRate": -2000
}
print(fyers.create_smartexit_trigger(data))

# Type 2: Exit with Alert (notification + immediate exit)
data = {
    "name": "Auto Exit Strategy",
    "type": 2,
    "profitRate": 5000,
    "lossRate": -2000
}
print(fyers.create_smartexit_trigger(data))

# Type 3: Exit with Alert + Wait for Recovery (notification + delayed exit)
data = {
    "name": "Recovery Exit Strategy",
    "type": 3,
    "profitRate": 10000,
    "lossRate": -3000,
    "waitTime": 5
}
print(fyers.create_smartexit_trigger(data))

## Get Smart Exit Triggers
# Get all smart exit triggers
print(fyers.get_smartexit_triggers())


## Update Smart Exit Trigger
data = {
    "flowId": "123456789",
    "triggerPrice": 610.00,
    "stopLoss": 600.00,
    "takeProfit": 630.00
}

print(fyers.update_smartexit_trigger(data))

## Activate / Deactivate Smart Exit Trigger
data = {"flowId": "123456789"}
print(fyers.activate_deactivate_smartexit_trigger(data))


#################################################################################################################

"""
GTT / OCO ORDERS : This includes following APIs (place_gtt_order, modify_gtt_order,
cancel_gtt_order, gtt_orderbook)
"""

## Place GTT order (leg1 is mandatory; add leg2 for an OCO order)
data = {
    "side": 1,
    "symbol": "NSE:CHOLAFIN-EQ",
    "productType": "CNC",
    "orderInfo": {
        "leg1": {
            "price": 1500,
            "triggerPrice": 1495,
            "qty": 1
        }
    }
}
print(fyers.place_gtt_order(data))

## Modify GTT order
data = {
    "id": "25010700000001",
    "orderInfo": {
        "leg1": {
            "price": 1510,
            "triggerPrice": 1505,
            "qty": 2
        }
    }
}
print(fyers.modify_gtt_order(data))

## Cancel GTT order
data = {"id": "25010700000001"}
print(fyers.cancel_gtt_order(data))

## GTT order book
print(fyers.gtt_orderbook())


#################################################################################################################

"""
MORE DATA / ACCOUNT APIS : (market_status, optionchain, get_orders, logout)
"""

## Market status - takes no arguments
print(fyers.market_status())

## Option chain
data = {
    "symbol": "NSE:NIFTY50-INDEX",
    "strikecount": 7,
    "timestamp": ""
}
print(fyers.optionchain(data))

## Order details by id
data = {"id": "808058117761"}
print(fyers.get_orders(data))

## Logout - invalidates the current access token, takes no arguments
print(fyers.logout())


#################################################################################################################

"""
REPORTS : This includes following APIs (orderhistory, tradehistory, charges_history,
realised_profit_history, tax_pnl_history, ledger_history)
"""

## Order history
data = {
    "symbol": "NSE:SBIN-EQ",
    "from_date": "2024-11-01",
    "to_date": "2024-11-28",
    "page_no": 1,
    "page_size": 100,
    "segment_type": "0",
    "exchange_type": "0",
    "status": "0"
}
print(fyers.orderhistory(data))

## Trade history
data = {
    "from_date": "2024-11-01",
    "to_date": "2024-11-28",
    "page_no": 1,
    "page_size": 100
}
print(fyers.tradehistory(data))

## Charges history
print(fyers.charges_history({"from_date": "2024-11-01", "to_date": "2024-11-28"}))

## Realised P&L history
print(fyers.realised_profit_history({"from_date": "2024-11-01", "to_date": "2024-11-28"}))

## Tax P&L history
print(fyers.tax_pnl_history({"from_date": "2024-11-01", "to_date": "2024-11-28"}))

## Ledger history
print(fyers.ledger_history({"from_date": "2024-11-01", "to_date": "2024-11-28"}))

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.

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


    # Subscribe to the specified symbols and data type
    symbols = ['NSE:SBIN-EQ', 'NSE:ADANIENT-EQ']
    fyers.subscribe(symbols=symbols, data_type=data_type)

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


# Replace the sample access token with your actual access token obtained from Fyers
access_token = "XCXXXXXXM-100:eyJ0tHfZNSBoLo"

# Create a FyersDataSocket instance with the provided parameters
fyers = data_ws.FyersDataSocket(
    access_token=access_token,       # Access token in the format "appid:accesstoken"
    log_path="",                     # Path to save logs. Leave empty to auto-create logs in the current directory.
    litemode=False,                  # Lite mode disabled. Set to True if you want a lite response.
    write_to_file=False,              # Save response in a log file instead of printing it.
    reconnect=True,                  # Enable auto-reconnection to WebSocket on disconnection.
    on_connect=onopen,               # Callback function to subscribe to data upon connection.
    on_close=onclose,                # Callback function to handle WebSocket connection close events.
    on_error=onerror,                # Callback function to handle WebSocket errors.
    on_message=onmessage             # Callback function to handle incoming messages from the WebSocket.
)

# Establish a connection to the Fyers WebSocket
fyers.connect()

Getting started with Order Socket

from fyers_apiv3.FyersWebsocket import order_ws


def onTrade(message):
    """
    Callback function to handle incoming trade messages from the FyersOrderSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.
            - message["trades"]: Contains trade data including id_fyers field if present
            - message["s"]: Status of the message
    
    Note: The message may contain an "id_fyers" field in the trades data, which is a unique identifier
    for Fyers-specific trade tracking.
    """
    print("Trade Response:", message)


def onOrder(message):
    """
    Callback function to handle incoming order messages from the FyersOrderSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.
            - message["orders"]: Contains order data including id_fyers field if present
            - message["s"]: Status of the message
    
    Note: The message may contain an "id_fyers" field in the orders data, which is a unique identifier
    for Fyers-specific order tracking.
    """
    print("Order Response:", message)


def onPosition(message):
    """
    Callback function to handle incoming position messages from the FyersOrderSocket WebSocket.

    Parameters:
        message (dict): The received message from the WebSocket.
            - message["positions"]: Contains position data including id_fyers field if present
            - message["s"]: Status of the message
    
    """
    print("Position Response:", message)


def onGeneral(message):
    """
    Callback function to handle incoming general messages from the FyersOrderSocket WebSocket.
    This includes eDIS updates, price alerts, and login events.

    Parameters:
        message (dict): The received message from the WebSocket.
            - May contain price alerts with id_fyers field if present
            - May contain eDIS updates
            - May contain login events

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

    """
    # Specify the data type and symbols you want to subscribe to
    # data_type = "OnOrders"
    # data_type = "OnTrades"
    # data_type = "OnPositions"
    # data_type = "OnGeneral"
    data_type = "OnOrders,OnTrades,OnPositions,OnGeneral"

    fyers.subscribe(data_type=data_type)

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


# Replace the sample access token with your actual access token obtained from Fyers
access_token = "XCXXXXXXM-100:eyJ0tHfZNSBoLo"

# Create a FyersDataSocket instance with the provided parameters
fyers = order_ws.FyersOrderSocket(
    access_token=access_token,  # Your access token for authenticating with the Fyers API.
    write_to_file=False,        # A boolean flag indicating whether to write data to a log file or not.
    log_path="",                # The path to the log file if write_to_file is set to True (empty string means current directory).
    on_connect=onopen,          # Callback function to be executed upon successful WebSocket connection.
    on_close=onclose,           # Callback function to be executed when the WebSocket connection is closed.
    on_error=onerror,           # Callback function to handle any WebSocket errors that may occur.
    on_general=onGeneral,       # Callback function to handle general events from the WebSocket.
    on_orders=onOrder,          # Callback function to handle order-related events from the WebSocket.
    on_positions=onPosition,    # Callback function to handle position-related events from the WebSocket.
    on_trades=onTrade           # Callback function to handle trade-related events from the WebSocket.
)

# Establish a connection to the Fyers WebSocket
fyers.connect()

Getting started with TBT Socket

from  fyers_apiv3.FyersWebsocket.tbt_ws import FyersTbtSocket, SubscriptionModes

def on_depth_update(ticker, message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        ticker (str): The symbol for which the message is received.
        message (dict): The received message from the WebSocket.

    """
    print("Depth Response:", ticker, message)


def onerror_message( message):
    """
    Callback function to handle incoming messages from the FyersDataSocket WebSocket.

    Parameters:
        message (str): error message from the server

    """
    print("server returned error:", 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.

    """
    print("Connection opened")
    # Specify the data type and symbols you want to subscribe to
    mode = SubscriptionModes.DEPTH
    Channel = '1'
    # Subscribe to the specified symbols and data type
    symbols = ['NSE:NIFTY25MARFUT']
    
    fyers.subscribe(symbol_tickers=symbols, channelNo=Channel, mode=mode)
    fyers.switchChannel(resume_channels=[Channel], pause_channels=[])

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


# Replace the sample access token with your actual access token obtained from Fyers
access_token = "XCXXXXXXM-100:eyJ0tHfZNSBoLo"

fyers = FyersTbtSocket(
    access_token=access_token,  # Your access token for authenticating with the Fyers API.
    write_to_file=False,        # A boolean flag indicating whether to write data to a log file or not.
    log_path="",                # The path to the log file if write_to_file is set to True (empty string means current directory).
    on_open=onopen,          # Callback function to be executed upon successful WebSocket connection.
    on_close=onclose,           # Callback function to be executed when the WebSocket connection is closed.
    on_error=onerror,           # Callback function to handle any WebSocket errors that may occur.
    on_depth_update=on_depth_update, # Callback function to handle depth-related events from the WebSocket
    on_error_message=onerror_message         # Callback function to handle server-related erros from the WebSocket.
)


# Establish a connection to the Fyers WebSocket
fyers.connect()

Metadata

Release files for fyers-apiv3 3.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fyers-apiv3 3.2.1
File Size Uploaded Provenance Actions
fyers_apiv3-3.2.1.tar.gz 60.8 kB Without provenance Details for fyers_apiv3-3.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fyers-apiv3 3.2.1
File Interpreter ABI Platform Actions
fyers_apiv3-3.2.1-py3-none-any.whl Python 3 none any Details for fyers_apiv3-3.2.1-py3-none-any.whl

Total release size: 111.0 kB

Release files / fyers_apiv3-3.2.1.tar.gz

Download URL fyers_apiv3-3.2.1.tar.gz
Size 60.8 kB
Tags Source
SHA-256 checksum
How to use checksums
b711cf21a4ded27749ba17613c36957731232e73e967a3f9d2a367202cecc6dd
BLAKE2b-256 checksum
How to use checksums
004a79f56a0447d3326e7d0637539dfea8cba5217d08cd12a6f67d1c0cb3edc4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Release files / fyers_apiv3-3.2.1-py3-none-any.whl

Download URL fyers_apiv3-3.2.1-py3-none-any.whl
Size 50.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
86e8d049128c192c26eba557a50e50b21288112cdf054ed8a22c512f1ea0eb40
BLAKE2b-256 checksum
How to use checksums
b284da627c6536b7f6657ebc22b6ed6a02bc83998f5b332cfb22f53ac7c71f1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Security for fyers-apiv3 3.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.2.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page