|
1 | 1 | package exchange
|
2 | 2 |
|
3 | 3 | import (
|
4 |
| - "encoding/json" |
| 4 | + "errors" |
5 | 5 | "fmt"
|
6 | 6 | "math"
|
7 | 7 | "strconv"
|
8 |
| - "strings" |
9 | 8 | "time"
|
10 | 9 |
|
11 | 10 | "github.com/polyrabbit/my-token/exchange/model"
|
12 |
| - |
13 | 11 | "github.com/polyrabbit/my-token/http"
|
14 | 12 | "github.com/sirupsen/logrus"
|
| 13 | + "github.com/tidwall/gjson" |
15 | 14 | )
|
16 | 15 |
|
17 |
| -// https://github.com/okcoin-okex/API-docs-OKEx.com |
18 |
| -const okexBaseApi = "https://www.okex.com/api/v1" |
| 16 | +// https://www.okex.com/docs/zh/#spot-some |
| 17 | +const okexBaseApi = "https://www.okex.com/api/spot/v3/instruments/" |
19 | 18 |
|
20 | 19 | type okexClient struct {
|
21 | 20 | AccessKey string
|
22 | 21 | SecretKey string
|
23 | 22 | }
|
24 | 23 |
|
25 |
| -type okexErrorResponse struct { |
26 |
| - ErrorCode int `json:"error_code"` |
27 |
| -} |
28 |
| - |
29 |
| -type okexTickerResponse struct { |
30 |
| - okexErrorResponse |
31 |
| - Date int64 `json:",string"` |
32 |
| - Ticker struct { |
33 |
| - Last float64 `json:",string"` |
34 |
| - } |
35 |
| -} |
36 |
| - |
37 |
| -type okexKlineResponse struct { |
38 |
| - okexErrorResponse |
39 |
| - Data [][]interface{} |
40 |
| -} |
41 |
| - |
42 |
| -func (resp *okexTickerResponse) getCommonResponse() okexErrorResponse { |
43 |
| - return resp.okexErrorResponse |
44 |
| -} |
45 |
| - |
46 |
| -func (resp *okexTickerResponse) getInternalData() interface{} { |
47 |
| - return resp |
48 |
| -} |
49 |
| - |
50 |
| -func (resp *okexKlineResponse) getCommonResponse() okexErrorResponse { |
51 |
| - return resp.okexErrorResponse |
52 |
| -} |
53 |
| - |
54 |
| -func (resp *okexKlineResponse) getInternalData() interface{} { |
55 |
| - return &resp.Data |
56 |
| -} |
57 |
| - |
58 |
| -// Any way to hold the common response, instead of adding an interface here? |
59 |
| -type okexCommonResponseProvider interface { |
60 |
| - getCommonResponse() okexErrorResponse |
61 |
| - getInternalData() interface{} |
62 |
| -} |
63 |
| - |
64 | 24 | func (client *okexClient) GetName() string {
|
65 | 25 | return "OKEx"
|
66 | 26 | }
|
67 | 27 |
|
68 |
| -func (client *okexClient) decodeResponse(respBytes []byte, respJSON okexCommonResponseProvider) error { |
69 |
| - // What a messy |
70 |
| - respBody := strings.TrimSpace(string(respBytes)) |
71 |
| - if respBody[0] == '[' { |
72 |
| - return json.Unmarshal(respBytes, respJSON.getInternalData()) |
| 28 | +func (client *okexClient) GetKlinePrice(symbol, granularity string, start, end time.Time) (float64, error) { |
| 29 | + respByte, err := http.Get(okexBaseApi+symbol+"/candles", map[string]string{ |
| 30 | + "granularity": granularity, |
| 31 | + "start": start.UTC().Format(time.RFC3339), |
| 32 | + "end": end.UTC().Format(time.RFC3339), |
| 33 | + }) |
| 34 | + if err := client.extractError(respByte); err != nil { |
| 35 | + return 0, fmt.Errorf("okex get candles: %w", err) |
73 | 36 | }
|
74 |
| - |
75 |
| - if err := json.Unmarshal(respBytes, &respJSON); err != nil { |
76 |
| - return err |
| 37 | + if err != nil { |
| 38 | + return 0, fmt.Errorf("okex get candles: %w", err) |
77 | 39 | }
|
78 | 40 |
|
79 |
| - // All I need is to get the common part, I don't like this |
80 |
| - commonResponse := respJSON.getCommonResponse() |
81 |
| - if commonResponse.ErrorCode != 0 { |
82 |
| - return fmt.Errorf("error_code: %v", commonResponse.ErrorCode) |
| 41 | + klines := gjson.ParseBytes(respByte).Array() |
| 42 | + if len(klines) == 0 { |
| 43 | + return 0, fmt.Errorf("okex got empty candles response") |
83 | 44 | }
|
84 |
| - return nil |
85 |
| -} |
86 |
| - |
87 |
| -func (client *okexClient) GetKlinePrice(symbol, period string, size int) (float64, error) { |
88 |
| - symbol = strings.ToLower(symbol) |
89 |
| - respByte, err := http.Get(okexBaseApi+"/kline.do", map[string]string{ |
90 |
| - "symbol": symbol, |
91 |
| - "type": period, |
92 |
| - "size": strconv.Itoa(size), |
93 |
| - }) |
94 |
| - if err != nil { |
95 |
| - return 0, err |
| 45 | + lastKline := klines[len(klines)-1] |
| 46 | + if len(lastKline.Array()) != 6 { |
| 47 | + return 0, fmt.Errorf(`okex malformed kline response, got size %d`, len(lastKline.Array())) |
96 | 48 | }
|
97 |
| - |
98 |
| - var respJSON okexKlineResponse |
99 |
| - err = client.decodeResponse(respByte, &respJSON) |
100 |
| - if err != nil { |
101 |
| - return 0, err |
| 49 | + updated := time.Now() |
| 50 | + if parsed, err := time.Parse(time.RFC3339, lastKline.Get("0").String()); err == nil { |
| 51 | + updated = parsed |
102 | 52 | }
|
103 |
| - logrus.Debugf("%s - Kline for %s*%v uses price at %s", client.GetName(), period, size, |
104 |
| - time.Unix(int64(respJSON.Data[0][0].(float64))/1000, 0)) |
105 |
| - return strconv.ParseFloat(respJSON.Data[0][1].(string), 64) |
| 53 | + logrus.Debugf("%s - Kline for %s seconds uses price at %s", |
| 54 | + client.GetName(), granularity, updated.Local()) |
| 55 | + return lastKline.Get("1").Float(), nil |
106 | 56 | }
|
107 | 57 |
|
108 | 58 | func (client *okexClient) GetSymbolPrice(symbol string) (*model.SymbolPrice, error) {
|
109 |
| - respByte, err := http.Get(okexBaseApi+"/ticker.do", map[string]string{"symbol": strings.ToLower(symbol)}) |
| 59 | + respByte, err := http.Get(okexBaseApi+symbol+"/ticker", nil) |
| 60 | + if err := client.extractError(respByte); err != nil { |
| 61 | + // Extract more readable first if have |
| 62 | + return nil, fmt.Errorf("okex get symbol price: %w", err) |
| 63 | + } |
110 | 64 | if err != nil {
|
111 |
| - return nil, err |
| 65 | + return nil, fmt.Errorf("okex get symbol price: %w", err) |
112 | 66 | }
|
113 |
| - |
114 |
| - var respJSON okexTickerResponse |
115 |
| - err = client.decodeResponse(respByte, &respJSON) |
| 67 | + lastV := gjson.GetBytes(respByte, "last") |
| 68 | + if !lastV.Exists() { |
| 69 | + return nil, fmt.Errorf(`okex malformed get symbol price response, missing "last" key`) |
| 70 | + } |
| 71 | + lastPrice := lastV.Float() |
| 72 | + updateAtV := gjson.GetBytes(respByte, "timestamp") |
| 73 | + if !updateAtV.Exists() { |
| 74 | + return nil, fmt.Errorf(`okex malformed get symbol price response, missing "timestamp" key`) |
| 75 | + } |
| 76 | + updateAt, err := time.Parse(time.RFC3339, updateAtV.String()) |
116 | 77 | if err != nil {
|
117 |
| - return nil, err |
| 78 | + return nil, fmt.Errorf("okex parse timestamp: %w", err) |
118 | 79 | }
|
119 | 80 |
|
120 | 81 | var percentChange1h, percentChange24h = math.MaxFloat64, math.MaxFloat64
|
121 |
| - price1hAgo, err := client.GetKlinePrice(symbol, "1min", 60) |
| 82 | + price1hAgo, err := client.GetKlinePrice(symbol, "60", updateAt.Add(-time.Hour), updateAt) |
122 | 83 | if err != nil {
|
123 | 84 | logrus.Warnf("%s - Failed to get price 1 hour ago, error: %v\n", client.GetName(), err)
|
124 | 85 | } else if price1hAgo != 0 {
|
125 |
| - percentChange1h = (respJSON.Ticker.Last - price1hAgo) / price1hAgo * 100 |
| 86 | + percentChange1h = (lastPrice - price1hAgo) / price1hAgo * 100 |
126 | 87 | }
|
127 | 88 |
|
128 |
| - time.Sleep(time.Second) // Limit 1 req/sec for Kline |
129 |
| - price24hAgo, err := client.GetKlinePrice(symbol, "3min", 492) // Why not 480? |
| 89 | + price24hAgo, err := client.GetKlinePrice(symbol, "900", updateAt.Add(-24*time.Hour), updateAt) |
130 | 90 | if err != nil {
|
131 | 91 | logrus.Warnf("%s - Failed to get price 24 hours ago, error: %v\n", client.GetName(), err)
|
132 | 92 | } else if price24hAgo != 0 {
|
133 |
| - percentChange24h = (respJSON.Ticker.Last - price24hAgo) / price24hAgo * 100 |
| 93 | + percentChange24h = (lastPrice - price24hAgo) / price24hAgo * 100 |
134 | 94 | }
|
135 | 95 |
|
136 | 96 | return &model.SymbolPrice{
|
137 | 97 | Symbol: symbol,
|
138 |
| - Price: strconv.FormatFloat(respJSON.Ticker.Last, 'f', -1, 64), |
139 |
| - UpdateAt: time.Unix(respJSON.Date, 0), |
| 98 | + Price: strconv.FormatFloat(lastPrice, 'f', -1, 64), |
| 99 | + UpdateAt: updateAt, |
140 | 100 | Source: client.GetName(),
|
141 | 101 | PercentChange1h: percentChange1h,
|
142 | 102 | PercentChange24h: percentChange24h,
|
143 | 103 | }, nil
|
144 | 104 | }
|
145 | 105 |
|
| 106 | +// Check to see if we have error in the response |
| 107 | +func (client *okexClient) extractError(respByte []byte) error { |
| 108 | + errorMsg := gjson.GetBytes(respByte, "error_message") |
| 109 | + if !errorMsg.Exists() { |
| 110 | + errorMsg = gjson.GetBytes(respByte, "message") |
| 111 | + } |
| 112 | + if len(errorMsg.String()) != 0 { |
| 113 | + return errors.New(errorMsg.String()) |
| 114 | + } |
| 115 | + return nil |
| 116 | +} |
| 117 | + |
146 | 118 | func init() {
|
147 | 119 | model.Register(new(okexClient))
|
148 | 120 | }
|
0 commit comments