Getting started overview
This guide outlines the essential steps for developers to integrate with SmartAPI, focusing on account setup, credential generation, and executing a foundational API request. SmartAPI provides programmatic access to Angel One's trading platform, enabling functionalities such as real-time market data retrieval, order placement, and portfolio management. The process involves creating an Angel One trading account, generating API credentials, and utilizing an SDK or direct HTTP requests for interaction. Users should be aware of the brokerage charges that apply to trades executed through the platform.
Before proceeding, ensure you have a stable internet connection and access to a development environment suitable for your chosen programming language. SmartAPI offers comprehensive documentation and SDKs for Python, Java, Node.js, PHP, and C# to facilitate integration.
Quick Reference Steps
| Step | What to do | Where |
|---|---|---|
| 1. Open Trading Account | Complete KYC and activate your Angel One demat and trading account. | Angel One website |
| 2. Register for SmartAPI | Log in to your Angel One account and navigate to the SmartAPI section. | SmartAPI portal |
| 3. Generate API Key | Create an application and obtain your unique API key and client ID. | SmartAPI dashboard |
| 4. Install SDK | Install the SmartAPI Python SDK (or your preferred language SDK). | Command line (pip install SmartApi) |
| 5. Authenticate | Use your client ID, API key, and TOTP to generate a session token. | Your application code |
| 6. Make First Request | Execute a simple request, such as fetching market data or placing a test order. | Your application code |
Create an account and get keys
Access to SmartAPI requires an active trading and demat account with Angel One. This is the foundational step for all subsequent API interactions, as your API access is linked to your brokerage account. The process generally involves identity verification (KYC) and account activation.
Step 1: Open an Angel One Trading Account
If you do not already have one, you must open a trading and demat account with Angel One. This process typically involves:
- Visiting the Angel One homepage and initiating the account opening process.
- Completing Know Your Customer (KYC) requirements by providing necessary identity and address proofs, as mandated by SEBI regulations for financial markets.
- Linking your bank account for fund transfers.
- Completing in-person verification (IPV) if required.
Once your account is successfully activated, you will receive your Client ID, which is essential for API access.
Step 2: Register for SmartAPI and Generate API Key
With an active Angel One trading account, you can proceed to register for SmartAPI and generate your API key:
- Log in to your Angel One account on the SmartAPI portal.
- Navigate to the 'My API' or 'Developer' section, typically found in your profile or dashboard.
- Click on 'Create New App' or a similar option.
- Provide an application name and a redirect URL. The redirect URL is crucial for the OAuth 2.0 flow, even if you are using a client-side SDK. For server-side applications, this might be a placeholder or a local callback URL during development.
- Upon successful creation, SmartAPI will provide you with an API Key. This key is unique to your application and acts as an identifier for your requests.
- Your Angel One Client ID (also known as User ID) will be used in conjunction with the API key for authentication.
- You will also need to set up a Time-based One-Time Password (TOTP) for enhanced security during the login process. This is typically configured through an authenticator app.
Keep your API Key, Client ID, and TOTP secret and secure. Do not embed them directly into client-side code or public repositories.
Your first request
This section demonstrates how to make a basic API call using the SmartAPI Python SDK. Before proceeding, ensure Python is installed and accessible in your environment.
Step 1: Install the SmartAPI Python SDK
Open your terminal or command prompt and install the SmartAPI Python SDK:
pip install SmartApi
Step 2: Basic Authentication and Session Creation
The first step in any interaction with SmartAPI is authentication. This involves using your Client ID, API Key, and TOTP to obtain a session token. The Python SDK simplifies this process.
Create a Python file (e.g., smartapi_test.py) and add the following code. Replace the placeholder values with your actual credentials.
from SmartApi import SmartConnect
from SmartApi.smartApiContext import SmartAPIContext
import pyotp
# --- Replace with your actual credentials ---
API_KEY = "YOUR_API_KEY"
CLIENT_ID = "YOUR_CLIENT_ID"
PASSWORD = "YOUR_PASSWORD" # Your Angel One trading account password
TOTP_SECRET = "YOUR_TOTP_SECRET" # The secret key from your authenticator app
FEED_TOKEN = "YOUR_FEED_TOKEN" # This is obtained after successful login
# Initialize SmartConnect
obj = SmartConnect(api_key=API_KEY)
# Generate TOTP
totp = pyotp.TOTP(TOTP_SECRET).now()
# Create a dictionary for login parameters
data = {
"clientcode": CLIENT_ID,
"password": PASSWORD,
"totp": totp
}
try:
# Login to generate session
session = obj.generateSession(data)
print("Login successful!")
print("Session data:", session)
# Extract JWT token and refreshToken
jwt_token = session['data']['jwtToken']
refresh_token = session['data']['refreshToken']
feed_token = session['data']['feedToken'] # This is the FEED_TOKEN you need
# Initialize SmartAPIContext with the obtained tokens
smartApiContext = SmartAPIContext(jwt_token, refresh_token, feed_token, API_KEY)
print("SmartAPIContext initialized.")
except Exception as e:
print(f"Login failed: {e}")
Execute the script:
python smartapi_test.py
A successful execution will print the session data, including the JWT token, refresh token, and feed token. These tokens are crucial for making subsequent authenticated requests.
Step 3: Make a Sample Market Data Request
Once authenticated, you can make requests to fetch market data. Let's retrieve the live quote for a specific instrument.
Add the following code to your smartapi_test.py file, after the successful session generation. Ensure you replace FEED_TOKEN with the actual feed token obtained from the generateSession response.
# --- Assuming successful login and smartApiContext is initialized ---
# Example: Get live market data for NIFTY 50
try:
# Refer to SmartAPI documentation for instrument tokens and exchange types
# For NIFTY 50, exchange is NSE, instrument token is often '26000'
# You can use the search API to find instrument tokens dynamically
instrument_token = "26000" # Example token for NIFTY 50 (verify from SmartAPI docs)
exchange_type = "NSE"
# Get a single quote
quote_data = smartApiContext.ltpData(
exchange=exchange_type,
tradingsymbol="NIFTY", # Trading symbol for display purposes
instrumenttoken=instrument_token
)
print("\nLive Quote for NIFTY 50:", quote_data)
# Get multiple quotes (example)
# data_payload = {
# "exchangeType": "NSE",
# "tokens": [{"instrumenttoken":"26000", "exchangeType":"NSE"}, {"instrumenttoken":"1532", "exchangeType":"NSE"}] # NIFTY 50 and RELIANCE
# }
# multiple_quotes = smartApiContext.ltpData(data_payload)
# print("\nMultiple Live Quotes:", multiple_quotes)
except Exception as e:
print(f"Error fetching market data: {e}")
Run the script again. You should see the live quote data for NIFTY 50 printed in your console.
Common next steps
After successfully making your first API call, consider these next steps to further develop your integration with SmartAPI:
- Explore More Endpoints: Review the SmartAPI documentation to understand the full range of available endpoints, including those for order placement, order book, trade book, positions, holdings, and historical data.
- Implement Error Handling: Incorporate robust error handling mechanisms in your code to manage API rate limits, authentication failures, and other potential issues. This ensures your application can gracefully recover from unexpected responses.
- Utilize Webhooks for Real-time Updates: For certain events, SmartAPI may offer webhook capabilities or streaming APIs (like WebSockets for live market data) to receive real-time updates without constant polling. Refer to the documentation for specifics on implementing these.
- Manage Authentication Tokens: Understand the expiry periods of JWT and refresh tokens. Implement logic to refresh tokens automatically before they expire to maintain continuous access to the API.
- Secure Your Credentials: Beyond not hardcoding, consider using environment variables, a secure configuration management system, or a secrets manager to store your API key, client ID, and TOTP secret.
- Develop Trading Strategies: Begin building and backtesting your algorithmic trading strategies using historical data and then testing with real-time data in a simulated or small-scale live environment.
- Monitor API Usage: Keep track of your API call frequency to stay within rate limits and avoid service interruptions.
- Explore Other SDKs: If Python is not your primary development language, explore the other available SDKs (Java, Node.js, PHP, C#) to integrate SmartAPI into your preferred environment.
Troubleshooting the first call
If your first API call encounters issues, consider the following troubleshooting steps:
- Verify Credentials: Double-check your API Key, Client ID, Password, and TOTP secret. Even a single character mismatch can cause authentication to fail. Ensure your TOTP is generated correctly at the time of the request.
- Check Account Status: Confirm that your Angel One trading account is active and fully operational. API access is contingent on an active account.
- Review Redirect URL: For OAuth-based flows, ensure the redirect URL configured in your SmartAPI application matches the one used in your code.
- Examine API Response: Print the full API response, including status codes and error messages. These messages often provide specific details about what went wrong. Common HTTP status codes to look for include
401 Unauthorized(credential issues),403 Forbidden(permission issues), and429 Too Many Requests(rate limits). - Consult Documentation: Refer to the SmartAPI documentation's troubleshooting section or API reference for specific error codes and their resolutions.
- Network Connectivity: Ensure your development environment has stable internet access and is not blocked by firewalls or proxy settings from reaching SmartAPI endpoints.
- SDK Version: Ensure you are using the latest version of the SmartAPI SDK. Outdated SDKs might have compatibility issues with the latest API versions.
- Rate Limits: If you are making multiple requests in quick succession, you might hit API rate limits. Implement delays or backoff strategies if this is suspected.
- TOTP Sync: If your TOTP constantly fails, ensure your device's clock is synchronized with a reliable time server. TOTP relies on accurate time synchronization.
- Contact Support: If you've exhausted all troubleshooting steps, contact Angel One's SmartAPI support for assistance. Provide them with your Client ID, API Key, and the exact error message you are receiving.