kiteconnect

package module
v0.0.0-...-5f92e86 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2020 License: MIT Imports: 13 Imported by: 1

README

The Kite Connect API Go client

The official Go client for communicating with the Kite Connect API.

Kite Connect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection.

Zerodha Technology (c) 2018. Licensed under the MIT License.

Documentation

Installation

go get github.com/zerodhatech/gokiteconnect

API usage

package main

import (
	"fmt"

	"github.com/zerodhatech/gokiteconnect"
)

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)
}

Kite ticker usage

package main

import (
	"fmt"
	"time"

	kiteconnect "github.com/zerodhatech/gokiteconnect"
	"github.com/zerodhatech/gokiteconnect/ticker"
)

var (
	ticker *kiteticker.Ticker
)

// Triggered when any error is raised
func onError(err error) {
	fmt.Println("Error: ", err)
}

// Triggered when websocket connection is closed
func onClose(code int, reason string) {
	fmt.Println("Close: ", code, reason)
}

// Triggered when connection is established and ready to send and accept data
func onConnect() {
	fmt.Println("Connected")
	err := ticker.Subscribe([]uint32{53718535})
	if err != nil {
		fmt.Println("err: ", err)
	}
}

// Triggered when tick is recevived
func onTick(tick kiteticker.Tick) {
	fmt.Println("Tick: ", tick)
}

// Triggered when reconnection is attempted which is enabled by default
func onReconnect(attempt int, delay time.Duration) {
	fmt.Printf("Reconnect attempt %d in %fs\n", attempt, delay.Seconds())
}

// Triggered when maximum number of reconnect attempt is made and the program is terminated
func onNoReconnect(attempt int) {
	fmt.Printf("Maximum no of reconnect attempt reached: %d", attempt)
}

// Triggered when order update is received
func onOrderUpdate(order kiteconnect.Order) {
	fmt.Printf("Order: ", order.OrderID)
}

func main() {
	apiKey := "my_api_key"
	accessToken := "my_access_token"

	// Create new Kite ticker instance
	ticker = kiteticker.New(apiKey, accessToken)

	// Assign callbacks
	ticker.OnError(onError)
	ticker.OnClose(onClose)
	ticker.OnConnect(onConnect)
	ticker.OnReconnect(onReconnect)
	ticker.OnNoReconnect(onNoReconnect)
	ticker.OnTick(onTick)
	ticker.OnOrderUpdate(onOrderUpdate)

	// Start the connection
	ticker.Serve()
}

Examples

Check examples folder for more examples.

You can run the following after updating the API Keys in the examples:

go run examples/connect/basic/connect.go

Run unit tests

go test -v

Changelog

Check CHANGELOG.md

Documentation

Index

Constants

View Source
const (
	// Varieties
	VarietyRegular = "regular"
	VarietyAMO     = "amo"
	VarietyBO      = "bo"
	VarietyCO      = "co"

	// Products
	ProductBO   = "BO"
	ProductCO   = "CO"
	ProductMIS  = "MIS"
	ProductCNC  = "CNC"
	ProductNRML = "NRML"

	// Order types
	OrderTypeMarket = "MARKET"
	OrderTypeLimit  = "LIMIT"
	OrderTypeSL     = "SL"
	OrderTypeSLM    = "SL-M"

	// Validities
	ValidityDay = "DAY"
	ValidityIOC = "IOC"

	// Transaction type
	TransactionTypeBuy  = "BUY"
	TransactionTypeSell = "SELL"

	// Exchanges
	ExchangeNSE = "NSE"
	ExchangeBSE = "BSE"
	ExchangeMCX = "MCX"
	ExchangeNFO = "NFO"
	ExchangeBFO = "BFO"
	ExchangeCDS = "CDS"

	// Margins segments
	MarginsEquity    = "equity"
	MarginsCommodity = "commodity"

	// Order status
	OrderStatusComplete  = "COMPLETE"
	OrderStatusRejected  = "REJECTED"
	OrderStatusCancelled = "CANCELLED"
)

Useful public constants

View Source
const (
	URIUserSession           string = "/session/token"
	URIUserSessionInvalidate string = "/session/token"
	URIUserSessionRenew      string = "/session/refresh_token"
	URIUserProfile           string = "/user/profile"
	URIUserMargins           string = "/user/margins"
	URIUserMarginsSegment    string = "/user/margins/%s" // "/user/margins/{segment}"

	URIGetOrders       string = "/orders"
	URIGetTrades       string = "/trades"
	URIGetOrderHistory string = "/orders/%s"        // "/orders/{order_id}"
	URIGetOrderTrades  string = "/orders/%s/trades" // "/orders/{order_id}/trades"
	URIPlaceOrder      string = "/orders/%s"        // "/orders/{variety}"
	URIModifyOrder     string = "/orders/%s/%s"     // "/orders/{variety}/{order_id}"
	URICancelOrder     string = "/orders/%s/%s"     // "/orders/{variety}/{order_id}"

	URIGetPositions    string = "/portfolio/positions"
	URIGetHoldings     string = "/portfolio/holdings"
	URIConvertPosition string = "/portfolio/positions"

	// MF endpoints
	URIGetMFOrders      string = "/mf/orders"
	URIGetMFOrderInfo   string = "/mf/orders/%s" // "/mf/orders/{order_id}"
	URIPlaceMFOrder     string = "/mf/orders"
	URICancelMFOrder    string = "/mf/orders/%s" // "/mf/orders/{order_id}"
	URIGetMFSIPs        string = "/mf/sips"
	URIGetMFSIPInfo     string = "/mf/sips/%s" //  "/mf/sips/{sip_id}"
	URIPlaceMFSIP       string = "/mf/sips"
	URIModifyMFSIP      string = "/mf/sips/%s" //  "/mf/sips/{sip_id}"
	URICancelMFSIP      string = "/mf/sips/%s" //  "/mf/sips/{sip_id}"
	URIGetMFHoldings    string = "/mf/holdings"
	URIGetMFHoldingInfo string = "/mf/holdings/%s" //  "/mf/holdings/{isin}"
	URIGetAllotedISINs  string = "/mf/allotments"

	// GTT endpoints
	URIPlaceGTT  string = "/gtt/triggers"
	URIGetGTTs   string = "/gtt/triggers"
	URIGetGTT    string = "/gtt/triggers/%d"
	URIModifyGTT string = "/gtt/triggers/%d"
	URIDeleteGTT string = "/gtt/triggers/%d"

	URIGetInstruments         string = "/instruments"
	URIGetMFInstruments       string = "/mf/instruments"
	URIGetInstrumentsExchange string = "/instruments/%s"                  // "/instruments/{exchange}"
	URIGetHistorical          string = "/instruments/historical/%d/%s"    // "/instruments/historical/{instrument_token}/{interval}"
	URIGetTriggerRange        string = "/instruments/%s/%s/trigger_range" // "/instruments/{exchange}/{tradingsymbol}/trigger_range"

	URIGetQuote string = "/quote"
	URIGetLTP   string = "/quote/ltp"
	URIGetOHLC  string = "/quote/ohlc"
)

API endpoints

View Source
const (
	GeneralError    = "GeneralException"
	TokenError      = "TokenException"
	PermissionError = "PermissionError"
	UserError       = "UserException"
	TwoFAError      = "TwoFAException"
	OrderError      = "OrderException"
	InputError      = "InputException"
	DataError       = "DataException"
	NetworkError    = "NetworkException"
)

API errors. Check documantation to learn about individual exception: https://kite.trade/docs/connect/v3/exceptions/.

Variables

This section is empty.

Functions

func GetErrorName

func GetErrorName(code int) string

GetErrorName returns an error name given an HTTP code.

func NewError

func NewError(etype string, message string, data interface{}) error

NewError creates and returns a new instace of Error with custom error metadata.

Types

type AllMargins

type AllMargins struct {
	Equity    Margins `json:"equity"`
	Commodity Margins `json:"commodity"`
}

AllMargins contains both equity and commodity margins.

type AvailableMargins

type AvailableMargins struct {
	AdHocMargin   float64 `json:"adhoc_margin"`
	Cash          float64 `json:"cash"`
	Collateral    float64 `json:"collateral"`
	IntradayPayin float64 `json:"intraday_payin"`
}

AvailableMargins represents the available margins from the margins response for a single segment.

type Bank

type Bank struct {
	Name    string `json:"name"`
	Branch  string `json:"branch"`
	Account string `json:"account"`
}

Bank represents the details of a single bank account entry on a user's file.

type Client

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

Client represents interface for Kite Connect client.

func New

func New(apiKey string) *Client

New creates a new Kite Connect client.

func (*Client) CancelMFOrder

func (c *Client) CancelMFOrder(orderID string) (MFOrderResponse, error)

CancelMFOrder cancels an mutualfund order.

func (*Client) CancelMFSIP

func (c *Client) CancelMFSIP(sipID string) (MFSIPResponse, error)

CancelMFSIP cancels an mutualfund SIP.

func (*Client) CancelOrder

func (c *Client) CancelOrder(variety string, orderID string, parentOrderID *string) (OrderResponse, error)

CancelOrder cancels/exits an order.

func (*Client) ConvertPosition

func (c *Client) ConvertPosition(positionParams ConvertPositionParams) (bool, error)

ConvertPosition converts postion's product type.

func (*Client) DeleteGTT

func (c *Client) DeleteGTT(triggerID int) (GTTResponse, error)

DeleteGTT deletes a GTT order.

func (*Client) ExitOrder

func (c *Client) ExitOrder(variety string, orderID string, parentOrderID *string) (OrderResponse, error)

ExitOrder is an alias for CancelOrder which is used to cancel/exit an order.

func (*Client) GenerateSession

func (c *Client) GenerateSession(requestToken string, apiSecret string) (UserSession, error)

GenerateSession gets a user session details in exchange or request token. Access token is automatically set if the session is retrieved successfully. Do the token exchange with the `requestToken` obtained after the login flow, and retrieve the `accessToken` required for all subsequent requests. The response contains not just the `accessToken`, but metadata for the user who has authenticated.

func (*Client) GetGTT

func (c *Client) GetGTT(triggerID int) (GTT, error)

GetGTT returns a specific GTT for the user.

func (*Client) GetGTTs

func (c *Client) GetGTTs() (GTTs, error)

GetGTTs returns the current GTTs for the user.

func (*Client) GetHistoricalData

func (c *Client) GetHistoricalData(instrumentToken int, interval string, fromDate time.Time, toDate time.Time, continuous bool) ([]HistoricalData, error)

GetHistoricalData gets list of historical data.

func (*Client) GetHoldings

func (c *Client) GetHoldings() (Holdings, error)

GetHoldings gets a list of holdings.

func (*Client) GetInstruments

func (c *Client) GetInstruments() (Instruments, error)

GetInstruments retrives list of instruments.

func (*Client) GetInstrumentsByExchange

func (c *Client) GetInstrumentsByExchange(exchange string) (Instruments, error)

GetInstrumentsByExchange retrives list of instruments for a given exchange.

func (*Client) GetLTP

func (c *Client) GetLTP(instruments ...string) (QuoteLTP, error)

GetLTP gets map of LTP quotes for given instruments in the format of `exchange:tradingsymbol`.

func (*Client) GetLoginURL

func (c *Client) GetLoginURL() string

GetLoginURL gets Kite Connect login endpoint.

func (*Client) GetMFAllottedISINs

func (c *Client) GetMFAllottedISINs() (MFAllottedISINs, error)

GetMFAllottedISINs gets list of user mutualfund holdings.

func (*Client) GetMFHoldingInfo

func (c *Client) GetMFHoldingInfo(isin string) (MFHoldingBreakdown, error)

GetMFHoldingInfo get individual Holding info.

func (*Client) GetMFHoldings

func (c *Client) GetMFHoldings() (MFHoldings, error)

GetMFHoldings gets list of user mutualfund holdings.

func (*Client) GetMFInstruments

func (c *Client) GetMFInstruments() (MFInstruments, error)

GetMFInstruments retrives list of mutualfund instruments.

func (*Client) GetMFOrderInfo

func (c *Client) GetMFOrderInfo(OrderID string) (MFOrder, error)

GetMFOrderInfo get individual mutualfund order info.

func (*Client) GetMFOrders

func (c *Client) GetMFOrders() (MFOrders, error)

GetMFOrders gets list of mutualfund orders.

func (*Client) GetMFSIPInfo

func (c *Client) GetMFSIPInfo(sipID string) (MFSIP, error)

GetMFSIPInfo get individual SIP info.

func (*Client) GetMFSIPs

func (c *Client) GetMFSIPs() (MFSIPs, error)

GetMFSIPs gets list of mutualfund SIPs.

func (*Client) GetOHLC

func (c *Client) GetOHLC(instruments ...string) (QuoteOHLC, error)

GetOHLC gets map of OHLC quotes for given instruments in the format of `exchange:tradingsymbol`.

func (*Client) GetOrderHistory

func (c *Client) GetOrderHistory(OrderID string) ([]Order, error)

GetOrderHistory gets history of an individual order.

func (*Client) GetOrderTrades

func (c *Client) GetOrderTrades(OrderID string) ([]Trade, error)

GetOrderTrades gets list of trades executed for a particular order.

func (*Client) GetOrders

func (c *Client) GetOrders() (Orders, error)

GetOrders gets list of orders.

func (*Client) GetPositions

func (c *Client) GetPositions() (Positions, error)

GetPositions gets user positions.

func (*Client) GetQuote

func (c *Client) GetQuote(instruments ...string) (Quote, error)

GetQuote gets map of quotes for given instruments in the format of `exchange:tradingsymbol`.

func (*Client) GetTrades

func (c *Client) GetTrades() (Trades, error)

GetTrades gets list of trades.

func (*Client) GetUserMargins

func (c *Client) GetUserMargins() (AllMargins, error)

GetUserMargins gets all user margins.

func (*Client) GetUserProfile

func (c *Client) GetUserProfile() (UserProfile, error)

GetUserProfile gets user profile.

func (*Client) GetUserSegmentMargins

func (c *Client) GetUserSegmentMargins(segment string) (Margins, error)

GetUserSegmentMargins gets segmentwise user margins.

func (*Client) InvalidateAccessToken

func (c *Client) InvalidateAccessToken() (bool, error)

InvalidateAccessToken invalidates the current access token.

func (*Client) InvalidateRefreshToken

func (c *Client) InvalidateRefreshToken(refreshToken string) (bool, error)

InvalidateRefreshToken invalidates the given refresh token.

func (*Client) ModifyGTT

func (c *Client) ModifyGTT(triggerID int, o GTTParams) (GTTResponse, error)

ModifyGTT modifies the condition or orders inside an already created GTT order.

func (*Client) ModifyMFSIP

func (c *Client) ModifyMFSIP(sipID string, sipParams MFSIPModifyParams) (MFSIPResponse, error)

ModifyMFSIP modifies an mutualfund SIP.

func (*Client) ModifyOrder

func (c *Client) ModifyOrder(variety string, orderID string, orderParams OrderParams) (OrderResponse, error)

ModifyOrder modifies an order.

func (*Client) PlaceGTT

func (c *Client) PlaceGTT(o GTTParams) (GTTResponse, error)

PlaceGTT constructs and places a GTT order using GTTParams.

func (*Client) PlaceMFOrder

func (c *Client) PlaceMFOrder(orderParams MFOrderParams) (MFOrderResponse, error)

PlaceMFOrder places an mutualfund order.

func (*Client) PlaceMFSIP

func (c *Client) PlaceMFSIP(sipParams MFSIPParams) (MFSIPResponse, error)

PlaceMFSIP places an mutualfund SIP order.

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(variety string, orderParams OrderParams) (OrderResponse, error)

PlaceOrder places an order.

func (*Client) RenewAccessToken

func (c *Client) RenewAccessToken(refreshToken string, apiSecret string) (UserSessionTokens, error)

RenewAccessToken renews expired access token using valid refresh token.

func (*Client) SetAccessToken

func (c *Client) SetAccessToken(accessToken string)

SetAccessToken sets the access token to the Kite Connect instance.

func (*Client) SetBaseURI

func (c *Client) SetBaseURI(baseURI string)

SetBaseURI overrides the base Kiteconnect API endpoint with custom url.

func (*Client) SetDebug

func (c *Client) SetDebug(debug bool)

SetDebug sets debug mode to enable HTTP logs.

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(h *http.Client)

SetHTTPClient overrides default http handler with a custom one. This can be used to set custom timeouts and transport.

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout sets request timeout for default http client.

type ConvertPositionParams

type ConvertPositionParams struct {
	Exchange        string `url:"exchange"`
	TradingSymbol   string `url:"tradingsymbol"`
	OldProduct      string `url:"old_product"`
	NewProduct      string `url:"new_product"`
	PositionType    string `url:"position_type"`
	TransactionType string `url:"transaction_type"`
	Quantity        string `url:"quantity"`
}

ConvertPositionParams represents the input params for a position conversion.

type Error

type Error struct {
	Code      int
	ErrorType string
	Message   string
	Data      interface{}
}

Error is the error type used for all API errors.

func (Error) Error

func (e Error) Error() string

This makes Error a valid Go error type.

type GTT

type GTT struct {
	ID        int          `json:"id"`
	UserID    string       `json:"user_id"`
	Type      GTTType      `json:"type" url:""`
	CreatedAt Time         `json:"created_at"`
	UpdatedAt Time         `json:"updated_at"`
	ExpiresAt Time         `json:"expires_at"`
	Status    string       `json:"status"`
	Condition GTTCondition `json:"condition"`
	Orders    []Order      `json:"orders"`
	Meta      GTTMeta      `json:"meta"`
}

GTT represents a single GTT order.

type GTTCondition

type GTTCondition struct {
	Exchange      string    `json:"exchange"`
	Tradingsymbol string    `json:"tradingsymbol"`
	LastPrice     float64   `json:"last_price"`
	TriggerValues []float64 `json:"trigger_values"`
}

GTTCondition represents the condition inside a GTT order.

type GTTMeta

type GTTMeta struct {
	RejectionReason string `json:"rejection_reason"`
}

GTTMeta contains information about the rejection reason received after GTT order was triggered.

type GTTOneCancelsOtherTrigger

type GTTOneCancelsOtherTrigger struct {
	Upper TriggerParams
	Lower TriggerParams
}

GTTOneCancelsOtherTrigger implements Trigger interface for the GTTOneCancelsOtherTrigger.

func (*GTTOneCancelsOtherTrigger) LimitPrices

func (t *GTTOneCancelsOtherTrigger) LimitPrices() []float64

func (*GTTOneCancelsOtherTrigger) Quantities

func (t *GTTOneCancelsOtherTrigger) Quantities() []float64

func (*GTTOneCancelsOtherTrigger) TriggerValues

func (t *GTTOneCancelsOtherTrigger) TriggerValues() []float64

func (*GTTOneCancelsOtherTrigger) Type

type GTTParams

type GTTParams struct {
	Tradingsymbol   string
	Exchange        string
	LastPrice       float64
	TransactionType string
	Trigger         Trigger
}

GTTParams is a helper struct used to populate an actual GTT before sending it to the API.

type GTTResponse

type GTTResponse struct {
	TriggerID int `json:"trigger_id"`
}

GTTResponse is returned by the API calls to GTT API.

type GTTSingleLegTrigger

type GTTSingleLegTrigger struct {
	TriggerParams
}

GTTSingleLegTrigger implements Trigger interface for the SingleLegTrigger.

func (*GTTSingleLegTrigger) LimitPrices

func (t *GTTSingleLegTrigger) LimitPrices() []float64

func (*GTTSingleLegTrigger) Quantities

func (t *GTTSingleLegTrigger) Quantities() []float64

func (*GTTSingleLegTrigger) TriggerValues

func (t *GTTSingleLegTrigger) TriggerValues() []float64

func (*GTTSingleLegTrigger) Type

func (t *GTTSingleLegTrigger) Type() GTTType

type GTTType

type GTTType string

GTTType represents the available GTT order types.

const (
	// GTTTypeSingle is used to monitor a single trigger value
	GTTTypeSingle GTTType = "single"
	// GTTTypeOCO is used to monitor two trigger values
	// where executing one cancels the other.
	GTTTypeOCO GTTType = "two-leg"
)

type GTTs

type GTTs []GTT

GTTs represents a list of GTT orders.

type HTTPClient

type HTTPClient interface {
	Do(method, rURL string, params url.Values, headers http.Header) (HTTPResponse, error)
	DoEnvelope(method, url string, params url.Values, headers http.Header, obj interface{}) error
	DoJSON(method, url string, params url.Values, headers http.Header, obj interface{}) (HTTPResponse, error)
	GetClient() *httpClient
}

HTTPClient represents an HTTP client.

func NewHTTPClient

func NewHTTPClient(h *http.Client, hLog *log.Logger, debug bool) HTTPClient

NewHTTPClient returns a self-contained HTTP request object with underlying keep-alive transport.

type HTTPResponse

type HTTPResponse struct {
	Body     []byte
	Response *http.Response
}

HTTPResponse encompasses byte body + the response of an HTTP request.

type HistoricalData

type HistoricalData struct {
	Date   Time    `json:"date"`
	Open   float64 `json:"open"`
	High   float64 `json:"high"`
	Low    float64 `json:"Low"`
	Close  float64 `json:"close"`
	Volume int     `json:"volume"`
}

HistoricalData represents individual historical data response.

type Holding

type Holding struct {
	Tradingsymbol   string `json:"tradingsymbol"`
	Exchange        string `json:"exchange"`
	InstrumentToken uint32 `json:"instrument_token"`
	ISIN            string `json:"isin"`
	Product         string `json:"product"`

	Price              float64 `json:"price"`
	Quantity           int     `json:"quantity"`
	T1Quantity         int     `json:"t1_quantity"`
	RealisedQuantity   int     `json:"realised_quantity"`
	CollateralQuantity int     `json:"collateral_quantity"`
	CollateralType     string  `json:"collateral_type"`

	AveragePrice        float64 `json:"average_price"`
	LastPrice           float64 `json:"last_price"`
	ClosePrice          float64 `json:"close_price"`
	PnL                 float64 `json:"pnl"`
	DayChange           float64 `json:"day_change"`
	DayChangePercentage float64 `json:"day_change_percentage"`
}

Holding is an individual holdings response.

type Holdings

type Holdings []Holding

Holdings is a list of holdings

type Instrument

type Instrument struct {
	InstrumentToken int     `csv:"instrument_token"`
	ExchangeToken   int     `csv:"exchange_token"`
	Tradingsymbol   string  `csv:"tradingsymbol"`
	Name            string  `csv:"name"`
	LastPrice       float64 `csv:"last_price"`
	Expiry          Time    `csv:"expiry"`
	StrikePrice     float64 `csv:"strike"`
	TickSize        float64 `csv:"tick_size"`
	LotSize         float64 `csv:"lot_size"`
	InstrumentType  string  `csv:"instrument_type"`
	Segment         string  `csv:"segment"`
	Exchange        string  `csv:"exchange"`
}

Instrument represents individual instrument response.

type Instruments

type Instruments []Instrument

Instruments represents list of instruments.

type MFAllottedISINs

type MFAllottedISINs []string

MFAllottedISINs represents a list of all ISINs in which atleast one allotment is present.

type MFHolding

type MFHolding struct {
	Folio         string  `json:"folio"`
	Fund          string  `json:"fund"`
	Tradingsymbol string  `json:"tradingsymbol"`
	AveragePrice  float64 `json:"average_price"`
	LastPrice     float64 `json:"last_price"`
	LastPriceDate string  `json:"last_price_date"`
	Pnl           float64 `json:"pnl"`
	Quantity      float64 `json:"quantity"`
}

MFHolding represents a individual mutualfund holding.

type MFHoldingBreakdown

type MFHoldingBreakdown []MFTrade

MFHoldingBreakdown represents a list of mutualfund holdings.

type MFHoldings

type MFHoldings []MFHolding

MFHoldings represents a list of mutualfund holdings.

type MFInstrument

type MFInstrument struct {
	Tradingsymbol string  `csv:"tradingsymbol"`
	Name          string  `csv:"name"`
	LastPrice     float64 `csv:"last_price"`
	AMC           string  `csv:"amc"`

	PurchaseAllowed                 bool    `csv:"purchase_allowed"`
	RedemtpionAllowed               bool    `csv:"redemption_allowed"`
	MinimumPurchaseAmount           float64 `csv:"minimum_purchase_amount"`
	PurchaseAmountMultiplier        float64 `csv:"purchase_amount_multiplier"`
	MinimumAdditionalPurchaseAmount float64 `csv:"additional_purchase_multiple"`
	MinimumRedemptionQuantity       float64 `csv:"minimum_redemption_quantity"`
	RedemptionQuantityMultiplier    float64 `csv:"redemption_quantity_multiplier"`
	DividendType                    string  `csv:"dividend_type"`
	SchemeType                      string  `csv:"scheme_type"`
	Plan                            string  `csv:"plan"`
	SettlementType                  string  `csv:"settlement_type"`
	LastPriceDate                   Time    `csv:"last_price_date"`
}

MFInstrument represents individual mutualfund instrument response.

type MFInstruments

type MFInstruments []MFInstrument

MFInstruments represents list of mutualfund instruments.

type MFOrder

type MFOrder struct {
	OrderID           string `json:"order_id"`
	ExchangeOrderID   string `json:"exchange_order_id"`
	Tradingsymbol     string `json:"tradingsymbol"`
	Status            string `json:"status"`
	StatusMessage     string `json:"status_message"`
	Folio             string `json:"folio"`
	Fund              string `json:"fund"`
	OrderTimestamp    Time   `json:"order_timestamp"`
	ExchangeTimestamp Time   `json:"exchange_timestamp"`
	SettlementID      string `json:"settlement_id"`

	TransactionType string  `json:"transaction_type"`
	Variety         string  `json:"variety"`
	PurchaseType    string  `json:"purchase_type"`
	Quantity        float64 `json:"quantity"`
	Amount          float64 `json:"amount"`
	LastPrice       float64 `json:"last_price"`
	AveragePrice    float64 `json:"average_price"`
	PlacedBy        string  `json:"placed_by"`
	Tag             string  `json:"tag"`
}

MFOrder represents a individual mutualfund order response.

type MFOrderParams

type MFOrderParams struct {
	Tradingsymbol   string  `json:"tradingsymbol" url:"tradingsymbol"`
	TransactionType string  `json:"transaction_type" url:"transaction_type"`
	Quantity        float64 `json:"quantity" url:"quantity,omitempty"`
	Amount          float64 `json:"amount" url:"amount,omitempty"`
	Tag             string  `json:"tag" url:"tag,omitempty"`
}

MFOrderParams represents parameters for placing an order.

type MFOrderResponse

type MFOrderResponse struct {
	OrderID string `json:"order_id"`
}

MFOrderResponse represents the successful order place response.

type MFOrders

type MFOrders []MFOrder

MFOrders represents a list of mutualfund orders.

type MFSIP

type MFSIP struct {
	ID              string `json:"sip_id"`
	Tradingsymbol   string `json:"tradingsymbol"`
	FundName        string `json:"fund"`
	DividendType    string `json:"dividend_type"`
	TransactionType string `json:"transaction_type"`

	Status               string  `json:"status"`
	SipType              string  `json:"sip_type"`
	Created              Time    `json:"created"`
	Frequency            string  `json:"frequency"`
	InstalmentAmount     float64 `json:"instalment_amount"`
	Instalments          int     `json:"instalments"`
	LastInstalment       Time    `json:"last_instalment"`
	PendingInstalments   int     `json:"pending_instalments"`
	InstalmentDay        int     `json:"instalment_day"`
	CompletedInstalments int     `json:"completed_instalments"`
	NextInstalment       string  `json:"next_instalment"`
	Tag                  string  `json:"tag"`
}

MFSIP represents a individual mutualfund SIP response.

type MFSIPModifyParams

type MFSIPModifyParams struct {
	Amount        float64 `json:"amount" url:"amount,omitempty"`
	Frequency     string  `json:"frequency" url:"frequency,omitempty"`
	InstalmentDay int     `json:"instalment_day" url:"instalment_day,omitempty"`
	Instalments   int     `json:"instalments" url:"instalments,omitempty"`
	Status        string  `json:"status" url:"status,omitempty"`
}

MFSIPModifyParams represents parameters for modifying a SIP.

type MFSIPParams

type MFSIPParams struct {
	Tradingsymbol string  `json:"tradingsymbol" url:"tradingsymbol"`
	Amount        float64 `json:"amount" url:"amount"`
	Instalments   int     `json:"instalments" url:"instalments"`
	Frequency     string  `json:"frequency" url:"frequency"`
	InstalmentDay int     `json:"instalment_day" url:"instalment_day,omitempty"`
	InitialAmount float64 `json:"initial_amount" url:"initial_amount,omitempty"`
	Tag           string  `json:"tag" url:"tag,omitempty"`
}

MFSIPParams represents parameters for placing a SIP.

type MFSIPResponse

type MFSIPResponse struct {
	OrderID *string `json:"order_id"`
	SIPID   string  `json:"sip_id"`
}

MFSIPResponse represents the successful SIP place response.

type MFSIPs

type MFSIPs []MFSIP

MFSIPs represents a list of mutualfund SIPs.

type MFTrade

type MFTrade struct {
	Fund              string  `json:"fund"`
	Tradingsymbol     string  `json:"tradingsymbol"`
	AveragePrice      float64 `json:"average_price"`
	Variety           string  `json:"variety"`
	ExchangeTimestamp Time    `json:"exchange_timestamp"`
	Amount            float64 `json:"amount"`
	Folio             string  `json:"folio"`
	Quantity          float64 `json:"quantity"`
}

MFTrade represents a individual trades of a mutualfund holding.

type Margins

type Margins struct {
	Category  string           `json:"-"`
	Enabled   bool             `json:"enabled"`
	Net       float64          `json:"net"`
	Available AvailableMargins `json:"available"`
	Used      UsedMargins      `json:"utilised"`
}

Margins represents the user margins for a segment.

type Order

type Order struct {
	AccountID string `json:"account_id"`
	PlacedBy  string `json:"placed_by"`

	OrderID                 string                 `json:"order_id"`
	ExchangeOrderID         string                 `json:"exchange_order_id"`
	ParentOrderID           string                 `json:"parent_order_id"`
	Status                  string                 `json:"status"`
	StatusMessage           string                 `json:"status_message"`
	OrderTimestamp          Time                   `json:"order_timestamp"`
	ExchangeUpdateTimestamp Time                   `json:"exchange_update_timestamp"`
	ExchangeTimestamp       Time                   `json:"exchange_timestamp"`
	Meta                    map[string]interface{} `json:"meta"`
	RejectedBy              string                 `json:"rejected_by"`
	Variety                 string                 `json:"variety"`

	Exchange        string `json:"exchange"`
	TradingSymbol   string `json:"tradingsymbol"`
	InstrumentToken uint32 `json:"instrument_token"`

	OrderType         string  `json:"order_type"`
	TransactionType   string  `json:"transaction_type"`
	Validity          string  `json:"validity"`
	Product           string  `json:"product"`
	Quantity          float64 `json:"quantity"`
	DisclosedQuantity float64 `json:"disclosed_quantity"`
	Price             float64 `json:"price"`
	TriggerPrice      float64 `json:"trigger_price"`

	AveragePrice      float64 `json:"average_price"`
	FilledQuantity    float64 `json:"filled_quantity"`
	PendingQuantity   float64 `json:"pending_quantity"`
	CancelledQuantity float64 `json:"cancelled_quantity"`
}

Order represents a individual order response.

type OrderParams

type OrderParams struct {
	Exchange        string `url:"exchange,omitempty"`
	Tradingsymbol   string `url:"tradingsymbol,omitempty"`
	Validity        string `url:"validity,omitempty"`
	Product         string `url:"product,omitempty"`
	OrderType       string `url:"order_type,omitempty"`
	TransactionType string `url:"transaction_type,omitempty"`

	Quantity          int     `url:"quantity,omitempty"`
	DisclosedQuantity int     `url:"disclosed_quantity,omitempty"`
	Price             float64 `url:"price,omitempty"`
	TriggerPrice      float64 `url:"trigger_price,omitempty"`

	Squareoff        float64 `url:"squareoff,omitempty"`
	Stoploss         float64 `url:"stoploss,omitempty"`
	TrailingStoploss float64 `url:"trailing_stoploss,omitempty"`

	Tag string `json:"tag" url:"tag,omitempty"`
}

OrderParams represents parameters for placing an order.

type OrderResponse

type OrderResponse struct {
	OrderID string `json:"order_id"`
}

OrderResponse represents the order place success response.

type Orders

type Orders []Order

Orders is a list of orders.

type PlainResponse

type PlainResponse struct {
	Code    int    `json:"code"`
	Message string `json:"string"`
}

PlainResponse is a helper for receiving blank HTTP envelop responses without any payloads.

type Position

type Position struct {
	Tradingsymbol   string `json:"tradingsymbol"`
	Exchange        string `json:"exchange"`
	InstrumentToken uint32 `json:"instrument_token"`
	Product         string `json:"product"`

	Quantity          int     `json:"quantity"`
	OvernightQuantity int     `json:"overnight_quantity"`
	Multiplier        float64 `json:"multiplier"`

	AveragePrice float64 `json:"average_price"`
	ClosePrice   float64 `json:"close_price"`
	LastPrice    float64 `json:"last_price"`
	Value        float64 `json:"value"`
	PnL          float64 `json:"pnl"`
	M2M          float64 `json:"m2m"`
	Unrealised   float64 `json:"unrealised"`
	Realised     float64 `json:"realised"`

	BuyQuantity int     `json:"buy_quantity"`
	BuyPrice    float64 `json:"buy_price"`
	BuyValue    float64 `json:"buy_value"`
	BuyM2MValue float64 `json:"buy_m2m"`

	SellQuantity int     `json:"sell_quantity"`
	SellPrice    float64 `json:"sell_price"`
	SellValue    float64 `json:"sell_value"`
	SellM2MValue float64 `json:"sell_m2m"`

	DayBuyQuantity int     `json:"day_buy_quantity"`
	DayBuyPrice    float64 `json:"day_buy_price"`
	DayBuyValue    float64 `json:"day_buy_value"`

	DaySellQuantity int     `json:"day_sell_quantity"`
	DaySellPrice    float64 `json:"day_sell_price"`
	DaySellValue    float64 `json:"day_sell_value"`
}

Position represents an individual position response.

type Positions

type Positions struct {
	Net []Position `json:"net"`
	Day []Position `json:"day"`
}

Positions represents a list of net and day positions.

type Quote

type Quote map[string]struct {
	InstrumentToken int     `json:"instrument_token"`
	Timestamp       Time    `json:"timestamp"`
	LastPrice       float64 `json:"last_price"`
	LastQuantity    int     `json:"last_quantity"`
	LastTradeTime   Time    `json:"last_trade_time"`
	AveragePrice    float64 `json:"average_price"`
	Volume          int     `json:"volume"`
	BuyQuantity     int     `json:"buy_quantity"`
	SellQuantity    int     `json:"sell_quantity"`
	OHLC            struct {
		Open  float64 `json:"open"`
		High  float64 `json:"high"`
		Low   float64 `json:"low"`
		Close float64 `json:"close"`
	} `json:"ohlc"`
	NetChange         float64 `json:"net_change"`
	OI                float64 `json:"oi"`
	OIDayHigh         float64 `json:"oi_day_high"`
	OIDayLow          float64 `json:"oi_day_low"`
	LowerCircuitLimit float64 `json:"lower_circuit_limit"`
	UpperCircuitLimit float64 `json:"upper_circuit_limit"`
	Depth             struct {
		Buy []struct {
			Price    float64 `json:"price"`
			Quantity int     `json:"quantity"`
			Orders   int     `json:"orders"`
		} `json:"buy"`
		Sell []struct {
			Price    float64 `json:"price"`
			Quantity int     `json:"quantity"`
			Orders   int     `json:"orders"`
		} `json:"sell"`
	} `json:"depth"`
}

Quote represents the full quote response.

type QuoteLTP

type QuoteLTP map[string]struct {
	InstrumentToken int     `json:"instrument_token"`
	LastPrice       float64 `json:"last_price"`
}

QuoteLTP represents last price quote response.

type QuoteOHLC

type QuoteOHLC map[string]struct {
	InstrumentToken int     `json:"instrument_token"`
	LastPrice       float64 `json:"last_price"`
	OHLC            struct {
		Open  float64 `json:"open"`
		High  float64 `json:"high"`
		Low   float64 `json:"low"`
		Close float64 `json:"close"`
	} `json:"ohlc"`
}

QuoteOHLC represents OHLC quote response.

type Time

type Time struct {
	time.Time
}

Time is custom time format used in all responses

func (*Time) UnmarshalCSV

func (t *Time) UnmarshalCSV(s string) (err error)

UnmarshalCSV converts CSV string field internal date

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON parses JSON time string with custom time formats

type Trade

type Trade struct {
	AveragePrice      float64 `json:"average_price"`
	Quantity          float64 `json:"quantity"`
	TradeID           string  `json:"trade_id"`
	Product           string  `json:"product"`
	FillTimestamp     Time    `json:"fill_timestamp"`
	ExchangeTimestamp Time    `json:"exchange_timestamp"`
	ExchangeOrderID   string  `json:"exchange_order_id"`
	OrderID           string  `json:"order_id"`
	TransactionType   string  `json:"transaction_type"`
	TradingSymbol     string  `json:"tradingsymbol"`
	Exchange          string  `json:"exchange"`
	InstrumentToken   uint32  `json:"instrument_token"`
}

Trade represents an individual trade response.

type Trades

type Trades []Trade

Trades is a list of trades.

type Trigger

type Trigger interface {
	TriggerValues() []float64
	LimitPrices() []float64
	Quantities() []float64
	Type() GTTType
}

Trigger is an abstraction over multiple GTT types.

type TriggerParams

type TriggerParams struct {
	TriggerValue float64
	LimitPrice   float64
	Quantity     float64
}

type UsedMargins

type UsedMargins struct {
	Debits        float64 `json:"debits"`
	Exposure      float64 `json:"exposure"`
	M2MRealised   float64 `json:"m2m_realised"`
	M2MUnrealised float64 `json:"m2m_unrealised"`
	OptionPremium float64 `json:"option_premium"`
	Payout        float64 `json:"payout"`
	Span          float64 `json:"span"`
	HoldingSales  float64 `json:"holding_sales"`
	Turnover      float64 `json:"turnover"`
}

UsedMargins represents the used margins from the margins response for a single segment.

type UserProfile

type UserProfile struct {
	UserName      string   `json:"user_name"`
	UserShortName string   `json:"user_shortname"`
	AvatarURL     string   `json:"avatar_url"`
	UserType      string   `json:"user_type"`
	Email         string   `json:"email"`
	Phone         string   `json:"phone"`
	Broker        string   `json:"broker"`
	Products      []string `json:"products"`
	OrderTypes    []string `json:"order_types"`
	Exchanges     []string `json:"exchanges"`
}

UserProfile represents a user's personal and financial profile.

type UserSession

type UserSession struct {
	UserProfile
	UserSessionTokens

	APIKey      string `json:"api_key"`
	PublicToken string `json:"public_token"`
	LoginTime   Time   `json:"login_time"`
}

UserSession represents the response after a successful authentication.

type UserSessionTokens

type UserSessionTokens struct {
	UserID       string `json:"user_id"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
}

UserSessionTokens represents response after renew access token.

Directories

Path Synopsis
examples
Package kiteticker provides kite ticker access using callbacks.
Package kiteticker provides kite ticker access using callbacks.

Jump to

Keyboard shortcuts

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