Install the Kite Connect Go client
masterTo use the Kite Connect API in your Go project, install the v4 client using go get:
go get github.com/zerodha/gokiteconnect/v4repository·master·Indexed 42 days ago
https://github.com/zerodha/gokiteconnectThe official SDK for interacting with Zerodha's Kite Connect REST APIs and WebSocket streaming services. Version v4 allows developers to build trading platforms to execute orders, manage portfolios, and stream live market data using the kiteticker package. Features include support for GTT (Good Till Trigger) orders, market price alerts with ATO (Alert To Order) baskets, and comprehensive error handling.
To use the Kite Connect API in your Go project, install the v4 client using go get:
go get github.com/zerodha/gokiteconnect/v4The kiteticker package provides WebSocket capabilities for streaming live market data and order updates.
kiteticker.New(apiKey, accessToken).On... methods (e.g., OnTick, OnConnect, OnError).ticker.Serve() to start the connection.OnConnect callback, use ticker.Subscribe(instTokens) to subscribe to specific instruments.ticker.SetMode(mode, instTokens). The default mode is ModeQuote.OnError(func(err error))OnClose(func(code int, reason string))OnConnect(func())OnReconnect(func(attempt int, delay time.Duration))OnNoReconnect(func(attempt int))OnTick(func(tick kitemodels.Tick))OnOrderUpdate(func(order kiteconnect.Order))package main
import (
"fmt"
"time"
kiteconnect "github.com/zerodha/gokiteconnect/v4"
kitemodels "github.com/zerodha/gokiteconnect/v4/models"
kiteticker "github.com/zerodha/gokiteconnect/v4/ticker"
)
var (
ticker *kiteticker.Ticker
)
var (
instToken = []uint32{408065, 112129}
)
func onError(err error) {
fmt.Println("Error: ", err)
}
func onClose(code int, reason string) {
fmt.Println("Close: ", code, reason)
}
func onConnect() {
fmt.Println("Connected")
err := ticker.Subscribe(instToken)
if err != nil {
fmt.Println("err: ", err)
}
err = ticker.SetMode(kiteticker.ModeFull, instToken)
if err != nil {
fmt.Println("err: ", err)
}
}
func onTick(tick kitemodels.Tick) {
fmt.Println("Tick: ", tick)
}
func onReconnect(attempt int, delay time.Duration) {
fmt.Printf("Reconnect attempt %d in %fs\n", attempt, delay.Seconds())
}
func onNoReconnect(attempt int) {
fmt.Printf("Maximum no of reconnect attempt reached: %d", attempt)
}
func onOrderUpdate(order kiteconnect.Order) {
fmt.Printf("Order: ", order.OrderID)
}
func main() {
apiKey := "my_api_key"
accessToken := "my_access_token"
ticker = kiteticker.New(apiKey, accessToken)
ticker.OnError(onError)
ticker.OnClose(onClose)
ticker.OnConnect(onConnect)
ticker.OnReconnect(onReconnect)
ticker.OnNoReconnect(onNoReconnect)
ticker.OnTick(onTick)
ticker.OnOrderUpdate(onOrderUpdate)
ticker.Serve()
}To interact with the REST-like APIs, follow the Kite Connect login flow:
kiteconnect.New(apiKey).kc.GetLoginURL() to obtain a requestToken through the Kite Connect login process.requestToken and your apiSecret for a session using kc.GenerateSession(requestToken, apiSecret).AccessToken on your client instance using kc.SetAccessToken(data.AccessToken) to authorize subsequent requests.package main
import (
"fmt"
kiteconnect "github.com/zerodha/gokiteconnect/v4"
)
const (
apiKey string = "my_api_key"
apiSecret string = "my_api_secret"
)
func main() {
// Create a new Kite connect instance
kc := kiteconnect.New(apiKey)
// Login URL from which request token can be obtained
fmt.Println(kc.GetLoginURL())
// Obtained request token after Kite Connect login flow
requestToken := "request_token_obtained"
// Get user details and access token
data, err := kc.GenerateSession(requestToken, apiSecret)
if err != nil {
fmt.Printf("Error: %v", err)
return
}
// Set access token
kc.SetAccessToken(data.AccessToken)
// Get margins
margins, err := kc.GetUserMargins()
if err != nil {
fmt.Printf("Error getting margins: %v", err)
}
fmt.Println("margins: ", margins)
}Good Till Trigger (GTT) orders allow you to set conditions that, when met, trigger a specific order. The library provides two main types of GTT orders via the Trigger interface:
GTTTypeSingle): Monitors a single trigger value. Use GTTSingleLegTrigger to implement this.GTTTypeOCO): Monitors two trigger values (an upper and a lower bound). Executing one leg automatically cancels the other. Use GTTOneCancelsOtherTrigger to implement this.To place or modify these orders, you use GTTParams, which encapsulates the trading symbol, exchange, transaction type, product, and the specific Trigger implementation.
// Example of a Single Leg GTT
trigger := &kiteconnect.GTTSingleLegTrigger{
TriggerParams: kiteconnect.TriggerParams{
TriggerValue: 1500.0,
LimitPrice: 1505.0,
Quantity: 10,
},
}
params := kiteconnect.GTTParams{
Tradingsymbol: "RELIANCE",
Exchange: "NSE",
LastPrice: 1495.0,
TransactionType: "BUY",
Product: "CNC",
Trigger: trigger,
}
// Place the GTT
resp, err := client.PlaceGTT(params)The market data API uses several specialized map types to return data keyed by the instrument identifier (exchange:tradingsymbol):
Quote: Full market depth and statistics.QuoteOHLC: Open, High, Low, Close, and Last Price.QuoteLTP: Only the Last Traded Price.Historical data is returned as a slice of HistoricalData objects, which are structured as individual candle records.
When creating an alert of type AlertTypeATO, you must include a Basket in your AlertParams. A Basket contains multiple BasketItems, each representing an order to be placed when the alert condition is met.
Each BasketItem requires:
Type: The type of item.TradingSymbol and Exchange.Params: An AlertOrderParams object defining the order details (transaction type, product, quantity, price, etc.).params := kiteconnect.AlertParams{
Name: "ATO Alert",
Type: kiteconnect.AlertTypeATO,
LHSExchange: "NSE",
LHSTradingSymbol: "INFY",
LHSAttribute: "ltp",
Operator: kiteconnect.AlertOperatorGE,
RHSType: "constant",
RHSConstant: 1500.0,
Basket: &kiteconnect.Basket{
Name: "My Basket",
Items: []kiteconnect.BasketItem{
{
Type: "order",
TradingSymbol: "INFY",
Exchange: "NSE",
Params: kiteconnect.AlertOrderParams{
TransactionType: "BUY",
Quantity: 10,
OrderType: "MARKET",
},
},
},
}Use GetBasketMargins to calculate the margin requirements for a basket of orders, including the impact on existing positions.
Key parameters in GetBasketParams:
OrderParams: A slice of OrderMarginParam representing the orders in the basket.Compact: If true, returns a compact response.ConsiderPositions: If true, the calculation will take into account your current open positions.params := kiteconnect.GetBasketParams{
OrderParams: []kiteconnect.OrderMarginParam{
// ... list of OrderMarginParam
},
Compact: true,
ConsiderPositions: true,
}
basketMargins, err := client.GetBasketMargins(params)Use GetAuctionInstruments() to retrieve a list of available instruments for an auction session. Each AuctionInstrument provides details about the instrument and its status in the auction, such as price, quantity, t1_quantity, and auction_number.
instruments, err := client.GetAuctionInstruments()
if err != nil {
// handle error
}Access margin details for equity and commodity segments using GetUserMargins or GetUserSegmentMargins.
GetUserMargins: Returns an AllMargins struct containing both Equity and Commodity margins.GetUserSegmentMargins(segment string): Returns Margins for a specific segment.Margin Data Structure:
Net: The net margin.Available: AvailableMargins containing Cash, Collateral, LiveBalance, etc.Used: UsedMargins containing Debits, Exposure, M2MRealised, Span, Turnover, etc.// Get all margins (Equity and Commodity)
allMargins, err := client.GetUserMargins()
// Get margins for a specific segment (e.g., "equity")
segmentMargins, err := client.GetUserSegmentMargins("equity")Use NewHTTPClient to create a new HTTPClient instance. You can provide a custom *http.Client, a *log.Logger, and a debug boolean flag. If h (the http client) is nil, it defaults to a client with a 5-second timeout and specific transport settings (MaxIdleConnsPerHost: 10). If hLog is nil, it defaults to logging to os.Stdout.
import (
"log"
"net/http"
"os"
"time"
"github.com/zerodha/gokiteconnect"
)
// Custom logger
logger := log.New(os.Stdout, "KITE: ", log.LstdFlags)
// Custom http client
httpClient := &http.Client{
Timeout: 10 * time.Second,
}
// Initialize the Kite HTTP client
client := kiteconnect.NewHTTPClient(httpClient, logger, true)Use GetHoldingsCompact() to retrieve a lightweight version of the holdings list. This is useful for reducing payload size when you only need basic identifiers like tradingsymbol, exchange, instrument_token, and quantity.
compactHoldings, err := client.GetHoldingsCompact()
if err != nil {
// handle error
}The DoRaw method executes an HTTP request and returns an HTTPResponse. It handles method-specific logic:
POST or PUT, the reqBody is sent as the request body.GET or DELETE, the reqBody is appended to the URL as a query string.Content-Type is not provided for POST/PUT requests, it defaults to application/x-www-form-urlencoded.// Example of using DoRaw
resp, err := client.DoRaw(http.MethodPost, "https://api.kite.trade/some/endpoint", []byte("param1=val1¶m2=val2"), nil)
if err != nil {
// handle error
}
// Access resp.Body ([]byte) or resp.Response (*http.Response)