|
| 1 | +package upbit |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "log/slog" |
| 8 | + "math/big" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/google/uuid" |
| 12 | + "github.com/nbitslabs/nOracle/pkg/connector" |
| 13 | + "github.com/nbitslabs/nOracle/pkg/utils/ticker" |
| 14 | + "github.com/recws-org/recws" |
| 15 | +) |
| 16 | + |
| 17 | +func NewConnector(ctx context.Context, wsUrl string, pairs []string) (connector.ExchangeConnector, error) { |
| 18 | + if wsUrl == "" { |
| 19 | + return nil, fmt.Errorf("wsUrl is required") |
| 20 | + } |
| 21 | + if len(pairs) == 0 { |
| 22 | + return nil, fmt.Errorf("pairs are required") |
| 23 | + } |
| 24 | + |
| 25 | + wsUrlWithChannels := fmt.Sprintf("%s/ws/v5/public", wsUrl) |
| 26 | + ws := &recws.RecConn{ |
| 27 | + KeepAliveTimeout: 10 * time.Second, |
| 28 | + } |
| 29 | + ws.Dial(wsUrlWithChannels, nil) |
| 30 | + |
| 31 | + req := []map[string]interface{}{ |
| 32 | + {"ticket": uuid.NewString()}, |
| 33 | + {"type": "ticker", "codes": pairs, "isOnlyRealtime": true}, |
| 34 | + {"format": "DEFAULT"}, |
| 35 | + } |
| 36 | + |
| 37 | + if err := ws.WriteJSON(req); err != nil { |
| 38 | + return nil, err |
| 39 | + } |
| 40 | + |
| 41 | + return &Connector{ |
| 42 | + ctx: ctx, |
| 43 | + pairs: pairs, |
| 44 | + ws: ws, |
| 45 | + }, nil |
| 46 | +} |
| 47 | + |
| 48 | +func (c *Connector) Close() error { |
| 49 | + if c.ctx != nil { |
| 50 | + c.ctx.Done() |
| 51 | + } |
| 52 | + if c.ws != nil { |
| 53 | + c.ws.Close() |
| 54 | + } |
| 55 | + |
| 56 | + return nil |
| 57 | +} |
| 58 | + |
| 59 | +func (c *Connector) StreamTickers(ctx context.Context, out chan<- connector.TickerUpdate) error { |
| 60 | + go func() { |
| 61 | + for { |
| 62 | + select { |
| 63 | + case <-ctx.Done(): |
| 64 | + return |
| 65 | + default: |
| 66 | + _, message, err := c.ws.ReadMessage() |
| 67 | + if err != nil { |
| 68 | + slog.Warn("error reading message", "error", err, "exchange", Name) |
| 69 | + continue |
| 70 | + } |
| 71 | + |
| 72 | + var tickerResponse TickerResponse |
| 73 | + if err := json.Unmarshal(message, &tickerResponse); err != nil { |
| 74 | + fmt.Println(string(message)) |
| 75 | + slog.Warn("error unmarshalling message", "error", err, "exchange", Name) |
| 76 | + continue |
| 77 | + } |
| 78 | + |
| 79 | + out <- connector.TickerUpdate{ |
| 80 | + Exchange: Name, |
| 81 | + Symbol: ticker.UpbitToStandardTicker(tickerResponse.Code), |
| 82 | + Price: big.NewFloat(tickerResponse.TradePrice), |
| 83 | + Volume: big.NewFloat(tickerResponse.TradeVolume), |
| 84 | + Timestamp: tickerResponse.TradeTimestamp, |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + }() |
| 89 | + |
| 90 | + return nil |
| 91 | +} |
| 92 | + |
| 93 | +func (c *Connector) Name() string { |
| 94 | + return Name |
| 95 | +} |
| 96 | + |
| 97 | +func (c *Connector) Tickers() []string { |
| 98 | + return c.pairs |
| 99 | +} |
0 commit comments