forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
itbithttp.go
387 lines (319 loc) · 9.77 KB
/
itbithttp.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"bytes"
"errors"
"log"
"net/url"
"strconv"
"time"
)
const (
ITBIT_API_URL = "https://api.itbit.com/v1"
ITBIT_API_VERSION = "1"
)
type ItBit struct {
Name string
Enabled bool
Verbose bool
Websocket bool
RESTPollingDelay time.Duration
AuthenticatedAPISupport bool
ClientKey, APISecret, UserID string
MakerFee, TakerFee float64
BaseCurrencies []string
AvailablePairs []string
EnabledPairs []string
}
type ItBitTicker struct {
Pair string
Bid float64 `json:",string"`
BidAmt float64 `json:",string"`
Ask float64 `json:",string"`
AskAmt float64 `json:",string"`
LastPrice float64 `json:",string"`
LastAmt float64 `json:",string"`
Volume24h float64 `json:",string"`
VolumeToday float64 `json:",string"`
High24h float64 `json:",string"`
Low24h float64 `json:",string"`
HighToday float64 `json:",string"`
LowToday float64 `json:",string"`
OpenToday float64 `json:",string"`
VwapToday float64 `json:",string"`
Vwap24h float64 `json:",string"`
ServertimeUTC string
}
func (i *ItBit) SetDefaults() {
i.Name = "ITBIT"
i.Enabled = false
i.MakerFee = -0.10
i.TakerFee = 0.50
i.Verbose = false
i.Websocket = false
i.RESTPollingDelay = 10
}
func (i *ItBit) GetName() string {
return i.Name
}
func (i *ItBit) SetEnabled(enabled bool) {
i.Enabled = enabled
}
func (i *ItBit) IsEnabled() bool {
return i.Enabled
}
func (i *ItBit) Setup(exch Exchanges) {
if !exch.Enabled {
i.SetEnabled(false)
} else {
i.Enabled = true
i.AuthenticatedAPISupport = exch.AuthenticatedAPISupport
i.SetAPIKeys(exch.APIKey, exch.APISecret, exch.ClientID)
i.RESTPollingDelay = exch.RESTPollingDelay
i.Verbose = exch.Verbose
i.Websocket = exch.Websocket
i.BaseCurrencies = SplitStrings(exch.BaseCurrencies, ",")
i.AvailablePairs = SplitStrings(exch.AvailablePairs, ",")
i.EnabledPairs = SplitStrings(exch.EnabledPairs, ",")
}
}
func (k *ItBit) GetEnabledCurrencies() []string {
return k.EnabledPairs
}
func (i *ItBit) Start() {
go i.Run()
}
func (i *ItBit) SetAPIKeys(apiKey, apiSecret, userID string) {
i.ClientKey = apiKey
i.APISecret = apiSecret
i.UserID = userID
}
func (i *ItBit) GetFee(maker bool) float64 {
if maker {
return i.MakerFee
} else {
return i.TakerFee
}
}
func (i *ItBit) Run() {
if i.Verbose {
log.Printf("%s polling delay: %ds.\n", i.GetName(), i.RESTPollingDelay)
log.Printf("%s %d currencies enabled: %s.\n", i.GetName(), len(i.EnabledPairs), i.EnabledPairs)
}
for i.Enabled {
for _, x := range i.EnabledPairs {
currency := x
go func() {
ticker := i.GetTicker(currency)
log.Printf("ItBit %s: Last %f High %f Low %f Volume %f\n", currency, ticker.LastPrice, ticker.High24h, ticker.Low24h, ticker.Volume24h)
AddExchangeInfo(i.GetName(), currency[0:3], currency[3:], ticker.LastPrice, ticker.Volume24h)
}()
}
time.Sleep(time.Second * i.RESTPollingDelay)
}
}
func (i *ItBit) GetTicker(currency string) ItBitTicker {
path := ITBIT_API_URL + "/markets/" + currency + "/ticker"
var itbitTicker ItBitTicker
err := SendHTTPGetRequest(path, true, &itbitTicker)
if err != nil {
log.Println(err)
return ItBitTicker{}
}
return itbitTicker
}
func (i *ItBit) GetTickerPrice(currency string) TickerPrice {
var tickerPrice TickerPrice
ticker := i.GetTicker(currency)
tickerPrice.Ask = ticker.Ask
tickerPrice.Bid = ticker.Bid
return tickerPrice
}
type ItbitOrderbookEntry struct {
Quantitiy float64 `json:"quantity,string"`
Price float64 `json:"price,string"`
}
type ItBitOrderbookResponse struct {
ServerTimeUTC string `json:"serverTimeUTC"`
LastUpdatedTimeUTC string `json:"lastUpdatedTimeUTC"`
Ticker string `json:"ticker"`
Bids []ItbitOrderbookEntry `json:"bids"`
Asks []ItbitOrderbookEntry `json:"asks"`
}
func (i *ItBit) GetOrderbook(currency string) (ItBitOrderbookResponse, error) {
response := ItBitOrderbookResponse{}
path := ITBIT_API_URL + "/markets/" + currency + "/order_book"
err := SendHTTPGetRequest(path, true, &response)
if err != nil {
return ItBitOrderbookResponse{}, err
}
return response, nil
}
func (i *ItBit) GetTradeHistory(currency, timestamp string) bool {
req := "/trades?since=" + timestamp
err := SendHTTPGetRequest(ITBIT_API_URL+"markets/"+currency+req, true, nil)
if err != nil {
log.Println(err)
return false
}
return true
}
func (i *ItBit) GetWallets(params url.Values) {
params.Set("userId", i.UserID)
path := "/wallets?" + params.Encode()
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
//TODO Get current holdings from ItBit
//GetExchangeAccountInfo : Retrieves balances for all enabled currencies for the ItBit exchange
func (e *ItBit) GetExchangeAccountInfo() (ExchangeAccountInfo, error) {
var response ExchangeAccountInfo
response.ExchangeName = e.GetName()
return response, nil
}
func (i *ItBit) CreateWallet(walletName string) {
path := "/wallets"
params := make(map[string]interface{})
params["userId"] = i.UserID
params["name"] = walletName
err := i.SendAuthenticatedHTTPRequest("POST", path, params)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetWallet(walletID string) {
path := "/wallets/" + walletID
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetWalletBalance(walletID, currency string) {
path := "/wallets/ " + walletID + "/balances/" + currency
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetWalletTrades(walletID string, params url.Values) {
path := EncodeURLValues("/wallets/"+walletID+"/trades", params)
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetWalletOrders(walletID string, params url.Values) {
path := EncodeURLValues("/wallets/"+walletID+"/orders", params)
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) PlaceWalletOrder(walletID, side, orderType, currency string, amount, price float64, instrument string, clientRef string) {
path := "/wallets/" + walletID + "/orders"
params := make(map[string]interface{})
params["side"] = side
params["type"] = orderType
params["currency"] = currency
params["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
params["price"] = strconv.FormatFloat(price, 'f', -1, 64)
params["instrument"] = instrument
if clientRef != "" {
params["clientOrderIdentifier"] = clientRef
}
err := i.SendAuthenticatedHTTPRequest("POST", path, params)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetWalletOrder(walletID, orderID string) {
path := "/wallets/" + walletID + "/orders/" + orderID
err := i.SendAuthenticatedHTTPRequest("GET", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) CancelWalletOrder(walletID, orderID string) {
path := "/wallets/" + walletID + "/orders/" + orderID
err := i.SendAuthenticatedHTTPRequest("DELETE", path, nil)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) PlaceWithdrawalRequest(walletID, currency, address string, amount float64) {
path := "/wallets/" + walletID + "/cryptocurrency_withdrawals"
params := make(map[string]interface{})
params["currency"] = currency
params["amount"] = amount
params["address"] = address
err := i.SendAuthenticatedHTTPRequest("POST", path, params)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) GetDepositAddress(walletID, currency string) {
path := "/wallets/" + walletID + "/cryptocurrency_deposits"
params := make(map[string]interface{})
params["currency"] = currency
err := i.SendAuthenticatedHTTPRequest("POST", path, params)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) WalletTransfer(walletID, sourceWallet, destWallet string, amount float64, currency string) {
path := "/wallets/" + walletID + "/wallet_transfers"
params := make(map[string]interface{})
params["sourceWalletId"] = sourceWallet
params["destinationWalletId"] = destWallet
params["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
params["currencyCode"] = currency
err := i.SendAuthenticatedHTTPRequest("POST", path, params)
if err != nil {
log.Println(err)
}
}
func (i *ItBit) SendAuthenticatedHTTPRequest(method string, path string, params map[string]interface{}) (err error) {
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)[0:13]
nonce, err := strconv.Atoi(timestamp)
if err != nil {
return err
}
nonce -= 1
request := make(map[string]interface{})
url := ITBIT_API_URL + path
if params != nil {
for key, value := range params {
request[key] = value
}
}
PayloadJson := []byte("")
if params != nil {
PayloadJson, err = JSONEncode(request)
if err != nil {
return errors.New("SendAuthenticatedHTTPRequest: Unable to JSON Marshal request")
}
if i.Verbose {
log.Printf("Request JSON: %s\n", PayloadJson)
}
}
nonceStr := strconv.Itoa(nonce)
message, err := JSONEncode([]string{method, url, string(PayloadJson), nonceStr, timestamp})
if err != nil {
log.Println(err)
return
}
hash := GetSHA256([]byte(nonceStr + string(message)))
hmac := GetHMAC(HASH_SHA512, []byte(url+string(hash)), []byte(i.APISecret))
signature := Base64Encode(hmac)
headers := make(map[string]string)
headers["Authorization"] = i.ClientKey + ":" + signature
headers["X-Auth-Timestamp"] = timestamp
headers["X-Auth-Nonce"] = nonceStr
headers["Content-Type"] = "application/json"
resp, err := SendHTTPRequest(method, url, headers, bytes.NewBuffer([]byte(PayloadJson)))
if i.Verbose {
log.Printf("Recieved raw: \n%s\n", resp)
}
return nil
}