47 lines
1.4 KiB
Rust
47 lines
1.4 KiB
Rust
use super::{AssetMPSC, StockStreamSubscription};
|
|
use crate::{
|
|
database::assets::get_assets_stocks,
|
|
pool::{alpaca::create_alpaca_client_from_env, postgres::PostgresPool},
|
|
};
|
|
use apca::data::v2::stream::{
|
|
drive, Bar, MarketData, Quote, RealtimeData, SymbolList, Symbols, Trade, IEX,
|
|
};
|
|
use futures_util::FutureExt;
|
|
use std::{error::Error, sync::Arc};
|
|
use tokio::sync::{mpsc, Mutex};
|
|
|
|
pub async fn init_stream_subscription_mpsc(
|
|
postgres_pool: PostgresPool,
|
|
) -> Result<(Arc<Mutex<StockStreamSubscription<IEX>>>, AssetMPSC), Box<dyn Error + Send + Sync>> {
|
|
let client = create_alpaca_client_from_env().await?;
|
|
|
|
let (mut stream, mut subscription) = client
|
|
.subscribe::<RealtimeData<IEX, Bar, Quote, Trade>>()
|
|
.await?;
|
|
|
|
let symbols = get_assets_stocks(&postgres_pool)
|
|
.await?
|
|
.iter()
|
|
.map(|asset| asset.symbol.clone())
|
|
.collect::<Vec<String>>();
|
|
|
|
if !symbols.is_empty() {
|
|
let data = MarketData {
|
|
bars: Symbols::List(SymbolList::from(symbols)),
|
|
..Default::default()
|
|
};
|
|
|
|
drive(subscription.subscribe(&data).boxed(), &mut stream)
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
.unwrap();
|
|
}
|
|
|
|
let stream_subscription_mutex = Arc::new(Mutex::new((stream, subscription)));
|
|
let (sender, receiver) = mpsc::channel(50);
|
|
let asset_mpcs = AssetMPSC { sender, receiver };
|
|
|
|
Ok((stream_subscription_mutex, asset_mpcs))
|
|
}
|