-
Notifications
You must be signed in to change notification settings - Fork 73
/
connect.go
255 lines (211 loc) · 7.46 KB
/
connect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package kiteconnect
import (
"fmt"
"net/http"
"net/url"
"time"
)
// PlainResponse is a helper for receiving blank HTTP
// envelop responses without any payloads.
type PlainResponse struct {
Code int `json:"code"`
Message string `json:"string"`
}
// Client represents interface for Kite Connect client.
type Client struct {
apiKey string
accessToken string
debug bool
baseURI string
httpClient HTTPClient
}
const (
name string = "gokiteconnect"
version string = "4.0.2"
requestTimeout time.Duration = 7000 * time.Millisecond
baseURI string = "https://api.kite.trade"
kiteBaseURI string = "https://kite.zerodha.com"
// Kite connect header version
kiteHeaderVersion string = "3"
)
// Useful public constants
const (
// Varieties
VarietyRegular = "regular"
VarietyAMO = "amo"
VarietyBO = "bo"
VarietyCO = "co"
VarietyIceberg = "iceberg"
VarietyAuction = "auction"
// 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"
ValidityTTL = "TTL"
// Position Type
PositionTypeDay = "day"
PositionTypeOvernight = "overnight"
// Transaction type
TransactionTypeBuy = "BUY"
TransactionTypeSell = "SELL"
// Exchanges
ExchangeNSE = "NSE"
ExchangeBSE = "BSE"
ExchangeMCX = "MCX"
ExchangeNFO = "NFO"
ExchangeBFO = "BFO"
ExchangeCDS = "CDS"
ExchangeBCD = "BCD"
// Margins segments
MarginsEquity = "equity"
MarginsCommodity = "commodity"
// Order status
OrderStatusComplete = "COMPLETE"
OrderStatusRejected = "REJECTED"
OrderStatusCancelled = "CANCELLED"
)
// API endpoints
const (
URIUserSession string = "/session/token"
URIUserSessionInvalidate string = "/session/token"
URIUserSessionRenew string = "/session/refresh_token"
URIUserProfile string = "/user/profile"
URIFullUserProfile string = "/user/profile/full"
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"
URIInitHoldingsAuth string = "/portfolio/holdings/authorise"
URIAuctionInstruments string = "/portfolio/holdings/auctions"
URIConvertPosition string = "/portfolio/positions"
URIOrderMargins string = "/margins/orders"
URIBasketMargins string = "/margins/basket"
URIOrderCharges string = "/charges/orders"
// 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"
)
// New creates a new Kite Connect client.
func New(apiKey string) *Client {
client := &Client{
apiKey: apiKey,
baseURI: baseURI,
}
// Create a default http handler with default timeout.
client.SetHTTPClient(&http.Client{
Timeout: requestTimeout,
})
return client
}
// SetHTTPClient overrides default http handler with a custom one.
// This can be used to set custom timeouts and transport.
func (c *Client) SetHTTPClient(h *http.Client) {
c.httpClient = NewHTTPClient(h, nil, c.debug)
}
// SetDebug sets debug mode to enable HTTP logs.
func (c *Client) SetDebug(debug bool) {
c.debug = debug
c.httpClient.GetClient().debug = debug
}
// SetBaseURI overrides the base Kiteconnect API endpoint with custom url.
func (c *Client) SetBaseURI(baseURI string) {
c.baseURI = baseURI
}
// SetTimeout sets request timeout for default http client.
func (c *Client) SetTimeout(timeout time.Duration) {
hClient := c.httpClient.GetClient().client
hClient.Timeout = timeout
}
// SetAccessToken sets the access token to the Kite Connect instance.
func (c *Client) SetAccessToken(accessToken string) {
c.accessToken = accessToken
}
// GetLoginURL gets Kite Connect login endpoint.
func (c *Client) GetLoginURL() string {
return fmt.Sprintf("%s/connect/login?api_key=%s&v=%s", kiteBaseURI, c.apiKey, kiteHeaderVersion)
}
func (c *Client) doEnvelope(method, uri string, params url.Values, headers http.Header, v interface{}) error {
if params == nil {
params = url.Values{}
}
// Send custom headers set
if headers == nil {
headers = map[string][]string{}
}
// Add Kite Connect version to header
headers.Add("X-Kite-Version", kiteHeaderVersion)
headers.Add("User-Agent", name+"/"+version)
if c.apiKey != "" && c.accessToken != "" {
authHeader := fmt.Sprintf("token %s:%s", c.apiKey, c.accessToken)
headers.Add("Authorization", authHeader)
}
return c.httpClient.DoEnvelope(method, c.baseURI+uri, params, headers, v)
}
func (c *Client) do(method, uri string, params url.Values, headers http.Header) (HTTPResponse, error) {
if params == nil {
params = url.Values{}
}
if headers == nil {
headers = map[string][]string{}
}
headers.Add("X-Kite-Version", kiteHeaderVersion)
headers.Add("User-Agent", name+"/"+version)
if c.apiKey != "" && c.accessToken != "" {
authHeader := fmt.Sprintf("token %s:%s", c.apiKey, c.accessToken)
headers.Add("Authorization", authHeader)
}
return c.httpClient.Do(method, c.baseURI+uri, params, headers)
}
func (c *Client) doRaw(method, uri string, reqBody []byte, headers http.Header) (HTTPResponse, error) {
if headers == nil {
headers = map[string][]string{}
}
headers.Add("X-Kite-Version", kiteHeaderVersion)
headers.Add("User-Agent", name+"/"+version)
if c.apiKey != "" && c.accessToken != "" {
authHeader := fmt.Sprintf("token %s:%s", c.apiKey, c.accessToken)
headers.Add("Authorization", authHeader)
}
return c.httpClient.DoRaw(method, c.baseURI+uri, reqBody, headers)
}