Angel One SmartAPI Python SDK

repository·main·Indexed 41 days ago

https://github.com/angel-one/smartapi-python

A Python library providing a wrapper around Angel One's REST-like HTTP APIs and WebSockets. It enables developers to build stock market investment and real-time trading platforms using the SmartConnect class for authentication and order placement, and SmartWebSocketV2 for real-time market data.

Tokens
1.9K
Snippets
7
Records
7
Agent score
2%

What's inside SmartAPI Python

  1. Authenticate and initialize SmartConnect

    main

    To interact with the Angel trading platform, initialize the SmartConnect class with your api_key. Use pyotp to generate a TOTP (Time-based One-Time Password) from your QR token to authenticate via generateSession.

    from SmartApi import SmartConnect
    import pyotp
    
    api_key = 'Your Api Key'
    username = 'Your client code'
    pwd = 'Your pin'
    
    smartApi = SmartConnect(api_key)
    
    token = "Your QR value"
    totp = pyotp.TOTP(token).now()
    
    # Authenticate and get session data
    data = smartApi.generateSession(username, pwd, totp)
    
    if data['status']:
        authToken = data['data']['jwtToken']
        refreshToken = data['data']['refreshToken']
  2. Install smartapi-python and dependencies

    main

    Install the core library and required dependencies using pip. Note that if you have pycrypto installed, you must uninstall it before installing pycryptodome to avoid conflicts.

    # Install required packages
    pip install -r requirements_dev.txt
    
    # Install specific dependencies
    pip install pyotp logzero websocket-client
    
    # Handle pycryptodome installation
    pip uninstall pycrypto
    pip install pycryptodome
  3. Use SmartWebSocketV2 for real-time data

    main

    The SmartWebSocketV2 class provides real-time market data via WebSockets. You must define callback functions for on_open, on_data, on_error, and on_close, then assign them to the instance before calling .connect().

    Workflow:

    1. Initialize SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN).
    2. Define callbacks.
    3. In on_open, call .subscribe(correlation_id, mode, token_list) to start receiving data.
    4. Call .connect() to start the connection.
    5. Use .close_connection() to disconnect.
    from SmartApi.smartWebSocketV2 import SmartWebSocketV2
    
    sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
    
    def on_data(wsapp, message):
        print(f"Ticks: {message}")
    
    def on_open(wsapp):
        # mode 1 for subscription
        sws.subscribe(correlation_id, 1, token_list)
    
    def on_error(wsapp, error):
        print(f"Error: {error}")
    
    def on_close(wsapp):
        print("Connection Closed")
    
    sws.on_open = on_open
    sws.on_data = on_data
    sws.on_error = on_error
    sws.on_close = on_close
    
    sws.connect()
  4. Fetch historical candle data

    main

    Use getCandleData(historicParam) to retrieve historical market data. The historicParam dictionary requires:

    • exchange: e.g., "NSE"
    • symboltoken: e.g., "3045"
    • interval: e.g., "ONE_MINUTE"
    • fromdate: "YYYY-MM-DD HH:MM"
    • todate: "YYYY-MM-DD HH:MM"
    historicParam = {
        "exchange": "NSE",
        "symboltoken": "3045",
        "interval": "ONE_MINUTE",
        "fromdate": "2021-02-08 09:00", 
        "todate": "2021-02-08 09:16"
    }
    smartApi.getCandleData(historicParam)
  5. Monitor order updates with SmartWebSocketOrderUpdate

    main

    To receive real-time updates on order status changes, use the SmartWebSocketOrderUpdate class.

    from SmartApi.smartWebSocketOrderUpdate import SmartWebSocketOrderUpdate
    
    client = SmartWebSocketOrderUpdate(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
    client.connect()
  6. Manage GTT (Good Till Triggered) rules

    main

    Use the following methods to manage GTT rules:

    • gttCreateRule(gttCreateParams): Creates a new GTT rule. Parameters include tradingsymbol, symboltoken, exchange, producttype, transactiontype, price, qty, disclosedqty, triggerprice, and timeperiod.
    • gttLists(status, page, count): Retrieves a list of GTT rules. status must be a list (e.g., ["FORALL"]).
    # Create GTT Rule
    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)
    
    # List GTT Rules
    status = ["FORALL"]
    lists = smartApi.gttLists(status, page=1, count=10)
  7. Place orders using SmartConnect

    main

    You can place orders using two different methods by passing an orderparams dictionary.

    Order Parameter Keys:

    • variety: e.g., "NORMAL"
    • tradingsymbol: e.g., "SBIN-EQ"
    • symboltoken: e.g., "3045"
    • transactiontype: "BUY" or "SELL"
    • exchange: e.g., "NSE"
    • ordertype: e.g., "LIMIT"
    • producttype: e.g., "INTRADAY"
    • duration: e.g., "DAY"
    • price: string representation of price
    • quantity: string representation of quantity
    • squareoff: string representation
    • stoploss: string representation

    Methods:

    • placeOrder(orderparams): Returns only the orderid.
    • placeOrderFullResponse(orderparams): Returns the full API response object.
    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
    orderid = smartApi.placeOrder(orderparams)
    
    # Method 2: Get full response
    response = smartApi.placeOrderFullResponse(orderparams)