SDKs overview

SmartAPI offers a suite of Software Development Kits (SDKs) designed to simplify interaction with its trading platform API. These SDKs provide pre-written code and libraries that encapsulate the underlying RESTful API calls, authentication mechanisms, and data parsing, allowing developers to focus on building trading logic rather than managing low-level network communication. The official SDKs support several popular programming languages, facilitating integration for a broad range of development environments and use cases, including algorithmic trading, backtesting strategies, and real-time market data acquisition SmartAPI official documentation.

The core functionalities exposed through the SmartAPI SDKs include order placement and modification, access to live market feeds, historical data retrieval, and portfolio management. By abstracting the complexities of HTTP requests and JSON responses, SDKs reduce development time and potential errors. Developers can leverage these tools to automate trading decisions, execute trades programmatically, and manage their investment portfolios directly through custom applications.

Official SDKs by language

SmartAPI provides official SDKs for five distinct programming languages, each designed to offer native-like integration capabilities. These SDKs are maintained by SmartAPI and are recommended for developers seeking stable and supported access to the platform's features. The following table outlines the available official SDKs, their typical package names, and installation commands.

Language Package Name Install Command Example Maturity
Python smartapi-python pip install smartapi-python Stable
Java smartapi-java Add to pom.xml (Maven) or build.gradle (Gradle) Stable
Node.js smartapi-javascript npm install smartapi-javascript Stable
PHP smartapi-php composer require angelbroking/smartapi-php Stable
C# SmartApi.Net dotnet add package SmartApi.Net Stable

Each SDK is typically hosted on its respective language's package manager, such as PyPI for Python, Maven Central for Java, npm for Node.js, Packagist for PHP, and NuGet for C#. This distribution model ensures ease of access and version management for developers. For detailed documentation specific to each SDK, including method signatures and usage patterns, developers should refer to the SmartAPI developer documentation portal.

Installation

Installing SmartAPI SDKs generally follows the standard practices for each programming ecosystem. Below are specific instructions for each officially supported language, detailing the common commands or procedures required to integrate the SDK into a project.

Python

The Python SDK is distributed via PyPI. Installation is performed using pip, the Python package installer. It is recommended to use a virtual environment to manage dependencies.

pip install smartapi-python

After installation, the library can be imported into Python scripts. Ensure your Python environment is correctly configured to resolve package dependencies.

Java

For Java projects, the SmartAPI SDK is typically managed using build automation tools like Maven or Gradle. Developers need to add the appropriate dependency entry to their project's configuration file.

Maven (pom.xml)

<dependency>
    <groupId>com.angelbroking</groupId>
    <artifactId>smartapi-java</artifactId>
    <version>1.0.0</version> <!-- Replace with the latest version -->
</dependency>

Gradle (build.gradle)

implementation 'com.angelbroking:smartapi-java:1.0.0' <!-- Replace with the latest version -->

After adding the dependency, rebuild your project to download and include the SmartAPI Java library.

Node.js

The Node.js SDK is available through npm, the Node.js package manager. Installation is straightforward:

npm install smartapi-javascript

Once installed, the module can be imported using require or import statements in your JavaScript/TypeScript files.

PHP

For PHP projects, Composer is the standard dependency manager. The SmartAPI PHP SDK can be added to your project using the following command:

composer require angelbroking/smartapi-php

This command will add the SDK to your composer.json file and install it into your vendor directory. Ensure Composer's autoloader is included in your application.

C#

The C# SDK is distributed as a NuGet package, which can be installed using the .NET CLI or through Visual Studio's NuGet Package Manager.

.NET CLI

dotnet add package SmartApi.Net

Visual Studio Package Manager Console

Install-Package SmartApi.Net

After installation, you can reference the library in your C# projects and begin using its functionalities.

Quickstart example

This Python quickstart example demonstrates how to initialize the SmartAPI client, generate a session, and fetch real-time market quotes. This snippet illustrates the basic authentication flow and a common data retrieval operation, which are fundamental to building any application with SmartAPI. For this example, replace placeholder values like YOUR_API_KEY, YOUR_CLIENT_CODE, YOUR_PASSWORD, and YOUR_TOTP_PIN with your actual credentials. The Time-based One-Time Password (TOTP) is a common multi-factor authentication method used to enhance security, as detailed in the IETF RFC 6238 on TOTP standard.

from SmartApi import SmartConnect
from SmartApi.webSocket import SmartWebSocket
import pyotp
import datetime
import time

# --- Configuration --- 
API_KEY = "YOUR_API_KEY"
CLIENT_CODE = "YOUR_CLIENT_CODE"
PASSWORD = "YOUR_PASSWORD"
TOTP_SECRET = "YOUR_TOTP_SECRET" # Secret for generating TOTP
FEED_TOKEN = None # This will be obtained after successful login

# --- Initialize SmartConnect --- 
ob = SmartConnect(api_key=API_KEY)

# --- Generate TOTP --- 
totp = pyotp.TOTP(TOTP_SECRET)
TOTP_PIN = totp.now()

# --- Login and generate session --- 
try:
    data = ob.generateSession(CLIENT_CODE, PASSWORD, TOTP_PIN)
    if data and data.get('status'):
        print("Login successful!")
        # Extract the access token and refresh token
        ACCESS_TOKEN = data['data']['jwtToken']
        REFRESH_TOKEN = data['data']['refreshToken']
        FEED_TOKEN = ob.getFeedToken()
        print(f"Access Token: {ACCESS_TOKEN}")
        print(f"Refresh Token: {REFRESH_TOKEN}")
        print(f"Feed Token: {FEED_TOKEN}")
    else:
        print(f"Login failed: {data.get('message', 'Unknown error')}")
        exit()
except Exception as e:
    print(f"An error occurred during login: {e}")
    exit()

# --- Initialize SmartWebSocket for real-time data --- 
# Ensure FEED_TOKEN is available from login
if FEED_TOKEN:
    sws = SmartWebSocket(FEED_TOKEN, CLIENT_CODE) # Pass CLIENT_CODE here

    def on_message(ws, message):
        print(f"Received message: {message}")

    def on_open(ws):
        print("WebSocket connection opened.")
        # Subscribe to market data for a specific scrip
        # Example: NIFTY BANK (NSE) - token 26009
        # Example: RELIANCE (NSE) - token 2885
        subscribe_payload = {
            "action": 1, # 1 for subscribe
            "task": "mw", # mw for market watch
            "instrumenttype": "NSE",
            "exchangeType": "NSE",
            "scripToken": "2885", # Reliance Industries Ltd
            "widgetType": "5Minute", # Market watch data
            "marketWatchOv": True
        }
        sws.send_message(subscribe_payload)

    def on_error(ws, error):
        print(f"WebSocket error: {error}")

    def on_close(ws, close_status_code, close_msg):
        print(f"WebSocket connection closed with code {close_status_code}: {close_msg}")

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

    # Start the WebSocket connection in a separate thread
    sws.connect()

    # Keep the main thread alive to receive WebSocket messages
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Disconnecting WebSocket...")
        sws.close()
else:
    print("Feed token not available. Cannot establish WebSocket connection.")

# --- Logout (optional, good practice) --- 
try:
    logout_response = ob.terminateSession(CLIENT_CODE)
    print(f"Logout response: {logout_response}")
except Exception as e:
    print(f"Error during logout: {e}")

This example demonstrates the critical steps: establishing a connection, authenticating, subscribing to real-time data, and handling data reception. Developers can extend this foundation to implement complex trading algorithms, integrate with charting libraries, or build custom dashboards for market analysis.

Community libraries

While SmartAPI provides official SDKs, the developer community often contributes additional libraries, tools, and wrappers that can extend functionality or offer alternative implementations. These community-driven projects typically emerge to address specific use cases, provide language support not officially covered, or integrate SmartAPI with other popular frameworks. For example, some community libraries might offer enhanced charting capabilities, backtesting frameworks built on top of SmartAPI data, or integrations with popular data science tools.

Community libraries are not officially supported by SmartAPI, meaning their maintenance, reliability, and security are dependent on their respective developers. Before integrating any community library, it is advisable to review its documentation, check its activity on platforms like GitHub, and assess its alignment with your project's security and performance requirements. The SmartAPI developer portal or community forums are good starting points for discovering such contributions, though direct links to specific community projects are not provided by SmartAPI itself. Developers are encouraged to explore community repositories and forums for additional tools that might complement the official SDKs, while exercising due diligence in their selection and implementation, a common practice for open source software adoption as noted by sources like Mozilla Developer Network's definition of open source principles.