Introduction
For algorithmic traders in India, Fyers has emerged as a premier choice due to its robust infrastructure and free API access. The Fyers API v3 provides endpoints for order execution, historical data fetching, and high-speed WebSocket streaming. In this guide, we will walk you through the entire lifecycle of a Fyers API integration using Python—focusing heavily on the often-tricky authentication process and live data ingestion.
1. The Authentication Flow (OAuth 2.0)
Fyers uses an OAuth 2.0 flow for authentication. This requires a user to log in via a web interface to generate an Authorization Code, which is then exchanged for a permanent Access Token valid for the day. Automating this daily can be done using headless browsers like Selenium, or by prompting the user for the redirect URL.
sequenceDiagram
participant User/Script
participant Fyers Auth Server
participant Fyers API
User/Script->>Fyers Auth Server: Request Login URL (client_id, redirect_uri)
Fyers Auth Server-->>User/Script: Login Page
User/Script->>Fyers Auth Server: Submit Credentials & OTP
Fyers Auth Server-->>User/Script: Redirect with Auth Code
User/Script->>Fyers API: Exchange Auth Code + App Secret
Fyers API-->>User/Script: Access Token (Valid for the day)
Python Authentication Example
Here is how you can generate the login URL and validate the auth code using the official `fyers-apiv3` Python library.
from fyers_apiv3 import fyersModel
client_id = "YOUR_APP_ID"
secret_key = "YOUR_APP_SECRET"
redirect_uri = "https://127.0.0.1:5000/login"
response_type = "code"
session = fyersModel.SessionModel(
client_id=client_id,
secret_key=secret_key,
redirect_uri=redirect_uri,
response_type=response_type,
grant_type="authorization_code"
)
# Step 1: Generate Login URL
auth_url = session.generate_authcode()
print(f"Please login via this URL: {auth_url}")
# Step 2: Extract Auth Code from redirect URI and generate token
auth_code = input("Enter the Auth Code from the URL: ")
session.set_token(auth_code)
response = session.generate_token()
access_token = response['access_token']
print("Successfully generated access token!")
Key Takeaway: The Access Token generated is valid from the moment of generation until the end of the trading day. Always generate a fresh token before 9:00 AM IST.
2. Streaming Data via WebSockets
Once authenticated, the next critical step is getting live data. The Fyers WebSocket API allows you to subscribe to multiple symbols and receive tick-by-tick updates. This is vastly superior and faster than polling REST endpoints.
from fyers_apiv3.FyersWebsocket import data_ws
def onmessage(message):
"""
Callback function triggered on receiving data
"""
print("Market Data:", message)
def onerror(message):
print("Error:", message)
def onclose(message):
print("Connection closed:", message)
def onopen():
"""
Subscribe to symbols once the connection is established
"""
symbols = ["NSE:RELIANCE-EQ", "NSE:TCS-EQ"]
# data_type 1 is for symbol data, 2 for depth
fyers_ws.subscribe(symbol=symbols, data_type=1)
# Enable keep-alive to prevent disconnections
fyers_ws.keep_alive()
# Initialize WebSocket
access_token = "YOUR_APP_ID:YOUR_ACCESS_TOKEN" # Note the format!
fyers_ws = data_ws.FyersDataSocket(
access_token=access_token,
log_path="/logs",
litemode=False,
write_to_file=False
)
fyers_ws.websocket_data = onmessage
fyers_ws.websocket_error = onerror
fyers_ws.websocket_close = onclose
fyers_ws.websocket_open = onopen
# Start the connection in a block format
fyers_ws.connect()
3. Placing an Order
Executing an order through Fyers is a simple POST request containing parameters such as symbol, quantity, side (1 for Buy, -1 for Sell), and order type.
Conclusion
The Fyers API is extremely capable, offering low-latency endpoints perfect for building both simple automation scripts and complex high-frequency algorithms. By mastering the authentication flow and WebSocket integration, you unlock the foundation needed for algorithmic success in the Indian markets.
Ready to Automate This?
We can build this exact logic for you, securely hosted on our servers.
Get a Free Quote