cripsy_binary_api/broker/
sync.rs1use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
16use std::time::Duration;
17
18use crate::broker::config::BrokerParams;
19use crate::broker::error::BrokerError;
20use crate::broker::iq_option::session::IqOptionBroker;
21use crate::broker::session::Session;
22use crate::broker::trait_::Broker;
23use crate::domain::*;
24
25const BUFFER_PUENTE: usize = 1024;
27
28const TIMEOUT_ITER: Duration = Duration::from_secs(30);
30
31pub struct SyncBroker {
33 runtime: tokio::runtime::Runtime,
34 nucleo: IqOptionBroker,
35}
36
37impl SyncBroker {
38 pub fn connect(params: BrokerParams) -> Result<Self, BrokerError> {
40 let runtime = tokio::runtime::Builder::new_multi_thread()
41 .enable_all()
42 .build()
43 .map_err(|e| BrokerError::Internal(format!("no se pudo crear el runtime: {e}")))?;
44 let nucleo = runtime.block_on(IqOptionBroker::nuevo(params))?;
45 Ok(Self { runtime, nucleo })
46 }
47
48 pub fn async_core(&self) -> &IqOptionBroker {
50 &self.nucleo
51 }
52
53 pub fn session(&self) -> Result<Session, BrokerError> {
56 self.runtime.block_on(self.nucleo.session())
57 }
58
59 pub fn is_connected(&self) -> bool {
60 self.runtime.block_on(self.nucleo.is_connected())
61 }
62
63 pub fn disconnect(&mut self) -> Result<(), BrokerError> {
64 self.runtime.block_on(self.nucleo.disconnect())
65 }
66
67 pub fn get_balance(&self) -> Result<Balance, BrokerError> {
68 self.runtime.block_on(self.nucleo.get_balance())
69 }
70
71 pub fn get_account_type(&self) -> Result<AccountType, BrokerError> {
72 self.runtime.block_on(self.nucleo.get_account_type())
73 }
74
75 pub fn switch_account(&mut self, kind: AccountType) -> Result<(), BrokerError> {
76 self.runtime.block_on(self.nucleo.switch_account(kind))
77 }
78
79 pub fn list_assets(&self) -> Result<Vec<Asset>, BrokerError> {
82 self.runtime.block_on(self.nucleo.list_assets())
83 }
84
85 pub fn asset_status(&self, symbol: &str) -> Result<MarketStatus, BrokerError> {
86 self.runtime.block_on(self.nucleo.asset_status(symbol))
87 }
88
89 pub fn get_candles(&self, req: CandleRequest) -> Result<Vec<Candle>, BrokerError> {
92 self.runtime.block_on(self.nucleo.get_candles(req))
93 }
94
95 pub fn subscribe_candles(&self, req: CandleSubscribe) -> Result<CandleIter, BrokerError> {
97 let stream = self.runtime.block_on(self.nucleo.subscribe_candles(req))?;
98 let (tx, rx) = mpsc::sync_channel::<Result<Candle, BrokerError>>(BUFFER_PUENTE);
99 self.runtime.spawn(puente_stream(stream, tx));
100 Ok(CandleIter { rx })
101 }
102
103 pub fn get_position_history(
106 &self,
107 symbol: Option<&str>,
108 limit: usize,
109 offset: usize,
110 ) -> Result<PositionHistory, BrokerError> {
111 self.runtime
112 .block_on(self.nucleo.get_position_history(symbol, limit, offset))
113 }
114
115 pub fn get_payout(&self, symbol: &str, expiration_seconds: u64) -> Result<Payout, BrokerError> {
116 self.runtime
117 .block_on(self.nucleo.get_payout(symbol, expiration_seconds))
118 }
119
120 pub fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError> {
121 self.runtime.block_on(self.nucleo.get_asset_profile(symbol))
122 }
123
124 pub fn get_technical_indicators(
125 &self,
126 symbol: &str,
127 ) -> Result<TechnicalIndicators, BrokerError> {
128 self.runtime
129 .block_on(self.nucleo.get_technical_indicators(symbol))
130 }
131
132 pub fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError> {
135 self.runtime
136 .block_on(self.nucleo.subscribe_live_deals(symbol))
137 }
138
139 pub fn subscribe_commission_changes(&self) -> Result<(), BrokerError> {
140 self.runtime
141 .block_on(self.nucleo.subscribe_commission_changes())
142 }
143
144 pub fn events(&self) -> Result<EventIter, BrokerError> {
146 let stream = self.runtime.block_on(self.nucleo.events())?;
147 let (tx, rx) = mpsc::sync_channel::<Event>(BUFFER_PUENTE);
148 self.runtime.spawn(puente_eventos(stream, tx));
149 Ok(EventIter { rx })
150 }
151
152 pub fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
155 self.runtime.block_on(self.nucleo.buy_binary(req))
156 }
157
158 pub fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError> {
159 self.runtime.block_on(self.nucleo.buy_digital_spot(req))
160 }
161
162 pub fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
163 self.runtime.block_on(self.nucleo.sell_option(order_id))
164 }
165
166 pub fn get_operation_result(&self, order_id: &OrderId) -> Result<OperationResult, BrokerError> {
167 self.runtime
168 .block_on(self.nucleo.get_operation_result(order_id))
169 }
170}
171
172pub struct CandleIter {
174 rx: Receiver<Result<Candle, BrokerError>>,
175}
176
177impl Iterator for CandleIter {
178 type Item = Result<Candle, BrokerError>;
179
180 fn next(&mut self) -> Option<Self::Item> {
181 match self.rx.recv_timeout(TIMEOUT_ITER) {
182 Ok(item) => Some(item),
183 Err(RecvTimeoutError::Timeout) => None,
184 Err(RecvTimeoutError::Disconnected) => None,
185 }
186 }
187}
188
189pub struct EventIter {
191 rx: Receiver<Event>,
192}
193
194impl Iterator for EventIter {
195 type Item = Event;
196
197 fn next(&mut self) -> Option<Self::Item> {
198 self.rx.recv_timeout(TIMEOUT_ITER).ok()
199 }
200}
201
202async fn puente_stream(
204 mut stream: crate::broker::trait_::CandleStream,
205 tx: mpsc::SyncSender<Result<Candle, BrokerError>>,
206) {
207 use futures_util::StreamExt;
208 while let Some(item) = stream.next().await {
209 if tx.send(item).is_err() {
210 break;
211 }
212 }
213}
214
215async fn puente_eventos(
217 mut stream: crate::broker::trait_::EventStream,
218 tx: mpsc::SyncSender<Event>,
219) {
220 use futures_util::StreamExt;
221 while let Some(ev) = stream.next().await {
222 if tx.send(ev).is_err() {
223 break;
224 }
225 }
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231
232 #[test]
233 fn iteradores_terminan_sin_stream() {
234 let (_tx, rx) = mpsc::sync_channel::<Event>(1);
236 let it = EventIter { rx };
237 assert!(it.into_iter().next().is_none());
238 }
239}