Python SDK Guide

AngelOne SmartAPI Python SDK

A comprehensive guide to integrating AngelOne's official SmartAPI Python SDK into your trading applications. Learn how to authenticate, place orders, fetch market data, and stream real-time ticks.

AngelOne Logo

What you can build with SmartAPI

The SmartAPI Python SDK provides comprehensive access to AngelOne's trading infrastructure.

Session Management

Authenticate using API key, client code, PIN, and TOTP for secure access.

Order Placement

Place, modify, and cancel orders with full control over order parameters.

GTT Orders

Create and manage Good Till Triggered orders for automated trading.

Historical Data

Fetch OHLCV candle data for backtesting and technical analysis.

WebSocket V2

Subscribe to real-time tick data with efficient WebSocket streaming.

Order Updates

Get live order status updates via dedicated WebSocket connection.

Installation

Install the required packages using pip. Make sure you have Python 3.7+ installed.

Terminal
# Install the SmartAPI SDK
pip install smartapi-python

# Install required dependencies
pip install pyotp
pip install logzero
pip install websocket-client

# Fix potential crypto library conflicts
pip uninstall pycrypto
pip install pycryptodome
smartapi-python

Official AngelOne SmartAPI SDK

pyotp

For TOTP-based authentication

logzero

Simple and effective logging

websocket-client

WebSocket support for live data

Authentication & Session

Initialize the SDK with your credentials and create a session using TOTP authentication.

authentication.py
from SmartApi import SmartConnect
import pyotp
from logzero import logger

# Initialize with your API key
api_key = 'Your Api Key'
username = 'Your Client Code'
pwd = 'Your PIN'

smartApi = SmartConnect(api_key)

# Generate TOTP for authentication
try:
    token = "Your QR Value"
    totp = pyotp.TOTP(token).now()
except Exception as e:
    logger.error("Invalid Token: The provided token is not valid.")
    raise e

# Create session
correlation_id = "abcde"
data = smartApi.generateSession(username, pwd, totp)

if data['status'] == False:
    logger.error(data)
else:
    authToken = data['data']['jwtToken']
    refreshToken = data['data']['refreshToken']
    feedToken = smartApi.getfeedToken()

    # Fetch user profile
    res = smartApi.getProfile(refreshToken)
    logger.info(f"Exchanges: {res['data']['exchanges']}")

Note: You can get your API key and QR value from the AngelOne SmartAPI portal. The QR value is used to generate TOTP for secure authentication.

Placing Orders

Execute trades programmatically with full control over order parameters.

place_order.py
# Place a limit order
try:
    orderparams = {
        "variety": "NORMAL",
        "tradingsymbol": "SBIN-EQ",
        "symboltoken": "3045",
        "transactiontype": "BUY",
        "exchange": "NSE",
        "ordertype": "LIMIT",
        "producttype": "INTRADAY",
        "duration": "DAY",
        "price": "19500",
        "squareoff": "0",
        "stoploss": "0",
        "quantity": "1"
    }

    # Method 1: Get order ID only
    orderid = smartApi.placeOrder(orderparams)
    logger.info(f"Order ID: {orderid}")

    # Method 2: Get full response
    response = smartApi.placeOrderFullResponse(orderparams)
    logger.info(f"Full Response: {response}")

except Exception as e:
    logger.exception(f"Order placement failed: {e}")

GTT (Good Till Triggered) Orders

Create automated orders that trigger when your specified price conditions are met.

gtt_orders.py
# Create a GTT (Good Till Triggered) order
try:
    gttCreateParams = {
        "tradingsymbol": "SBIN-EQ",
        "symboltoken": "3045",
        "exchange": "NSE",
        "producttype": "MARGIN",
        "transactiontype": "BUY",
        "price": 100000,
        "qty": 10,
        "disclosedqty": 10,
        "triggerprice": 200000,
        "timeperiod": 365
    }

    rule_id = smartApi.gttCreateRule(gttCreateParams)
    logger.info(f"GTT Rule ID: {rule_id}")

except Exception as e:
    logger.exception(f"GTT Rule creation failed: {e}")

# List GTT orders
try:
    status = ["FORALL"]  # Filter by status
    page = 1
    count = 10
    lists = smartApi.gttLists(status, page, count)

except Exception as e:
    logger.exception(f"GTT Rule List failed: {e}")

Historical Data & Session Management

Fetch historical OHLCV data for analysis and properly terminate your session.

historic_data.py
# Fetch historical candle data
try:
    historicParam = {
        "exchange": "NSE",
        "symboltoken": "3045",
        "interval": "ONE_MINUTE",
        "fromdate": "2021-02-08 09:00",
        "todate": "2021-02-08 09:16"
    }

    candle_data = smartApi.getCandleData(historicParam)
    logger.info(f"Candle Data: {candle_data}")

except Exception as e:
    logger.exception(f"Historic API failed: {e}")

# Logout when done
try:
    logout = smartApi.terminateSession('Your Client Id')
    logger.info("Logout Successful")

except Exception as e:
    logger.exception(f"Logout failed: {e}")

WebSocket Streaming

Subscribe to real-time market data using WebSocket V2 for low-latency tick updates.

Market Data WebSocket

websocket_v2.py
from SmartApi.smartWebSocketV2 import SmartWebSocketV2
from logzero import logger

AUTH_TOKEN = "authToken"
API_KEY = "api_key"
CLIENT_CODE = "client_code"
FEED_TOKEN = "feedToken"

correlation_id = "abc123"
action = 1
mode = 1

token_list = [
    {
        "exchangeType": 1,
        "tokens": ["26009"]
    }
]

sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)

def on_data(wsapp, message):
    logger.info(f"Ticks: {message}")

def on_open(wsapp):
    logger.info("Connection opened")
    sws.subscribe(correlation_id, mode, token_list)

def on_error(wsapp, error):
    logger.error(error)

def on_close(wsapp):
    logger.info("Connection closed")

# Assign callbacks
sws.on_open = on_open
sws.on_data = on_data
sws.on_error = on_error
sws.on_close = on_close

# Connect to WebSocket
sws.connect()

Order Update WebSocket

order_updates.py
from SmartApi.smartWebSocketOrderUpdate import SmartWebSocketOrderUpdate

AUTH_TOKEN = "authToken"
API_KEY = "api_key"
CLIENT_CODE = "client_code"
FEED_TOKEN = "feedToken"

# Initialize and connect to order update stream
client = SmartWebSocketOrderUpdate(
    AUTH_TOKEN,
    API_KEY,
    CLIENT_CODE,
    FEED_TOKEN
)
client.connect()

Supported Exchanges & Instruments

Trade across multiple exchanges and instrument types using the SmartAPI SDK.

NSE Equity
BSE Equity
NSE F&O
BSE F&O
MCX Commodity
Currency Futures

Prerequisites

AngelOne Demat Account

Active trading account with AngelOne

SmartAPI Access

Register at SmartAPI portal for API key

Python 3.7+

Compatible Python installation

TOTP Setup

QR code from SmartAPI for 2FA

Ready to start building?

Get your API credentials from the AngelOne SmartAPI portal and start integrating today.