Skip to content

Getting Started with INDstocks API

Welcome! This guide will walk you through everything you need to start trading with the INDstocks API.

Choose your path based on how you want to use the API:


šŸ“‹ Prerequisites

Before you begin, make sure you have:

  • An INDstocks account - Sign up here (free)
  • Completed KYC verification - Required by SEBI regulations
  • Funds in your account - For placing actual trades

For Algo Platform Users

If you want to use INDstocks API with algo trading platforms like Tradetron, follow these simple steps:

Step 1: Get Your Access Token

  1. Log in to your INDstocks account at indstocks.com
  2. Navigate to indstocks.com/app/api-trading
  3. Click "Get Started with INDstocks APIs" or "Generate Token"
  4. Copy your access token

Token Security

  • Your access token is like a password - keep it secure
  • Never share it publicly or commit it to version control
  • Tokens expire after 24 hours and must be regenerated
  • Revoke immediately if compromised

Step 2: Connect to Tradetron

  1. Open Tradetron and log in to your account
  2. Navigate to the broker integration or API settings section
  3. Select "INDmoney" as your broker
  4. Paste your access token from Step 1
  5. Save and verify the connection

You're All Set!

Your Tradetron account is now connected to INDstocks. You can start deploying strategies, placing orders, and managing your portfolio through Tradetron's interface.

Detailed Integration Guide

Step-by-step instructions with screenshots coming soon!

What's Next?

  • Create and deploy trading strategies on Tradetron
  • Monitor your orders and positions
  • Backtest your strategies with historical data
  • Set up automated trading rules

Need Help?

If you face issues connecting to Tradetron, reach out to us at [email protected]


For Developers (DIY Approach)

If you want to build your own trading applications, bots, or custom integrations, this comprehensive guide will walk you through everything - from authentication to placing your first order.

Step 1: Get Your Access Token

Your access token is your key to the INDstocks API. Here's how to get it:

  1. Log in to indstocks.com
  2. Navigate to the API section in your dashboard
  3. Click "Get Started with INDstocks APIs"
  4. Copy your access token

Security Best Practice

  • Never commit your access token to version control
  • Store it securely (environment variables, secrets manager)
  • Tokens expire after 24 hours and must be regenerated
  • Revoke immediately if compromised

Step 2: Make Your First API Call

Let's verify your setup by fetching your user profile.

Python
import requests
import os

# Get access token from environment variable
access_token = os.getenv('INDSTOCKS_TOKEN')

# API base URL
base_url = 'https://api.indstocks.com'

# Headers for authentication
headers = {
    'Authorization': access_token,
    'Content-Type': 'application/json'
}

# Fetch user profile
response = requests.get(f'{base_url}/user/profile', headers=headers)

if response.status_code == 200:
    profile = response.json()
    print(f"āœ… Connected! Welcome, {profile['data']['first_name']} {profile['data']['last_name']}")
    print(f"User ID: {profile['data']['user_id']}")
    print(f"Email: {profile['data']['email']}")
else:
    print(f"āŒ Error: {response.json()}")
JavaScript
const fetch = require('node-fetch');

// Get access token from environment variable
const accessToken = process.env.INDSTOCKS_TOKEN;

// API base URL
const baseUrl = 'https://api.indstocks.com';

// Headers for authentication
const headers = {
    'Authorization': accessToken,
    'Content-Type': 'application/json'
};

// Fetch user profile
async function getUserProfile() {
    try {
        const response = await fetch(`${baseUrl}/user/profile`, {
            headers: headers
        });

        if (response.ok) {
            const data = await response.json();
            console.log(`āœ… Connected! Welcome, ${data.data.first_name} ${data.data.last_name}`);
            console.log(`User ID: ${data.data.user_id}`);
            console.log(`Email: ${data.data.email}`);
        } else {
            console.log('āŒ Error:', await response.json());
        }
    } catch (error) {
        console.error('Connection error:', error);
    }
}

getUserProfile();
Bash
curl -X GET "https://api.indstocks.com/user/profile" \
  -H "Authorization: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json"

Expected Response:

JSON
{
  "status": "success",
  "data": {
    "user_id": "5960668",
    "email": "[email protected]",
    "first_name": "John",
    "last_name": "Doe",
    "demat_id": "",
    "is_nse_onboarded": true,
    "is_bse_onboarded": true,
    "is_nse_fno_onboarded": true,
    "is_bse_fno_onboarded": true
  }
}

Congratulations!

If you see your profile details, you're all set! You've successfully authenticated with the API.


Step 3: Get Market Data

Now let's fetch real-time quotes for a stock.

Python
import requests
import os

access_token = os.getenv('INDSTOCKS_TOKEN')
base_url = 'https://api.indstocks.com'
headers = {'Authorization': access_token}

# Fetch real-time quotes for Reliance (NSE_2885) and TCS (NSE_11536)
# Get scrip codes from the instruments API
params = {
    'scrip-codes': 'NSE_2885,NSE_11536'
}

response = requests.get(
    f'{base_url}/market/quotes/full',
    headers=headers,
    params=params
)

if response.status_code == 200:
    quotes = response.json()
    for symbol, data in quotes['data'].items():
        print(f"\nšŸ“ˆ {symbol}")
        print(f"   LTP: ₹{data['live_price']}")
        print(f"   Change: {data['day_change_percentage']}%")
        print(f"   Volume: {data['volume']:,}")
else:
    print(f"Error: {response.json()}")
JavaScript
const fetch = require('node-fetch');

const accessToken = process.env.INDSTOCKS_TOKEN;
const baseUrl = 'https://api.indstocks.com';
const headers = {'Authorization': accessToken};

// Fetch real-time quotes for Reliance (NSE_2885) and TCS (NSE_11536)
// Get scrip codes from the instruments API
async function getMarketQuotes() {
    const scripCodes = 'NSE_2885,NSE_11536';
    const url = `${baseUrl}/market/quotes/full?scrip-codes=${scripCodes}`;

    try {
        const response = await fetch(url, { headers });
        const quotes = await response.json();

        if (response.ok) {
            for (const [symbol, data] of Object.entries(quotes.data)) {
                console.log(`\nšŸ“ˆ ${symbol}`);
                console.log(`   LTP: ₹${data.live_price}`);
                console.log(`   Change: ${data.day_change_percentage}%`);
                console.log(`   Volume: ${data.volume.toLocaleString()}`);
            }
        } else {
            console.log('Error:', quotes);
        }
    } catch (error) {
        console.error('Request failed:', error);
    }
}

getMarketQuotes();
Bash
curl -X GET "https://api.indstocks.com/market/quotes/full?scrip-codes=NSE_2885,NSE_11536" \
  -H "Authorization: YOUR_ACCESS_TOKEN"

Sample Output:

Text Only
šŸ“ˆ NSE_2885
   LTP: ₹2,456.75
   Change: +1.23%
   Volume: 12,345,678

šŸ“ˆ NSE_11536
   LTP: ₹3,890.50
   Change: -0.45%
   Volume: 5,678,901

Step 4: Place Your First Order

Ready to place a trade? Let's place a simple limit order to buy shares.

Real Money Alert

The following code places real orders with real money. Start with small quantities to test your integration!

Python
import requests
import os

access_token = os.getenv('INDSTOCKS_TOKEN')
base_url = 'https://api.indstocks.com'
headers = {
    'Authorization': access_token,
    'Content-Type': 'application/json'
}

# Order parameters
order_data = {
    'txn_type': 'BUY',           # BUY or SELL
    'exchange': 'NSE',           # NSE or BSE
    'segment': 'EQUITY',         # EQUITY, FNO, etc.
    'security_id': '2885',       # Reliance security ID (get from instruments API)
    'qty': 1,                    # Quantity to buy
    'order_type': 'LIMIT',       # LIMIT, MARKET, STOP_LOSS, etc.
    'limit_price': 2450.00,      # Limit price
    'validity': 'DAY',           # DAY or IOC
    'product': 'CNC',            # CNC (delivery) or INTRADAY (intraday) or MARGIN (derivatives)
    'is_amo': False,             # After Market Order flag
    'algo_id': '99999'           # Required: Use 99999 for regular orders
}

# Place the order
response = requests.post(
    f'{base_url}/order',
    headers=headers,
    json=order_data
)

if response.status_code == 200:
    result = response.json()
    print(f"āœ… Order placed successfully!")
    print(f"Order ID: {result['data']['order_id']}")
    print(f"Status: {result['data']['order_status']}")
else:
    error = response.json()
    print(f"āŒ Order failed: {error.get('message', error)}")
JavaScript
const fetch = require('node-fetch');

const accessToken = process.env.INDSTOCKS_TOKEN;
const baseUrl = 'https://api.indstocks.com';
const headers = {
    'Authorization': accessToken,
    'Content-Type': 'application/json'
};

// Order parameters
const orderData = {
    txn_type: 'BUY',
    exchange: 'NSE',
    segment: 'EQUITY',
    security_id: '2885',        // Reliance security ID
    qty: 1,
    order_type: 'LIMIT',
    limit_price: 2450.00,
    validity: 'DAY',
    product: 'CNC',
    is_amo: false,              // After Market Order flag
    algo_id: '99999'            // Required: Use 99999 for regular orders
};

// Place the order
async function placeOrder() {
    try {
        const response = await fetch(`${baseUrl}/order`, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(orderData)
        });

        const result = await response.json();

        if (response.ok) {
            console.log('āœ… Order placed successfully!');
            console.log(`Order ID: ${result.data.order_id}`);
            console.log(`Status: ${result.data.order_status}`);
        } else {
            console.log(`āŒ Order failed: ${result.message || JSON.stringify(result)}`);
        }
    } catch (error) {
        console.error('Request failed:', error);
    }
}

placeOrder();
Bash
curl -X POST "https://api.indstocks.com/order" \
  -H "Authorization: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "txn_type": "BUY",
    "exchange": "NSE",
    "segment": "EQUITY",
    "security_id": "2885",
    "qty": 1,
    "order_type": "LIMIT",
    "limit_price": 2450.00,
    "validity": "DAY",
    "product": "CNC",
    "is_amo": false,
    "algo_id": "99999"
  }'

Success Response:

JSON
{
  "status": "success",
  "data": {
    "order_id": "DRV-29301125",
    "order_status": "O-PENDING"
  }
}

Understanding Order Parameters

Parameter Description Example Values
txn_type Transaction type BUY, SELL
exchange Stock exchange NSE, BSE
segment Market segment EQUITY, FNO, CURRENCY
security_id Instrument ID Get from Instruments API
qty Quantity 1, 10, 100
order_type Order type LIMIT, MARKET, STOP_LOSS
limit_price Price limit 2450.00 (for LIMIT orders)
product Product type CNC (delivery), INTRADAY (intraday), MARGIN (derivatives)
validity Order validity DAY, IOC
algo_id Algo identifier (required) 99999 (for regular orders)

Step 5: Check Your Order Status

After placing an order, you'll want to check its status:

Python
import requests
import os

access_token = os.getenv('INDSTOCKS_TOKEN')
base_url = 'https://api.indstocks.com'
headers = {'Authorization': access_token}

# Get order book (all orders for the day)
response = requests.get(f'{base_url}/order-book', headers=headers)

if response.status_code == 200:
    orders = response.json()
    print("\nšŸ“‹ Today's Orders:\n")
    for order in orders['data']:
        print(f"Order ID: {order['id']}")
        print(f"Symbol: {order['name']}")
        print(f"Status: {order['status']}")
        print(f"Qty: {order['requested_qty']} @ ₹{order['requested_price']}")
        print(f"Traded: {order['traded_qty']} @ ₹{order['traded_price']}")
        print("---")
JavaScript
const fetch = require('node-fetch');

const accessToken = process.env.INDSTOCKS_TOKEN;
const baseUrl = 'https://api.indstocks.com';
const headers = {'Authorization': accessToken};

async function getOrderBook() {
    try {
        const response = await fetch(`${baseUrl}/order-book`, { headers });
        const orders = await response.json();

        if (response.ok) {
            console.log('\nšŸ“‹ Today\'s Orders:\n');
            orders.data.forEach(order => {
                console.log(`Order ID: ${order.id}`);
                console.log(`Symbol: ${order.name}`);
                console.log(`Status: ${order.status}`);
                console.log(`Qty: ${order.requested_qty} @ ₹${order.requested_price}`);
                console.log(`Traded: ${order.traded_qty} @ ₹${order.traded_price}`);
                console.log('---');
            });
        }
    } catch (error) {
        console.error('Request failed:', error);
    }
}

getOrderBook();

šŸŽÆ What's Next?

Congratulations! You've successfully:

  • āœ… Authenticated with the INDstocks API
  • āœ… Fetched real-time market data
  • āœ… Placed your first order
  • āœ… Checked order status

Continue Your Journey


šŸ“š Essential Resources

Resource Description
API Overview Complete endpoint catalog
Order Management Advanced order types and management
Market Data Real-time quotes and market depth
WebSockets Live streaming data
Error Handling Error codes and troubleshooting
FAQ Common questions answered

šŸ› Common Issues & Solutions

TokenException: Invalid token

Problem: Your access token is invalid or expired.

Solution: 1. Log in to indstocks.com 2. Navigate to API section 3. Generate a new access token 4. Update your code with the new token

OrderException: Insufficient margin

Problem: Not enough funds in your account.

Solution: 1. Check available funds: GET /funds 2. Add funds to your account 3. Reduce order quantity 4. Use intraday (MIS) product for lower margin

InputException: Invalid security_id

Problem: The security_id doesn't exist or is incorrect.

Solution: 1. Download instruments master: GET /market/instruments 2. Search for your symbol in the CSV 3. Use the correct security_id from the file

NetworkException: Connection timeout

Problem: Network connectivity issues.

Solution: 1. Check your internet connection 2. Verify API endpoint URL 3. Implement retry logic with exponential backoff 4. Check status page for API health


šŸ’” Best Practices

Production-Ready Code

  1. Error Handling: Always wrap API calls in try-catch blocks
  2. Rate Limiting: Respect rate limits (10 orders/sec, 100 API calls/sec)
  3. Retry Logic: Implement exponential backoff for transient errors
  4. Logging: Log all API requests and responses for debugging
  5. Testing: Test thoroughly with small quantities before scaling up
  6. Security: Never expose your access token in client-side code

Example: Production-Grade Order Placement

Python
import requests
import time
import logging
from typing import Dict, Optional

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class INDstocksAPI:
    def __init__(self, access_token: str):
        self.base_url = 'https://api.indstocks.com'
        self.headers = {
            'Authorization': access_token,
            'Content-Type': 'application/json'
        }
        self.max_retries = 3

    def place_order(self, order_data: Dict) -> Optional[Dict]:
        """Place an order with retry logic and error handling"""
        for attempt in range(self.max_retries):
            try:
                response = requests.post(
                    f'{self.base_url}/order',
                    headers=self.headers,
                    json=order_data,
                    timeout=10
                )

                if response.status_code == 200:
                    result = response.json()
                    logger.info(f"Order placed: {result['data']['order_id']} - Status: {result['data']['order_status']}")
                    return result

                elif response.status_code == 429:  # Rate limit
                    wait_time = 2 ** attempt  # Exponential backoff
                    logger.warning(f"Rate limited. Retrying in {wait_time}s...")
                    time.sleep(wait_time)
                    continue

                else:
                    error = response.json()
                    logger.error(f"Order failed: {error['message']}")
                    return None

            except requests.exceptions.Timeout:
                logger.warning(f"Request timeout. Attempt {attempt + 1}/{self.max_retries}")
                time.sleep(2 ** attempt)

            except Exception as e:
                logger.error(f"Unexpected error: {str(e)}")
                return None

        logger.error("Max retries exceeded")
        return None

# Usage
api = INDstocksAPI(os.getenv('INDSTOCKS_TOKEN'))
order = {
    'txn_type': 'BUY',
    'exchange': 'NSE',
    'segment': 'EQUITY',
    'security_id': '2885',
    'qty': 1,
    'order_type': 'LIMIT',
    'limit_price': 2450.00,
    'validity': 'DAY',
    'product': 'CNC',
    'is_amo': False,
    'algo_id': '99999'
}
result = api.place_order(order)

šŸš€ Take It Further

Build a Simple Trading Bot

Want to automate your trading? Here's a simple example:

Python
import requests
import time
import os

class SimpleBot:
    def __init__(self, access_token):
        self.api_url = 'https://api.indstocks.com'
        self.headers = {'Authorization': access_token}

    def get_ltp(self, scrip_code):
        """Get last traded price"""
        response = requests.get(
            f'{self.api_url}/market/quotes/ltp',
            headers=self.headers,
            params={'scrip-codes': scrip_code}
        )
        return response.json()['data'][scrip_code]['live_price']

    def buy_at_support(self, scrip_code, security_id, support_price, qty):
        """Buy when price hits support level"""
        while True:
            current_price = self.get_ltp(scrip_code)
            print(f"Current price: ₹{current_price} | Target: ₹{support_price}")

            if current_price <= support_price:
                # Place order
                order_data = {
                    'txn_type': 'BUY',
                    'exchange': 'NSE',
                    'segment': 'EQUITY',
                    'security_id': security_id,
                    'qty': qty,
                    'order_type': 'MARKET',
                    'product': 'CNC',
                    'is_amo': False,
                    'validity': 'DAY',
                    'algo_id': '99999'
                }
                response = requests.post(
                    f'{self.api_url}/order',
                    headers=self.headers,
                    json=order_data
                )
                print(f"Order placed: {response.json()}")
                break

            time.sleep(5)  # Check every 5 seconds

# Usage
bot = SimpleBot(os.getenv('INDSTOCKS_TOKEN'))
# bot.buy_at_support('NSE_2885', '2885', 2400, 1)  # Reliance

Trading Bot Disclaimer

This is a educational example. Real trading bots require sophisticated risk management, error handling, and testing. Always backtest strategies before deploying with real money.


šŸ†˜ Need Help?

Having trouble getting started? We're here to help!


See Also


Ready to build something amazing? Let's trade! šŸš€