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 quote_payout(
122 &self,
123 symbol: &str,
124 option_type: OptionType,
125 expiration_seconds: u64,
126 amount: f64,
127 ) -> Result<PayoutQuote, BrokerError> {
128 self.runtime.block_on(self.nucleo.quote_payout(
129 symbol,
130 option_type,
131 expiration_seconds,
132 amount,
133 ))
134 }
135
136 pub fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError> {
137 self.runtime.block_on(self.nucleo.get_asset_profile(symbol))
138 }
139
140 pub fn get_technical_indicators(
141 &self,
142 symbol: &str,
143 ) -> Result<TechnicalIndicators, BrokerError> {
144 self.runtime
145 .block_on(self.nucleo.get_technical_indicators(symbol))
146 }
147
148 pub fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError> {
151 self.runtime
152 .block_on(self.nucleo.subscribe_live_deals(symbol))
153 }
154
155 pub fn subscribe_commission_changes(&self) -> Result<(), BrokerError> {
156 self.runtime
157 .block_on(self.nucleo.subscribe_commission_changes())
158 }
159
160 pub fn events(&self) -> Result<EventIter, BrokerError> {
162 let stream = self.runtime.block_on(self.nucleo.events())?;
163 let (tx, rx) = mpsc::sync_channel::<Event>(BUFFER_PUENTE);
164 self.runtime.spawn(puente_eventos(stream, tx));
165 Ok(EventIter { rx })
166 }
167
168 pub fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
171 self.runtime.block_on(self.nucleo.buy_binary(req))
172 }
173
174 pub fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError> {
175 self.runtime.block_on(self.nucleo.buy_digital_spot(req))
176 }
177
178 pub fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
179 self.runtime.block_on(self.nucleo.sell_option(order_id))
180 }
181
182 pub fn get_operation_result(&self, order_id: &OrderId) -> Result<OperationResult, BrokerError> {
183 self.runtime
184 .block_on(self.nucleo.get_operation_result(order_id))
185 }
186}
187
188pub struct CandleIter {
190 rx: Receiver<Result<Candle, BrokerError>>,
191}
192
193impl Iterator for CandleIter {
194 type Item = Result<Candle, BrokerError>;
195
196 fn next(&mut self) -> Option<Self::Item> {
197 match self.rx.recv_timeout(TIMEOUT_ITER) {
198 Ok(item) => Some(item),
199 Err(RecvTimeoutError::Timeout) => None,
200 Err(RecvTimeoutError::Disconnected) => None,
201 }
202 }
203}
204
205pub struct EventIter {
207 rx: Receiver<Event>,
208}
209
210impl Iterator for EventIter {
211 type Item = Event;
212
213 fn next(&mut self) -> Option<Self::Item> {
214 self.rx.recv_timeout(TIMEOUT_ITER).ok()
215 }
216}
217
218async fn puente_stream(
220 mut stream: crate::broker::trait_::CandleStream,
221 tx: mpsc::SyncSender<Result<Candle, BrokerError>>,
222) {
223 use futures_util::StreamExt;
224 while let Some(item) = stream.next().await {
225 if tx.send(item).is_err() {
226 break;
227 }
228 }
229}
230
231async fn puente_eventos(
233 mut stream: crate::broker::trait_::EventStream,
234 tx: mpsc::SyncSender<Event>,
235) {
236 use futures_util::StreamExt;
237 while let Some(ev) = stream.next().await {
238 if tx.send(ev).is_err() {
239 break;
240 }
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn iteradores_terminan_sin_stream() {
250 let (_tx, rx) = mpsc::sync_channel::<Event>(1);
252 let it = EventIter { rx };
253 assert!(it.into_iter().next().is_none());
254 }
255}