Kite Connect API Go Client

repository·master·Indexed 42 days ago

https://github.com/zerodha/gokiteconnect

The 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.

Tokens
18.2K
Snippets
58
Records
69
Agent score
53%

What's inside Kite Connect Go

  1. Stream live market data with Kite Ticker

    master

    The kiteticker package provides WebSocket capabilities for streaming live market data and order updates.

    Workflow:

    1. Initialize the ticker with kiteticker.New(apiKey, accessToken).
    2. Register event callbacks using the On... methods (e.g., OnTick, OnConnect, OnError).
    3. Call ticker.Serve() to start the connection.
    4. Inside the OnConnect callback, use ticker.Subscribe(instTokens) to subscribe to specific instruments.
    5. Optionally change the subscription mode using ticker.SetMode(mode, instTokens). The default mode is ModeQuote.

    Available Callbacks:

    • 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()
    }
  2. Authenticate and use the Kite Connect API

    master

    To interact with the REST-like APIs, follow the Kite Connect login flow:

    1. Initialize the client using kiteconnect.New(apiKey).
    2. Retrieve the login URL via kc.GetLoginURL() to obtain a requestToken through the Kite Connect login process.
    3. Exchange the requestToken and your apiSecret for a session using kc.GenerateSession(requestToken, apiSecret).
    4. Set the resulting 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)
    }
  3. How GTT (Good Till Trigger) orders work

    master

    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:

    1. Single Leg (GTTTypeSingle): Monitors a single trigger value. Use GTTSingleLegTrigger to implement this.
    2. Two-Leg / OCO (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)
  4. Understand market data response types

    master

    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.

  5. Configure ATO (Alert To Order) baskets

    master

    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",
    				},
    			},
    		},
    }
  6. Calculate basket margins with GetBasketMargins

    master

    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)
  7. Retrieve auction instruments

    master

    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
    }
  8. Retrieve user margin information

    master

    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")
  9. Initialize an HTTPClient with NewHTTPClient

    master

    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)
  10. Retrieve compact holdings list

    master

    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
    }
  11. Execute raw HTTP requests with DoRaw

    master

    The DoRaw method executes an HTTP request and returns an HTTPResponse. It handles method-specific logic:

    • For POST or PUT, the reqBody is sent as the request body.
    • For GET or DELETE, the reqBody is appended to the URL as a query string.
    • If 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&param2=val2"), nil)
    if err != nil {
    	// handle error
    }
    // Access resp.Body ([]byte) or resp.Response (*http.Response)