Meta description: A beginner-friendly Python SDK for Jainam ProTrade Open API v2, covering authentication, portfolio APIs, orders, contract masters, historical data, and WebSocket market feeds.
Developed by Sreenivasulu Malkari
Python is one of the most popular languages for market research, automation, data analysis, and algorithmic trading.
It is easy to read, has an enormous ecosystem, and allows developers to move quickly from an idea to a working prototype. But broker API integration still requires a fair amount of plumbing: authentication, checksums, sessions, contract masters, instrument IDs, JSON payloads, order management, error handling, and WebSocket connections.
That is why I built Jainam API Python: a reusable, open-source Python SDK for developers working with the Jainam ProTrade Open API v2.
The goal is simple: make Jainam API integration more approachable for Python developers while keeping the package structured enough for serious backend and trading applications.
GitHub repository:
github.com/malkarisreenivasulu/jainam-api-python
Why I Built Jainam API Python
When developers first explore a broker API, they often have to deal with several low-level tasks before they can even retrieve a profile or place a test order.
Typical integration work includes:
- building the login flow
- generating authentication checksums
- exchanging authorization codes
- storing and using user sessions
- constructing REST API payloads
- downloading contract masters
- resolving instrument IDs
- handling API errors
- receiving live market data
- processing order-status events
- reconnecting WebSockets
- testing without accidentally sending live trades
For beginners, that can be a lot to absorb at once.
Jainam API Python packages the repetitive integration work into a reusable library so that developers can focus more on application logic and less on rebuilding the same API plumbing.
The project is useful for:
- students learning broker API integration
- Python developers
- data analysts
- algorithmic trading developers
- fintech developers
- researchers
- portfolio-monitoring projects
- market scanners
- alerting tools
- historical-data research
- backend automation
What Can You Build with Jainam API Python?
The SDK can serve as the foundation for many different types of applications.
For example:
Portfolio Dashboards
Retrieve profile, funds, holdings, positions, orders, and trade information and display it in a web or desktop dashboard.
Market Scanners
Combine live market data with custom filtering rules to identify instruments that meet predefined conditions.
Historical Research Tools
Download or request historical candle data and use Python libraries such as pandas, NumPy, or matplotlib for research and analysis.
Trading Utilities
Build monitored utilities for order placement, order modification, cancellation, margin checking, and reconciliation.
Alerting Systems
Generate alerts based on price changes, order status, position changes, or portfolio conditions.
Educational Projects
Learn how broker authentication, REST APIs, WebSockets, contract masters, and trading workflows work without having to design an SDK from scratch.
Installing Jainam API Python
The tagged release can be installed directly from GitHub.
pip install git+https://github.com/malkarisreenivasulu/jainam-api-python.git@v0.1.1
Then import the SDK:
from jainam_api import Client, Order
If you want to work on the project itself, clone the repository:
git clone https://github.com/malkarisreenivasulu/jainam-api-python.git
cd jainam-api-python
Create a virtual environment:
python -m venv .venv
On Linux or macOS:
source .venv/bin/activate
Then install the project in development mode:
python -m pip install -e '.[dev]'
Run the test suite:
pytest
Understanding Jainam Authentication
Before calling authenticated APIs, create an application in the Jainam developer portal.
Jainam Developers:
https://protrade.jainam.in/developers
Your application configuration includes values such as the app code, callback URL, and API secret.
The API secret should be stored securely and should never be committed to Git.
Generating the Login URL
Jainam API Python includes a helper for generating the login URL.
from jainam_api import build_login_url
login_url = build_login_url("YOUR_APP_CODE")
print(login_url)
Your application can redirect the user to this URL.
After successful authentication, Jainam redirects the browser to your registered callback URL with values such as:
authCode
userId
These values are then used to exchange the authorization code for a user session.
How the Authentication Checksum Works
Jainam documents the checksum using the following input:
SHA-256(userId + authCode + apiSecret)
Instead of implementing that flow manually every time, the SDK handles it for you.
from jainam_api import Client
response = Client().exchange_auth_code(
user_id="USER_ID",
auth_code="AUTH_CODE",
api_secret="API_SECRET",
)
print(response)
The response can then be used to obtain the authenticated user session required for subsequent API calls.
Protect Your Credentials
Broker API credentials are sensitive.
Do not publish or log:
API secrets
user sessions
authorization codes
passwords
OTP values
authorization headers
personal account data
complete authentication responses
Avoid code such as:
print(api_secret)
print(user_session)
In development and production, environment variables are a much better option.
For example:
export JAINAM_USER_ID="your-user-id"
export JAINAM_USER_SESSION="your-session"
In a production environment, a secrets manager is preferable.
Your First Read-Only Jainam API Program
Once you have an authenticated session, you can create the client.
import os
from jainam_api import Client
api = Client(
user_session=os.environ["JAINAM_USER_SESSION"],
user_id=os.environ["JAINAM_USER_ID"],
)
Now try a few read-only requests.
print(api.profile())
print(api.funds())
print(api.holdings("cnc"))
print(api.positions())
These are useful as your first authenticated API calls because they do not intentionally submit a new trading order.
If these requests succeed, you know that your session and user ID are being passed correctly.
Reading Profile Information
You can retrieve account profile information with:
profile = api.profile()
print(profile)
In a real application, avoid printing complete profile responses to logs if they contain personal account data.
It is usually better to extract only the fields your application needs.
Reading Funds
Funds or margin-related account information can be retrieved with:
funds = api.funds()
print(funds)
This information can be useful when building dashboards, risk monitors, and pre-order checks.
Applications should still treat the broker response as one input into the overall risk system rather than assuming available funds alone make an order appropriate.
Holdings and Positions
Holdings can be retrieved with:
holdings = api.holdings("cnc")
print(holdings)
Positions can be retrieved using:
positions = api.positions()
print(positions)
These APIs are useful for:
- portfolio dashboards
- reconciliation
- exposure monitoring
- position limits
- post-trade reporting
- daily summaries
Order Book and Trade Book
Trading applications should regularly reconcile their internal state against broker data.
For example:
orders = api.order_book()
trades = api.trade_book()
print(orders)
print(trades)
This is especially important for applications that also consume WebSocket order updates.
A WebSocket feed is excellent for real-time events, but REST responses remain important for reconciliation after reconnects, application restarts, or missed events.
Contract Masters Come Before Orders
One of the most important parts of broker API development is instrument resolution.
A company name or trading symbol is not always enough.
Trading APIs often require an exchange-specific instrument ID or token.
That means you should not copy an instrument ID from:
- an old tutorial
- a screenshot
- a blog article
- a previous day’s CSV
- another broker’s API
- an old database record
Instead, download the latest contract master and resolve the instrument using current data.
Jainam API Python supports contract downloads.
api.download_contracts(
exchange="NSE",
destination="data/NSE.csv",
fmt="csv",
)
Before building an order, verify:
- exchange
- segment
- trading symbol
- instrument ID
- lot size
- tick size
- instrument type
For systems that trade multiple instruments, contract data can be loaded into memory or a database and indexed for quick lookup.
Useful lookup keys might include:
exchange + trading symbol
instrument ID
ISIN
segment + symbol
Why Instrument IDs Matter
A trading application should avoid assumptions based only on human-readable names.
For example, your interface might display:
ABC COMPANY
But the broker API may require something like:
exchange = NSE
instrument_id = 123456
The exact identifier should come from the current contract master.
This separation is useful because a trading system can display friendly names to users while still sending precise identifiers to the broker.
Creating an Order Object
Jainam API Python provides an Order object for constructing orders.
from jainam_api import Order
order = Order(
exchange="NSE",
instrument_id="VERIFY_FROM_TODAYS_CONTRACT",
transaction_type="BUY",
quantity=1,
product="LONGTERM",
order_type="LIMIT",
price="VERIFY_CURRENT_PRICE",
validity="DAY",
order_tag="jainam-api-python",
)
Before sending the order, inspect the API payload:
print(order.to_api())
This can help catch mistakes in:
- transaction type
- quantity
- product
- order type
- price
- validity
- instrument ID
Checking Margin Before an Order
The SDK can also be used to request order-margin information.
margin = api.order_margin(order)
print(margin)
This can be useful as one part of a pre-trade validation process.
However, margin availability should not be treated as the only trading control.
A robust system should implement its own independent rules.
Placing an Order
Methods that change trading state require explicit confirmation.
response = api.place_order(
order,
confirm=True,
)
The confirm=True parameter is designed to reduce accidental method calls.
It should not be confused with a full risk-management system.
Before sending a live order, an application should independently verify:
- the correct account
- exchange
- instrument
- quantity
- order side
- product
- order type
- price
- current market state
- available limits
- strategy state
- position limits
Build Risk Controls Outside the SDK
A broker SDK should provide reliable API integration.
Trading risk controls should belong to the application using that SDK.
Useful safeguards include:
Maximum Order Quantity
Reject orders larger than a predefined quantity.
Maximum Order Value
Estimate order value before submission and reject values above your limit.
Position Limits
Prevent exposure from exceeding configured thresholds.
Daily Loss Limits
Disable new order generation after predefined risk conditions are reached.
Symbol Restrictions
Allow trading only in explicitly approved instruments.
Duplicate Order Detection
Protect against repeated submissions caused by retries or programming errors.
Stale Market Data Protection
Do not generate decisions from a feed that has stopped updating.
Kill Switch
Provide a clear mechanism to stop new order generation.
Monitoring
Generate alerts when API requests, WebSockets, or reconciliation checks fail.
Live Market Data with WebSockets
Polling a REST API repeatedly is not the right approach for live market data.
Jainam API Python includes a MarketTicker implementation for consuming the Jainam WebSocket market feed.
The SDK handles protocol details such as the documented session transformation and heartbeat behavior.
It supports:
- market ticks
- five-level market depth
A typical application architecture might look like:
Jainam WebSocket
|
v
MarketTicker
|
v
Message Handler
|
v
Queue / Buffer
|
+--> Scanner
|
+--> Strategy
|
+--> Database
|
+--> Alerts
The important principle is to keep WebSocket callbacks fast.
Do not perform large database operations, long calculations, or blocking network calls directly inside the WebSocket callback.
Live Order-Status Updates
Jainam API Python also includes an OrderTicker for receiving live order-status events through the separate order WebSocket feed.
Depending on the broker event, your application may receive updates when an order is:
- accepted
- rejected
- pending
- modified
- cancelled
- partially executed
- fully executed
These real-time updates can be extremely useful for order-management systems.
But your application should still reconcile against the REST APIs.
For example:
Order WebSocket
|
v
Local Order State
|
v
Periodic REST Reconciliation
|
+--> Order Book
+--> Trade Book
+--> Positions
This prevents your application from permanently relying on a single event stream.
WebSocket Reconnection
Network connections eventually fail.
Production software should assume that WebSocket connections will disconnect at some point.
A good reconnect strategy uses bounded exponential backoff.
For example:
1 second
2 seconds
4 seconds
8 seconds
16 seconds
30 seconds
30 seconds
Do not reconnect continuously with no delay.
You should also add jitter where appropriate so that many processes do not reconnect simultaneously.
Restore Subscriptions After Reconnection
After a WebSocket reconnects, the application should restore any subscriptions that were active before the connection failed.
That means your application should maintain subscription state separately from the WebSocket itself.
For example:
subscribed_instruments = {
"NSE:12345",
"NSE:67890",
}
After reconnecting, the application can resubscribe to those instruments.
Detect Stale Market Data
A WebSocket connection can remain technically open while useful data stops arriving.
For that reason, production systems should track the timestamp of the most recent valid market message.
For example:
last_tick_time = 10:15:25
current_time = 10:15:35
If your application expects frequent updates and receives nothing for an unexpectedly long period, it can:
- raise an alert
- stop strategy execution
- reconnect
- switch to a safe state
This is usually safer than assuming an open socket means the feed is healthy.
Keep Trading Decisions Away from Network Callbacks
One of the easiest mistakes to make is placing too much logic inside a WebSocket callback.
For example:
def on_tick(message):
calculate_100_indicators()
query_database()
call_external_api()
place_order()
This design can block incoming messages.
A better pattern is:
def on_tick(message):
tick_queue.put(message)
Then another worker processes the queue.
while True:
message = tick_queue.get()
process_market_data(message)
This separation becomes increasingly valuable as the application grows.
Historical Market Data
Historical candle data is useful for:
- charting
- strategy research
- backtesting
- signal development
- indicator calculations
- volatility analysis
- market studies
Python is particularly useful here because historical API responses can be combined with tools such as:
pandas
NumPy
matplotlib
Jupyter
Polars
SciPy
A typical workflow is:
Jainam Historical API
|
v
Python
|
v
DataFrame / Data Processing
|
+--> Research
+--> Charts
+--> Statistics
+--> Backtesting
Historical analysis should still account for data quality, missing candles, symbol changes, corporate actions, and other market-data considerations.
Error Handling in Python Trading Applications
Do not ignore exceptions.
For example, avoid patterns like:
try:
api.profile()
except Exception:
pass
This hides important failures.
Instead:
try:
profile = api.profile()
except Exception as exc:
print(f"Unable to retrieve profile: {exc}")
Production systems should go further and categorize failures.
Examples include:
authentication failure
network timeout
connection error
invalid request
broker rejection
exchange rejection
rate limit
WebSocket disconnect
unexpected response
application bug
Different failures should produce different behavior.
For example:
- a temporary network failure might be retried
- invalid credentials should not be retried indefinitely
- a rejected order should be recorded and investigated
- stale market data may require strategy suspension
Avoid Blind Retries
Retries are useful, but they can also create problems in trading systems.
Suppose an application sends an order, loses the HTTP response, and immediately retries.
If the first request reached the broker successfully, the retry could create a duplicate order.
That means retry logic for trading mutations should be designed carefully.
Applications should use:
- unique client order tags where supported
- idempotency mechanisms where available
- local request tracking
- broker reconciliation
- duplicate-order protection
Read-only requests are generally much safer to retry than state-changing requests.
Logging for Production
Logs are essential for troubleshooting.
But logs should not become a second copy of your account credentials.
Avoid logging:
API secrets
sessions
authorization codes
passwords
OTP values
complete authorization headers
personal account details
Prefer structured logs.
For example:
event=order_request
exchange=NSE
symbol=EXAMPLE
quantity=1
side=BUY
order_type=LIMIT
request_id=abc123
This gives you useful operational information without exposing secrets.
Testing Without Live Trading
Automated testing should never depend on placing a real market order.
Jainam API Python uses test fixtures and local or fake responses for automated checks.
This makes it possible to validate functionality without:
- live credentials
- real account data
- exchange availability
- real money
- live order submission
The repository checks the project with tools including:
pytest
and Ruff for Python linting and formatting checks.
The Python package build is also validated.
Why Fake Test Data Matters
Test fixtures should never contain personal information or real credentials.
Good fixture values look like:
USER_123
SESSION_FAKE_001
INSTRUMENT_ABC
ORDER_TEST_001
Avoid committing:
real user IDs
real sessions
real mobile numbers
real email addresses
real account numbers
real authorization responses
This is particularly important for open-source financial software.
Open-Source Development
Jainam API Python is designed as an open-source project with a focused Python codebase.
The repository includes:
- SDK source code
- tests
- beginner documentation
- API reference documentation
- examples
- CI checks
- tagged releases
The project also documents gaps or ambiguities discovered while working with API documentation rather than silently guessing behavior.
That is an important principle for API libraries.
When behavior is unknown, it is better to document the uncertainty than make an assumption that could affect a user’s trading application.
Project Documentation
The repository contains separate documentation depending on how deeply you want to explore the SDK.
Main Repository
github.com/malkarisreenivasulu/jainam-api-python
Python-Only Blog
Beginner Guide
API Reference
Release v0.1.1
github.com/malkarisreenivasulu/jainam-api-python/releases/tag/v0.1.1
Quick Start
Install the SDK:
pip install git+https://github.com/malkarisreenivasulu/jainam-api-python.git@v0.1.1
Import the package:
from jainam_api import Client, Order
Create an authenticated client:
import os
from jainam_api import Client
api = Client(
user_session=os.environ["JAINAM_USER_SESSION"],
user_id=os.environ["JAINAM_USER_ID"],
)
Test the connection:
profile = api.profile()
print(profile)
Then gradually add:
funds
holdings
positions
orders
trades
contract resolution
margin checks
historical data
market WebSockets
order WebSockets
monitoring
reconciliation
risk controls
Building one layer at a time makes debugging considerably easier.
A Practical Application Architecture
For developers moving beyond simple scripts, one possible architecture is:
+------------------+
| Jainam REST APIs |
+--------+---------+
|
v
+------------------+
| API Client |
+--------+---------+
|
+----------------+----------------+
| |
v v
+----------------+ +----------------+
| Portfolio Data | | Order Manager |
+----------------+ +--------+-------+
|
v
+----------------+
| Risk Controls |
+--------+-------+
|
v
Order Submission
+-----------------------+
| Jainam Market WS Feed |
+-----------+-----------+
|
v
+---------------+
| MarketTicker |
+-------+-------+
|
v
+---------------+
| Event Queue |
+-------+-------+
|
+----------------+----------------+
| | |
v v v
+---------+ +----------+ +---------+
| Scanner | | Strategy | | Storage |
+---------+ +----------+ +---------+
This is only one possible design, but it demonstrates an important principle: separate network communication, strategy logic, order execution, and risk management.
Python Is Excellent for Research and Automation
One of Python’s strongest advantages is its ecosystem.
Broker API data can be integrated with libraries such as:
pandas
NumPy
matplotlib
Polars
FastAPI
Flask
Django
SQLAlchemy
Jupyter
Redis clients
PostgreSQL clients
That makes it possible to use the same broker integration for:
- notebooks
- dashboards
- scheduled jobs
- REST services
- market scanners
- research pipelines
- monitoring systems
You can begin with a simple Python script and later move the same integration into a larger backend application.
Open a Jainam Account
If you need a Jainam account, you may use one of my referral links.
Jainam Premium
https://jplus.jainam.in/refer/feSFm58qRQBC
Jainam DIY
https://jplus.jainam.in/refer/aPY9Y2QeHnTy
Referral disclosure: I may receive a referral benefit if you register through these links. Please verify Jainam’s latest brokerage charges, pricing, features, eligibility requirements, and terms directly with Jainam before selecting a plan.
About the Developer
Jainam API Python was developed by Sreenivasulu Malkari.
I built the project to make Jainam API integration easier to understand and reuse for Python developers, students, researchers, and algorithmic trading developers.
The project is intended for people who want a focused Python package rather than having to repeatedly implement authentication, request handling, contract resolution, and WebSocket plumbing themselves.
You can find the project and my other work here:
Jainam API Python:
github.com/malkarisreenivasulu/jainam-api-python
GitHub profile:
github.com/malkarisreenivasulu
If the project is useful to you, consider starring the repository.
Contributions are also welcome.
When opening an issue or submitting a pull request, please remove:
- credentials
- sessions
- authorization codes
- personal account details
- personally identifiable information
Reproducible examples with fake identifiers make open-source debugging much safer.
Final Thoughts
Broker API development looks simple from the outside.
There is an HTTP endpoint, you send JSON, and you receive JSON.
In practice, reliable trading integrations need much more than that.
You need to think about:
- authentication lifecycle
- credential security
- current contract data
- instrument resolution
- network failures
- API errors
- WebSocket reconnects
- subscription recovery
- stale market feeds
- order reconciliation
- duplicate requests
- risk controls
- monitoring
- safe deployment
Python makes it possible to build all of these components without a large amount of boilerplate, while its data ecosystem makes it especially useful for market research and analytics.
Jainam API Python provides a reusable foundation for that work and aims to make the Jainam ProTrade Open API more accessible to Python developers.
If you are learning broker APIs, building a market-data project, creating a portfolio dashboard, or developing your own monitored trading infrastructure, you can start with the repository here:
github.com/malkarisreenivasulu/jainam-api-python
Developed by Sreenivasulu Malkari.
Disclaimer
Jainam API Python is an independent software-development project developed by Sreenivasulu Malkari.
This article, source code, documentation, examples, and related software are provided for educational and software-development purposes only.
They do not constitute:
- investment advice
- financial advice
- trading advice
- a recommendation to buy or sell securities
- a guarantee of trading performance
Trading and automated trading involve financial risk.
API specifications, instrument information, broker rules, exchange rules, trading hours, margins, charges, and other operational details may change.
Before connecting any software to a live trading account:
- verify the latest Jainam API documentation
- use the latest contract master
- verify all instrument IDs
- test with non-destructive requests first
- validate order parameters
- implement independent risk controls
- protect credentials
- monitor WebSocket connections
- reconcile orders and trades
- maintain a kill switch
- actively monitor every live trading system
Use the SDK carefully and review every live-trading workflow before enabling real order submission.