Jainam API Go: Build Fast, Reliable Trading Integrations with Golang

A practical Go SDK for Jainam ProTrade Open API v2, covering authentication, portfolio APIs, order management, historical data, contract masters, and WebSocket market feeds.

Developed by Sreenivasulu Malkari

Building a trading application is very different from writing a typical web script. Trading systems often run continuously, maintain multiple network connections, process live events, handle failures, and need predictable behavior under load.

That is exactly the kind of workload where Go works well.

I built Jainam API Go as a dedicated Golang SDK for developers who want to integrate their applications with the Jainam ProTrade Open API v2.

The project is designed specifically for Go developers, with its own module, documentation, examples, tests, CI workflow, and release history.

GitHub repository:
github.com/malkarisreenivasulu/jainam-api-go


Why I Built a Dedicated Go SDK

Broker API integrations usually involve more than sending a few HTTP requests.

A production application may need to:

  • authenticate users securely
  • download and process instrument contract masters
  • retrieve account, funds, holdings, positions, orders, and trades
  • place and manage orders
  • consume live market data
  • listen for order-status updates
  • reconnect after network interruptions
  • enforce request timeouts
  • shut down gracefully
  • reconcile WebSocket events with REST API data

Go provides a strong foundation for this type of software because of its simple concurrency model, efficient networking, static binaries, good standard library, and straightforward deployment.

Rather than maintaining Go examples inside a repository designed primarily for another language, I wanted Jainam API Go to be a proper standalone Go project.

The SDK is suitable for developers building:

  • algorithmic trading infrastructure
  • trading gateways
  • portfolio dashboards
  • order-monitoring services
  • market-data consumers
  • alerting systems
  • backend APIs
  • event-processing applications
  • containerized trading services
  • educational projects for learning broker API integration

Installing Jainam API Go

The package can be installed directly with Go modules.

go get github.com/malkarisreenivasulu/jainam-api-go@v0.1.0

Import it into your project:

import jainam "github.com/malkarisreenivasulu/jainam-api-go"

The SDK requires Go 1.21 or newer.

For package documentation, you can also visit:

https://pkg.go.dev/github.com/malkarisreenivasulu/jainam-api-go


Authentication with Jainam ProTrade

The first step is to create an application in the Jainam developer portal and configure your callback URL.

Jainam Developer Portal:

https://protrade.jainam.in/developers

Store your application code and API secret securely. Credentials should never be committed to source control.

You can generate the Jainam login URL using:

loginURL := jainam.LoginURL("YOUR_APP_CODE")
fmt.Println(loginURL)

After authentication, Jainam redirects the user to the configured callback URL with values such as authCode and userId.

The authentication checksum follows the documented format:

SHA-256(userId + authCode + apiSecret)

The SDK handles the exchange request through ExchangeAuthCode.

api := jainam.New("", "")

response, err := api.ExchangeAuthCode(
    context.Background(),
    "USER_ID",
    "AUTH_CODE",
    "API_SECRET",
)
if err != nil {
    log.Fatal(err)
}

fmt.Println(response)

Authentication credentials should always be treated as sensitive data.

Avoid logging:

  • API secrets
  • authorization codes
  • user sessions
  • access credentials
  • personal account information
  • complete API responses containing sensitive data

Environment variables or a proper secrets-management system are preferable to hard-coded credentials.


Creating a Jainam API Client

Once you have a valid session, create the API client using the user session and user ID.

api := jainam.New(
    os.Getenv("JAINAM_USER_SESSION"),
    os.Getenv("JAINAM_USER_ID"),
)

One of the important design choices in Jainam API Go is that REST methods accept Go’s context.Context.

That allows your application to control request deadlines and cancellation.

ctx, cancel := context.WithTimeout(
    context.Background(),
    10*time.Second,
)
defer cancel()

profile, err := api.Profile(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println(profile)

Using contexts becomes particularly important in long-running trading applications. A service should be able to cancel outstanding work when requests expire, dependencies fail, or the application is shutting down.


Accessing Account and Portfolio Information

Jainam API Go provides methods for commonly required account information.

For example:

ctx := context.Background()

profile, err := api.Profile(ctx)
funds, err := api.Funds(ctx)
holdings, err := api.Holdings(ctx, "cnc")
positions, err := api.Positions(ctx)
orders, err := api.OrderBook(ctx)
trades, err := api.TradeBook(ctx)

In real applications, every error should be checked independently rather than reusing the same err variable without validation.

For example:

profile, err := api.Profile(ctx)
if err != nil {
    log.Printf("profile request failed: %v", err)
}

funds, err := api.Funds(ctx)
if err != nil {
    log.Printf("funds request failed: %v", err)
}

The SDK returns a structured APIError for API-level failures and preserves response information that can be useful during debugging.

This makes it easier for applications to distinguish between network errors, context cancellation, and API responses indicating a rejected request.


Working with the Contract Master

One of the most important parts of any broker integration is instrument resolution.

You should never depend permanently on an instrument ID copied from an article, sample project, screenshot, or old database.

Contract information can change.

Before creating an order, resolve the instrument using the latest contract master and verify details such as:

  • exchange
  • trading symbol
  • instrument ID
  • segment
  • lot size
  • tick size
  • instrument type

Jainam API Go can download the contract master directly.

err := api.DownloadContracts(
    context.Background(),
    "NSE",
    "csv",
    "NSE.csv",
)
if err != nil {
    log.Fatal(err)
}

The package also provides ParseContractCSV, which converts the downloaded contract data into Go maps that can be searched or indexed.

A production application will usually load the contract master into an in-memory index or database at startup and refresh it regularly.

For example, you may create indexes by:

exchange + trading symbol
instrument ID
ISIN
segment + symbol

This avoids repeatedly scanning a large CSV file when resolving instruments.


Creating and Reviewing Orders

A typical order can be represented using the jainam.Order structure.

order := jainam.Order{
    Exchange:        "NSE",
    InstrumentID:    "VERIFY_FROM_TODAYS_CONTRACT",
    TransactionType: "BUY",
    Quantity:        1,
    Product:         "LONGTERM",
    OrderType:       "LIMIT",
    Price:           "VERIFY_CURRENT_PRICE",
    Validity:        "DAY",
    OrderTag:        "jainam-api-go",
}

Before submitting an order, applications can perform additional validation or request margin information.

margin, err := api.OrderMargin(
    context.Background(),
    order,
)
if err != nil {
    log.Fatal(err)
}

fmt.Println(margin)

Live order submission requires explicit confirmation:

response, err := api.PlaceOrder(
    context.Background(),
    order,
    true,
)

The confirmation argument provides an additional safeguard against accidentally calling a live trading method.

However, this boolean should not be considered a complete risk-management system.

A production trading application should implement independent controls such as:

  • maximum order quantity
  • maximum order value
  • daily loss limits
  • position limits
  • symbol restrictions
  • duplicate-order detection
  • stale-price protection
  • order-rate limits
  • exchange-session validation
  • kill switches
  • monitoring and alerts
  • reconciliation

Risk checks should exist outside the broker SDK so that trading rules remain under the control of the application using the library.


WebSocket Market Data

REST APIs are useful for account information and transactional operations, but live trading systems usually require streaming data.

Jainam API Go includes MarketTicker for receiving Jainam market-data events.

It supports tick subscriptions and five-level depth subscriptions while handling the session transformation and heartbeat behavior required by the protocol.

A basic example looks like this:

ticker := &jainam.MarketTicker{
    UserID:      os.Getenv("JAINAM_USER_ID"),
    UserSession: os.Getenv("JAINAM_USER_SESSION"),
    OnMessage: func(message map[string]any) {
        fmt.Println(message)
    },
}

if err := ticker.Connect(); err != nil {
    log.Fatal(err)
}

For demonstrations, printing messages is convenient.

In production, however, WebSocket callbacks should remain lightweight.

Avoid running strategy logic, database writes, or slow external API calls directly inside a socket callback.

A better architecture is:

WebSocket
    |
    v
Message Decoder
    |
    v
Buffered Channel / Queue
    |
    +--> Market Data Processor
    |
    +--> Strategy Engine
    |
    +--> Persistence
    |
    +--> Monitoring

This helps prevent a slow consumer from blocking market-data processing.


Receiving Live Order Updates

Market prices are only one part of a trading system.

Applications also need to know when orders are:

  • accepted
  • rejected
  • modified
  • cancelled
  • partially filled
  • completely filled

Jainam API Go includes a separate OrderTicker for consuming live order-status events using the appropriate order WebSocket token.

Even with real-time order updates, REST reconciliation is important.

A robust trading application should periodically compare WebSocket events with:

  • Order Book
  • Trade Book
  • Positions
  • Holdings where applicable

WebSocket connections can disconnect, messages can be delayed, and applications can restart.

The REST APIs should therefore remain the authoritative reconciliation mechanism.


Designing WebSocket Connections for Production

A basic WebSocket connection is straightforward.

A production-grade WebSocket client requires considerably more care.

Consider implementing:

Reconnection Backoff

Avoid reconnecting continuously in a tight loop.

Use increasing delays with an upper limit.

For example:

1 second
2 seconds
4 seconds
8 seconds
16 seconds
30 seconds maximum

Adding random jitter can also help avoid synchronized reconnect storms.

Subscription Recovery

After reconnecting, the client should restore its previous subscriptions automatically.

Feed Freshness Monitoring

Your application should know when the market-data stream has stopped updating.

A watchdog can track the timestamp of the most recently received message and raise an alert when data becomes stale.

Protected Concurrent Writes

Multiple goroutines should not write to the same WebSocket connection simultaneously unless the WebSocket implementation explicitly supports it.

Use a dedicated writer goroutine or synchronization mechanism.

Graceful Shutdown

When the application receives a termination signal:

  1. stop creating new work
  2. cancel active contexts
  3. stop strategy execution
  4. close WebSocket connections
  5. flush important pending events
  6. persist required state
  7. exit cleanly

Go’s context and signal-handling packages make this architecture relatively straightforward.


Why Go Works Well for Trading Infrastructure

Go has several characteristics that make it particularly suitable for broker integrations.

Goroutines

A trading service may need separate concurrent processes for:

  • market data
  • order updates
  • REST polling
  • strategy execution
  • reconciliation
  • database persistence
  • risk monitoring
  • metrics
  • health checks

Goroutines make these components relatively easy to structure.

Channels

Channels provide a clean mechanism for moving events between parts of the system.

For example:

MarketTicker
   |
   v
marketDataChannel
   |
   v
Strategy Engine
   |
   v
orderIntentChannel
   |
   v
Risk Engine
   |
   v
Order Manager

Context

Go’s context model is valuable for enforcing deadlines and coordinated shutdown.

Static Binaries

Go applications can often be deployed as a single compiled binary without requiring a language runtime on the server.

That simplifies deployment to:

  • VPS servers
  • Docker containers
  • Kubernetes
  • cloud instances
  • on-premise infrastructure

Strong Standard Library

Go includes solid standard-library support for HTTP, JSON, cryptography, concurrency, testing, profiling, and networking.

These are all fundamental building blocks of a trading integration.


Error Handling Matters

Trading software should never silently ignore an error.

For example, this pattern is dangerous:

profile, _ := api.Profile(ctx)

The application no longer knows whether the request succeeded.

Instead:

profile, err := api.Profile(ctx)
if err != nil {
    log.Printf("unable to load profile: %v", err)
    return
}

Applications should also distinguish between different categories of failures.

Examples include:

context deadline exceeded
network timeout
authentication failure
invalid request
broker rejection
exchange rejection
rate limit
WebSocket disconnect
internal application error

Not every failure should trigger the same retry behavior.

For example, retrying an invalid order indefinitely is very different from retrying a temporary network timeout.


Logging Without Leaking Credentials

Logs are essential when debugging production systems, but they are also a common place where secrets accidentally appear.

Do not log:

API secret
session token
authentication code
complete authorization headers
passwords
OTP values
private account details

Instead of:

log.Printf("request: %+v", request)

prefer structured logs containing only the information required for diagnostics.

For example:

event=order_request
exchange=NSE
symbol=EXAMPLE
quantity=1
order_type=LIMIT
request_id=abc123

Sensitive fields should be removed or masked before logging.


Testing

Jainam API Go is designed so that tests do not depend on placing real trades.

GitHub Actions runs checks including:

go test ./...
go vet ./...

The repository also verifies formatting with gofmt.

Tests use local or fake responses rather than sending live orders during CI.

This is important because automated test pipelines should never depend on real brokerage credentials or live market transactions.


Continuous Integration

Every software library benefits from automated checks.

The Jainam API Go repository uses GitHub Actions so that changes can be validated consistently.

A typical workflow checks:

Compilation
Unit tests
go vet
gofmt

This helps catch issues before a release reaches users.

For trading infrastructure in particular, reproducibility matters. A small change in request handling, concurrency, parsing, or authentication can have a significant operational impact.


Project Documentation

The repository contains separate documentation for different use cases.

Main Repository

github.com/malkarisreenivasulu/jainam-api-go

Complete Go Blog

docs/BLOG.md

Beginner Guide

docs/GETTING_STARTED.md

API Reference

docs/API_REFERENCE.md

Go Package Documentation

pkg.go.dev/github.com/malkarisreenivasulu/jainam-api-go

Release v0.1.0

github.com/malkarisreenivasulu/jainam-api-go/releases/tag/v0.1.0


Quick Start

Install the package:

go get github.com/malkarisreenivasulu/jainam-api-go@v0.1.0

Import it:

import jainam "github.com/malkarisreenivasulu/jainam-api-go"

Create the client:

api := jainam.New(
    os.Getenv("JAINAM_USER_SESSION"),
    os.Getenv("JAINAM_USER_ID"),
)

Then start with a simple authenticated request:

ctx, cancel := context.WithTimeout(
    context.Background(),
    10*time.Second,
)
defer cancel()

profile, err := api.Profile(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println(profile)

From there, you can gradually add contract resolution, portfolio APIs, order workflows, WebSocket feeds, reconciliation, logging, monitoring, and independent risk controls.


Open a Jainam Account

If you are planning to use Jainam and need an account, you can 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 choosing a plan.


About the Developer

Jainam API Go was developed by Sreenivasulu Malkari.

I created the project to provide Go developers with a focused Jainam API integration package without requiring them to work through mixed-language examples or unrelated packaging conventions.

The project is intended to be useful for:

  • Go developers
  • backend engineers
  • students
  • API integration developers
  • fintech developers
  • algorithmic trading developers
  • developers learning event-driven systems

You can find the project and my other work on GitHub:

Jainam API Go:
github.com/malkarisreenivasulu/jainam-api-go

GitHub profile:
github.com/malkarisreenivasulu

If the project helps you, consider starring the repository.

Bug reports and pull requests are also welcome. When reporting an issue, please provide enough information to reproduce the problem while removing API secrets, sessions, credentials, account information, and other sensitive data.


Final Thoughts

Broker integrations become much easier to maintain when the underlying software has clear boundaries.

Authentication should be separate from trading logic. Contract resolution should be separate from order construction. WebSocket processing should be isolated from strategy execution. Risk controls should exist independently of the broker SDK. REST APIs should reconcile live events rather than assuming every WebSocket message will always arrive.

Go provides a strong set of tools for building this kind of architecture, and Jainam API Go aims to provide a practical foundation for developers working with the Jainam ProTrade Open API.

The goal of the project is straightforward: make Jainam API integration feel natural to Go developers while keeping the codebase focused, testable, and suitable for real backend applications.

If you are building something with Jainam ProTrade and Golang, you can start here:

github.com/malkarisreenivasulu/jainam-api-go

Developed by Sreenivasulu Malkari.


Disclaimer

Jainam API Go is an independent software-development project developed by Sreenivasulu Malkari.

This article, source code, documentation, and examples are provided for educational and software-development purposes only. They do not constitute investment advice, trading advice, financial advice, or a recommendation to buy or sell any security.

Trading and algorithmic trading involve financial risk. API availability, exchange rules, broker specifications, margin requirements, charges, instrument details, and order behavior can change.

Before using any trading integration with real money:

  • verify the latest Jainam API documentation
  • verify current instrument and contract information
  • test your application carefully
  • implement independent risk controls
  • protect credentials and personal information
  • monitor all live services
  • reconcile orders, trades, and positions
  • understand the financial risks involved

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top