Documentation
¶
Overview ¶
auth.go
client.go
constants.go
Package arrow provides a Go client for Arrow Trade APIs.
It includes:
- authentication helpers (request-token auth and AutoLogin with TOTP)
- order/trade endpoints (place, modify, cancel, books)
- user/portfolio endpoints (profile, holdings, positions, limits)
- market endpoints (quotes, option chain, instruments, candles)
- WebSocket streams (order updates; token market data on ds.arrow.trade; HFT market data on socket.arrow.trade — use NewStreams / NewStreamsWithHFT / NewStreamsOrderOnly as needed)
Basic usage:
client := arrow.NewClient(appID, appSecret) client.SetDebug(true) // optional err := client.AutoLogin(userID, password, totpSecret)
API docs:
holdings.go
orders.go
positions.go
quotes.go
user.go
Index ¶
- Constants
- func GenerateChecksum(appID, appSecret, requestToken string) string
- func StartKeepAlive(ctx context.Context, conn *websocket.Conn, interval time.Duration)
- type ArrowStreams
- type AuthResponse
- type BankDetail
- type BasketMarginRequest
- type Client
- func (c *Client) Authenticate(requestToken string) (string, error)
- func (c *Client) AutoLogin(username, password, totpSecret string) error
- func (c *Client) CancelAllOrders() error
- func (c *Client) CancelOrder(orderType, orderID string) error
- func (c *Client) ConnectDataStream() (*DataStream, error)
- func (c *Client) ConnectHFTDataStream() (*HFTDataStream, error)
- func (c *Client) ConnectOrderStream() (*OrderStream, error)
- func (c *Client) GetAllOptionChainSymbols() (OptionChainSymbolsByCategory, error)
- func (c *Client) GetBasketMargin(req BasketMarginRequest) (*MarginResponse, error)
- func (c *Client) GetCandleData(exchange Exchange, token, interval, fromTimestamp, toTimestamp string, oi bool) (json.RawMessage, error)
- func (c *Client) GetHoldings() ([]Holding, error)
- func (c *Client) GetHolidays() ([]Holiday, error)
- func (c *Client) GetIndexList() ([]map[string]any, error)
- func (c *Client) GetInstruments(segment InstrumentSegment) ([][]string, error)
- func (c *Client) GetInstrumentsCSV(segment InstrumentSegment) (string, error)
- func (c *Client) GetLimits() (*Limits, error)
- func (c *Client) GetMargin(order MarginRequest) (*MarginResponse, error)
- func (c *Client) GetOptionChain(req OptionChainRequest) (json.RawMessage, error)
- func (c *Client) GetOrder(orderID string) (*OrderDetailsResponse, error)
- func (c *Client) GetOrderBook() ([]OrderDetails, error)
- func (c *Client) GetPositions() ([]Position, error)
- func (c *Client) GetQuote(exchange Exchange, symbol string, mode InfoQuoteMode) (map[string]any, error)
- func (c *Client) GetQuotes(instruments []QuoteInstrument, mode InfoQuoteMode) ([]map[string]any, error)
- func (c *Client) GetRefreshToken() string
- func (c *Client) GetToken() string
- func (c *Client) GetTradeBook() ([]Trade, error)
- func (c *Client) GetUserDetails() (*User, error)
- func (c *Client) IsDebug() bool
- func (c *Client) Login()
- func (c *Client) ModifyOrder(orderType, orderID string, order OrderRequest) (*OrderResponse, error)
- func (c *Client) NewStreams() (*ArrowStreams, error)
- func (c *Client) NewStreamsOrderOnly() (*ArrowStreams, error)
- func (c *Client) NewStreamsWithHFT() (*ArrowStreams, error)
- func (c *Client) PlaceOrder(orderType string, order OrderRequest) (*OrderResponse, error)
- func (c *Client) SetDebug(enabled bool)
- func (c *Client) SetToken(token string)
- type Config
- type DataStream
- type Depository
- type DepthLevel
- type Exchange
- type GenericResponse
- type HFTDataStream
- func (s *HFTDataStream) Close() error
- func (s *HFTDataStream) ReadHFT(ctx context.Context, onLTP func(HFTLTPTick), onFull func(HFTFullTick), ...)
- func (s *HFTDataStream) SubscribeHFTBySegment(mode string, segments map[int][]int32, latencyMs int) error
- func (s *HFTDataStream) SubscribeHFTSymbols(mode string, symbols []string, latencyMs int) error
- func (s *HFTDataStream) SubscribeHFTTokens(mode string, exchSeg int, ids []int32, latencyMs int) error
- func (s *HFTDataStream) UnsubscribeHFTSymbols(mode string, symbols []string) error
- func (s *HFTDataStream) UnsubscribeHFTTokens(mode string, exchSeg int, ids []int32) error
- type HFTFullTick
- type HFTLTPTick
- type HFTResponsePacket
- type Holding
- type HoldingsResponse
- type Holiday
- type InfoQuoteMode
- type InstrumentSegment
- type Limits
- type MarginRequest
- type MarginResponse
- type MarketTick
- type OptionChainRequest
- type OptionChainSymbolsByCategory
- type OrderBookResponse
- type OrderDetails
- type OrderDetailsResponse
- type OrderRequest
- type OrderResponse
- type OrderStream
- type OrderType
- type Position
- type PositionsResponse
- type Product
- type QuoteInstrument
- type QuoteLTP
- type QuoteLTPResponse
- type QuoteRequest
- type StreamMode
- type Symbol
- type Trade
- type TransactionType
- type User
- type UserData
- type Validity
Constants ¶
const ( HFTExchNSECM = 0 // NSE cash HFTExchNSEFO = 1 // NSE F&O HFTExchBSECM = 2 // BSE cash HFTExchBSEFO = 3 // BSE F&O )
HFT exchange segments (symIds / wire exch_seg). See Arrow WebSocket docs.
Variables ¶
This section is empty.
Functions ¶
func GenerateChecksum ¶
GenerateChecksum creates a SHA256 hash of "appId:appSecret:request-token".
This is used to securely authenticate API requests.
Parameters:
- appID: The application ID.
- appSecret: The application secret key.
- requestToken: The temporary request token obtained from the login process.
Returns:
- A SHA256 checksum string.
Types ¶
type ArrowStreams ¶
type ArrowStreams struct {
Client *Client
OrderStream *OrderStream
DataStream *DataStream
HFTDataStream *HFTDataStream // set by NewStreamsWithHFT when used; optional (see hft_stream.go)
}
func (*ArrowStreams) Close ¶
func (s *ArrowStreams) Close() error
type AuthResponse ¶
type AuthResponse struct {
Status string `json:"status"` // API response status (e.g., "success" or "error").
Data struct {
Name string `json:"name"` // User's name.
Token string `json:"token"` // Authentication token.
UserID string `json:"userId"` // Unique identifier for the user.
RefreshToken string `json:"refreshToken"` // Token used for refreshing authentication.
} `json:"data"`
}
AuthResponse represents the structure of the authentication response from the API.
type BankDetail ¶
type BankDetail struct {
ID string `json:"id"` // Unique identifier for the bank detail record
Vpa string `json:"vpa"` // Virtual Payment Address (UPI ID)
BankName string `json:"bankName"` // Name of the bank (e.g., "HDFC Bank")
AccountType string `json:"accountType"` // Type of account (e.g., "SAVINGS", "CURRENT")
AccountNumber string `json:"accountNumber"` // Bank account number (may be masked, e.g. "*9380")
IfscCode string `json:"ifscCode"` // Indian Financial System Code for the bank branch
IsDefault bool `json:"isDefault"` // Whether this is the default bank account for transactions
}
BankDetail represents a single bank account associated with a user. Each user can have multiple bank accounts configured for transactions.
type BasketMarginRequest ¶
type BasketMarginRequest struct {
Orders []MarginRequest `json:"orders"`
IncludePositions bool `json:"includePositions"`
}
type Client ¶
type Client struct {
Config Config // Configuration settings for the API client.
HTTPClient *fasthttp.Client // HTTP client for executing requests.
// contains filtered or unexported fields
}
Client is the main struct for interacting with the Arrow API.
It contains the configuration settings and an HTTP client for making API requests.
func NewClient ¶
NewClient initializes a new SDK client with the provided application credentials.
Parameters:
- appID: The application ID used for authentication.
- appSecret: The application secret key used for authentication.
Returns:
- A pointer to a newly created Client instance.
func (*Client) Authenticate ¶
Authenticate exchanges the request token for an access token.
This function sends a POST request to authenticate the user and obtain an API token.
Parameters:
- requestToken: The temporary token received after user login.
Returns:
- A string containing the authentication token if successful.
- An error if authentication fails.
func (*Client) AutoLogin ¶
AutoLogin handles the entire authentication flow automatically using credentials.
This function logs in a user programmatically by sending the credentials, performing 2FA verification using TOTP, extracting the request token, and exchanging it for an access token.
Parameters:
- username: The user's registered ID or email.
- password: The user's password.
- totpSecret: The TOTP secret key used to generate 2FA codes.
Returns:
- An error if authentication fails; otherwise, nil.
func (*Client) CancelAllOrders ¶
CancelAllOrders cancels all open orders (DELETE /user/orders).
func (*Client) CancelOrder ¶
CancelOrder cancels an existing order.
It sends a DELETE request to the API endpoint "/order/{orderType}/{orderID}".
Parameters:
- orderType: Type of the order to be canceled (e.g., MARKET, LIMIT).
- orderID: Unique identifier of the order.
Returns:
- An error if the cancellation fails; otherwise, nil.
func (*Client) ConnectDataStream ¶
func (c *Client) ConnectDataStream() (*DataStream, error)
func (*Client) ConnectHFTDataStream ¶ added in v1.3.0
func (c *Client) ConnectHFTDataStream() (*HFTDataStream, error)
func (*Client) ConnectOrderStream ¶
func (c *Client) ConnectOrderStream() (*OrderStream, error)
func (*Client) GetAllOptionChainSymbols ¶
func (c *Client) GetAllOptionChainSymbols() (OptionChainSymbolsByCategory, error)
GetAllOptionChainSymbols fetches all option-chain symbol listings and expiries (GET /info/option-chain-symbols/all).
func (*Client) GetBasketMargin ¶
func (c *Client) GetBasketMargin(req BasketMarginRequest) (*MarginResponse, error)
func (*Client) GetCandleData ¶
func (c *Client) GetCandleData(exchange Exchange, token, interval, fromTimestamp, toTimestamp string, oi bool) (json.RawMessage, error)
GetCandleData calls the Historical Data API (GET /candle/:exchange/:token/:interval). Query parameters from and to must be in yyyy-MM-ddTHH:mm:ss form; oi adds oi=1 (NFO only, extra OHLC field in each row). On success the body is a JSON array of candle rows (arrays), as in the docs — not the usual REST {data,status} envelope. On failure the HTTP API may return 4xx JSON such as {"status":"error","errorMessage":"invalid token","errorCode":"BadRequestError"}: that means the exchange/token pair is not recognised (wrong segment or expired derivatives token), not a client-side parse error. See https://docs.arrow.trade/rest-api/historical-candle-data/
func (*Client) GetHoldings ¶
GetHoldings retrieves all investment holdings for the authenticated user.
This method sends a GET request to the "/user/holdings" endpoint to fetch comprehensive holdings data including long-term investments, quantity breakdowns across different settlement cycles, collateral information, and current valuations.
The returned holdings include equity shares, ETFs, mutual funds, and other investment instruments held across all exchanges and depositories.
Holdings represent long-term investments that are carried forward beyond the current trading session, unlike positions which may include intraday transactions. The data includes detailed quantity classifications that determine trading eligibility and margin benefits.
Returns:
- A slice of Holding structs containing detailed information about each investment holding.
- An error if the API request fails, authentication is invalid, or response parsing fails.
Example usage:
holdings, err := client.GetHoldings()
if err != nil {
log.Printf("Failed to get holdings: %v", err)
return
}
for _, holding := range holdings {
if len(holding.Symbols) > 0 {
fmt.Printf("Symbol: %s, Qty: %s, PnL: %s, Sellable: %s\n",
holding.Symbols[0].Symbol, holding.Qty,
holding.Pnl, holding.SellableQty)
}
}
Note: Holdings data is typically updated at the end of each trading day and reflects the settled quantities in the user's demat account.
func (*Client) GetHolidays ¶
func (*Client) GetInstruments ¶
func (c *Client) GetInstruments(segment InstrumentSegment) ([][]string, error)
func (*Client) GetInstrumentsCSV ¶
func (c *Client) GetInstrumentsCSV(segment InstrumentSegment) (string, error)
func (*Client) GetLimits ¶
GetLimits fetches the trading limits and margin details for the authenticated user.
This function sends a GET request to the "/user/limits" endpoint to retrieve available margins, blocked funds, collateral, pending orders, and other financial details.
Returns:
- A pointer to a Limits struct containing the trading limits if successful.
- An error if the request fails or the response cannot be parsed.
func (*Client) GetMargin ¶
func (c *Client) GetMargin(order MarginRequest) (*MarginResponse, error)
func (*Client) GetOptionChain ¶
func (c *Client) GetOptionChain(req OptionChainRequest) (json.RawMessage, error)
func (*Client) GetOrder ¶
func (c *Client) GetOrder(orderID string) (*OrderDetailsResponse, error)
GetOrder retrieves details of a specific order.
It sends a GET request to the API endpoint "/order/{orderID}".
Parameters:
- orderID: Unique identifier of the order.
Returns:
- A pointer to OrderDetailsResponse containing order details if successful.
- An error if the retrieval fails.
func (*Client) GetOrderBook ¶
func (c *Client) GetOrderBook() ([]OrderDetails, error)
GetOrderBook retrieves all orders for the current trading day.
This method sends a GET request to the "/user/orders" endpoint to fetch comprehensive order data including current orders, historical orders, execution details, and order status information.
The returned orders include all order types (MARKET, LIMIT, SL, SL-M) across all exchanges and product types associated with the user's account. Each order contains detailed information about execution status, fill quantities, average prices, and various timestamps for comprehensive order tracking.
Returns:
- A slice of OrderDetails structs containing detailed information about each order.
- An error if the API request fails, authentication is invalid, or response parsing fails.
Example usage:
orders, err := client.GetOrderBook()
if err != nil {
log.Printf("Failed to get order book: %v", err)
return
}
for _, order := range orders {
fmt.Printf("Order ID: %s, Symbol: %s, Status: %s, Qty: %s/%s\n",
order.ID, order.Symbol, order.OrderStatus,
order.FillShares, order.Quantity)
}
func (*Client) GetPositions ¶
GetPositions retrieves all trading positions for the authenticated user.
This method sends a GET request to the "/user/positions" endpoint to fetch comprehensive position data including current holdings, day trading activities, carry-forward positions, and profit/loss calculations.
The returned positions include both equity and derivative instruments across all exchanges and product types associated with the user's account.
Returns:
- A slice of Position structs containing detailed information about each position.
- An error if the API request fails, authentication is invalid, or response parsing fails.
Example usage:
positions, err := client.GetPositions()
if err != nil {
log.Printf("Failed to get positions: %v", err)
return
}
for _, position := range positions {
fmt.Printf("Symbol: %s, Qty: %s, PnL: %s\n",
position.Symbol, position.Qty, position.UnrealisedMarkToMarket)
}
func (*Client) GetQuote ¶
func (c *Client) GetQuote(exchange Exchange, symbol string, mode InfoQuoteMode) (map[string]any, error)
GetQuote posts to /info/quote/{mode} with {"symbol","exchange"}.
func (*Client) GetQuotes ¶
func (c *Client) GetQuotes(instruments []QuoteInstrument, mode InfoQuoteMode) ([]map[string]any, error)
GetQuotes posts to /info/quotes/{mode} with a JSON array of {exchange, symbol} (no mode in body).
func (*Client) GetRefreshToken ¶
GetRefreshToken gets the refresh token of the user.
This function allows to get the refresh token at runtime which can be used to create new Token.
Returns:
- refreshToken: The refresh token.
func (*Client) GetToken ¶
GetToken retrieves the current authentication token.
This function returns the current API token used for authentication.
Returns:
- The current authentication token.
func (*Client) GetTradeBook ¶
GetTradeBook retrieves executed trades for the user (GET /user/trades).
func (*Client) GetUserDetails ¶
GetUserDetails fetches comprehensive user profile details from the Arrow API.
This method retrieves all available information about the authenticated user, including personal details, linked bank accounts, depository information, trading permissions, and account settings.
The method handles the complete request lifecycle:
- Sends an authenticated GET request to the user details endpoint
- Parses the JSON response into a structured User object
- Validates the response status for success
- Provides detailed error logging for troubleshooting
Returns:
- *User: A pointer to the User struct containing all profile details
- error: nil on success, or an error describing what went wrong
func (*Client) Login ¶
func (c *Client) Login()
Login prompts the user to log in manually and enter the request token.
This function prints a login URL and asks the user to enter the request token to complete the authentication process.
func (*Client) ModifyOrder ¶
func (c *Client) ModifyOrder(orderType, orderID string, order OrderRequest) (*OrderResponse, error)
ModifyOrder modifies an existing order.
It sends a PATCH request to the API endpoint "/order/{orderType}/{orderID}" with the modified order details.
Parameters:
- orderType: Type of the order being modified (e.g., MARKET, LIMIT).
- orderID: Unique identifier of the order to be modified.
- order: OrderRequest struct containing updated order details.
Returns:
- A pointer to OrderResponse with the updated order details if successful.
- An error if the modification fails.
func (*Client) NewStreams ¶
func (c *Client) NewStreams() (*ArrowStreams, error)
func (*Client) NewStreamsOrderOnly ¶ added in v1.3.0
func (c *Client) NewStreamsOrderOnly() (*ArrowStreams, error)
NewStreamsOrderOnly connects only the order-updates WebSocket (wss://order-updates.arrow.trade).
func (*Client) NewStreamsWithHFT ¶ added in v1.3.0
func (c *Client) NewStreamsWithHFT() (*ArrowStreams, error)
NewStreamsWithHFT connects order updates (wss://order-updates.arrow.trade) and the HFT market socket (wss://socket.arrow.trade). It does not open the standard token data stream (wss://ds.arrow.trade); use NewStreams for order + standard market data.
func (*Client) PlaceOrder ¶
func (c *Client) PlaceOrder(orderType string, order OrderRequest) (*OrderResponse, error)
PlaceOrder places a new order in the market.
It sends a POST request to the API endpoint "/order/{orderType}" with the order details.
Parameters:
- orderType: Type of order (e.g., regular for now).
- order: OrderRequest struct containing the order details.
Returns:
- A pointer to OrderResponse with the order confirmation details if successful.
- An error if the order placement fails.
type Config ¶
type Config struct {
AppID string // Application ID for API authentication.
AppSecret string // Application secret key for API authentication.
Token string // Authentication token for API requests.
BaseURL string // Base URL of the Arrow API.
RefreshToken string // Token used to refresh authentication when expired.
Debug bool // Enables verbose SDK debug logs when true.
}
Config holds the SDK configuration settings.
type DataStream ¶
type DataStream struct {
// contains filtered or unexported fields
}
func (*DataStream) Close ¶
func (s *DataStream) Close() error
func (*DataStream) ReadTicks ¶
func (s *DataStream) ReadTicks(ctx context.Context, onTick func(MarketTick), onError func(error))
func (*DataStream) Subscribe ¶
func (s *DataStream) Subscribe(mode StreamMode, tokens []int32) error
func (*DataStream) Unsubscribe ¶
func (s *DataStream) Unsubscribe(mode StreamMode, tokens []int32) error
type Depository ¶
type Depository struct {
Dp string `json:"dp"` // Depository Participant identifier
ID string `json:"id"` // Unique client ID with the depository
}
Depository represents a depository participant (DP) account for securities trading. Users need DP accounts to hold and trade securities in electronic form.
type DepthLevel ¶
type Exchange ¶
type Exchange string
Exchange represents a trading exchange. Use these constants when specifying exchange in requests (e.g., arrow.ExchangeNSE).
type GenericResponse ¶
type HFTDataStream ¶ added in v1.3.0
type HFTDataStream struct {
// contains filtered or unexported fields
}
HFTDataStream is the low-latency market WebSocket (wss://socket.arrow.trade). Wire format matches the Python client: little-endian binary inbound, JSON sub/unsub outbound. See https://docs.arrow.trade/python-sdk/websocket-streaming/ (HFT Data Stream).
func (*HFTDataStream) Close ¶ added in v1.3.0
func (s *HFTDataStream) Close() error
func (*HFTDataStream) ReadHFT ¶ added in v1.3.0
func (s *HFTDataStream) ReadHFT(ctx context.Context, onLTP func(HFTLTPTick), onFull func(HFTFullTick), onResponse func(HFTResponsePacket), onError func(error))
ReadHFT dispatches binary HFT packets until ctx is done or the socket errors. Text frames (e.g. keepalives) are ignored. Callbacks may be nil.
func (*HFTDataStream) SubscribeHFTBySegment ¶ added in v1.3.0
func (s *HFTDataStream) SubscribeHFTBySegment(mode string, segments map[int][]int32, latencyMs int) error
SubscribeHFTBySegment subscribes token IDs grouped by exchange segment.
func (*HFTDataStream) SubscribeHFTSymbols ¶ added in v1.3.0
func (s *HFTDataStream) SubscribeHFTSymbols(mode string, symbols []string, latencyMs int) error
SubscribeHFTSymbols subscribes by symbol strings (e.g. NSE.SBIN-EQ). latencyMs is tick spacing (50–60000).
func (*HFTDataStream) SubscribeHFTTokens ¶ added in v1.3.0
func (s *HFTDataStream) SubscribeHFTTokens(mode string, exchSeg int, ids []int32, latencyMs int) error
SubscribeHFTTokens subscribes integer instrument IDs on a single exchange segment (default NSE cash = 0).
func (*HFTDataStream) UnsubscribeHFTSymbols ¶ added in v1.3.0
func (s *HFTDataStream) UnsubscribeHFTSymbols(mode string, symbols []string) error
UnsubscribeHFTSymbols sends unsub for symbol strings.
func (*HFTDataStream) UnsubscribeHFTTokens ¶ added in v1.3.0
func (s *HFTDataStream) UnsubscribeHFTTokens(mode string, exchSeg int, ids []int32) error
UnsubscribeHFTTokens sends unsub for token IDs on one segment.
type HFTFullTick ¶ added in v1.3.0
type HFTFullTick struct {
Size int16
PktType uint8
ExchSeg uint8
Token int32
LTP int32
LTQ int32
VWAP int32
Open int32
High int32
Close int32
Low int32
LTT int32
DprL int32
DprH int32
TBQ int64
TSQ int64
Volume int64
BidPx [5]int32
AskPx [5]int32
BidSize [5]int32
AskSize [5]int32
BidOrd [5]uint16
AskOrd [5]uint16
OI uint64
TS uint64
ATV uint32
BTV uint32
}
HFTFullTick is one full-depth packet (prices in paise).
type HFTLTPTick ¶ added in v1.3.0
type HFTLTPTick struct {
Size int16
PktType uint8
ExchSeg uint8
Token int32
LTP int32
VWAP int32
Volume int64
LTT uint64
ATV uint32
BTV uint32
}
HFTLTPTick is one LTP-style packet (prices in paise).
type HFTResponsePacket ¶ added in v1.3.0
type HFTResponsePacket struct {
FrameSize int16 // LE int16 at wire bytes 0–1 (expected 540 for a full response frame)
PktType uint8 // wire byte 2 (99)
ExchSeg uint8 // wire byte 3
ErrorCode string
ErrorMsg string
RequestType uint8 // 0=sub, 1=unsub (wire byte 534)
Mode uint8 // 0=ltpc, 1=full (wire byte 535)
SuccessCount uint16
ErrorCount uint16
RequestTypeStr string
ModeStr string
}
HFTResponsePacket is a subscribe/unsubscribe acknowledgement (binary pkt_type 99) from wss://socket.arrow.trade. ErrorCode / ErrorMsg describe subscription outcome; common values include SUCCESS, E_PARTIAL, E_ALL_INVALID, E_INVALID_JSON, E_MISSING_FIELD, E_INVALID_PARAM, E_PARSE_ERROR (see Arrow WebSocket HFT documentation). These strings are unrelated to REST historical errors (e.g. BadRequestError / invalid token on GET /candle/...).
type Holding ¶
type Holding struct {
Symbols []Symbol `json:"symbols"` // Array of symbol information for the holding across different exchanges.
AvgPrice string `json:"avgPrice"` // Average price at which the holding was acquired.
Qty string `json:"qty"` // Total quantity of the holding owned by the user.
UsedQty string `json:"usedQty"` // Quantity currently used as collateral or margin.
T1Qty string `json:"t1Qty"` // Quantity in T1 (Trade day + 1) settlement cycle, available for trading next day.
DepositoryQty string `json:"depositoryQty"` // Quantity held in the depository (NSDL/CDSL) and available for trading.
CollateralQty string `json:"collateralQty"` // Quantity pledged as collateral for margin requirements.
BrokerCollateralQty string `json:"brokerCollateralQty"` // Quantity pledged with the broker for additional margin benefits.
AuthorizedQty string `json:"authorizedQty"` // Total authorized quantity including all categories.
UnPledgedQty string `json:"unPledgedQty"` // Quantity not pledged as collateral and available for free trading.
NonPOAQty string `json:"nonPOAQty"` // Quantity for which Power of Attorney (POA) is not provided.
Haircut string `json:"haircut"` // Haircut percentage applied to the holding value for margin calculations.
EffectiveQty string `json:"effectiveQty"` // Effective quantity after applying haircuts and margin requirements.
SellableQty string `json:"sellableQty"` // Quantity available for immediate selling in the market.
Ltp string `json:"ltp"` // Last traded price of the instrument.
Pnl string `json:"pnl"` // Profit and loss calculated based on current market price vs average price.
Close string `json:"close"` // Previous day's closing price of the instrument.
}
Holding represents a long-term investment holding owned by the user.
This struct contains comprehensive information about investment holdings, including quantity details across different categories (T1, depository, collateral), pricing information, profit/loss calculations, and various quantity classifications that determine trading eligibility and collateral usage.
type HoldingsResponse ¶
type HoldingsResponse struct {
Data []Holding `json:"data"` // Array of Holding objects representing all user holdings.
Status string `json:"status"` // API response status indicating success or failure.
}
HoldingsResponse represents the API response structure for user holdings.
This struct encapsulates the response from the holdings API endpoint, containing both the holdings data and the API response status.
type InfoQuoteMode ¶
type InfoQuoteMode string
InfoQuoteMode is the URL segment for REST /info/quote/{mode} and /info/quotes/{mode}. This matches pyarrow_client.constants.QuoteMode (ltp, full, ohlcv). It is not the same as WebSocket StreamMode (which includes ltpc, quote, full, ltp for binary ticks).
const ( InfoQuoteLTP InfoQuoteMode = "ltp" InfoQuoteFull InfoQuoteMode = "full" InfoQuoteOHLCV InfoQuoteMode = "ohlcv" )
type InstrumentSegment ¶
type InstrumentSegment string
const ( InstrumentSegmentAll InstrumentSegment = "all" InstrumentSegmentNSE InstrumentSegment = "nse" InstrumentSegmentBSE InstrumentSegment = "bse" InstrumentSegmentMCX InstrumentSegment = "mcx" InstrumentSegmentIndices InstrumentSegment = "indices" )
type Limits ¶
type Limits struct {
Data struct {
Utilized float64 `json:"utilized"`
Allocated float64 `json:"allocated"`
NonCashOpen int `json:"nonCashOpen"`
CashOpen float64 `json:"cashOpen"`
NonCashCurrent int `json:"nonCashCurrent"`
CashCurrent float64 `json:"cashCurrent"`
CashUsed int `json:"cashUsed"`
SpanMargin int `json:"spanMargin"`
ExposureMargin int `json:"exposureMargin"`
OtherMargin int `json:"otherMargin"`
IntradayCashMargin float64 `json:"intradayCashMargin"`
TotalMargin float64 `json:"totalMargin"`
RealizedPnl int `json:"realizedPnl"`
UnrealizedPnl int `json:"unrealizedPnl"`
} `json:"data"`
Status string `json:"status"`
}
Limits represents the trading limits and margin details for a user.
type MarginRequest ¶
type MarginRequest struct {
Exchange Exchange `json:"exchange"`
Symbol string `json:"symbol"`
Quantity string `json:"quantity"`
Price string `json:"price"`
Product Product `json:"product"`
TransactionType TransactionType `json:"transactionType"`
Order OrderType `json:"order"`
IncludePositions bool `json:"includePositions"`
}
MarginRequest represents the request payload for margin calculation.
type MarginResponse ¶
type MarginResponse struct {
Data struct {
RequiredMargin float64 `json:"requiredMargin"`
MinimumCashRequired float64 `json:"minimumCashRequired"`
MarginUsedAfterTrade float64 `json:"marginUsedAfterTrade"`
Charge struct {
Brokerage float64 `json:"brokerage"`
ExchangeTxnFee float64 `json:"exchangeTxnFee"`
Gst struct {
Cgst float64 `json:"cgst"`
Igst float64 `json:"igst"`
Sgst float64 `json:"sgst"`
Total float64 `json:"total"`
} `json:"gst"`
Ipft float64 `json:"ipft"`
SebiCharges float64 `json:"sebiCharges"`
StampDuty float64 `json:"stampDuty"`
Total float64 `json:"total"`
TransactionTax float64 `json:"transactionTax"`
} `json:"charge"`
} `json:"data"`
Status string `json:"status"`
}
type MarketTick ¶
type MarketTick struct {
Token int32 `json:"token"`
Mode StreamMode `json:"mode"`
LTP int32 `json:"ltp"`
Close int32 `json:"close"`
NetChange float64 `json:"netChange"`
ChangeFlag int8 `json:"changeFlag"`
LTQ int32 `json:"ltq"`
AvgPrice int32 `json:"avgPrice"`
TotalBuyQuantity int64 `json:"totalBuyQuantity"`
TotalSellQuantity int64 `json:"totalSellQuantity"`
Open int32 `json:"open"`
High int32 `json:"high"`
Low int32 `json:"low"`
Volume int64 `json:"volume"`
LTT int32 `json:"ltt"`
Time int32 `json:"time"`
OI int64 `json:"oi"`
OIDayHigh int64 `json:"oiDayHigh"`
OIDayLow int64 `json:"oiDayLow"`
LowerLimit int32 `json:"lowerLimit"`
UpperLimit int32 `json:"upperLimit"`
Bids []DepthLevel `json:"bids"`
Asks []DepthLevel `json:"asks"`
}
func ParseMarketTick ¶
func ParseMarketTick(data []byte) (MarketTick, error)
type OptionChainRequest ¶
type OptionChainSymbolsByCategory ¶
OptionChainSymbolsByCategory is the object under response "data" for option-chain symbol listings. Keys are categories (e.g. "equity", "indices"); values map listing ids such as "NSE:RELIANCE-EQ" or "INDEX:NIFTY" to available expiry date strings.
type OrderBookResponse ¶
type OrderBookResponse struct {
Data []OrderDetails `json:"data"` // Array of OrderDetails objects representing all user orders.
Status string `json:"status"` // API response status indicating success or failure.
}
OrderBookResponse represents the API response structure for the order book.
This struct encapsulates the response from the order book API endpoint, containing both the order details and the API response status.
type OrderDetails ¶
type OrderDetails struct {
UserID string `json:"userID"` // Unique identifier for the user who placed the order.
AccountID string `json:"accountID"` // Account ID associated with the order.
Exchange string `json:"exchange"` // Exchange where the order is placed (e.g., NSE, BSE).
Symbol string `json:"symbol"` // Trading symbol of the instrument.
ID string `json:"id"` // Unique order identifier assigned by the system.
RejectReason string `json:"rejectReason"` // Reason for order rejection (if applicable).
Price string `json:"price"` // Order price specified by the user.
Quantity string `json:"quantity"` // Total order quantity.
MarketProtection string `json:"marketProtection"` // Market protection percentage applied to the order.
Product string `json:"product"` // Product type (e.g., MIS, CNC, NRML).
OrderStatus string `json:"orderStatus"` // Current status of the order (e.g., OPEN, COMPLETE, REJECTED).
ReportType string `json:"reportType"` // Type of order report (e.g., NEW, FILL, CANCEL).
TransactionType string `json:"transactionType"` // Order transaction type (BUY/SELL).
Order string `json:"order"` // Type of order (e.g., MARKET, LIMIT, SL, SL-M).
AveragePrice string `json:"averagePrice"` // Average execution price of filled shares.
ExchangeOrderID string `json:"exchangeOrderID"` // Order ID assigned by the exchange.
CancelQuantity string `json:"cancelQuantity"` // Quantity that was cancelled.
Remarks string `json:"remarks"` // Additional remarks or comments for the order.
DisclosedQuantity string `json:"disclosedQuantity"` // Disclosed quantity for iceberg orders.
OrderTriggerPrice string `json:"orderTriggerPrice"` // Trigger price for stop-loss orders.
Validity string `json:"validity"` // Order validity period (e.g., DAY, IOC, GTC).
BookProfitPrice string `json:"bookProfitPrice"` // Book profit price for bracket orders.
BookLossPrice string `json:"bookLossPrice"` // Book loss price for bracket orders.
TrailingPrice string `json:"trailingPrice"` // Trailing stop loss price.
Amo string `json:"amo"` // After Market Order flag.
PricePrecision string `json:"pricePrecision"` // Number of decimal places for price precision.
TickSize string `json:"tickSize"` // Minimum price movement allowed for the instrument.
LotSize string `json:"lotSize"` // Minimum trading quantity for the instrument.
Token string `json:"token"` // Unique token identifier for the trading instrument.
OrderTime string `json:"orderTime"` // Timestamp when the order was placed.
ExchangeUpdateTime string `json:"exchangeUpdateTime"` // Last update timestamp from the exchange.
ExchangeTime string `json:"exchangeTime"` // Timestamp from the exchange system.
OrderSource string `json:"orderSource"` // Source from which the order was placed (e.g., WEB, MOBILE, API).
LeavesQuantity string `json:"leavesQuantity"` // Remaining quantity yet to be executed.
}
OrderDetails represents detailed information about an order from the order book.
This struct contains comprehensive information about an order including execution details, pricing information, timestamps, and various order parameters for tracking and management purposes.
type OrderDetailsResponse ¶
type OrderDetailsResponse struct {
Data []struct {
Status string `json:"status"`
Exchange string `json:"exchange"`
Symbol string `json:"symbol"`
ID string `json:"id"`
Price string `json:"price"`
Quantity string `json:"quantity"`
Product string `json:"product"`
OrderStatus string `json:"orderStatus"`
ReportType string `json:"reportType"`
TransactionType string `json:"transactionType"`
Order string `json:"order"`
FillShares string `json:"fillShares"`
AveragePrice string `json:"averagePrice"`
RejectReason string `json:"rejectReason"`
ExchangeOrderID string `json:"exchangeOrderID"`
CancelQuantity string `json:"cancelQuantity"`
Remarks string `json:"remarks"`
DisclosedQuantity string `json:"disclosedQuantity"`
OrderTriggerPrice string `json:"orderTriggerPrice"`
Retention string `json:"retention"`
BookProfitPrice string `json:"bookProfitPrice"`
BookLossPrice string `json:"bookLossPrice"`
TrailingPrice string `json:"trailingPrice"`
Amo string `json:"amo"`
PricePrecision string `json:"pricePrecision"`
TickSize string `json:"tickSize"`
LotSize string `json:"lotSize"`
Token string `json:"token"`
TimeStamp string `json:"timeStamp"`
OrderTime string `json:"orderTime"`
ExchangeUpdateTime string `json:"exchangeUpdateTime"`
RequestTime string `json:"requestTime"`
ErrorMessage string `json:"errorMessage"`
} `json:"data"`
Status string `json:"status"`
}
type OrderRequest ¶
type OrderRequest struct {
Exchange string `json:"exchange"` // Exchange where the order is placed (e.g., NSE, BSE).
Quantity string `json:"quantity"` // Order quantity.
DisclosedQty string `json:"disclosedQty,omitempty"` // Disclosed quantity (optional).
Product string `json:"product"` // Product type (e.g., MIS, CNC, NRML).
Symbol string `json:"symbol"` // Trading symbol of the instrument.
TransactionType string `json:"transactionType"` // Order transaction type (BUY/SELL).
OrderType string `json:"order"` // Type of order (e.g., MARKET, LIMIT).
Price string `json:"price"` // Order price (applicable for LIMIT orders).
Validity string `json:"validity"` // Order validity (e.g., DAY, IOC).
Remarks string `json:"remarks,omitempty"` // Custom Remarks for order tracking (optional).
MarketProtection bool `json:"mpp"` // Market protection flag; defaults to false when not set.
}
OrderRequest represents the structure for placing an order.
type OrderResponse ¶
type OrderResponse struct {
Status string `json:"status"` // API response status (e.g., "success", "error").
Message string `json:"message,omitempty"` // Message from the API (if any).
ErrorCode string `json:"errorCode,omitempty"` // Error code in case of failure.
Data struct {
OrderNo string `json:"orderNo,omitempty"` // Order number assigned by the exchange.
RequestTime string `json:"requestTime,omitempty"` // Timestamp of the order request.
} `json:"data,omitempty"`
}
OrderResponse represents the API response after placing an order.
type OrderStream ¶
type OrderStream struct {
// contains filtered or unexported fields
}
func (*OrderStream) Close ¶
func (s *OrderStream) Close() error
func (*OrderStream) ReadUpdates ¶
type OrderType ¶
type OrderType string
OrderType represents the type of order (limit, market, etc.).
type Position ¶
type Position struct {
UserID string `json:"userID"` // Unique identifier for the user holding the position.
AccountID string `json:"accountID"` // Account ID associated with the position.
Token string `json:"token"` // Unique token identifier for the trading instrument.
Exchange string `json:"exchange"` // Name of the exchange where the instrument is traded (e.g., NSE, BSE).
Symbol string `json:"symbol"` // Trading symbol of the instrument (e.g., RELIANCE, TCS).
Product string `json:"product"` // Product type (e.g., MIS, CNC, NRML).
Qty string `json:"qty"` // Net quantity of the position (positive for long, negative for short).
AvgPrice string `json:"avgPrice"` // Average price at which the position was acquired.
DayBuyQty string `json:"dayBuyQty"` // Quantity bought during the current trading day.
DaySellQty string `json:"daySellQty"` // Quantity sold during the current trading day.
DayBuyAmount string `json:"dayBuyAmount"` // Total amount spent on buying during the current day.
DayBuyAvgPrice string `json:"dayBuyAvgPrice"` // Average price of buy transactions for the current day.
DaySellAmount string `json:"daySellAmount"` // Total amount received from selling during the current day.
DaySellAvgPrice string `json:"daySellAvgPrice"` // Average price of sell transactions for the current day.
CarryForwardBuyQty string `json:"carryForwardBuyQty"` // Quantity bought and carried forward from previous sessions.
CarryForwardSellQty string `json:"carryForwardSellQty"` // Quantity sold and carried forward from previous sessions.
CarryForwardBuyAmount string `json:"carryForwardBuyAmount"` // Total amount of carried forward buy transactions.
CarryForwardBuyAvgPrice string `json:"carryForwardBuyAvgPrice"` // Average price of carried forward buy transactions.
CarryForwardSellAmount string `json:"carryForwardSellAmount"` // Total amount of carried forward sell transactions.
CarryForwardSellAvgPrice string `json:"carryForwardSellAvgPrice"` // Average price of carried forward sell transactions.
CarryForwardAvgPrice string `json:"carryForwardAvgPrice"` // Average price of all carried forward transactions.
Ltp string `json:"ltp"` // Last traded price of the instrument.
RealisedPnL string `json:"realisedPnL"` // Realized profit and loss from closed positions.
UnrealisedMarkToMarket string `json:"unrealisedMarkToMarket"` // Unrealized profit and loss based on current market price.
BreakEvenPrice string `json:"breakEvenPrice"` // Price at which the position would break even.
OpenBuyQty string `json:"openBuyQty"` // Outstanding buy quantity yet to be settled.
OpenSellQty string `json:"openSellQty"` // Outstanding sell quantity yet to be settled.
OpenBuyAmount string `json:"openBuyAmount"` // Total amount of outstanding buy transactions.
OpenSellAmount string `json:"openSellAmount"` // Total amount of outstanding sell transactions.
OpenBuyAvgPrice string `json:"openBuyAvgPrice"` // Average price of outstanding buy transactions.
OpenSellAvgPrice string `json:"openSellAvgPrice"` // Average price of outstanding sell transactions.
Multiplier string `json:"multiplier"` // Contract multiplier for derivative instruments.
PricePrecision string `json:"pricePrecision"` // Number of decimal places for price precision.
PriceFactor string `json:"priceFactor"` // Factor used for price calculations.
TickSize string `json:"tickSize"` // Minimum price movement allowed for the instrument.
LotSize string `json:"lotSize"` // Minimum trading quantity for the instrument.
UploadPrice string `json:"uploadPrice"` // Price used for position upload calculations.
NetUploadPrice string `json:"netUploadPrice"` // Net price after adjustments for upload calculations.
RequestTime string `json:"requestTime"` // Timestamp when the position data was requested.
}
Position represents a trading position held by the user.
This struct contains comprehensive information about a trading position, including quantity details, pricing information, profit/loss calculations, and various trading metrics for both current day and carry-forward transactions.
type PositionsResponse ¶
type PositionsResponse struct {
Data []Position `json:"data"` // Array of Position objects representing all user positions.
Status string `json:"status"` // API response status indicating success or failure.
}
PositionsResponse represents the API response structure for user positions.
This struct encapsulates the response from the positions API endpoint, containing both the position data and the API response status.
type Product ¶
type Product string
Product represents the order product type (delivery, intraday, etc.).
type QuoteInstrument ¶
QuoteInstrument is the JSON body shape for /info/quotes/{mode} (symbol + exchange only).
type QuoteLTP ¶
QuoteLTP is a common subset of quote fields when the API returns token/LTP/close style data.
type QuoteLTPResponse ¶
QuoteLTPResponse is the batch quotes API envelope when data is a list of QuoteLTP-like objects.
type QuoteRequest ¶
type QuoteRequest struct {
Exchange string `json:"exchange"`
Symbol string `json:"symbol"`
Mode string `json:"mode,omitempty"`
}
QuoteRequest is kept for documentation compatibility; do not set Mode — it is omitted from JSON.
type StreamMode ¶
type StreamMode string
StreamMode is the subscription mode for the token-based market WebSocket (wss://ds.arrow.trade). Inbound ticks are binary, big-endian int fields, with lengths 13 / 17 / 93 / 241 by mode (aligned with Arrow’s JS/Python clients). REST /info/quote uses a smaller set; see InfoQuoteMode in quote.go.
const ( StreamModeLTP StreamMode = "ltp" StreamModeLTPC StreamMode = "ltpc" StreamModeQuote StreamMode = "quote" StreamModeFull StreamMode = "full" )
type Symbol ¶
type Symbol struct {
Symbol string `json:"symbol"` // Base symbol of the instrument (e.g., RELIANCE, TCS, HDFCBANK).
TradingSymbol string `json:"tradingSymbol"` // Exchange-specific trading symbol (e.g., RELIANCE-EQ for NSE).
Exchange string `json:"exchange"` // Name of the exchange (e.g., NSE, BSE).
Token string `json:"token"` // Unique token identifier for the trading instrument.
}
Symbol represents trading symbol information within a holding.
A holding can have multiple symbols (e.g., NSE and BSE variants of the same instrument). This struct contains the essential identifiers for a trading instrument.
type Trade ¶
type Trade struct {
Exchange string `json:"exchange"`
Symbol string `json:"symbol"`
ID string `json:"id"`
OrderID string `json:"orderID"`
TransactionType string `json:"transactionType"`
Product string `json:"product"`
Quantity string `json:"quantity"`
FillPrice string `json:"fillPrice"`
FillTime string `json:"fillTime"`
}
Trade is a single execution line from the trade book (/user/trades).
type TransactionType ¶
type TransactionType string
TransactionType represents buy or sell.
const ( TransactionTypeBuy TransactionType = "B" TransactionTypeSell TransactionType = "S" )
type User ¶
type User struct {
Data UserData `json:"data"` // The actual user profile data
Status string `json:"status"` // API response status ("success" or "error")
}
User represents the complete API response structure for user details. This follows Arrow API's standard response format with data and status fields.
func (*User) GetDefaultBankAccount ¶
func (u *User) GetDefaultBankAccount() *BankDetail
GetDefaultBankAccount returns the user's default bank account details.
Returns:
- *BankDetail: pointer to the default bank account, or nil if none exists
func (*User) HasDefaultBankAccount ¶
HasDefaultBankAccount checks if the user has configured a default bank account.
This is a convenience method to quickly determine if the user has set up their banking details for transactions.
Returns:
- bool: true if a default bank account exists, false otherwise
func (*User) HasExchangeAccess ¶
HasExchangeAccess checks if the user has access to trade on a specific exchange.
Parameters:
- exchange: The exchange code to check (e.g., "NSE", "BSE", "MCX")
Returns:
- bool: true if the user has access to the specified exchange
func (*User) IsTotpEnabled ¶
IsTotpEnabled returns whether the user has enabled Two-Factor Authentication.
Returns:
- bool: true if TOTP/2FA is enabled for the user account
type UserData ¶
type UserData struct {
BankDetails []BankDetail `json:"bankDetails"` // List of linked bank accounts
Depository []Depository `json:"depository"` // List of depository accounts for securities
Email string `json:"email"` // User's email address
Exchanges []string `json:"exchanges"` // List of exchanges user has access to (e.g., "NSE", "BSE")
ID string `json:"id"` // Unique user identifier in Arrow system
Image string `json:"image"` // URL to user's profile image
Name string `json:"name"` // Full name of the user
OrdersTypes int `json:"ordersTypes"` // Bitmask representing allowed order types
Pan string `json:"pan"` // Permanent Account Number (Indian tax identifier)
Phone string `json:"phone"` // User's phone number
Products []string `json:"products"` // List of enabled products (e.g., "CNC", "MIS", "NRML")
TotpEnabled bool `json:"totpEnabled"` // Whether Time-based One-Time Password is enabled
UserType string `json:"userType"` // Type of user account (e.g., "INDIVIDUAL", "HUF")
}
UserData contains all the profile information for a user. This includes personal details, financial accounts, and trading permissions.