|
| 1 | +package fiat |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/shopspring/decimal" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + coinbaseHistoryAPI = "https://api.exchange.coinbase.com/products/%s/candles" |
| 16 | + coinbaseDefaultPair = "BTC-USD" |
| 17 | + coinbaseCandleCap = 300 // max buckets. |
| 18 | + coinbaseGranHourSec = 3600 // 1‑hour buckets. |
| 19 | + coinbaseGranDaySec = 86400 // 1‑day buckets. |
| 20 | + coinbaseDefaultCurr = "USD" |
| 21 | +) |
| 22 | + |
| 23 | +type coinbaseAPI struct { |
| 24 | + // granularity is the price granularity (must be GranularityHour or |
| 25 | + // GranularityDay for coinbase). |
| 26 | + granularity Granularity |
| 27 | + |
| 28 | + // product is the Coinbase product pair (e.g. BTC-USD). |
| 29 | + product string |
| 30 | + |
| 31 | + // client is the HTTP client used to make requests. |
| 32 | + client *http.Client |
| 33 | +} |
| 34 | + |
| 35 | +// newCoinbaseAPI returns an implementation that satisfies fiatBackend. |
| 36 | +func newCoinbaseAPI(g Granularity) *coinbaseAPI { |
| 37 | + return &coinbaseAPI{ |
| 38 | + granularity: g, |
| 39 | + product: coinbaseDefaultPair, |
| 40 | + client: &http.Client{ |
| 41 | + Timeout: 10 * time.Second, |
| 42 | + }, |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// queryCoinbase performs one HTTP request for a single <300‑bucket window. |
| 47 | +func queryCoinbase(start, end time.Time, product string, |
| 48 | + g Granularity, cl *http.Client) ([]byte, error) { |
| 49 | + |
| 50 | + url := fmt.Sprintf(coinbaseHistoryAPI, product) + |
| 51 | + fmt.Sprintf("?start=%s&end=%s&granularity=%d", |
| 52 | + start.Format(time.RFC3339), |
| 53 | + end.Format(time.RFC3339), |
| 54 | + int(g.aggregation.Seconds())) |
| 55 | + |
| 56 | + // #nosec G107 – public data |
| 57 | + resp, err := cl.Get(url) |
| 58 | + if err != nil { |
| 59 | + return nil, err |
| 60 | + } |
| 61 | + defer resp.Body.Close() |
| 62 | + |
| 63 | + return io.ReadAll(resp.Body) |
| 64 | +} |
| 65 | + |
| 66 | +// parseCoinbaseData parses the JSON response from Coinbase's candles endpoint. |
| 67 | +// |
| 68 | +// Coinbase “product candles” endpoint |
| 69 | +// |
| 70 | +// GET https://api.exchange.coinbase.com/products/<product‑id>/candles |
| 71 | +// |
| 72 | +// Response body ─ array of fixed‑width arrays: |
| 73 | +// |
| 74 | +// [ |
| 75 | +// [ time, low, high, open, close, volume ], |
| 76 | +// ... |
| 77 | +// ] |
| 78 | +// |
| 79 | +// Field meanings (per Coinbase docs [1]): |
| 80 | +// - time – UNIX epoch **seconds** marking the *start* of the bucket (UTC). |
| 81 | +// - low – lowest trade price during the bucket interval. |
| 82 | +// - high – highest trade price during the bucket interval. |
| 83 | +// - open – price of the first trade in the interval. |
| 84 | +// - close – price of the last trade in the interval. |
| 85 | +// - volume – amount of the base‑asset traded during the interval. |
| 86 | +// |
| 87 | +// Additional quirks |
| 88 | +// - Candles are returned in *reverse‑chronological* order (newest‑first). |
| 89 | +// - `granularity` must be one of 60, 300, 900, 3600, 21600, 86400 seconds. |
| 90 | +// - A single request can return at most 300 buckets; larger spans must be |
| 91 | +// paged by adjusting `start`/`end` query parameters. |
| 92 | +// |
| 93 | +// Example (1‑hour granularity, newest‑first): |
| 94 | +// |
| 95 | +// [ |
| 96 | +// [1714632000, 64950.12, 65080.00, 65010.55, 65075.00, 84.213], |
| 97 | +// [1714628400, 64890.00, 65020.23, 64900.00, 64950.12, 92.441], |
| 98 | +// ... |
| 99 | +// ] |
| 100 | +// |
| 101 | +// [1] https://docs.cdp.coinbase.com/exchange/reference/exchangerestapi_getproductcandles |
| 102 | +func parseCoinbaseData(data []byte) ([]*Price, error) { |
| 103 | + var raw [][]float64 |
| 104 | + if err := json.Unmarshal(data, &raw); err != nil { |
| 105 | + return nil, err |
| 106 | + } |
| 107 | + |
| 108 | + prices := make([]*Price, 0, len(raw)) |
| 109 | + for _, c := range raw { |
| 110 | + // Historical rate data may be incomplete. No data is published |
| 111 | + // for intervals where there are no ticks. |
| 112 | + if len(c) < 5 { |
| 113 | + continue |
| 114 | + } |
| 115 | + ts := time.Unix(int64(c[0]), 0).UTC() |
| 116 | + closePx := decimal.NewFromFloat(c[4]) |
| 117 | + |
| 118 | + prices = append(prices, &Price{ |
| 119 | + Timestamp: ts, |
| 120 | + Price: closePx, |
| 121 | + Currency: coinbaseDefaultCurr, |
| 122 | + }) |
| 123 | + } |
| 124 | + return prices, nil |
| 125 | +} |
| 126 | + |
| 127 | +// rawPriceData satisfies the fiatBackend interface. |
| 128 | +func (c *coinbaseAPI) rawPriceData(ctx context.Context, |
| 129 | + startTime, endTime time.Time) ([]*Price, error) { |
| 130 | + |
| 131 | + // Coinbase cap = 300 * granularity. |
| 132 | + chunk := c.granularity.aggregation * coinbaseCandleCap |
| 133 | + start := startTime.Truncate(c.granularity.aggregation) |
| 134 | + end := start.Add(chunk) |
| 135 | + if end.After(endTime) { |
| 136 | + end = endTime |
| 137 | + } |
| 138 | + |
| 139 | + var all []*Price |
| 140 | + for start.Before(endTime) { |
| 141 | + query := func() ([]byte, error) { |
| 142 | + return queryCoinbase( |
| 143 | + start, end, c.product, c.granularity, c.client, |
| 144 | + ) |
| 145 | + } |
| 146 | + |
| 147 | + records, err := retryQuery(ctx, query, parseCoinbaseData) |
| 148 | + if err != nil { |
| 149 | + return nil, err |
| 150 | + } |
| 151 | + all = append(all, records...) |
| 152 | + |
| 153 | + start = end |
| 154 | + end = start.Add(chunk) |
| 155 | + if end.After(endTime) { |
| 156 | + end = endTime |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + return all, nil |
| 161 | +} |
0 commit comments