redgold 0.1.23

p2p database / compute engine & portfolio target models
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
use std::time::Duration;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use redgold_schema::{EasyJson, EasyJsonDeser, error_info, ErrorInfoContext, RgResult, SafeOption};
use redgold_schema::errors::EnhanceErrorInfo;
use redgold_schema::structs::SupportedCurrency;
use crate::util;
use crate::util::{current_time_millis_i64, current_time_unix};


// "https://api.coinbase.com/v2/exchange-rates?currency=BTC".to_string();


/*
[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quote_qty": "48.000012",
    "time": 1499865549590,
    "is_buyer_maker": true,
    "is_best_match": true
  }
]

 */
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BinanceTradesResponse {
    id: u64,
    price: String,
    qty: String,
    quote_qty: String,
    time: u64,
    is_buyer_maker: bool,
    is_best_match: bool,
}

pub async fn binance_trades_recent() -> RgResult<Vec<BinanceTradesResponse>> {

    let url = "https://api.binance.us/api/v3/trades";

    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .query(&[("symbol", "BTCUSD")])
        .send();
    let response = sent.await;
    match response {
        Ok(r) => {
            let text = r.text().await
                .map_err(|e| error_info(format!("{} {}", "Failed to get response text ", e.to_string())))?;
            println!("Response text: {}", text.clone());
            let resp = serde_json::from_str::<Vec<BinanceTradesResponse>>(&*text.clone())
                .map_err(|e| error_info(format!("{} {}", e.to_string(), text)))?;
            Ok(resp)
        },
        Err(e) => Err(error_info(e.to_string())),
    }
}


/*

Kline/Candlestick chart intervals:

s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months

1s 1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M

`GET /api/v3/klines`

Kline/candlestick bars for a symbol.
Klines are uniquely identified by their open time.

**Weight(IP):** 2

**Parameters:**

|Name|Type|Mandatory|Description|
|---|---|---|---|
|symbol|STRING|YES||
|interval|ENUM|YES||
|startTime|LONG|NO||
|endTime|LONG|NO||
|timeZone|STRING|NO|Default: 0 (UTC)|
|limit|INT|NO|Default 500; max 1000.|

- If startTime and endTime are not sent, the most recent klines are returned.
- Supported values for `timeZone`:
    - Hours and minutes (e.g. `-1:00`, `05:45`)
    - Only hours (e.g. `0`, `8`, `4`)
    - Accepted range is strictly [-12:00 to +14:00] inclusive
- If `timeZone` provided, kline intervals are interpreted in that timezone instead of UTC.
- Note that `startTime` and `endTime` are always interpreted in UTC, regardless of `timeZone`.

**Data Source:** Database
 */


/*
Doesn't seem to work for new data, 6 months out of date FOR binance.US
// for binance.com, banned in some countries.
// does seem to work if you access from the website for historical data.
 */
pub async fn binance_klines_historical(
    start_time: u64, interval: String
) -> RgResult<()> {

    let url = "https://api.binance.com/api/v3/klines";

    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .query(&[
            ("symbol", "BTCUSD"),
            ("interval", &*interval),
            // ("startTime", &*start_time.to_string()),
            // ("endTime", &*end_time.to_string()),
            // ("limit", &*limit.to_string())
        ])
        .send();
    let response = sent.await.error_info("Failed to get response")?;
    let text = response.text().await.error_info("Failed to get response text")?;
    println!("Response text: {}", text.clone());
    Ok(())
}

#[ignore]
#[tokio::test]
async fn test_binance_klines_historical() {
    let t = util::current_time_millis() - 1000*3600*24; // 1 hour ago
    println!("t: {}", t);
    // 1709607936485
    // let t = 1689273600000;
    // let t = 1709676464727;
    // let start_time = t;
    // let end_time = t + 1000*600;
    let interval = "1d".to_string();
    // let limit = 100;
    let r = binance_klines_historical(t, interval).await;
    assert!(r.is_ok());
}

/*
[
  {
    "a": 26129,         // Aggregate tradeId
    "p": "0.01633102",  // Price
    "q": "4.70443515",  // Quantity
    "f": 27781,         // First tradeId
    "l": 27781,         // Last tradeId
    "T": 1498793709153, // Timestamp
    "m": true,          // Was the buyer the maker?
    "M": true           // Was the trade the best price match?
  }
]
 */
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BinanceAggTradesResponse {
    a: u64,
    p: String,
    q: String,
    f: u64,
    l: u64,
    t: u64,
    m: bool,
    M: bool,
}

pub async fn binance_trades_aggregate() -> RgResult<Vec<BinanceAggTradesResponse>> {

    let neg_offset = 1000*5*24;
    let window_dur = 1000*60;
    let ct = util::current_time_millis();
    let end_time = ct - neg_offset;
    let start_time = end_time - window_dur;


    let url = "https://api.binance.us/api/v3/aggTrades";

    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .query(&[("symbol", "BTCUSD")])
        .query(&[("startTime", &*start_time.to_string())])
        .query(&[("endTime", &*end_time.to_string())])
        .send();
    let response = sent.await;
    match response {
        Ok(r) => {
            let text = r.text().await
                .map_err(|e| error_info(format!("{} {}", "Failed to get response text ", e.to_string())))?;
            println!("Response text: {}", text.clone());
            let resp = serde_json::from_str::<Vec<BinanceAggTradesResponse>>(&*text.clone())
                .map_err(|e| error_info(format!("{} {}", e.to_string(), text)))?;
            Ok(resp)
        },
        Err(e) => Err(error_info(e.to_string())),
    }
}


#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CoinbaseBtcSpotLatestData {
    amount: String,
    currency: String
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CoinbaseBtcSpotLatest {
    data: CoinbaseBtcSpotLatestData,
}

impl CoinbaseBtcSpotLatest {
    pub fn usd_btc(&self) -> RgResult<f64> {
        let amt = self.data.amount.parse::<f64>()
            .map_err(|e| error_info(format!("{} {}", "Failed to parse amount ", e.to_string())))?;
        Ok(amt)
    }
}


// https://api.coinbase.com/v2/prices/BTC-USD/spot
pub async fn coinbase_btc_spot_latest() -> RgResult<CoinbaseBtcSpotLatest> {

    let url = "https://api.coinbase.com/v2/prices/BTC-USD/spot";

    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .send();
    let response = sent.await;
    match response {
        Ok(r) => {
            let text = r.text().await
                .map_err(|e| error_info(format!("{} {}", "Failed to get response text ", e.to_string())))?;
            println!("Response text: {}", text.clone());
            let resp = serde_json::from_str::<CoinbaseBtcSpotLatest>(&*text.clone())
                .map_err(|e| error_info(format!("{} {}", e.to_string(), text)))?;
            Ok(resp)
        },
        Err(e) => Err(error_info(e.to_string())),
    }
}


#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CoinbaseHistoricalDataResponse {
    data: CoinbaseHistoricalData

}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CoinbaseHistoricalData {
    base: String,
    currency: String,
    prices: Vec<CoinbasePriceTime>
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CoinbasePriceTime {
    price: String,
    time: String
}

impl CoinbasePriceTime {
    pub fn price_f64(&self) -> RgResult<f64> {
        self.price.parse::<f64>()
            .error_info(format!("Failed to parse price {}", self.price))
    }
    pub fn time_i64(&self) -> RgResult<i64> {
        self.time.parse::<i64>()
            .error_info(format!("Failed to parse time {}", self.time))
    }
}


/*
Doesn't work
 */
// https://api.coinbase.com/v2/prices/BTC-USD/spot
pub async fn coinbase_historical(
    time: i64, supported_currency: SupportedCurrency
) -> RgResult<CoinbasePriceTime> {
    let product = translate_currency(supported_currency)?;
    let granularity = 3600;

    let url =
        format!(
            "https://api.coinbase.com/v2/prices/{}/historic?start={}&end={}granularity={}",
            product, time, time, granularity
        );
    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .send();
    let response = sent.await.error_info("Failed to get response")?;
    let text = response.text().await.error_info("Failed to get response text")?;
    // println!("Response text: {}", text.clone());
    let resp = text.json_from::<CoinbaseHistoricalDataResponse>()?;
    resp.data.prices.iter().filter_map(|a|
        a.time_i64().ok().map(|b| ((time - b).abs(), a))
    ).min_by(|a, b| a.0.cmp(&b.0))
        .map(|a| a.1)
        .cloned().ok_msg("Failed to find min").add(text)
}

fn translate_currency(supported_currency: SupportedCurrency) -> RgResult<String> {
    let product = match supported_currency {
        SupportedCurrency::Bitcoin => {
            "BTC-USD"
        },
        SupportedCurrency::Ethereum => {
            "ETH-USD"
        },
        _ => {
            return Err(error_info("Unsupported currency for coinbase historical data".to_string()));
        }
    };
    Ok(product.to_string())
}


/*
Get index candlesticks history
Retrieve the candlestick charts of the index from recent years.

Rate Limit: 10 requests per 2 seconds
Rate limit rule: IP
HTTP Request
GET /api/v5/market/history-index-candles

Request Example

GET /api/v5/market/history-index-candles?instId=BTC-USD
Request Parameters
Parameter	Type	Required	Description
instId	String	Yes	Index, e.g. BTC-USD
after	String	No	Pagination of data to return records earlier than the requested ts
before	String	No	Pagination of data to return records newer than the requested ts. The latest data will be returned when using before individually
bar	String	No	Bar size, the default is 1m
e.g. [1m/3m/5m/15m/30m/1H/2H/4H]
Hong Kong time opening price k-line: [6H/12H/1D/1W/1M]
UTC time opening price k-line: [/6Hutc/12Hutc/1Dutc/1Wutc/1Mutc]
limit	String	No	Number of results per request. The maximum is 100; The default is 100
 */

pub async fn okx_historical_test(before: Option<i64>, after: i64, currency: SupportedCurrency) -> RgResult<Vec<OkxParsedRow>> {
    let url = "https://www.okx.com/api/v5/market/history-index-candles";

    // Default to previous ten minutes.
    let before = before.unwrap_or(after- 1000*60*10);

    let product = translate_currency(currency)?;

    use reqwest::ClientBuilder;
    let client = ClientBuilder::new().timeout(Duration::from_secs(10)).build().unwrap();
    let sent = client
        .get(url)
        .query(&[
            ("instId", &*product),
            ("before", &*before.to_string()),
            ("after", &*after.to_string()),
            // ("bar", "1d"),
            // ("limit", "100")
        ])
        .send();
    let response = sent.await.error_info("Failed to get response")?;
    let text = response.text().await.error_info("Failed to get response text")?;
    // println!("Response text: {}", text.clone());
    let res = text.json_from::<OkxHistoricalResponse>()?.data()?;
    if res.len() == 0 {
        return Err(error_info("No data found in response")).add(text)
    }
    let res = res.iter()
        .filter(|a| a.confirmed)
        .map(|a| a.clone()).collect_vec();
    if res.len() == 0 {
        return Err(error_info("No confirmed data found in response")).add(text)
    }
    Ok(res)

}



/**
Get the closest point to the given time from OKX for the supported product type
This returns OHLC candlestick data for the previous closest time to the given time.

It has an accuracy of roughly 1 minute, and returns a 1 minute candlestick. Appears to be stable
going back at least a year, and is likely to be stable for the foreseeable future.

This is the only function tested in here that works properly over long time series.
 */
pub async fn okx_point(time: i64, supported_currency: SupportedCurrency) -> RgResult<OkxParsedRow> {
    let res = okx_historical_test(None, time, supported_currency).await?;
    res.iter()
        .map(|r| ((time - r.time).abs(), r))
        .min_by(|a, b| a.0.cmp(&b.0))
        .map(|a| a.1).cloned().ok_msg("No data found")

}

#[derive(Clone, Serialize, Deserialize)]
struct OkxHistoricalResponse {
    code: String,
    msg: String,
    data: Vec<Vec<String>>
}

#[derive(Clone, Serialize, Deserialize)]
pub struct OkxParsedRow {
    time: i64,
    open: f64,
    high: f64,
    low: f64,
    close: f64,
    confirmed: bool
}


impl OkxHistoricalResponse {
    pub fn parse(row: &Vec<String>) -> RgResult<OkxParsedRow> {
        let time = row.get(0).ok_or(error_info("Failed to get time"))?;
        let open = row.get(1).ok_or(error_info("Failed to get open"))?;
        let high = row.get(2).ok_or(error_info("Failed to get high"))?;
        let low = row.get(3).ok_or(error_info("Failed to get low"))?;
        let close = row.get(4).ok_or(error_info("Failed to get close"))?;
        let confirmed = row.get(5).ok_or(error_info("Failed to get confirmed"))?;
        Ok(OkxParsedRow {
            time: time.parse::<i64>().error_info("Failed to parse time")?,
            open: open.parse::<f64>().error_info("Failed to parse open")?,
            high: high.parse::<f64>().error_info("Failed to parse high")?,
            low: low.parse::<f64>().error_info("Failed to parse low")?,
            close: close.parse::<f64>().error_info("Failed to parse close")?,
            confirmed: confirmed == "1"
        })
    }
    pub fn data(&self) -> RgResult<Vec<OkxParsedRow>> {
        self.data.iter().map(|row| Self::parse(row)).collect()
    }
}


#[ignore]
#[tokio::test]
async fn okx_debug_routes() {
    // let c = coinbase_btc_spot_latest().await.unwrap();
    // println!("{}", c.json_or());
    // let start = current_time_millis_i64() - 1000*60*60*24*1;
    // let end = start + 60*10*1000;
    // let res = okx_historical_test(Some(start), end, SupportedCurrency::Bitcoin).await.unwrap();
    // for x in res {
    //     let delta = end - x.time;
    //     println!("delta {} json {}", delta, x.json_or());
    // }

    let start = current_time_millis_i64() - 1000*60*5;
    for i in 500..510 {
        let t = start - i*1000*60*60*24;
        let c = okx_point(t, SupportedCurrency::Bitcoin).await.unwrap();
        let delta = (t- c.time).abs();
        let price = c.open.clone();
        println!("{} {} {}", t, delta, price);

    }
}

#[ignore]
#[tokio::test]
async fn debug_routes() {
    // let c = coinbase_btc_spot_latest().await.unwrap();
    // println!("{}", c.json_or());
    let start = current_time_unix() as i64;
    for i in 0..20 {
        let t = start - i*60*60*24;
        let c = coinbase_historical(t, SupportedCurrency::Bitcoin).await.unwrap();
        let delta = (t- c.time_i64().unwrap()).abs();
        let price = c.price.clone();
        println!("{} {} {}", t, delta, price);

    }
}