forked from nntaoli-project/goex
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fcoin.go
773 lines (653 loc) · 19.9 KB
/
fcoin.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
package fcoin
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
. "github.com/nntaoli-project/GoEx"
"net/http"
"net/url"
"strings"
"time"
"unsafe"
)
const (
SPOT = "spot"
ASSETS = "assets"
EXCHANGE = "exchange"
)
type FCoin struct {
httpClient *http.Client
baseUrl,
accessKey,
secretKey string
timeoffset int64
tradeSymbols []TradeSymbol
tradeSymbols2 []TradeSymbol2
}
type TradeSymbol struct {
Name string `json:"name"`
BaseCurrency string `json:"base_currency"`
QuoteCurrency string `json:"quote_currency"`
PriceDecimal int `json:"price_decimal"`
AmountDecimal int `json:"amount_decimal"`
Tradeable bool `json:"tradable"`
}
type TradeSymbol2 struct {
TradeSymbol
Category string `json:"category"`
LeveragedMultiple int `json:"leveraged_multiple"`
MarketOrderEnabled bool `json:"market_order_enabled"`
LimitAmountMin float64 `json:"limit_amount_min"`
LimitAmountMax float64 `json:"limit_amount_max"`
MainTag string `json:"main_tag"`
DailyOpenAt string `json:"daily_open_at"`
DailyCloseAt string `json:"daily_close_at"`
}
type Asset struct {
Currency Currency
Avaliable float64
Frozen float64
Finances float64
Lock float64
Total float64
}
type RawTicker struct {
Ticker
SellAmount float64
BuyAmount float64
LastTradeVol float64
}
func NewFCoin(client *http.Client, apikey, secretkey string) *FCoin {
fc := &FCoin{baseUrl: "https://api.fcoin.com/v2/", accessKey: apikey, secretKey: secretkey, httpClient: client}
fc.setTimeOffset()
var err error
fc.tradeSymbols, err = fc.GetTradeSymbols()
if len(fc.tradeSymbols) == 0 || err != nil {
panic("trade symbol is empty, pls check connection...")
}
return fc
}
func (fc *FCoin) GetExchangeName() string {
return FCOIN
}
func (fc *FCoin) GetServerTime() (int64, error) {
respmap, err := HttpGet(fc.httpClient, fc.baseUrl+"public/server-time")
if err != nil {
return 0, err
}
stime := int64(ToInt(respmap["data"]))
return stime, nil
}
func (fc *FCoin) setTimeOffset() error {
stime, err := fc.GetServerTime()
if err != nil {
return err
}
st := time.Unix(stime/1000, 0)
lt := time.Now()
offset := st.Sub(lt).Seconds()
fc.timeoffset = int64(offset)
return nil
}
func (fc *FCoin) GetTicker(currencyPair CurrencyPair) (*Ticker, error) {
respmap, err := HttpGet(fc.httpClient, fc.baseUrl+fmt.Sprintf("market/ticker/%s",
strings.ToLower(currencyPair.ToSymbol(""))))
if err != nil {
return nil, err
}
if respmap["status"].(float64) != 0 {
return nil, errors.New(respmap["msg"].(string))
}
tick, ok := respmap["data"].(map[string]interface{})
if !ok {
return nil, API_ERR
}
tickmap, ok := tick["ticker"].([]interface{})
if !ok {
return nil, API_ERR
}
ticker := new(RawTicker)
ticker.Pair = currencyPair
ticker.Date = uint64(time.Now().UnixNano() / 1000000)
ticker.Last = ToFloat64(tickmap[0])
ticker.Vol = ToFloat64(tickmap[9])
ticker.Low = ToFloat64(tickmap[8])
ticker.High = ToFloat64(tickmap[7])
ticker.Buy = ToFloat64(tickmap[2])
ticker.Sell = ToFloat64(tickmap[4])
ticker.SellAmount = ToFloat64(tickmap[5])
ticker.BuyAmount = ToFloat64(tickmap[3])
ticker.LastTradeVol = ToFloat64(tickmap[1])
return (*Ticker)(unsafe.Pointer(ticker)), nil
}
func (fc *FCoin) GetDepth(size int, currency CurrencyPair) (*Depth, error) {
var uri string
if size <= 20 {
uri = fmt.Sprintf("market/depth/L20/%s", strings.ToLower(currency.ToSymbol("")))
} else {
uri = fmt.Sprintf("market/depth/L150/%s", strings.ToLower(currency.ToSymbol("")))
}
respmap, err := HttpGet(fc.httpClient, fc.baseUrl+uri)
if err != nil {
return nil, err
}
if respmap["status"].(float64) != 0 {
return nil, errors.New(respmap["msg"].(string))
}
datamap := respmap["data"].(map[string]interface{})
bids, ok1 := datamap["bids"].([]interface{})
asks, ok2 := datamap["asks"].([]interface{})
if !ok1 || !ok2 {
return nil, errors.New("depth error")
}
depth := new(Depth)
depth.Pair = currency
n := 0
for i := 0; i < len(bids); {
depth.BidList = append(depth.BidList, DepthRecord{ToFloat64(bids[i]), ToFloat64(bids[i+1])})
i += 2
n++
if n == size {
break
}
}
n = 0
for i := 0; i < len(asks); {
depth.AskList = append(depth.AskList, DepthRecord{ToFloat64(asks[i]), ToFloat64(asks[i+1])})
i += 2
n++
if n == size {
break
}
}
return depth, nil
}
func (fc *FCoin) doAuthenticatedRequest(method, uri string, params url.Values) (interface{}, error) {
timestamp := time.Now().Unix()*1000 + fc.timeoffset*1000
sign := fc.buildSigned(method, fc.baseUrl+uri, timestamp, params)
header := map[string]string{
"FC-ACCESS-KEY": fc.accessKey,
"FC-ACCESS-SIGNATURE": sign,
"FC-ACCESS-TIMESTAMP": fmt.Sprint(timestamp)}
var (
respmap map[string]interface{}
err error
)
switch method {
case "GET":
respmap, err = HttpGet2(fc.httpClient, fc.baseUrl+uri+"?"+params.Encode(), header)
if err != nil {
return nil, err
}
case "POST":
var parammap = make(map[string]string, 1)
for k, v := range params {
parammap[k] = v[0]
}
respbody, err := HttpPostForm4(fc.httpClient, fc.baseUrl+uri, parammap, header)
if err != nil {
return nil, err
}
json.Unmarshal(respbody, &respmap)
}
if ToInt(respmap["status"]) != 0 {
return nil, errors.New(respmap["msg"].(string))
}
return respmap["data"], err
}
func (fc *FCoin) doAuthenticatedRequest2(method, uri string, params url.Values) (map[string]interface{}, error) {
timestamp := time.Now().Unix()*1000 + fc.timeoffset*1000
sign := fc.buildSigned(method, fc.baseUrl+uri, timestamp, params)
header := map[string]string{
"FC-ACCESS-KEY": fc.accessKey,
"FC-ACCESS-SIGNATURE": sign,
"FC-ACCESS-TIMESTAMP": fmt.Sprint(timestamp)}
var (
respmap map[string]interface{}
err error
)
switch method {
case "GET":
respmap, err = HttpGet2(fc.httpClient, fc.baseUrl+uri+"?"+params.Encode(), header)
if err != nil {
return nil, err
}
case "POST":
var parammap = make(map[string]string, 1)
for k, v := range params {
parammap[k] = v[0]
}
respbody, err1 := HttpPostForm4(fc.httpClient, fc.baseUrl+uri, parammap, header)
if err1 != nil {
return nil, err1
}
err = json.Unmarshal(respbody, &respmap)
if err != nil {
return nil, err
}
}
return respmap, err
}
func (fc *FCoin) buildSigned(httpmethod string, apiurl string, timestamp int64, para url.Values) string {
var (
param = ""
err error
)
if para != nil {
param = para.Encode()
}
if "GET" == httpmethod && param != "" {
apiurl += "?" + param
}
signStr := httpmethod + apiurl + fmt.Sprint(timestamp)
if "POST" == httpmethod && param != "" {
signStr += param
}
signStr2, err := url.QueryUnescape(signStr) // 不需要编码
if err != nil {
signStr2 = signStr
}
sign := base64.StdEncoding.EncodeToString([]byte(signStr2))
mac := hmac.New(sha1.New, []byte(fc.secretKey))
mac.Write([]byte(sign))
sum := mac.Sum(nil)
s := base64.StdEncoding.EncodeToString(sum)
return s
}
// ORDERTYPE:limit, market, fok, ioc
func (fc *FCoin) PlaceOrder(orderType OrderType, orderSide, amount, price string, pair CurrencyPair, isMargin bool) (*Order, error) {
params := url.Values{}
params.Set("side", orderSide)
params.Set("amount", amount)
params.Set("symbol", strings.ToLower(pair.AdaptUsdToUsdt().ToSymbol("")))
if ORDER_TYPE_MARKET != orderType {
params.Set("price", price)
}
if isMargin {
params.Set("account_type", "margin")
}
params.Set("type", strings.ToLower(orderType.String()))
if ORDER_TYPE_MARKET == orderType {
params.Del("price")
}
r, err := fc.doAuthenticatedRequest("POST", "orders", params)
if err != nil {
return nil, err
}
side := SELL
if orderSide == "buy" {
side = BUY
}
return &Order{
Currency: pair,
OrderID2: r.(string),
Amount: ToFloat64(amount),
Price: ToFloat64(price),
Side: TradeSide(side),
Status: ORDER_UNFINISH,
OrderTime: int(time.Now().UnixNano() / 1000000),
OrderType: int(orderType),
}, nil
}
func (fc *FCoin) LimitBuy(amount, price string, currency CurrencyPair) (*Order, error) {
return fc.PlaceOrder(ORDER_TYPE_LIMIT, "buy", amount, price, currency, false)
}
func (fc *FCoin) LimitSell(amount, price string, currency CurrencyPair) (*Order, error) {
return fc.PlaceOrder(ORDER_TYPE_LIMIT, "sell", amount, price, currency, false)
}
func (fc *FCoin) MarketBuy(amount, price string, currency CurrencyPair) (*Order, error) {
return fc.PlaceOrder(ORDER_TYPE_MARKET, "buy", amount, price, currency, false)
}
func (fc *FCoin) MarketSell(amount, price string, currency CurrencyPair) (*Order, error) {
return fc.PlaceOrder(ORDER_TYPE_MARKET, "sell", amount, price, currency, false)
}
func (fc *FCoin) CancelOrder(orderId string, currency CurrencyPair) (bool, error) {
uri := fmt.Sprintf("orders/%s/submit-cancel", orderId)
_, err := fc.doAuthenticatedRequest("POST", uri, url.Values{})
if err != nil {
return false, err
}
return true, nil
}
func (fc *FCoin) toOrder(o map[string]interface{}, pair CurrencyPair) *Order {
side := SELL
if o["side"].(string) == "buy" {
side = BUY
}
orderStatus := ORDER_UNFINISH
switch o["state"].(string) {
case "partial_filled":
orderStatus = ORDER_PART_FINISH
case "filled":
orderStatus = ORDER_FINISH
case "pending_cancel":
orderStatus = ORDER_CANCEL_ING
case "canceled", "partial_canceled":
orderStatus = ORDER_CANCEL
}
var fees float64
refund := ToFloat64(o["fees_income"])
fee := ToFloat64(o["fill_fees"])
if fee == 0 {
fees = -refund
} else {
fees = fee
}
avgPrice := 0.0
dealAmount := ToFloat64(o["filled_amount"])
executeValue := ToFloat64(o["executed_value"])
if dealAmount != 0.0 {
avgPrice = executeValue / dealAmount
}
return &Order{
Currency: pair,
Side: TradeSide(side),
OrderID2: o["id"].(string),
Amount: ToFloat64(o["amount"]),
Price: ToFloat64(o["price"]),
DealAmount: dealAmount,
Status: TradeStatus(orderStatus),
Type: o["type"].(string),
Fee: fees,
AvgPrice: avgPrice,
OrderTime: ToInt(o["created_at"])}
}
func (fc *FCoin) GetOneOrder(orderId string, currency CurrencyPair) (*Order, error) {
uri := fmt.Sprintf("orders/%s", orderId)
r, err := fc.doAuthenticatedRequest("GET", uri, url.Values{})
if err != nil {
return nil, err
}
return fc.toOrder(r.(map[string]interface{}), currency), nil
}
func (fc *FCoin) GetUnfinishOrders(currency CurrencyPair) ([]Order, error) {
params := url.Values{}
params.Set("symbol", strings.ToLower(currency.AdaptUsdToUsdt().ToSymbol("")))
params.Set("states", "submitted,partial_filled")
//params.Set("before", "1")
//params.Set("after", "0")
params.Set("limit", "100")
r, err := fc.doAuthenticatedRequest("GET", "orders", params)
if err != nil {
return nil, err
}
var ords []Order
for _, ord := range r.([]interface{}) {
ords = append(ords, *fc.toOrder(ord.(map[string]interface{}), currency))
}
return ords, nil
}
func (fc *FCoin) getAfterTimeOrderHistorys(currency CurrencyPair, times time.Time) ([]Order, error) {
params := url.Values{}
params.Set("symbol", strings.ToLower(currency.AdaptUsdToUsdt().ToSymbol("")))
params.Set("states", "filled")
params.Set("after", fmt.Sprint(times.Unix()*1000))
params.Set("limit", "100")
r, err := fc.doAuthenticatedRequest("GET", "orders", params)
if err != nil {
return nil, err
}
var ords []Order
for _, ord := range r.([]interface{}) {
ords = append(ords, *fc.toOrder(ord.(map[string]interface{}), currency))
}
return ords, nil
}
func (fc *FCoin) getBeforeTimeOrderHistorys(currency CurrencyPair, times time.Time) ([]Order, error) {
params := url.Values{}
params.Set("symbol", strings.ToLower(currency.AdaptUsdToUsdt().ToSymbol("")))
params.Set("states", "filled")
params.Set("before", fmt.Sprint(times.Unix()*1000))
params.Set("limit", "100")
r, err := fc.doAuthenticatedRequest("GET", "orders", params)
if err != nil {
return nil, err
}
var ords []Order
for _, ord := range r.([]interface{}) {
ords = append(ords, *fc.toOrder(ord.(map[string]interface{}), currency))
}
return ords, nil
}
func (fc *FCoin) GetHoursOrderHistorys(currency CurrencyPair, start time.Time, hours int64) ([]Order, error) {
ord1, _ := fc.getAfterTimeOrderHistorys(currency, start)
ord2, _ := fc.getBeforeTimeOrderHistorys(currency, start.Add(time.Hour*time.Duration(hours)))
ords := make([]Order, 0)
for _, v1 := range ord1 {
for _, v2 := range ord2 {
if v1.OrderID2 == v2.OrderID2 {
ords = append(ords, v1)
}
}
}
return ords, nil
}
func (fc *FCoin) GetDaysOrderHistorys(currency CurrencyPair, start time.Time, days int64) ([]Order, error) {
ord1, _ := fc.getAfterTimeOrderHistorys(currency, start)
ord2, _ := fc.getBeforeTimeOrderHistorys(currency, start.Add(time.Hour*24*time.Duration(days)))
ords := make([]Order, 0)
for _, v1 := range ord1 {
for _, v2 := range ord2 {
if v1.OrderID2 == v2.OrderID2 {
ords = append(ords, v1)
}
}
}
if len(ords) == 0 && len(ord2) > 1 && len(ord1) > 1 {
return nil, errors.New("more than 100 orders")
}
return ords, nil
}
func (fc *FCoin) GetOrderHistorys(currency CurrencyPair, currentPage, pageSize int) ([]Order, error) {
params := url.Values{}
params.Set("symbol", strings.ToLower(currency.AdaptUsdToUsdt().ToSymbol("")))
params.Set("states", "partial_canceled,filled")
//params.Set("before", "1")
//params.Set("after", "0")
params.Set("limit", fmt.Sprint(pageSize))
r, err := fc.doAuthenticatedRequest("GET", "orders", params)
if err != nil {
return nil, err
}
var ords []Order
for _, ord := range r.([]interface{}) {
ords = append(ords, *fc.toOrder(ord.(map[string]interface{}), currency))
}
return ords, nil
}
func (fc *FCoin) GetOrderHistorys2(currency CurrencyPair, currentPage, pageSize int, states ...string) ([]Order, error) {
sts := ""
for i := 0; i < len(states); i++ {
sts += states[i] + ","
}
sts = sts[:len(sts)-1]
params := url.Values{}
params.Set("symbol", strings.ToLower(currency.AdaptUsdToUsdt().ToSymbol("")))
params.Set("states", sts)
params.Set("limit", fmt.Sprint(pageSize))
r, err := fc.doAuthenticatedRequest("GET", "orders", params)
if err != nil {
return nil, err
}
var ords []Order
for _, ord := range r.([]interface{}) {
ords = append(ords, *fc.toOrder(ord.(map[string]interface{}), currency))
}
return ords, nil
}
func (fc *FCoin) GetAccount() (*Account, error) {
r, err := fc.doAuthenticatedRequest("GET", "accounts/balance", url.Values{})
if err != nil {
return nil, err
}
acc := new(Account)
acc.SubAccounts = make(map[Currency]SubAccount)
acc.Exchange = fc.GetExchangeName()
balances := r.([]interface{})
for _, v := range balances {
vv := v.(map[string]interface{})
currency := NewCurrency(vv["currency"].(string), "")
acc.SubAccounts[currency] = SubAccount{
Currency: currency,
Amount: ToFloat64(vv["available"]),
ForzenAmount: ToFloat64(vv["frozen"]),
}
}
return acc, nil
}
func (fc *FCoin) GetAssets() ([]Asset, error) {
r, err := fc.doAuthenticatedRequest("GET", "assets/accounts/balance", url.Values{})
if err != nil {
return nil, err
}
assets := make([]Asset, 0)
balances := r.([]interface{})
for _, v := range balances {
vv := v.(map[string]interface{})
currency := NewCurrency(vv["currency"].(string), "")
assets = append(assets, Asset{
Currency: currency,
Avaliable: ToFloat64(vv["available"]),
Frozen: ToFloat64(vv["frozen"]),
Finances: ToFloat64(vv["demand_deposit"]),
Lock: ToFloat64(vv["lock_deposit"]),
Total: ToFloat64(vv["balance"]),
})
}
return assets, nil
}
// from, to: assets, spot
func (fc *FCoin) AssetTransfer(currency Currency, amount, from, to string) (bool, error) {
params := url.Values{}
params.Set("currency", strings.ToLower(currency.String()))
params.Set("amount", amount)
_, err := fc.doAuthenticatedRequest("POST", fmt.Sprintf("assets/accounts/%s-to-%s", from, to), params)
if err != nil {
return false, err
}
return true, nil
}
func (fc *FCoin) GetKlineRecords(currency CurrencyPair, period, size, since int) ([]Kline, error) {
uri := fmt.Sprintf("market/candles/%s/%s?limit=%d", _INERNAL_KLINE_PERIOD_CONVERTER[period], strings.ToLower(currency.ToSymbol("")), size)
respmap, err := HttpGet(fc.httpClient, fc.baseUrl+uri)
if err != nil {
return nil, err
}
if respmap["status"].(float64) != 0 {
return nil, errors.New(respmap["msg"].(string))
}
datamap, isOk := respmap["data"].([]interface{})
if !isOk {
return nil, errors.New("kline error")
}
var klineRecords []Kline
for _, record := range datamap {
r := record.(map[string]interface{})
klineRecords = append(klineRecords, Kline{
Pair: currency,
Timestamp: int64(ToInt(r["id"])),
Open: ToFloat64(r["open"]),
Close: ToFloat64(r["close"]),
High: ToFloat64(r["high"]),
Low: ToFloat64(r["low"]),
Vol: ToFloat64(r["quote_vol"]),
})
}
return klineRecords, nil
}
//非个人,整个交易所的交易记录
func (fc *FCoin) GetTrades(currencyPair CurrencyPair, since int64) ([]Trade, error) {
panic("not implement")
}
//交易符号
func (fc *FCoin) GetTradeSymbols() ([]TradeSymbol, error) {
respmap, err := HttpGet(fc.httpClient, fc.baseUrl+"public/symbols")
if err != nil {
return nil, err
}
if respmap["status"].(float64) != 0 {
return nil, errors.New(respmap["msg"].(string))
}
datamap := respmap["data"].([]interface{})
tradeSymbols := make([]TradeSymbol, 0)
for _, v := range datamap {
vv := v.(map[string]interface{})
var symbol TradeSymbol
symbol.Name = vv["name"].(string)
symbol.BaseCurrency = vv["base_currency"].(string)
symbol.QuoteCurrency = vv["quote_currency"].(string)
symbol.PriceDecimal = int(vv["price_decimal"].(float64))
symbol.AmountDecimal = int(vv["amount_decimal"].(float64))
symbol.Tradeable = vv["tradable"].(bool)
if symbol.Tradeable {
tradeSymbols = append(tradeSymbols, symbol)
}
}
return tradeSymbols, nil
}
func (fc *FCoin) GetTradeSymbol(currencyPair CurrencyPair) (*TradeSymbol, error) {
if len(fc.tradeSymbols) == 0 {
var err error
fc.tradeSymbols, err = fc.GetTradeSymbols()
if err != nil {
return nil, err
}
}
for k, v := range fc.tradeSymbols {
if v.Name == strings.ToLower(currencyPair.ToSymbol("")) {
return &fc.tradeSymbols[k], nil
}
}
return nil, errors.New("symbol not found")
}
func (fc *FCoin) GetTradeSymbols2() ([]TradeSymbol2, error) {
respmap, err := HttpGet(fc.httpClient, "https://www.fcoin.com/openapi/v2/symbols")
if err != nil {
return nil, err
}
if respmap["status"].(string) != "ok" {
return nil, errors.New(respmap["msg"].(string))
}
datamap := respmap["data"].(map[string]interface{})
symbols := datamap["symbols"].(map[string]interface{})
tradeSymbols := make([]TradeSymbol2, 0)
for _, v := range symbols {
vv := v.(map[string]interface{})
var symbol TradeSymbol2
symbol.Name, _ = vv["symbol"].(string)
symbol.BaseCurrency, _ = vv["base_currency"].(string)
symbol.QuoteCurrency, _ = vv["quote_currency"].(string)
symbol.PriceDecimal = ToInt(vv["price_decimal"])
symbol.AmountDecimal = ToInt(vv["amount_decimal"])
symbol.Tradeable, _ = vv["tradeable"].(bool)
symbol.Category, _ = vv["category"].(string)
symbol.LeveragedMultiple = ToInt(vv["leveraged_multiple"])
symbol.MarketOrderEnabled, _ = vv["market_order_enabled"].(bool)
symbol.LimitAmountMin = ToFloat64(vv["limit_amount_min"])
symbol.LimitAmountMax = ToFloat64(vv["limit_amount_max"])
symbol.MainTag, _ = vv["main_tag"].(string)
symbol.DailyOpenAt, _ = vv["daily_open_at"].(string)
symbol.DailyCloseAt, _ = vv["daily_close_at"].(string)
if symbol.Tradeable {
tradeSymbols = append(tradeSymbols, symbol)
}
}
return tradeSymbols, nil
}
func (fc *FCoin) GetTradeSymbol2(currencyPair CurrencyPair) (*TradeSymbol2, error) {
if len(fc.tradeSymbols2) == 0 {
var err error
fc.tradeSymbols2, err = fc.GetTradeSymbols2()
if err != nil {
return nil, err
}
}
for k, v := range fc.tradeSymbols2 {
if v.Name == strings.ToLower(currencyPair.ToSymbol("")) {
return &fc.tradeSymbols2[k], nil
}
}
return nil, errors.New("symbol not found")
}