kiteconnect

package module
v0.0.0-...-f26f781 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2019 License: MIT Imports: 13 Imported by: 0

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.

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"

	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) 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) 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) 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) 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) 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) 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 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 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 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 []Order

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"`
	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"`
	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 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                    string `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"`
	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 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