forked from baibaratsky/go-poloniex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrading.go
298 lines (238 loc) · 6.88 KB
/
trading.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
package poloniex
import (
"context"
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/shopspring/decimal"
)
const tradingApiEndpoint = "https://poloniex.com/tradingApi"
const (
TypeBuy = "buy"
TypeSell = "sell"
)
type FeeInfo struct {
MakerFee decimal.Decimal
TakerFee decimal.Decimal
ThirtyDayVolume decimal.Decimal
NextTier decimal.Decimal
}
func (client *Client) FeeInfo() (feeInfo FeeInfo, err error) {
err = client.tradingApiRequest(&feeInfo, "returnFeeInfo")
return
}
func (client *Client) Balances() (balances map[string]decimal.Decimal, err error) {
err = client.tradingApiRequest(&balances, "returnBalances")
return
}
func (client *Client) DepositAddresses() (addresses map[string]string, err error) {
err = client.tradingApiRequest(&addresses, "returnDepositAddresses")
return
}
func (client *Client) NewAddress(currency string) (address string, err error) {
params := Params{
"currency": currency,
}
result := struct {
Success convertibleBool `json:"success"`
Response string `json:"response"`
}{}
if err = client.tradingApiRequest(&result, "generateNewAddress", params); err != nil {
return result.Response, err
}
if !result.Success {
return result.Response, fmt.Errorf("generateNewAddress for currency %s success = %s, response = %s", currency, result.Success, result.Response)
}
return result.Response, err
}
type Trade struct {
GlobalTradeId uint64 `json:"globalTradeID"`
Id convertibleUint `json:"tradeID"`
OrderNumber uint64 `json:"orderNumber,string"`
CurrencyPair string
Type string
Rate decimal.Decimal
Amount decimal.Decimal
Total decimal.Decimal
Fee decimal.Decimal
Date string
}
func (client *Client) TradeHistory(currencyPair string, start, end int64) (trades []Trade, err error) {
params := Params{
"currencyPair": currencyPair,
}
if start > 0 {
params["start"] = fmt.Sprintf("%d", start)
}
if end > 0 {
params["end"] = fmt.Sprintf("%d", end)
}
err = client.tradingApiRequest(&trades, "returnTradeHistory", params)
for i := range trades {
trades[i].CurrencyPair = currencyPair
}
return
}
func (client *Client) TradeHistoryAll(start, end int64) (trades map[string][]Trade, err error) {
params := Params{
"currencyPair": "all",
}
if start > 0 {
params["start"] = fmt.Sprintf("%d", start)
}
if end > 0 {
params["end"] = fmt.Sprintf("%d", end)
}
err = client.tradingApiRequest(&trades, "returnTradeHistory", params)
for pair := range trades {
for i := range trades[pair] {
trades[pair][i].CurrencyPair = pair
}
}
return
}
func (client *Client) OrderTrades(orderNumber uint64) (trades []Trade, err error) {
err = client.tradingApiRequest(&trades, "returnOrderTrades",
Params{"orderNumber": fmt.Sprintf("%d", orderNumber)})
for i := range trades {
trades[i].OrderNumber = orderNumber
}
return
}
type OwnOrder struct {
OrderNumber uint64 `json:"orderNumber,string"`
Type string
Rate decimal.Decimal
Amount decimal.Decimal
Total decimal.Decimal
}
func (client *Client) OpenOrders(currencyPair string) (orders []OwnOrder, err error) {
err = client.tradingApiRequest(&orders, "returnOpenOrders", Params{
"currencyPair": currencyPair,
})
return
}
func (client *Client) OpenOrdersAll() (orders map[string][]OwnOrder, err error) {
err = client.tradingApiRequest(&orders, "returnOpenOrders", Params{
"currencyPair": "all",
})
return
}
type PlacedOrder struct {
OrderNumber convertibleUint `json:"orderNumber"`
ResultingTrades []Trade
}
type UpdatedOrder struct {
OrderNumber convertibleUint `json:"orderNumber"`
ResultingTrades map[string][]Trade
}
func (client *Client) Buy(currencyPair string, rate, amount decimal.Decimal) (placedOrder PlacedOrder, err error) {
err = client.tradingApiRequest(&placedOrder, "buy", Params{
"currencyPair": currencyPair,
"rate": rate.String(),
"amount": amount.String(),
})
return
}
func (client *Client) Sell(currencyPair string, rate, amount decimal.Decimal) (placedOrder PlacedOrder, err error) {
err = client.tradingApiRequest(&placedOrder, "sell", Params{
"currencyPair": currencyPair,
"rate": rate.String(),
"amount": amount.String(),
})
return
}
func (client *Client) CancelOrder(orderNumber uint64) (success bool, err error) {
result := struct {
Success convertibleBool
}{}
err = client.tradingApiRequest(&result, "cancelOrder",
Params{"orderNumber": fmt.Sprintf("%d", orderNumber)})
success = bool(result.Success)
return
}
func (client *Client) MoveOrder(orderNumber uint64, rate, amount decimal.Decimal) (updatedOrder UpdatedOrder, err error) {
result := struct {
Success convertibleBool
UpdatedOrder
}{}
params := Params{
"orderNumber": fmt.Sprintf("%d", orderNumber),
"rate": rate.String(),
}
if amount.GreaterThan(decimal.Zero) {
params["amount"] = amount.String()
}
err = client.tradingApiRequest(&result, "moveOrder", params)
if !result.Success {
err = errors.New("result is not successful")
}
updatedOrder = result.UpdatedOrder
return
}
func (client *Client) Withdraw(currency, address string, amount decimal.Decimal) (response string, err error) {
result := struct {
Response string
}{}
params := Params{
"currency": currency,
"address": address,
"amount": amount.String(),
}
err = client.tradingApiRequest(&result, "withdraw", params)
return result.Response, err
}
type errorResponse struct {
Error *string
}
type emptyArrayResponse []struct{}
func (client *Client) tradingApiRequest(result interface{}, method string, params ...Params) (err error) {
if len(params) > 1 {
return errors.New("too much arguments")
}
formData := Params{
"command": method,
}
if len(params) == 1 {
for name, value := range params[0] {
formData[name] = value
}
}
err = client.limiter.Wait(context.TODO())
if err != nil {
return err
}
key := client.keyPool.Get()
nonce := time.Now().UnixNano()
formData["nonce"] = fmt.Sprintf("%d", nonce)
request := client.resty.R().
SetFormData(formData)
signature := hmac.New(sha512.New, []byte(key.Secret))
signature.Write([]byte(request.FormData.Encode()))
request.SetHeader("Key", key.Key).
SetHeader("Sign", hex.EncodeToString(signature.Sum(nil)))
response, err := request.Post(tradingApiEndpoint)
client.keyPool.Put(key)
if err != nil {
return err
}
errorResponse := errorResponse{}
json.Unmarshal(response.Body(), &errorResponse)
if errorResponse.Error != nil {
return errors.New(*errorResponse.Error)
}
emptyArrayResponse := emptyArrayResponse{}
err = json.Unmarshal(response.Body(), &emptyArrayResponse)
if err == nil && len(emptyArrayResponse) == 0 {
return nil
}
err = json.Unmarshal(response.Body(), result)
if err != nil {
err = fmt.Errorf("%s\nServer response: %s", err.Error(), string(response.Body()))
}
return err
}