use std::sync::Arc;
use digdigdig3::connector_manager::ExchangeHub;
use digdigdig3::core::types::{AccountType, ExchangeId, SymbolInput};
use digdigdig3::core::websocket::KlineInterval;
use crate::data::{BarPoint, TradePoint};
use crate::error::{Result, StationError};
pub async fn trades_recent(
hub: &Arc<ExchangeHub>,
exchange: ExchangeId,
account: AccountType,
symbol: &str,
limit: usize,
) -> Vec<TradePoint> {
let Some(rest) = hub.rest(exchange) else { return Vec::new(); };
let limit = limit.min(1000).max(1) as u32;
let res = rest
.get_recent_trades(SymbolInput::Raw(symbol), Some(limit), account)
.await;
match res {
Ok(trades) => trades.iter().map(TradePoint::from_public).collect(),
Err(e) => {
tracing::debug!(?e, exchange = ?exchange, "rest backfill trades failed");
Vec::new()
}
}
}
pub async fn fetch_history(
hub: &Arc<ExchangeHub>,
exchange: ExchangeId,
symbol: &str,
account_type: AccountType,
interval: &KlineInterval,
end_time_ms: i64,
limit: u16,
) -> Result<Vec<BarPoint>> {
let rest = hub
.rest(exchange)
.ok_or_else(|| StationError::Core(format!("{exchange:?} not connected in hub")))?;
let limit = limit.min(1000).max(1);
let bars = rest
.get_klines(
SymbolInput::Raw(symbol),
interval.as_str(),
Some(limit),
account_type,
Some(end_time_ms),
)
.await
.map_err(|e| StationError::Core(format!("get_klines failed: {e}")))?;
let mut points: Vec<BarPoint> = bars.iter().map(BarPoint::from_kline).collect();
points.sort_unstable_by_key(|p| p.open_time);
Ok(points)
}
pub async fn klines_recent(
hub: &Arc<ExchangeHub>,
exchange: ExchangeId,
account: AccountType,
symbol: &str,
interval: &str,
limit: usize,
) -> Vec<BarPoint> {
let Some(rest) = hub.rest(exchange) else { return Vec::new(); };
let limit = limit.min(1000).max(1) as u16;
let res = rest
.get_klines(
SymbolInput::Raw(symbol),
interval,
Some(limit),
account,
None,
)
.await;
match res {
Ok(bars) => bars.iter().map(BarPoint::from_kline).collect(),
Err(e) => {
tracing::debug!(?e, exchange = ?exchange, interval, "rest backfill klines failed");
Vec::new()
}
}
}