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};
#[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())),
}
}
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),
])
.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; println!("t: {}", t);
let interval = "1d".to_string();
let r = binance_klines_historical(t, interval).await;
assert!(r.is_ok());
}
#[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)
}
}
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))
}
}
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")?;
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())
}
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";
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()),
])
.send();
let response = sent.await.error_info("Failed to get response")?;
let text = response.text().await.error_info("Failed to get response text")?;
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)
}
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 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 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);
}
}