Setup and Activate Fyers API with Python and Perform Automated TOTP Login
Automating stock trading requires reliable access to your broker’s API and secure authentication. Fyers offers a powerful API that can be integrated using Python. In this tutorial, we’ll walk you through setting up the Fyers API, activating it, and automating the TOTP (Time-Based One-Time Password) login process. Here you will learn step by step how to setup and activate fyers API with python and perform automated TOTP Loing.
Prerequisites
Before you begin, ensure you have the following:
- A Fyers account (https://fyers.in)
- Python installed on your system
- A virtual environment (optional but recommended)
- Basic knowledge of Python
- Fyers API App created from your Fyers developer account
- TOTP enabled on your Fyers account
Step 1: Create and Activate Your Fyers API App
- Go to Fyers Developer Console.
- Log in and click on Create App.
- Fill in the required details:
- App Name
- Redirect URL (e.g.,
https://127.0.0.1
) - Description
- Once created, note down:
- Client ID
- Secret ID
- Redirect URL
- App ID
- Set up TOTP for your account using an app like Google Authenticator or Authy and save the TOTP secret (hash string) securely (we’ll need this for automation).
Step 2: Install Required Python Packages
pip install fyers-apiv2 pyotp requests
Step 3: Automate the TOTP Generation
Use pyotp
to generate the current TOTP for your Fyers login:
import pyotp
totp_secret = "YOUR_TOTP_SECRET" # Replace with your TOTP secret
totp = pyotp.TOTP(totp_secret)
print(totp.now())
The Complete Source Code
Here’s a full script to automate the login and generate the access token:
Troubleshooting
- If you encounter
invalid TOTP
, make sure your system clock is synchronized. - Make sure you input the correct auth code in the script.
- Always use secure methods to store your credentials and tokens.
Conclusion
With this setup, you’ve successfully setup and activated the Fyers API, automated your TOTP-based login using Python, and are ready to make authorized requests. This is the first step in building a robust automated trading system. Next you can learn to use this script to Fetch Historical Data, Daily Quote, Market Depth of any Stock. If you want to explore more interesting videos you can visit my YouTube Channel also.
Need help with placing orders or creating strategies? Stay tuned for upcoming tutorials!