Kotak Neo API - Python SDK
Official Python SDK for Kotak Neo Trading APIs - a modern, well-tested trading client for the Kotak Neo platform.
This is the actively maintained Python SDK, superseding
kotak-neo-api-v2(now legacy). Already onkotak-neo-api-v2? See the Migration Guide.
Features
✅ Authentication - TOTP-based secure login with 2FA
✅ Order Management - Place, modify, cancel orders (Regular/AMO)
✅ Portfolio & Positions - Real-time holdings, positions, and limits
✅ Market Data - Live quotes, scrip master, search functionality
✅ SFeed WebSocket Streaming - Modern async/await live market feed with typed messages, enriched with trading_symbol
✅ HTTP/2 Transport - REST calls use HTTP/2 (via httpx) with automatic HTTP/1.1 fallback
✅ Optional Reliability Utilities - Opt-in rate limiting, plus retry and circuit-breaker helpers
✅ Comprehensive Error Handling - Detailed exception hierarchy with input validation
✅ Type Safety - Full mypy type checking support
✅ Extensive Testing - 100% test coverage (unit, integration, and E2E tests)
Installation
From PyPI
pip install kotakneoapi
For Development (Local Installation)
# Clone the repository
git clone https://github.com/Kotak-Neo/kotak-neo-python.git
cd kotak-neo-python
# Install in development/editable mode
pip install -e .
# Or install with development dependencies
pip install -e ".[dev]"
Quick Start
Prerequisites
- Get Consumer Key (REQUIRED): Login to Kotak NEO app/web → More tab → Trade API card → Generate application → Copy the token
- This token is used in the Authorization header for all API requests
- Authentication will fail without this token
- Register for TOTP: Visit API Dashboard (Neo App/Web → more tab → trade API), on top right menu bar click "TOTP Registration" → Register for TOTP → Scan QR code with authenticator app (Google Authenticator, Authy, etc.)
Getting started with quick order placement
from neo_api_client import NeoAPI
# Initialize the client
client = NeoAPI(
consumer_key="your-consumer-key-token", # Token from NEO app Trade API card
environment="prod", # production (default)
access_token=None, # Optional
neo_fin_key=None, # Optional
)
# Step 1: Login with TOTP
login_response = client.totp_login(
mobile_number="+919876543210", # Your registered mobile with country code
ucc="YOUR_UCC", # Find in NEO app/web under Profile section
totp="123456", # 6-digit code from authenticator app (changes every 30 seconds)
)
# Step 2: Validate with MPIN to complete authentication
validate_response = client.totp_validate(mpin="123456") # Your trading MPIN
# Place an order
order_response = client.place_order(
exchange_segment="nse_cm",
product="CNC",
price="1500.00",
order_type="L",
quantity="10",
validity="DAY",
trading_symbol="RELIANCE-EQ",
transaction_type="B",
)
# Get real-time quotes
quotes = client.quotes(
instrument_tokens=[{"instrument_token": "1333", "exchange_segment": "nse_cm"}], quote_type="all"
)
# Logout
client.logout()
Documentation
📚 Complete API Documentation
Detailed documentation for all SDK functions with examples and real API responses.
Quick Links
Authentication
Order Management
Portfolio & Positions
Market Data
WebSocket
- Market data (SFeed): Market Feed (Subscribe/Unsubscribe)
- Order & positions: Order Feed
- Full guide: SFeed WebSocket
📖 Guides & Documentation
Upgrading:
- Migration Guide (v2.0.2 → v3.0.0) - Upgrade existing code to the latest version
- Migration Scanner - Run against your project to auto-detect v2-only calls before you start migrating by hand
Installation:
- Installation Overview - All installation options
- Local Installation - Install from source (for contributors)
- Platform-Specific Guides - Windows, macOS, Linux, VS Code
API Documentation:
- Complete API Reference - All SDK functions
- SFeed WebSocket Guide - Async streaming client, protocol & migration
- All Guides - Complete guide index
WebSocket Streaming Example (SFeed)
Live market data is delivered through the modern async/await SFeed WebSocket
client. It uses async for iteration and returns type-safe Pydantic messages,
each enriched with its trading_symbol (resolved from the subscribe ack).
import asyncio
from neo_api_client import NeoAPI
from neo_api_client.websocket.feed import WsToken, SFeedScrip
async def main():
client = NeoAPI(consumer_key="your-consumer-key-token", environment="prod")
client.totp_login(mobile_number="+919876543210", ucc="YOUR_UCC", totp="123456")
client.totp_validate(mpin="123456")
# create_websocket() builds a SFeedWebSocket from the current session
async with client.create_websocket() as ws:
# Batch-subscribe any number of instruments in a single call
await ws.subscribe_scrips([
WsToken("nse_cm", "Nifty 50"),
WsToken("nse_cm", "11536"),
])
async for message in ws:
if isinstance(message, SFeedScrip):
print(
f"{message.trading_symbol} ({message.instrument_token}) "
f"LTP: {message.last_traded_price}"
)
asyncio.run(main())
Note: The SFeed client works out of the box — its dependencies (
websockets,pydantic) ship with the base install. The legacy callback-based WebSocket (client.subscribe(...),on_message, etc.) was removed in v2.2.0 — see the SFeed WebSocket guide for the full API and a migration reference.
Order & Position Streaming Example
Order-lifecycle events and live position updates stream over a separate
async/await WebSocket, create_order_feed(). It returns type-safe OrderUpdate /
PositionUpdate messages.
import asyncio
from neo_api_client import NeoAPI
from neo_api_client.websocket.orderfeed import OrderUpdate, PositionUpdate, OrderStatus
async def main():
client = NeoAPI(consumer_key="your-consumer-key-token", environment="prod")
client.totp_login(mobile_number="+919876543210", ucc="YOUR_UCC", totp="123456")
client.totp_validate(mpin="123456")
# create_order_feed() connects to wss://<baseurl>/realtime using the session
async with client.create_order_feed() as feed:
async for message in feed:
if isinstance(message, OrderUpdate):
print(f"order {message.data.order_no} -> {message.data.order_status}")
elif isinstance(message, PositionUpdate):
print(f"position {message.data.symbol}")
asyncio.run(main())
Full reference: Order & Position Feed.
Exception Handling
from neo_api_client import (
NeoAPIException,
AuthenticationError,
ValidationError,
RateLimitError,
NetworkError,
OrderError,
)
try:
response = client.place_order(...)
except AuthenticationError:
print("Authentication failed - please login again")
except ValidationError as e:
print(f"Invalid parameters: {e}")
except RateLimitError:
print("Rate limit exceeded - please retry after some time")
except OrderError as e:
print(f"Order placement failed: {e}")
except NeoAPIException as e:
print(f"API error: {e}")
Environment Setup
Create a .env file for credentials (copy from .env.example):
# Consumer Key from NEO app (REQUIRED - Used in Authorization header)
# Get it: NEO app → More → Trade API → Generate application → Copy token
NEO_CONSUMER_KEY=your-consumer-key-token
# Your registered mobile number with country code
NEO_MOBILE_NUMBER=+919876543210
# Your UCC (User Client Code) from NEO app Profile section
NEO_UCC=YOUR_UCC
# TOTP secret key (base32 string from QR code during TOTP registration)
# This is NOT the 6-digit code - it's the secret key from authenticator setup
NEO_TOTP_SECRET=YOUR_TOTP_SECRET_KEY
# Your trading MPIN
NEO_MPIN=123456
How to get credentials:
- Consumer Key: NEO app → More → Trade API → Generate application → Copy token
- UCC: NEO app → Profile section
- TOTP Secret: https://www.kotakneo.com/platform/kotak-neo-trade-api/ → Register for TOTP → Note the secret from QR code setup
Performance Benchmarks
Average API response times (production environment):
| API Function | Avg Latency |
|---|---|
| Login & Authentication | 134-367 ms |
| Order Operations | 67-71 ms |
| Portfolio & Positions | 68-77 ms |
| Market Data (Quotes) | 289 ms |
| Margin Calculation | 110 ms |
| Scrip Master | 1250 ms |
Tested on production environment with real API calls
Common Parameters
Exchange Segments
nse_cm- NSE Cash Marketbse_cm- BSE Cash Marketnse_fo- NSE Futures & Optionsbse_fo- BSE Futures & Optionsmcx_fo- MCX Commoditiescde_fo- Currency Derivatives (market data/quotes only — not accepted byplace_order/margin_required, which don't support this segment)
Product Types
CNC- Cash & Carry (Delivery)MIS- Margin Intraday Square-offNRML- Normal (Carry Forward)MTF- Margin Trading Facility
Note: place_order/modify_order only accept these four exact codes (Bracket
and Cover orders are no longer supported).
Order Types
L- Limit OrderMKT- Market OrderSL- Stop Loss LimitSL-M- Stop Loss Market
Transaction Types
B- BuyS- Sell
Validity Types
DAY- Valid for the dayIOC- Immediate or Cancel
Architecture
Always on for every request:
- HTTP/2 Transport - REST calls run over HTTP/2 (via
httpx) with connection pooling and automatic HTTP/1.1 fallback - Structured Logging - Request/response tracking with correlation IDs
- Type Safety - Full mypy type checking support
Optional reliability utilities (shipped, tested, and importable, but not wired into the request path by default — you opt in):
- Rate Limiter - Token-bucket throttling (per second/minute/hour) to avoid tripping API quotas. Enable with
RESTClientObject(..., enable_rate_limiting=True). - Retry Logic - Exponential backoff with jitter for transient errors, via the
with_retry/create_retry_decoratordecorators inneo_api_client.retry. - Circuit Breaker -
CircuitBreakerinneo_api_client.circuit_breakerto stop calling a failing service and let it recover.
Development
Setup
# Clone repository
git clone https://github.com/Kotak-Neo/kotak-neo-python.git
cd kotak-neo-python
# Install dependencies
pip install -e ".[dev]"
# Setup pre-commit hooks
pre-commit install
Testing
# Run all tests
pytest
# Run with coverage
pytest --cov=neo_api_client --cov-report=html
# Run smoke tests (requires .env configuration)
python tests/e2e/smoke_test.py
SDK contributors: the smoke/integration test runners can target an internal environment via the
NEO_ENVIRONMENTvariable. Ask an internal maintainer for the dev.envtemplate for that setup. This is not needed by normal SDK users — the client always uses production by default.
Code Quality
# Format code
ruff format .
# Lint code
ruff check .
# Type checking
mypy neo_api_client
# Security scan
bandit -r neo_api_client
Requirements
- Python: 3.10 or higher
- Core Dependencies: numpy, pandas, PyJWT, httpx[http2], websocket-client, structlog, tenacity, python-decouple, pyotp, websockets, pydantic
See pyproject.toml for complete dependency list.
Repository Structure
kotak-neo-python/
├── neo_api_client/ # Main package
│ ├── services/ # API service modules
│ ├── websocket/ # WebSocket implementation
│ ├── utils/ # Utility functions
│ ├── neo_api.py # Main NeoAPI class
│ ├── exceptions.py # Exception hierarchy
│ └── ... # Core modules
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── docs/ # Documentation
│ ├── functions/ # API function docs
│ └── installation/ # Installation guides
└── pyproject.toml # Project configuration
Support
- Documentation: GitHub Docs
- Issues: GitHub Issues
- Email: support@kotakneo.com
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see LICENSE file for details.
Disclaimer
This is the official SDK for Kotak Neo Trading APIs. Trading in financial markets involves substantial risk. Users are responsible for their own trading decisions and should thoroughly test their strategies before live trading.
⚠️ Risk Warning: As per SEBI study, 9 out of 10 individual traders in equity F&O segment incur net losses. Please trade responsibly.
Changelog
See CHANGELOG.md for version history and updates.
Version: 3.0.0
Status: Production/Stable
Built with ❤️ by Kotak Neo Team
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file kotakneoapi-3.0.0.tar.gz.
File metadata
- Download URL: kotakneoapi-3.0.0.tar.gz
- Upload date:
- Size: 71.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
48f0c5a9be71bcbaba4fff6b7ec5ce397d3b4e4e6e0d1fc7d2ab35b9cc89993d
|
|
| MD5 |
15cfc90c5a3d80e2f484e563f8d5fb2d
|
|
| BLAKE2b-256 |
43e55728bf9550c9b6d3e1f2f1b86e94aa9536633a587d2176ef8a3091d0944f
|
Provenance
The following attestation bundles were made for kotakneoapi-3.0.0.tar.gz:
Publisher:
publish.yml on Kotak-Neo/kotak-neo-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
kotakneoapi-3.0.0.tar.gz -
Subject digest:
48f0c5a9be71bcbaba4fff6b7ec5ce397d3b4e4e6e0d1fc7d2ab35b9cc89993d - Sigstore transparency entry: 2473452561
- Sigstore integration time:
-
Permalink:
Kotak-Neo/kotak-neo-python@7cbb485c5aaed7dde8ce8e9922dec70d5ca6dec3 -
Branch / Tag:
refs/tags/v3.0.0 - Owner: https://github.com/Kotak-Neo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7cbb485c5aaed7dde8ce8e9922dec70d5ca6dec3 -
Trigger Event:
release
-
Statement type:
File details
Details for the file kotakneoapi-3.0.0-py3-none-any.whl.
File metadata
- Download URL: kotakneoapi-3.0.0-py3-none-any.whl
- Upload date:
- Size: 85.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d59fa791fb4cbe2acada66a4ff4d166337b97f53ecc7d7ec3cdc0c556165f3cb
|
|
| MD5 |
fc17eaeabb91b6ba431bd3cfe2e9ac46
|
|
| BLAKE2b-256 |
9b58927308537583173982d13dd8ba4d2f9efd0fd9be694d2dd206aa93fcf81a
|
Provenance
The following attestation bundles were made for kotakneoapi-3.0.0-py3-none-any.whl:
Publisher:
publish.yml on Kotak-Neo/kotak-neo-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
kotakneoapi-3.0.0-py3-none-any.whl -
Subject digest:
d59fa791fb4cbe2acada66a4ff4d166337b97f53ecc7d7ec3cdc0c556165f3cb - Sigstore transparency entry: 2473452608
- Sigstore integration time:
-
Permalink:
Kotak-Neo/kotak-neo-python@7cbb485c5aaed7dde8ce8e9922dec70d5ca6dec3 -
Branch / Tag:
refs/tags/v3.0.0 - Owner: https://github.com/Kotak-Neo
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7cbb485c5aaed7dde8ce8e9922dec70d5ca6dec3 -
Trigger Event:
release
-
Statement type: