-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
351 lines (321 loc) · 12.1 KB
/
main.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
package tulip
import (
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
)
// Client is the struct that interacts with buda server and executes the requests
type client struct {
apiURL string
apiKey string
apiSecret string
authenticated bool
}
// order is the struct that will be sent in the request payload as a json to create a new order
// CreateClient returns a new client
func CreateClient(apikey string, apisecret string) *client {
var newClient client
if apikey != "" && apisecret != "" {
newClient.authenticated = true
}
newClient.apiURL = "https://www.buda.com/api/v2"
newClient.apiKey = apikey
newClient.apiSecret = apisecret
return &newClient
}
// GetMarkets Returns info about all markets
func (c *client) GetMarkets() (MarketsResponse, error) {
finalURL := c.apiURL + "/markets"
resp := execute("GET", finalURL, "", "", "", "")
var jsonMarketsResponse MarketsResponse
err := json.Unmarshal([]byte(resp), &jsonMarketsResponse)
if err != nil {
return jsonMarketsResponse, err
}
return jsonMarketsResponse, nil
}
// GetTicker Returns info about a specific market
func (c *client) GetTicker(ticker string) (MarketResponse, error) {
finalURL := c.apiURL + "/markets/" + ticker
resp := execute("GET", finalURL, "", "", "", "")
var jsonMarketResponse MarketResponse
err := json.Unmarshal([]byte(resp), &jsonMarketResponse)
if err != nil {
return jsonMarketResponse, err
}
return jsonMarketResponse, nil
}
//GetOrderBook is used to get current state of the market.
// It shows the best offers (bid, ask) and the price from the
// last transaction, daily volume and the price in the last 24 hours
func (c *client) GetOrderBook(marketID string) (OrderBook, error) {
finalURL := c.apiURL + "/markets/" + marketID + "/order_book"
resp := execute("GET", finalURL, "", "", "", "")
var orderBook OrderBook
err := json.Unmarshal([]byte(resp), &orderBook)
if err != nil {
return orderBook, err
}
return orderBook, nil
}
//GetTrades returns a list of recent trades
func (c *client) GetTrades(marketID string) (TradesResponse, error) {
finalURL := c.apiURL + "/markets/" + marketID + "/trades"
resp := execute("GET", finalURL, "", "", "", "")
var jsonTrades TradesResponse
err := json.Unmarshal([]byte(resp), &jsonTrades)
if err != nil {
return jsonTrades, err
}
return jsonTrades, nil
}
func execute(method string, completeURL string, apikey string, signature string, Nonce string, reqPayload string) string {
// responseData will contain the body of the response from the server, execute(...) will return this variable as a string
responseData := "An error ocurred, check the request method, check your apikey ,signature and nonce"
// httpClient will make the http requests to the server
httpClient := &http.Client{}
// req is the request that will hold all the info
req, err := http.NewRequest(method, completeURL, nil)
if err != nil {
log.Fatal(("Error creating new request, submitted url was: " +
completeURL + "with method" + method +
". Error: "), err)
}
if method == "GET" && apikey == "" && signature == "" && Nonce == "" {
// The GET requests that do not require authentication will end here
// res is the response from the server when the request is executed
res, err := httpClient.Do(req)
if err != nil {
log.Fatal(("Error executing new request, submitted url was: " +
completeURL + "with method" + method +
". Error: "), err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(("Error reading response, submitted url was: " +
completeURL + "with method" + method +
". Error: "), err)
}
responseData = string(body)
} else if apikey != "" && signature != "" && Nonce != "" {
// The POST AND GET requests that DO NEED AUTHENTICATION will end here
req.Header.Set("X-SBTC-SIGNATURE", signature)
req.Header.Set("X-SBTC-APIKEY", apikey)
req.Header.Set("X-SBTC-NONCE", Nonce)
req.Header.Set("Content-Type", "application/json")
if method == "POST" || method == "PUT" {
req.Body = ioutil.NopCloser(strings.NewReader(reqPayload))
}
res, err := httpClient.Do(req)
if err != nil {
log.Fatal(("Error executing new request, submitted url was: " +
completeURL + "with method" + method +
". Error: "), err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(("Error reading response, submitted url was: " +
completeURL + "with method" + method +
". Error: "), err)
}
responseData = string(body)
}
return responseData
}
// HERE STARTS THE PRIVATE CALLS
func signMessage(APISecret string, method string, query string, Nonce string, body string) string {
var stringMessage string
if body != "" {
stringMessage = method + " /api/v2/" + query + " " + body + " " + Nonce
} else {
stringMessage = method + " /api/v2/" + query + " " + Nonce
}
fmt.Println(stringMessage)
key := []byte(APISecret)
h := hmac.New(sha512.New384, key)
h.Write([]byte(stringMessage))
signature := hex.EncodeToString(h.Sum(nil))
return signature
}
// GetBalances get the wallet balances in all cryptocurrencies and fiat currencies
func (c *client) GetBalances() (BalancesResponse, error) {
const method string = "GET"
const query string = "balances"
var jsonBalances BalancesResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonBalances)
if err != nil {
return jsonBalances, err
}
return jsonBalances, nil
}
err := errors.New("Authentication Required GetBalances")
return jsonBalances, err
}
// GetBalance get the wallet balance in a specific cryptocurrency or fiat currency
func (c *client) GetBalance(currency string) (BalanceResponse, error) {
const method string = "GET"
var query = "balances/" + currency
var jsonBalance BalanceResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonBalance)
if err != nil {
return jsonBalance, err
}
return jsonBalance, nil
}
err := errors.New("Authentication Required GetBalance")
return jsonBalance, err
}
// GetOrders gets your orders made in a specific market with a specific status
func (c *client) GetOrders(marketID string, per int, page int, state string, minimumExchanged float64) (MyOrdersResponse, error) {
const method string = "GET"
var query = "markets/" + marketID + "/orders?per=" + strconv.Itoa(per) + "&page=" + strconv.Itoa(page) + "&state=" + state + "&minimumExchanged=" + strconv.FormatFloat(minimumExchanged, 'g', 20, 32)
var jsonOrders MyOrdersResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonOrders)
if err != nil {
return jsonOrders, err
}
return jsonOrders, nil
}
err := errors.New("Authentication Required GetOrders")
return jsonOrders, err
}
// PostOrder creates a new order (bid or ask) in a specific market
func (c *client) PostOrder(marketID string, orderType string, priceType string, limit float64, amount float64) (OrderResponse, error) {
var jsonPostOrder OrderResponse
if c.authenticated == true {
const method string = "POST"
var query = "markets/" + marketID + "/orders"
var newOrder interface{}
if priceType == "market" {
newOrder = MarketOrder{orderType, priceType, amount}
} else if priceType == "limit" {
newOrder = LimitOrder{orderType, priceType, limit, amount}
}
var valueofjson = Describe(newOrder)
myOrder, err := json.Marshal(valueofjson)
if err != nil {
fmt.Println("THE ORDER HAS WRONG VALUES, CHECK THE API DOCUMENTATION" + marketID + " , " + orderType + ", " + priceType + ", " + strconv.FormatFloat(limit, 'g', 20, 32) + ", " + strconv.FormatFloat(amount, 'g', 20, 32))
return jsonPostOrder, err
}
encodedRequestPayload := base64.StdEncoding.EncodeToString([]byte(myOrder))
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
signature := signMessage(c.apiSecret, method, query, Nonce, encodedRequestPayload)
resp := execute(method, finalURL, c.apiKey, signature, Nonce, string(myOrder))
err2 := json.Unmarshal([]byte(resp), &jsonPostOrder)
if err2 != nil {
return jsonPostOrder, err
}
return jsonPostOrder, nil
}
err3 := errors.New("AUTHENTICATION REQUIRED PostOrder")
return jsonPostOrder, err3
}
// CancelOrder cancels a specified order
func (c *client) CancelOrder(orderID string) (OrderResponse, error) {
const method string = "PUT"
var query = "orders/" + orderID
requestPayloadString := "{ \"state\": \"canceling\" }"
encodedRequestPayload := base64.StdEncoding.EncodeToString([]byte(requestPayloadString))
var jsonCancelOrder OrderResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
signature := signMessage(c.apiSecret, method, query, Nonce, encodedRequestPayload)
resp := execute(method, finalURL, c.apiKey, signature, Nonce, requestPayloadString)
err := json.Unmarshal([]byte(resp), &jsonCancelOrder)
if err != nil {
return jsonCancelOrder, err
}
return jsonCancelOrder, nil
}
err2 := errors.New("AUTHENTICATION REQUIRED CancelOrder")
return jsonCancelOrder, err2
}
// GetOrder returns the current state of the order
func (c *client) GetOrder(orderID string) (OrderResponse, error) {
const method string = "GET"
var query = "orders/" + orderID
var jsonOrder OrderResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
fmt.Println("finalurl " + finalURL)
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonOrder)
if err != nil {
return jsonOrder, err
}
return jsonOrder, nil
}
err2 := errors.New("AUTHENTICATION REQUIRED GetOrder")
return jsonOrder, err2
}
// GetDepositHistory returns the historic deposits
func (c *client) GetDepositHistory(currency string) (HistoricDespositsResponse, error) {
const method string = "GET"
var query = "currencies/" + currency + "/deposits"
var jsonHistoricDeposit HistoricDespositsResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
fmt.Println("finalurl " + finalURL)
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonHistoricDeposit)
if err != nil {
return jsonHistoricDeposit, err
}
return jsonHistoricDeposit, nil
}
err2 := errors.New("AUTHENTICATION REQUIRED GetDepositHistory")
return jsonHistoricDeposit, err2
}
// GetWithdrawHistory returns the historic withdrawls
func (c *client) GetWithdrawHistory(currency string) (HistoricWithdrawResponse, error) {
const method string = "GET"
var query = "currencies/" + currency + "/withdrawals"
var jsonHistoricWithdraw HistoricWithdrawResponse
if c.authenticated == true {
Nonce := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
finalURL := c.apiURL + "/" + query
fmt.Println("finalurl " + finalURL)
signature := signMessage(c.apiSecret, method, query, Nonce, "")
resp := execute(method, finalURL, c.apiKey, signature, Nonce, "")
err := json.Unmarshal([]byte(resp), &jsonHistoricWithdraw)
if err != nil {
return jsonHistoricWithdraw, err
}
return jsonHistoricWithdraw, nil
}
err2 := errors.New("AUTHENTICATION REQUIRED GetWithdrawHistory")
return jsonHistoricWithdraw, err2
}