Help us shape the future of Go! Take the 2026 Go Developer Survey

godhan

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 16 Imported by: 0

README

godhan

Go Reference Go Report Card

High-performance, production-grade Go SDK for the DhanHQ API v2 trading infrastructure. Built with 1:1 functional parity in the image of gokiteconnect, featuring strict decimal precision, single-socket multiplexed streaming (live ticks + order postbacks), Forever/GTT orders, super orders, portfolio management, and historical chart parsing.


Architecture & Package Layout

godhan enforces clean package boundaries with domain isolation:

godhan/
├── client.go              # Root Client & functional configuration options
├── auth.go                # Token renewal & 24h validity extension
├── proxy.go               # Static forward proxy support (WithProxy / ProxyConfig)
├── transport.go           # HTTPClient seam, connection pooling & header injection
├── endpoints.go           # DhanHQ API v2 REST URI constants
├── errors.go              # Structured APIError and domain sentinels
├── orders.go              # Regular order execution, modification, slicing & cancellation
├── forever_orders.go      # Forever (GTT / OCO) order lifecycle
├── super_orders.go        # Target & Stop-loss multi-leg Bracket orders
├── portfolio.go           # Positions, Demat Holdings & Margin conversions
├── funds.go               # Account funds, margin calculations & limit checks
├── charts.go              # Historical Intraday & Daily OHLCV candle charts
├── data.go                # Market depth, quote snapshots & LTP
├── security.go            # Security master lookup & scrip details
├── instruments.go         # Bulk instrument contract master downloader
├── ledger.go              # Historical trade ledger & financial transactions
├── edis.go                # CDSL eDIS authorization & form generation
├── trades.go              # Trade book queries
├── user.go                # Client profile, KYC & segment configurations
├── postback.go            # Postback webhook parsing & validation
│
├── models/                # Pure domain data models & custom serialization
│   ├── orders.go          # OrderRequest, OrderModifyRequest, OrderResponse, OrderItem
│   ├── forever_orders.go  # ForeverOrderRequest, ForeverOrderResponse
│   ├── super_orders.go    # SuperOrderRequest, SuperOrderResponse
│   ├── portfolio.go       # Position, Holding, ConvertPositionRequest
│   ├── funds.go           # FundLimits, MarginCalculationRequest, MarginData
│   ├── charts.go          # HistoricalData, IntradayData, ToCandles() converter
│   ├── data.go            # Quote, MarketDepth, DepthItem
│   ├── security.go        # SecurityDetails, SecurityID
│   ├── instruments.go     # Instrument contract definitions
│   ├── ledger.go          # LedgerEntry structures
│   ├── edis.go            # EDISInquiryResponse, EDISFormRequest
│   ├── trades.go          # TradeItem structures
│   ├── user.go            # UserProfile, SegmentStatus
│   ├── postback.go        # OrderPostback structures
│   └── time.go            # Custom timestamp deserializer (models.Time)
│
├── ticker/                # Single-Socket Multiplexed WebSocket Streaming
│   ├── ticker.go          # Single-socket client, auto-reconnect & callback router
│   ├── parser.go          # Binary tick demuxer (LTP, Quote, Depth) & text order parser
│   └── types.go           # Tick, OrderUpdate, TickerSubscription
│
└── example/
    └── main.go            # End-to-end runnable demonstration

Key Features

  • Standardized Namespace: Packaged as github.com/DragoHex/godhan.
  • Zero Loss Financial Precision: Strict use of shopspring/decimal.Decimal for prices, trigger levels, and account balances.
  • Single-Socket Multiplexed Ticker (ticker):
    • Connects to DhanHQ's unified binary WebSocket feed.
    • Demultiplexes binary quote packets (OnTick) and asynchronous JSON order postbacks (OnOrderUpdate) over a single persistent TCP connection.
  • Context First: Full context propagation across all network requests.
  • Historical Chart Transformation: Custom models.HistoricalData.ToCandles() method transforms columnar chart responses into standard time-series slices.
  • Advanced Order Varieties: Full support for Forever (GTT), Bracket/Super orders, AMO, and Iceberg/Slicing.

Installation

go get github.com/DragoHex/godhan

Requires Go 1.23 or later.


Quickstart

1. Initialize Client & Query Balances
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/DragoHex/godhan"
)

func main() {
	ctx := context.Background()

	// Initialize with your Dhan Client ID and Access Token
	client := godhan.NewClient("1000000001", "your-access-token")

	// Query Profile
	profile, err := client.GetUserProfile(ctx)
	if err != nil {
		log.Fatalf("GetUserProfile error: %v", err)
	}
	fmt.Printf("Logged in: Dhan Client ID = %s\n", profile.DhanClientID)

	// Query Available Funds
	funds, err := client.GetFundLimits(ctx)
	if err != nil {
		log.Fatalf("GetFundLimits error: %v", err)
	}
	fmt.Printf("Available Cash Balance: %s\n", funds.AvailableBalance.String())
}

2. Place & Manage Orders
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/DragoHex/godhan"
	"github.com/DragoHex/godhan/models"
	"github.com/shopspring/decimal"
)

func main() {
	ctx := context.Background()
	client := godhan.NewClient("1000000001", "your-access-token")

	// Place Limit Buy Order
	orderResp, err := client.PlaceOrder(ctx, models.OrderRequest{
		TransactionType: "BUY",
		ExchangeSegment: "NSE_EQ",
		ProductType:     "INTRADAY",
		OrderType:       "LIMIT",
		Validity:        "DAY",
		TradingSymbol:   "TATASTEEL",
		SecurityID:      "11536",
		Quantity:        10,
		Price:           decimal.NewFromFloat(120.50),
	})
	if err != nil {
		log.Fatalf("PlaceOrder error: %v", err)
	}

	fmt.Printf("Order Submitted! OrderID: %s, Status: %s\n",
		orderResp.OrderID, orderResp.OrderStatus)

	// Query Positions
	positions, err := client.GetPositions(ctx)
	if err != nil {
		log.Fatalf("GetPositions error: %v", err)
	}
	for _, p := range positions {
		fmt.Printf("Position %s: NetQty = %d, Unrealized PnL = %s\n",
			p.TradingSymbol, p.NetQty, p.UnrealizedProfitLoss.String())
	}
}

3. Multiplexed Streaming Ticker (ticker)

Connect to DhanHQ's unified WebSocket feed for live market data and instant order alerts:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/DragoHex/godhan/ticker"
)

func main() {
	// Initialize single-socket multiplexed ticker
	tk := ticker.NewTicker("1000000001", "your-access-token")

	tk.OnConnect(func() {
		fmt.Println("[WebSocket] Connected to DhanHQ Feed Gateway!")
		_ = tk.Subscribe([]ticker.TickerSubscription{
			{ExchangeSegment: 1, SecurityID: 11536}, // NSE EQ - TATASTEEL
		})
	})

	// Market Quote Packet Callback
	tk.OnTick(func(tick ticker.Tick) {
		fmt.Printf("[Tick] Security: %d, LTP: %s, Volume: %d\n",
			tick.SecurityID, tick.LTP.String(), tick.Volume)
	})

	// Real-Time Order Execution Callback
	tk.OnOrderUpdate(func(update ticker.OrderUpdate) {
		fmt.Printf("[Order Alert] %s -> Status: %s, FilledQty: %d\n",
			update.OrderID, update.OrderStatus, update.FilledQty)
	})

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

	_ = tk.ServeWithContext(ctx)
}

4. Static IP & Forward Proxy (Algo IP Whitelisting)

Dhan enforces static IP whitelisting for order execution and trader control APIs. Configure dedicated forward proxies (such as algoip.in, staticip.in, or private forward proxies) with a single option:

// Option A: Structured ProxyConfig
client := godhan.NewClient("1000000001", "your-access-token",
	godhan.WithProxy(godhan.ProxyConfig{
		Host:         "dc46-mum-01.algoip.in",
		Port:         443,
		ClientID:     "your_proxy_username",
		ClientSecret: "your_proxy_password",
	}),
)

// Option B: Proxy URL string
client := godhan.NewClient("1000000001", "your-access-token",
	godhan.WithProxyURL("https://user:pass@dc46-mum-01.algoip.in:443"),
)

// WebSocket Ticker through proxy
tk := ticker.NewTicker("1000000001", "your-access-token",
	ticker.WithTickerProxyURL("https://user:pass@dc46-mum-01.algoip.in:443"),
)

Error Handling & Sentinels

if err != nil {
	switch {
	case errors.Is(err, godhan.ErrUnauthorized):
		// Dhan token expired
	case errors.Is(err, godhan.ErrRateLimit):
		// Dhan rate limit hit
	case errors.Is(err, godhan.ErrNotFound):
		// Resource not found
	default:
		var apiErr *godhan.APIError
		if errors.As(err, &apiErr) {
			fmt.Printf("Dhan API Error [%s]: %s (HTTP %d)\n",
				apiErr.ErrorCode, apiErr.Message, apiErr.HTTPStatus)
		}
	}
}

Testing & Verification

Run tests with race detection:

go test -race ./...

Run linter / compiler diagnostics:

go vet ./...

Build the runnable example:

go build -o /dev/null ./example/main.go

Documentation

Index

Constants

View Source
const (
	DefaultBaseURI = "https://api.dhan.co/v2"
	DefaultFeedURI = "wss://api-feed.dhan.co"
)

Default API Gateway URLs

View Source
const (
	// Authentication
	URIRenewToken = "/RenewToken"

	// IP Whitelisting
	URIGetIP    = "/ip/getIP"
	URISetIP    = "/ip/setIP"
	URIModifyIP = "/ip/modifyIP"

	// Trader Controls
	URIKillSwitch = "/killswitch"
	URIPnLExit    = "/pnlExit"

	// EDIS
	URIEDISTpin     = "/edis/tpin"
	URIEDISForm     = "/edis/form"
	URIEDISBulkForm = "/edis/bulkform"
	URIEDISInquire  = "/edis/inquire" // /edis/inquire/{isin}

	// Orders
	URIOrders         = "/orders"
	URIOrdersSlicing  = "/orders/slicing"
	URIOrdersExternal = "/orders/external" // /orders/external/{correlation-id}

	// Super Orders (Bracket Orders)
	URISuperOrders = "/super/orders"

	// Forever Orders (GTT)
	URIForeverOrders = "/forever/orders"

	// Conditional & Multi Orders (Alerts)
	URIAlertOrders      = "/alerts/orders"
	URIMultiAlertOrders = "/alerts/multi/orders"

	// Trades
	URITrades = "/trades"

	// Portfolio
	URIHoldings         = "/holdings"
	URIPositions        = "/positions"
	URIPositionsConvert = "/positions/convert"

	// Funds & Margin
	URIFundLimit             = "/fundlimit"
	URIMarginCalculator      = "/margincalculator"
	URIMarginCalculatorMulti = "/margincalculator/multi"

	// Statements
	URILedger = "/ledger"

	// Charts & Market Analytics
	URIChartsHistorical    = "/charts/historical"
	URIChartsIntraday      = "/charts/intraday"
	URIChartsRollingOption = "/charts/rollingoption"
	URIDataCompanyInfo     = "/data/companyinfo"
	URIDataMarketMovers    = "/data/marketmovers"
	URIDataNewsHeadline    = "/data/newsheadline"
	URIDataTechnical       = "/data/technical"
)

API Endpoint Paths

View Source
const DefaultScripMasterURL = "https://images.dhan.co/api-data/api-scrip-master.csv"

DefaultScripMasterURL is the public URL for Dhan's daily security master CSV dump

Variables

View Source
var (
	ErrAuthExpired        = errors.New("authentication expired or invalid")
	ErrInsufficientFunds  = errors.New("insufficient funds in trading account")
	ErrOrderNotModifiable = errors.New("order is closed or cannot be modified")
	ErrInvalidInput       = errors.New("invalid request parameters")
	ErrRateLimited        = errors.New("rate limit exceeded")
	ErrBrokerUnavailable  = errors.New("broker gateway unavailable or timed out")
	ErrOrderRejected      = errors.New("order rejected by broker RMS or exchange")
	ErrNotFound           = errors.New("resource not found")
	ErrPermissionDenied   = errors.New("permission denied for exchange or product")
)

Standard Sentinel Domain Errors

Functions

func IsTerminalStatus

func IsTerminalStatus(status string) bool

IsTerminalStatus checks if the given Dhan orderStatus string represents a final state

func ParseInstruments

func ParseInstruments(r io.Reader) ([]models.Instrument, error)

ParseInstruments parses a CSV stream of Dhan security master records row-by-row

func ParsePostback

func ParsePostback(body []byte) (*models.PostbackPayload, error)

ParsePostback unmarshals raw JSON bytes received from Dhan webhook into models.PostbackPayload

func ParsePostbackRequest

func ParsePostbackRequest(r *http.Request) (*models.PostbackPayload, error)

ParsePostbackRequest extracts and decodes models.PostbackPayload from incoming HTTP request

func RESTClientFor added in v0.1.3

func RESTClientFor(cfg ProxyConfig) (*http.Client, error)

RESTClientFor builds an *http.Client configured with dedicated proxy settings and connection pooling.

Types

type APIError

type APIError struct {
	HTTPStatus int
	ErrorCode  string
	ErrorType  string
	Message    string
	RawBody    []byte
	Err        error
}

APIError represents structured error from DhanHQ gateway

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the primary interface for communicating with DhanHQ REST API

func New

func New(opts ...Option) *Client

New creates a new Client configured via functional options (parity alias)

func NewClient

func NewClient(clientID, accessToken string, opts ...Option) *Client

NewClient creates a new configured DhanHQ API Client

func (*Client) AccessToken

func (c *Client) AccessToken() string

AccessToken returns the configured Access Token thread-safely

func (*Client) CalculateMargin

CalculateMargin computes pre-trade margin requirement for a single order

func (*Client) CalculateMultiMargin

CalculateMultiMargin computes basket margin and hedging benefits across multiple legs

func (*Client) CancelAlertOrder

func (c *Client) CancelAlertOrder(ctx context.Context, alertID string) (*models.AlertOrderResponse, error)

CancelAlertOrder removes a conditional alert

func (*Client) CancelForeverOrder

func (c *Client) CancelForeverOrder(ctx context.Context, orderID string) (*models.GttOrderStatusResponse, error)

CancelForeverOrder cancels an open GTT order

func (*Client) CancelOrder

func (c *Client) CancelOrder(ctx context.Context, orderID string) (*models.OrderStatusResponse, error)

CancelOrder cancels a pending order

func (*Client) CancelSuperOrder

func (c *Client) CancelSuperOrder(ctx context.Context, orderID string, orderLeg string) (*models.OrderStatusResponse, error)

CancelSuperOrder cancels an individual super order leg or entire bracket order

func (*Client) ClientID

func (c *Client) ClientID() string

ClientID returns the configured Dhan Client ID thread-safely

func (*Client) ConvertPosition

func (c *Client) ConvertPosition(ctx context.Context, req models.PositionConversionRequest) error

ConvertPosition switches position product type

func (*Client) ExitAllPositions

func (c *Client) ExitAllPositions(ctx context.Context) (*models.UserIPResponse, error)

ExitAllPositions squares off all open intraday and derivative positions

func (*Client) ExitOrder

func (c *Client) ExitOrder(ctx context.Context, orderID string) (*models.OrderStatusResponse, error)

ExitOrder cancels an open or pending order (parity alias for CancelOrder)

func (*Client) GenerateBulkEDISForm

func (c *Client) GenerateBulkEDISForm(ctx context.Context, req models.EdisBulkFormRequest) (*models.EdisFormResponse, error)

GenerateBulkEDISForm generates HTML form payload for CDSL T-PIN authorization of multiple scrips

func (*Client) GenerateEDISForm

func (c *Client) GenerateEDISForm(ctx context.Context, req models.EdisFormRequest) (*models.EdisFormResponse, error)

GenerateEDISForm generates HTML form payload for CDSL T-PIN authorization of a single scrip

func (*Client) GenerateTPIN

func (c *Client) GenerateTPIN(ctx context.Context) (*models.TPINResponse, error)

GenerateTPIN requests CDSL to send a new T-PIN to the client's registered mobile/email

func (*Client) GetAlertOrderByID

func (c *Client) GetAlertOrderByID(ctx context.Context, alertID string) (*models.GetAlertResponse, error)

GetAlertOrderByID fetches conditional alert details by alert ID

func (*Client) GetAlertOrders

func (c *Client) GetAlertOrders(ctx context.Context) ([]models.GetAlertResponse, error)

GetAlertOrders lists all configured conditional alerts

func (*Client) GetCompanyInfo

GetCompanyInfo fetches corporate and fundamental details for an equity scrip

func (*Client) GetForeverOrders

func (c *Client) GetForeverOrders(ctx context.Context) ([]models.ForeverOrderResponse, error)

GetForeverOrders retrieves all active and historical GTT orders

func (*Client) GetFundLimits

func (c *Client) GetFundLimits(ctx context.Context) (*models.FundLimitResponse, error)

GetFundLimits fetches available trading balances and collateral limits

func (*Client) GetHistoricalCharts

func (c *Client) GetHistoricalCharts(ctx context.Context, req models.HistoricalChartsRequest) (*models.ChartsResponse, error)

GetHistoricalCharts queries daily historical OHLC candle data

func (*Client) GetHoldings

func (c *Client) GetHoldings(ctx context.Context) ([]models.Holding, error)

GetHoldings retrieves long-term Demat holdings

func (*Client) GetIP

GetIP fetches registered static IP configuration

func (*Client) GetInstruments

func (c *Client) GetInstruments(ctx context.Context) ([]models.Instrument, error)

GetInstruments streams and parses the official DhanHQ daily security master CSV

func (*Client) GetIntradayCharts

func (c *Client) GetIntradayCharts(ctx context.Context, req models.IntradayChartsRequest) (*models.ChartsResponse, error)

GetIntradayCharts queries minute-level historical OHLC candle data

func (*Client) GetKillSwitchStatus

func (c *Client) GetKillSwitchStatus(ctx context.Context) (*models.KillSwitchResponse, error)

GetKillSwitchStatus checks whether the account trading kill switch is active

func (*Client) GetLedger

func (c *Client) GetLedger(ctx context.Context, fromDate, toDate string) ([]models.BoLedgerEntry, error)

GetLedger retrieves statement of ledger financial transactions

func (*Client) GetLoginURL

func (c *Client) GetLoginURL(partnerID string) string

GetLoginURL generates the DhanHQ consent login URL for partner authentication

func (*Client) GetMarketMovers

GetMarketMovers fetches top gaining and losing instruments

func (*Client) GetNewsHeadlines

GetNewsHeadlines fetches financial news headlines

func (*Client) GetOrderByCorrelationID

func (c *Client) GetOrderByCorrelationID(ctx context.Context, correlationID string) (*models.OrderResponse, error)

GetOrderByCorrelationID retrieves order by client external correlation ID

func (*Client) GetOrderByID

func (c *Client) GetOrderByID(ctx context.Context, orderID string) (*models.OrderResponse, error)

GetOrderByID retrieves specific order details by internal Dhan order ID

func (*Client) GetOrderHistory

func (c *Client) GetOrderHistory(ctx context.Context, orderID string) (*models.OrderResponse, error)

GetOrderHistory retrieves audit history for a specific order (parity alias for GetOrderByID)

func (*Client) GetOrderTrades

func (c *Client) GetOrderTrades(ctx context.Context, orderID string) ([]models.TradeResponse, error)

GetOrderTrades retrieves all trades executed for a given order (parity alias for GetTradesByOrderID)

func (*Client) GetOrders

func (c *Client) GetOrders(ctx context.Context) ([]models.OrderResponse, error)

GetOrders retrieves all orders placed during the current trading day

func (*Client) GetPnLExit

func (c *Client) GetPnLExit(ctx context.Context) (*models.ExitPnlResponse, error)

GetPnLExit fetches current P&L based exit configurations

func (*Client) GetPositions

func (c *Client) GetPositions(ctx context.Context) ([]models.Position, error)

GetPositions retrieves open and closed positions for the trading day

func (*Client) GetRollingOptionCharts

func (c *Client) GetRollingOptionCharts(ctx context.Context, req models.OptionChartRequest) (*models.OptionChartResponse, error)

GetRollingOptionCharts queries historical candles for expired options

func (*Client) GetSuperOrders

func (c *Client) GetSuperOrders(ctx context.Context) ([]models.SuperOrderResponse, error)

GetSuperOrders retrieves all super/bracket orders placed today

func (*Client) GetTechnicalData

GetTechnicalData fetches calculated technical indicators

func (*Client) GetTradeHistory

func (c *Client) GetTradeHistory(ctx context.Context, fromDate, toDate string, page int) ([]models.TradeResponse, error)

GetTradeHistory retrieves historical trade executions within a specified date window

func (*Client) GetTrades

func (c *Client) GetTrades(ctx context.Context) ([]models.TradeResponse, error)

GetTrades retrieves all executed trades for the current trading day

func (*Client) GetTradesByOrderID

func (c *Client) GetTradesByOrderID(ctx context.Context, orderID string) ([]models.TradeResponse, error)

GetTradesByOrderID retrieves all trade fills associated with a specific order

func (*Client) GetUserProfile

func (c *Client) GetUserProfile(ctx context.Context) (*models.UserProfile, error)

GetUserProfile retrieves current user profile and whitelisted IP details

func (*Client) InquireEDISQuantity

func (c *Client) InquireEDISQuantity(ctx context.Context, isin string) (*models.EdisQtyStatusResponse, error)

InquireEDISQuantity checks current EDIS authorization status and approved quantity for an ISIN

func (*Client) ModifyAlertOrder

func (c *Client) ModifyAlertOrder(ctx context.Context, alertID string, req models.AlertModifyRequest) (*models.AlertOrderResponse, error)

ModifyAlertOrder modifies conditional alert thresholds

func (*Client) ModifyForeverOrder

func (c *Client) ModifyForeverOrder(ctx context.Context, orderID string, req models.GttModifyRequest) (*models.GttOrderStatusResponse, error)

ModifyForeverOrder updates price or trigger parameters of an open GTT order

func (*Client) ModifyIP

ModifyIP updates an existing static IP

func (*Client) ModifyOrder

func (c *Client) ModifyOrder(ctx context.Context, orderID string, req models.OrderModifyRequest) (*models.OrderStatusResponse, error)

ModifyOrder modifies price, trigger price, or quantity of a pending order

func (*Client) ModifySuperOrder

func (c *Client) ModifySuperOrder(ctx context.Context, orderID string, req models.SuperModifyRequest) (*models.OrderStatusResponse, error)

ModifySuperOrder modifies target, stop loss, or entry price of a super order

func (*Client) PlaceAlertOrder

func (c *Client) PlaceAlertOrder(ctx context.Context, req models.AlertOrderRequest) (*models.AlertOrderResponse, error)

PlaceAlertOrder creates conditional trigger alert

func (*Client) PlaceForeverOrder

func (c *Client) PlaceForeverOrder(ctx context.Context, req models.GTTOrderModel) (*models.GttOrderStatusResponse, error)

PlaceForeverOrder creates a GTT (Good-Til-Triggered) conditional order

func (*Client) PlaceMultiOrder

func (c *Client) PlaceMultiOrder(ctx context.Context, req models.MultiOrderRequest) (*models.MultiOrderResponse, error)

PlaceMultiOrder dispatches a batch of orders simultaneously

func (*Client) PlaceOrder

PlaceOrder places a regular, AMO, or intraday order on DhanHQ

func (*Client) PlaceSuperOrder

func (c *Client) PlaceSuperOrder(ctx context.Context, req models.SuperOrderRequest) (*models.OrderStatusResponse, error)

PlaceSuperOrder places a bracket order with automated target and stop loss legs

func (*Client) RenewAccessToken added in v0.1.1

func (c *Client) RenewAccessToken(ctx context.Context, tokenOverride ...string) (*models.RenewTokenResponse, error)

RenewAccessToken is a parity alias for RenewToken.

func (*Client) RenewToken added in v0.1.1

func (c *Client) RenewToken(ctx context.Context, tokenOverride ...string) (*models.RenewTokenResponse, error)

RenewToken refreshes an active access token for an additional 24 hours. If tokenOverride is passed, that token will be renewed; otherwise, c.AccessToken() is used. On success, the client's internal accessToken is automatically updated thread-safely.

func (*Client) SetAccessToken added in v0.1.1

func (c *Client) SetAccessToken(token string)

SetAccessToken updates the configured access token thread-safely

func (*Client) SetClientID added in v0.1.1

func (c *Client) SetClientID(clientID string)

SetClientID updates the configured Dhan Client ID thread-safely

func (*Client) SetIP

SetIP registers a new static IP (PRIMARY or SECONDARY)

func (*Client) SetKillSwitch

func (c *Client) SetKillSwitch(ctx context.Context, status string) (*models.KillSwitchResponse, error)

SetKillSwitch activates or deactivates the trading kill switch ("ACTIVATE" or "DEACTIVATE")

func (*Client) SetPnLExit

SetPnLExit configures automated P&L thresholds to exit open positions

func (*Client) SliceOrder

SliceOrder auto-splits large quantity orders across exchange freeze limits

func (*Client) StopPnLExit

func (c *Client) StopPnLExit(ctx context.Context) (*models.UserIPResponse, error)

StopPnLExit cancels active P&L monitoring and square-off rule

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface abstracts the underlying HTTP transport seam

type Option

type Option func(*Client)

Option represents a functional configuration option for Client

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken sets or overrides the access token

func WithBaseURI

func WithBaseURI(uri string) Option

WithBaseURI overrides the default DhanHQ REST API base URL

func WithClientID

func WithClientID(clientID string) Option

WithClientID sets or overrides the client ID

func WithHTTPClient

func WithHTTPClient(client HTTPClient) Option

WithHTTPClient provides a custom HTTP client (useful for fakes, proxy rotators, rate limiters)

func WithProxy added in v0.1.2

func WithProxy(cfg ProxyConfig) Option

WithProxy configures an authenticated HTTP/HTTPS forward proxy on the client using ProxyConfig.

func WithProxyURL added in v0.1.2

func WithProxyURL(rawURL string) Option

WithProxyURL configures a forward proxy on the client from a raw URL string. Example: "https://user:pass@dc46-mum-01.algoip.in:443"

type ProxyConfig added in v0.1.2

type ProxyConfig struct {
	Scheme       string // "http" or "https" (default "https")
	Host         string // e.g. "dc46-mum-01.algoip.in" or "103.21.54.1"
	Port         int    // e.g. 443 (default 443 for https, 80 for http)
	ClientID     string // proxy username / client ID
	ClientSecret string // proxy password / client secret
}

ProxyConfig holds forward proxy credentials and endpoint for static IP routing.

func (ProxyConfig) URL added in v0.1.2

func (p ProxyConfig) URL() (*url.URL, error)

URL constructs a validated *url.URL from the ProxyConfig.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL