use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bar {
pub time: u64,
pub low: f64,
pub high: f64,
pub open: f64,
pub close: f64,
}
#[derive(Clone)]
pub struct Handler {
pub id: String,
pub callback: mpsc::UnboundedSender<Bar>,
}
#[derive(Clone)]
pub struct Subscription {
pub subscriber_uid: String,
pub resolution: String,
pub last_daily_bar: Bar,
pub handlers: Vec<Handler>,
}
pub type Subscriptions = Arc<Mutex<HashMap<String, Subscription>>>;
pub type LastBarsCache = Arc<Mutex<HashMap<String, Bar>>>;
#[derive(Clone, Debug)]
pub struct SymbolInfo {
pub ticker: String,
}
#[derive(Clone, Debug)]
pub struct PeriodParams {
pub from: u64,
pub to: u64,
pub first_data_request: bool,
}
#[derive(Debug, Deserialize, Clone)]
pub(crate) struct StreamData {
pub id: String,
pub p: f64,
pub t: u64,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(untagged)]
pub(crate) enum StreamMessage {
Data(StreamData),
HeartbeatOrId(i64),
Other(serde_json::Value),
}
#[derive(Deserialize, Debug)]
pub(crate) struct HistoryResponse {
pub t: Vec<u64>,
pub l: Vec<f64>,
pub h: Vec<f64>,
pub o: Vec<f64>,
pub c: Vec<f64>,
}
impl Bar {
pub fn new(time: u64, open: f64, high: f64, low: f64, close: f64) -> Self {
Self {
time,
open,
high,
low,
close,
}
}
pub fn update_with_price(&mut self, price: f64) {
self.high = self.high.max(price);
self.low = self.low.min(price);
self.close = price;
}
}
impl SymbolInfo {
pub fn new(ticker: impl Into<String>) -> Self {
Self {
ticker: ticker.into(),
}
}
}
impl PeriodParams {
pub fn new(from: u64, to: u64, first_data_request: bool) -> Self {
Self {
from,
to,
first_data_request,
}
}
pub fn last_days(days: u64, first_data_request: bool) -> Self {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
Self {
from: now - (days * 24 * 60 * 60),
to: now,
first_data_request,
}
}
}