1use std::collections::{HashMap, HashSet};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::Arc;
11
12use serde_json::{json, Value};
13use tokio::sync::{broadcast, mpsc, Notify, RwLock};
14
15use crate::broker::config::{BrokerParams, IqOptionConfig};
16use crate::broker::error::BrokerError;
17use crate::broker::iq_option::endpoints::{self, msg};
18use crate::broker::iq_option::mapper;
19use crate::broker::session::Session;
20use crate::domain::*;
21use crate::transport::http::HttpClient;
22use crate::transport::router::RequestRouter;
23use crate::transport::websocket::WsClient;
24
25pub(crate) struct Saliente {
27 name: String,
28 msg: Value,
29 request_id: String,
30}
31
32#[derive(Debug, Clone)]
34pub(crate) struct Suscripcion {
35 pub(crate) clave: String,
36 pub(crate) name: String,
37 pub(crate) msg: Value,
38}
39
40const MOTIVO_CIERRE: &str = "cierre solicitado";
42
43fn registrar_suscripcion(
48 lista: &mut Vec<Suscripcion>,
49 clave: &str,
50 name: &str,
51 msg: &Value,
52) -> bool {
53 if lista.iter().any(|s| s.clave == clave) {
54 return false;
55 }
56 lista.push(Suscripcion {
57 clave: clave.to_string(),
58 name: name.to_string(),
59 msg: msg.clone(),
60 });
61 true
62}
63
64fn siguiente_espera(actual: u64, maximo: u64) -> u64 {
66 let techo = maximo.max(1);
67 actual.saturating_mul(2).clamp(1, techo)
68}
69
70fn es_fatal(e: &BrokerError) -> bool {
72 matches!(e, BrokerError::Authentication(_))
73}
74
75#[derive(Default)]
77pub(crate) struct Estado {
78 pub(crate) session: Option<Session>,
79 pub(crate) balances: Vec<AccountBalance>,
80 pub(crate) conectado: bool,
81}
82
83pub(crate) struct SubVelas {
85 pub(crate) symbol: String,
86 pub(crate) interval: u64,
87 pub(crate) tx: mpsc::UnboundedSender<Candle>,
88}
89
90pub struct IqOptionBroker {
92 config: IqOptionConfig,
93 salida: Option<mpsc::Sender<Saliente>>,
94 pub(crate) suscripciones: Arc<RwLock<Vec<Suscripcion>>>,
96 pub(crate) vivo: Arc<AtomicBool>,
98 pub(crate) cortar: Arc<Notify>,
100 pub(crate) abiertas: Arc<RwLock<HashSet<OrderId>>>,
102 pub(crate) router: Arc<RequestRouter>,
103 pub(crate) estado: Arc<RwLock<Estado>>,
104 pub(crate) catalogo: Arc<RwLock<Vec<Asset>>>,
105 pub(crate) sub_velas: Arc<RwLock<Vec<SubVelas>>>,
106 pub(crate) eventos: broadcast::Sender<Event>,
107 pub(crate) precios: broadcast::Sender<Value>,
109 pub(crate) resultados: Arc<RwLock<HashMap<String, OperationResult>>>,
111 pub(crate) digitales: Arc<RwLock<HashMap<String, OrderId>>>,
113}
114
115impl IqOptionBroker {
116 pub async fn nuevo(params: BrokerParams) -> Result<Self, BrokerError> {
118 let (config, cfg_trafico) = match params {
119 BrokerParams::IqOption(c) => (c.clone(), c.transport.clone()),
120 BrokerParams::Deriv(_) => {
121 return Err(BrokerError::Internal(
122 "iq_option: se esperaba BrokerParams::IqOption".into(),
123 ))
124 }
125 };
126
127 let http = HttpClient::new(
129 &endpoints::api_base_url(&config.auth_host),
130 cfg_trafico.clone(),
131 )?;
132 let (cuerpo, headers) = http
133 .post_json_completo(
134 endpoints::LOGIN_PATH.trim_start_matches('/'),
135 &json!({ "identifier": config.email, "password": config.password }),
136 )
137 .await?;
138 let ssid = extraer_ssid(&headers, &cuerpo).ok_or_else(|| {
139 BrokerError::Authentication("el login no devolvió cookie ssid".into())
140 })?;
141
142 let ws = WsClient::connect_con_reintentos(
146 &endpoints::ws_url(&config.ws_host),
147 vec![("Cookie".to_string(), format!("ssid={ssid}"))],
148 cfg_trafico.clone(),
149 )
150 .await?;
151
152 let (tx_salida, rx_salida) = mpsc::channel::<Saliente>(config.transport.cola_salida.max(1));
155 let (tx_eventos, _rx_eventos) = broadcast::channel::<Event>(1024);
156 let (tx_precios, _rx_precios) = broadcast::channel::<Value>(512);
157 let router = Arc::new(RequestRouter::new());
158 let estado = Arc::new(RwLock::new(Estado::default()));
159 let catalogo = Arc::new(RwLock::new(Vec::new()));
160 let sub_velas: Arc<RwLock<Vec<SubVelas>>> = Arc::new(RwLock::new(Vec::new()));
161 let resultados: Arc<RwLock<HashMap<String, OperationResult>>> =
162 Arc::new(RwLock::new(HashMap::new()));
163 let digitales: Arc<RwLock<HashMap<String, OrderId>>> =
164 Arc::new(RwLock::new(HashMap::new()));
165 let suscripciones: Arc<RwLock<Vec<Suscripcion>>> = Arc::new(RwLock::new(Vec::new()));
166 let vivo = Arc::new(AtomicBool::new(true));
167 let cortar = Arc::new(Notify::new());
168 let abiertas: Arc<RwLock<HashSet<OrderId>>> = Arc::new(RwLock::new(HashSet::new()));
169
170 let broker = Self {
171 config,
172 salida: Some(tx_salida),
173 suscripciones: suscripciones.clone(),
174 vivo: vivo.clone(),
175 cortar: cortar.clone(),
176 abiertas: abiertas.clone(),
177 router: router.clone(),
178 estado: estado.clone(),
179 catalogo: catalogo.clone(),
180 sub_velas: sub_velas.clone(),
181 eventos: tx_eventos.clone(),
182 precios: tx_precios.clone(),
183 resultados: resultados.clone(),
184 digitales: digitales.clone(),
185 };
186
187 tokio::spawn(tarea_socket(
189 ws,
190 rx_salida,
191 Ctx {
192 config: broker.config.clone(),
193 suscripciones: suscripciones.clone(),
194 vivo: vivo.clone(),
195 cortar: cortar.clone(),
196 abiertas: abiertas.clone(),
197 router: router.clone(),
198 estado: estado.clone(),
199 catalogo: catalogo.clone(),
200 sub_velas: sub_velas.clone(),
201 eventos: tx_eventos,
202 precios: tx_precios,
203 resultados: resultados.clone(),
204 digitales: digitales.clone(),
205 },
206 ));
207
208 let perfil = broker
210 .solicitar(msg::SSID, &json!(ssid), msg::PROFILE)
211 .await?;
212 let (session, balances) = mapper::sesion_desde_perfil(&perfil, &broker.config.account)
213 .ok_or_else(|| BrokerError::Rejected("profile sin balances utilizables".into()))?;
214 {
215 let mut e = estado.write().await;
216 e.session = Some(session);
217 e.balances = balances;
218 e.conectado = true;
219 }
220
221 let init = broker
223 .solicitar(
224 msg::SEND_MESSAGE,
225 &json!({ "name": msg::GET_INITIALIZATION_DATA, "version": "3.0", "body": {} }),
226 msg::INITIALIZATION_DATA,
227 )
228 .await?;
229 let activos = mapper::catalogo_desde_init(&init);
230 {
231 let mut c = catalogo.write().await;
232 *c = activos;
233 }
234
235 for instrumento in ["digital-option", "binary-option", "trading"] {
237 broker
238 .suscribir(
239 &format!("posicion:{instrumento}"),
240 msg::SUBSCRIBE_MESSAGE,
241 &json!({
242 "name": msg::POSITION_CHANGED,
243 "version": "2.0",
244 "params": { "routingFilters": { "instrument_type": instrumento } }
245 }),
246 )
247 .await?;
248 }
249 Ok(broker)
250 }
251
252 pub(crate) async fn solicitar(
254 &self,
255 name: &str,
256 msg: &Value,
257 _respuesta: &str,
258 ) -> Result<Value, BrokerError> {
259 if !self.vivo.load(Ordering::Acquire) {
262 return Err(BrokerError::NotConnected);
263 }
264 let (rid, rx) = self.router.register("iq");
265 self.salida
266 .as_ref()
267 .ok_or_else(|| BrokerError::Internal("canal de salida cerrado".into()))?
268 .send(Saliente {
269 name: name.into(),
270 msg: msg.clone(),
271 request_id: rid.clone(),
272 })
273 .await
274 .map_err(|_| BrokerError::Internal("canal de salida cerrado".into()))?;
275 let plazo = std::time::Duration::from_secs(self.config.timeout_secs);
276 match tokio::time::timeout(plazo, rx).await {
277 Ok(Ok(msg)) => Ok(msg),
278 Ok(Err(_)) => Err(BrokerError::Internal("respuesta descartada".into())),
279 Err(_) => {
280 self.router.discard(&rid);
283 Err(BrokerError::Timeout)
284 }
285 }
286 }
287
288 pub(crate) async fn enviar_sin_espera(
290 &self,
291 name: &str,
292 msg: &Value,
293 ) -> Result<(), BrokerError> {
294 if !self.vivo.load(Ordering::Acquire) {
295 return Err(BrokerError::NotConnected);
296 }
297 let rid = self.router.next_id("iq");
300 self.salida
301 .as_ref()
302 .ok_or_else(|| BrokerError::Internal("canal de salida cerrado".into()))?
303 .send(Saliente {
304 name: name.into(),
305 msg: msg.clone(),
306 request_id: rid,
307 })
308 .await
309 .map_err(|_| BrokerError::Internal("canal de salida cerrado".into()))?;
310 Ok(())
311 }
312
313 pub(crate) async fn suscribir(
318 &self,
319 clave: &str,
320 name: &str,
321 msg: &Value,
322 ) -> Result<(), BrokerError> {
323 let nueva = {
324 let reg = self.suscripciones.read().await;
325 !reg.iter().any(|s| s.clave == clave)
326 };
327 if !nueva {
328 return Ok(());
329 }
330 self.enviar_sin_espera(name, msg).await?;
333 let mut reg = self.suscripciones.write().await;
334 registrar_suscripcion(&mut reg, clave, name, msg);
335 Ok(())
336 }
337
338 pub(crate) async fn estado_lectura(&self) -> tokio::sync::RwLockReadGuard<'_, Estado> {
339 self.estado.read().await
340 }
341
342 pub(crate) async fn hora_servidor_segs(&self) -> i64 {
344 let offset = self
345 .estado_lectura()
346 .await
347 .session
348 .as_ref()
349 .map(|s| s.server_time_offset_ms)
350 .unwrap_or(0);
351 let ahora_ms = std::time::SystemTime::now()
352 .duration_since(std::time::UNIX_EPOCH)
353 .map(|d| d.as_millis() as i64)
354 .unwrap_or_default();
355 (ahora_ms + offset) / 1000
356 }
357
358 pub(crate) fn cerrar_salida(&mut self) {
360 self.salida = None;
361 }
362
363 #[doc(hidden)]
370 pub async fn simular_caida_de_conexion(&self) {
371 self.cortar.notify_one();
372 }
373}
374
375fn extraer_ssid(headers: &reqwest::header::HeaderMap, cuerpo: &Value) -> Option<String> {
377 for header in headers.get_all("set-cookie") {
378 if let Ok(raw) = header.to_str() {
379 if let Some(rest) = raw.strip_prefix("ssid=") {
380 return Some(rest.split(';').next().unwrap_or(rest).trim().to_string());
381 }
382 }
383 }
384 cuerpo
385 .get("ssid")
386 .and_then(|s| s.as_str())
387 .map(str::to_string)
388}
389
390pub(crate) struct Ctx {
392 pub(crate) config: IqOptionConfig,
393 pub(crate) suscripciones: Arc<RwLock<Vec<Suscripcion>>>,
394 pub(crate) vivo: Arc<AtomicBool>,
395 pub(crate) cortar: Arc<Notify>,
396 pub(crate) abiertas: Arc<RwLock<HashSet<OrderId>>>,
397 pub(crate) router: Arc<RequestRouter>,
398 pub(crate) estado: Arc<RwLock<Estado>>,
399 pub(crate) catalogo: Arc<RwLock<Vec<Asset>>>,
400 pub(crate) sub_velas: Arc<RwLock<Vec<SubVelas>>>,
401 pub(crate) eventos: broadcast::Sender<Event>,
402 pub(crate) precios: broadcast::Sender<Value>,
403 pub(crate) resultados: Arc<RwLock<HashMap<String, OperationResult>>>,
404 pub(crate) digitales: Arc<RwLock<HashMap<String, OrderId>>>,
405}
406async fn tarea_socket(mut ws: WsClient, mut rx_salida: mpsc::Receiver<Saliente>, ctx: Ctx) {
413 loop {
414 let motivo = bucle_socket(&mut ws, &mut rx_salida, &ctx).await;
415
416 ctx.router.fail_all();
419 ctx.vivo.store(false, Ordering::Release);
420 ctx.estado.write().await.conectado = false;
421 let _ = ctx.eventos.send(Event::Disconnected {
422 motivo: motivo.to_string(),
423 });
424
425 if motivo == MOTIVO_CIERRE {
426 break;
427 }
428
429 tracing::warn!(motivo, "conexión perdida; reintentando");
430 let inicio = tokio::time::Instant::now();
431 let mut intentos = 0u32;
432 match reconectar(&ctx, &mut intentos).await {
433 Ok(nuevo) => {
434 ws = nuevo;
435 ctx.vivo.store(true, Ordering::Release);
436 ctx.estado.write().await.conectado = true;
437 let _ = ctx.eventos.send(Event::Reconnected {
438 intentos,
439 downtime_ms: inicio.elapsed().as_millis() as u64,
440 });
441 tracing::info!(intentos, "sesión restablecida");
442 }
443 Err(e) => {
444 tracing::error!(error = %e, "reconexión abandonada");
445 break;
446 }
447 }
448 }
449
450 ctx.sub_velas.write().await.clear();
452 ctx.suscripciones.write().await.clear();
453 tracing::warn!("sesión cerrada; no habrá más reconexiones");
454}
455
456async fn bucle_socket(
458 ws: &mut WsClient,
459 rx_salida: &mut mpsc::Receiver<Saliente>,
460 ctx: &Ctx,
461) -> &'static str {
462 loop {
463 tokio::select! {
464 frame = ws.siguiente() => {
465 match frame {
466 Some(Ok(f)) => {
467 if let Some(rid) = f.request_id.as_deref() {
468 if !ctx.router.deliver(Some(rid), f.msg.clone()) {
469 tracing::debug!(rid, "request_id tardío o desconocido");
470 }
471 }
472 enrutar_evento(&f, ctx).await;
473 }
474 Some(Err(e)) => {
475 tracing::warn!(error = %e, "error de lectura del websocket");
476 return "error de lectura";
477 }
478 None => return "el bróker cerró el socket",
479 }
480 }
481
482 saliente = rx_salida.recv() => {
483 match saliente {
484 Some(s) => {
485 if let Err(e) = ws.enviar(&s.name, &s.msg, &s.request_id).await {
486 tracing::warn!(error = %e, "error de escritura del websocket");
487 return "error de escritura";
488 }
489 }
490 None => {
491 let _ = ws.cerrar().await;
492 return MOTIVO_CIERRE;
493 }
494 }
495 }
496
497 _ = ctx.cortar.notified() => {
498 tracing::warn!("caída simulada: cerrando el socket");
500 let _ = ws.cerrar().await;
501 return "caída simulada";
502 }
503 }
504 }
505}
506
507async fn iniciar_sesion(ctx: &Ctx) -> Result<String, BrokerError> {
509 let http = HttpClient::new(
510 &endpoints::api_base_url(&ctx.config.auth_host),
511 ctx.config.transport.clone(),
512 )?;
513 let (cuerpo, headers) = http
514 .post_json_completo(
515 endpoints::LOGIN_PATH.trim_start_matches('/'),
516 &json!({ "identifier": ctx.config.email, "password": ctx.config.password }),
517 )
518 .await?;
519 extraer_ssid(&headers, &cuerpo)
520 .ok_or_else(|| BrokerError::Authentication("el login no devolvió cookie ssid".into()))
521}
522
523async fn reconectar(ctx: &Ctx, intentos: &mut u32) -> Result<WsClient, BrokerError> {
525 let cfg = &ctx.config.transport;
526 let mut espera = siguiente_espera(0, cfg.backoff_base_ms.max(1));
527 let mut ssid: Option<String> = None;
528
529 loop {
530 tokio::time::sleep(std::time::Duration::from_millis(espera)).await;
531 *intentos += 1;
532
533 let credencial = match ssid.clone() {
534 Some(s) => Ok(s),
535 None => iniciar_sesion(ctx).await,
536 };
537 match credencial {
538 Ok(sesion) => match abrir_y_restaurar(ctx, &sesion).await {
539 Ok(ws) => return Ok(ws),
540 Err(e) if es_fatal(&e) => return Err(e),
541 Err(e) => {
542 tracing::warn!(error = %e, "no se pudo restaurar la sesión");
544 ssid = None;
545 }
546 },
547 Err(e) if es_fatal(&e) => return Err(e),
548 Err(e) => tracing::warn!(error = %e, "login fallido durante la reconexión"),
549 }
550 espera = siguiente_espera(espera, cfg.backoff_max_ms);
551 }
552}
553
554async fn abrir_y_restaurar(ctx: &Ctx, ssid: &str) -> Result<WsClient, BrokerError> {
556 let mut ws = WsClient::connect_con_reintentos(
557 &endpoints::ws_url(&ctx.config.ws_host),
558 vec![("Cookie".to_string(), format!("ssid={ssid}"))],
559 ctx.config.transport.clone(),
560 )
561 .await?;
562
563 let plazo = std::time::Duration::from_secs(ctx.config.timeout_secs);
564 let perfil = solicitar_directo(&mut ws, ctx, msg::SSID, &json!(ssid), plazo).await?;
565 let (session, balances) = mapper::sesion_desde_perfil(&perfil, &ctx.config.account)
566 .ok_or_else(|| BrokerError::Rejected("profile sin balances utilizables".into()))?;
567 {
568 let mut e = ctx.estado.write().await;
569 e.session = Some(session);
570 e.balances = balances;
571 }
572
573 let init = solicitar_directo(
574 &mut ws,
575 ctx,
576 msg::SEND_MESSAGE,
577 &json!({ "name": msg::GET_INITIALIZATION_DATA, "version": "3.0", "body": {} }),
578 plazo,
579 )
580 .await?;
581 {
582 let mut c = ctx.catalogo.write().await;
583 *c = mapper::catalogo_desde_init(&init);
584 }
585
586 let pendientes = ctx.suscripciones.read().await.clone();
589 for sub in pendientes {
590 let rid = ctx.router.next_id("iq");
591 ws.enviar(&sub.name, &sub.msg, &rid).await?;
592 }
593
594 reconciliar_pendientes(&mut ws, ctx, plazo).await;
597 Ok(ws)
598}
599
600const PÁGINAS_RECONCILIACION: usize = 10;
602const POSICIONES_POR_PAGINA: usize = 100;
604
605#[async_trait::async_trait]
607trait PaginadorHistorial: Send {
608 async fn pagina(&mut self, offset: usize) -> Result<PositionHistory, BrokerError>;
609}
610
611struct PaginadorWs<'a> {
613 ws: &'a mut WsClient,
614 ctx: &'a Ctx,
615 plazo: std::time::Duration,
616}
617
618#[async_trait::async_trait]
619impl PaginadorHistorial for PaginadorWs<'_> {
620 async fn pagina(&mut self, offset: usize) -> Result<PositionHistory, BrokerError> {
621 pedir_historial(self.ws, self.ctx, self.plazo, offset).await
622 }
623}
624
625async fn recorrer_paginas(
633 fuente: &mut (dyn PaginadorHistorial + Send),
634 pendientes: &HashSet<OrderId>,
635) -> (Vec<(OrderId, OperationResult)>, HashSet<OrderId>, usize) {
636 let mut faltan = pendientes.clone();
637 let mut encontrados = Vec::new();
638 let mut paginas = 0usize;
639
640 for pagina in 0..PÁGINAS_RECONCILIACION {
641 let offset = pagina * POSICIONES_POR_PAGINA;
642 let historial = match fuente.pagina(offset).await {
643 Ok(h) => h,
644 Err(e) => {
645 tracing::warn!(error = %e, offset, "sin historial: reconciliación incompleta");
646 break;
647 }
648 };
649 paginas += 1;
650 if historial.positions.is_empty() {
651 break;
652 }
653 let ultima_pagina = historial.positions.len() < POSICIONES_POR_PAGINA;
654
655 let nuevos = reconciliar(&faltan, &historial);
656 for (id, _) in &nuevos {
657 faltan.remove(id);
658 }
659 encontrados.extend(nuevos);
660
661 if faltan.is_empty() || ultima_pagina {
662 break;
663 }
664 }
665
666 (encontrados, faltan, paginas)
667}
668
669async fn reconciliar_pendientes(ws: &mut WsClient, ctx: &Ctx, plazo: std::time::Duration) {
671 let pendientes = ctx.abiertas.read().await.clone();
672 if pendientes.is_empty() {
673 return;
674 }
675
676 let mut fuente = PaginadorWs { ws, ctx, plazo };
677 let (encontrados, faltan, paginas) = recorrer_paginas(&mut fuente, &pendientes).await;
678
679 for (id, result) in encontrados {
680 let nuevo = {
681 let mut cache = ctx.resultados.write().await;
682 if cache.contains_key(&id) {
683 false
684 } else {
685 cache.insert(id.clone(), result);
686 true
687 }
688 };
689 ctx.abiertas.write().await.remove(&id);
690 if nuevo {
691 let _ = ctx.eventos.send(Event::OrderClosed { id, result });
692 }
693 }
694
695 if !faltan.is_empty() {
696 tracing::warn!(
697 pendientes = faltan.len(),
698 paginas,
699 "cierres no encontrados en el historial"
700 );
701 }
702}
703
704async fn pedir_historial(
706 ws: &mut WsClient,
707 ctx: &Ctx,
708 plazo: std::time::Duration,
709 offset: usize,
710) -> Result<PositionHistory, BrokerError> {
711 let balance_id = ctx
712 .estado
713 .read()
714 .await
715 .session
716 .as_ref()
717 .and_then(|s| s.balance_id);
718 let respuesta = solicitar_directo(
719 ws,
720 ctx,
721 msg::SEND_MESSAGE,
722 &json!({
723 "name": msg::PORTFOLIO_GET_HISTORY,
724 "body": {
725 "instrument_types": ["turbo-option", "binary-option", "digital-option"],
726 "limit": POSICIONES_POR_PAGINA,
727 "offset": offset,
728 "start": 0,
729 "end": 0,
730 "user_balance_id": balance_id
731 }
732 }),
733 plazo,
734 )
735 .await?;
736 mapper::historial_desde_positions(&respuesta, offset)
737 .ok_or_else(|| BrokerError::Rejected("historial sin positions".into()))
738}
739
740fn resultado_desde_posicion(p: &Position) -> Option<OperationResult> {
742 let pnl = p.pnl?;
743 Some(if pnl > 0.0 {
744 OperationResult::Win(pnl)
745 } else if pnl < 0.0 {
746 OperationResult::Loss(pnl.abs())
747 } else {
748 OperationResult::Equal(p.amount)
749 })
750}
751
752fn reconciliar(
757 pendientes: &HashSet<OrderId>,
758 historial: &PositionHistory,
759) -> Vec<(OrderId, OperationResult)> {
760 let mut vistos = HashSet::new();
761 historial
762 .positions
763 .iter()
764 .filter(|p| pendientes.contains(&p.id) && vistos.insert(p.id.clone()))
765 .filter_map(|p| resultado_desde_posicion(p).map(|r| (p.id.clone(), r)))
766 .collect()
767}
768
769async fn solicitar_directo(
774 ws: &mut WsClient,
775 ctx: &Ctx,
776 name: &str,
777 msg: &Value,
778 plazo: std::time::Duration,
779) -> Result<Value, BrokerError> {
780 let (rid, mut rx) = ctx.router.register("iq");
781 ws.enviar(name, msg, &rid).await?;
782 let limite = tokio::time::Instant::now() + plazo;
783 loop {
784 tokio::select! {
785 respuesta = &mut rx => {
786 return respuesta.map_err(|_| BrokerError::Internal("respuesta descartada".into()));
787 }
788 frame = ws.siguiente() => {
789 match frame {
790 Some(Ok(f)) => {
791 if f.request_id.as_deref() == Some(rid.as_str()) {
792 return Ok(f.msg);
793 }
794 if let Some(otro) = f.request_id.as_deref() {
795 let _ = ctx.router.deliver(Some(otro), f.msg.clone());
796 }
797 enrutar_evento(&f, ctx).await;
798 }
799 Some(Err(e)) => return Err(BrokerError::Transport(e)),
800 None => {
801 return Err(BrokerError::Connection(
802 "el socket se cerró durante la reautenticación".into(),
803 ))
804 }
805 }
806 }
807 _ = tokio::time::sleep_until(limite) => {
808 ctx.router.discard(&rid);
809 return Err(BrokerError::Timeout);
810 }
811 }
812 }
813}
814
815async fn enrutar_evento(frame: &crate::transport::websocket::WsFrame, ctx: &Ctx) {
817 let Ctx {
818 config: _,
819 suscripciones: _,
820 vivo: _,
821 cortar: _,
822 abiertas,
823 router: _,
824 estado,
825 catalogo,
826 sub_velas,
827 eventos,
828 precios,
829 resultados,
830 digitales,
831 } = ctx;
832 match frame.name.as_str() {
833 msg::TIME_SYNC => {
834 if let Some(ms) = frame.msg.as_i64() {
835 let ahora = std::time::SystemTime::now()
836 .duration_since(std::time::UNIX_EPOCH)
837 .map(|d| d.as_millis() as i64)
838 .unwrap_or(ms);
839 let mut e = estado.write().await;
840 if let Some(s) = e.session.as_mut() {
841 s.server_time_offset_ms = ms - ahora;
842 }
843 }
844 }
845 msg::PROFILE | msg::BALANCES => {
846 let balances = if frame.msg.is_array() {
847 mapper::balances_desde_lista(&frame.msg)
848 } else {
849 mapper::balances_desde_perfil(&frame.msg)
850 };
851 let mut e = estado.write().await;
852 if !balances.is_empty() {
853 e.balances = balances;
854 }
855 }
856 msg::BALANCE_CHANGED => {
857 if let Some(bal) = mapper::balance_desde_cambio(&frame.msg) {
858 let mut e = estado.write().await;
859 e.balances.retain(|b| b.id != bal.id);
860 e.balances.push(bal.clone());
861 let _ = eventos.send(Event::BalanceChanged(bal));
862 }
863 }
864 msg::CANDLE_GENERATED => {
865 let active_id = frame
866 .msg
867 .get("active_id")
868 .and_then(|a| a.as_u64())
869 .unwrap_or(0) as u32;
870 let catalogo = catalogo.read().await;
871 if let Some(symbol) = catalogo
872 .iter()
873 .find(|a| a.opcode == active_id)
874 .map(|a| a.symbol.clone())
875 {
876 if let Some(tick) = mapper::tick_desde_frame(&frame.msg) {
878 let _ = eventos.send(Event::PriceTick {
879 symbol: symbol.clone(),
880 tick,
881 });
882 }
883 if let Some((_, candle)) = mapper::vela_viva_unica(&frame.msg) {
884 let mut subs = sub_velas.write().await;
887 subs.retain(|s| !s.tx.is_closed());
888 for sub in subs.iter() {
889 if sub.symbol == symbol
890 && (sub.interval == 0 || sub.interval as i64 == candle.to - candle.from)
891 {
892 let _ = sub.tx.send(candle);
893 }
894 }
895 }
896 }
897 }
898 msg::CANDLES_GENERATED => {
899 let active_id = frame
900 .msg
901 .get("active_id")
902 .and_then(|a| a.as_u64())
903 .unwrap_or(0) as u32;
904 if active_id > 0 {
905 let catalogo = catalogo.read().await;
906 if let Some(symbol) = catalogo
907 .iter()
908 .find(|a| a.opcode == active_id)
909 .map(|a| a.symbol.clone())
910 {
911 if let Some(tick) = mapper::tick_desde_frame(&frame.msg) {
913 let _ = eventos.send(Event::PriceTick {
914 symbol: symbol.clone(),
915 tick,
916 });
917 }
918 let mut subs = sub_velas.write().await;
919 subs.retain(|s| !s.tx.is_closed());
920 for (size, candle) in mapper::velas_vivas_multi(&frame.msg) {
921 for sub in subs.iter() {
922 if sub.symbol == symbol && (sub.interval == 0 || sub.interval == size) {
923 let _ = sub.tx.send(candle);
924 }
925 }
926 }
927 }
928 }
929 }
930 msg::CLIENT_PRICE_GENERATED => {
931 let _ = precios.send(frame.msg.clone());
933 if let Some((active_id, payout)) = mapper::payout_price_splitter_con_id(&frame.msg) {
934 let catalogo = catalogo.read().await;
935 if let Some(asset) = catalogo.iter().find(|a| a.opcode == active_id) {
936 let payout = Payout {
937 symbol: asset.symbol.clone(),
938 ..payout
939 };
940 let _ = eventos.send(Event::PayoutChanged(payout));
941 }
942 }
943 }
944 msg::OPTION_OPENED => {
945 if let Some(operacion) = mapper::operacion_desde_apertura(&frame.msg) {
946 let _ = eventos.send(Event::OrderOpened(operacion));
947 }
948 }
949 msg::OPTION_CLOSED | msg::SOCKET_OPTION_CLOSED => {
950 let (id, result) = if frame.name == msg::OPTION_CLOSED {
951 (
952 frame.msg.get("option_id").map(|i| i.to_string()),
953 mapper::resultado_desde_cierre(&frame.msg),
954 )
955 } else {
956 (
957 frame.msg.get("id").map(|i| i.to_string()),
958 mapper::resultado_desde_socket_cerrado(&frame.msg),
959 )
960 };
961 if let (Some(id), Some(result)) = (id, result) {
962 let mut cache = resultados.write().await;
968 if !cache.contains_key(&id) {
969 cache.insert(id.clone(), result);
970 abiertas.write().await.remove(&id);
971 drop(cache);
972 let _ = eventos.send(Event::OrderClosed { id, result });
973 }
974 }
975 }
976 msg::POSITION_CHANGED => {
977 if let Some((instrument_id, result)) = mapper::cierre_digital_desde_position(&frame.msg)
978 {
979 let order_id = digitales.write().await.remove(&instrument_id);
980 if let Some(id) = order_id {
981 let mut cache = resultados.write().await;
982 if !cache.contains_key(&id) {
983 cache.insert(id.clone(), result);
984 abiertas.write().await.remove(&id);
985 drop(cache);
986 let _ = eventos.send(Event::OrderClosed { id, result });
987 }
988 }
989 }
990 }
991 msg::LIVE_DEAL | msg::LIVE_DEAL_BINARY => {
992 let active_id = frame
993 .msg
994 .get("active_id")
995 .or_else(|| frame.msg.get("instrument_active_id"))
996 .and_then(|a| a.as_i64())
997 .unwrap_or(0) as u32;
998 let catalogo = catalogo.read().await;
999 if let Some(symbol) = catalogo
1000 .iter()
1001 .find(|a| a.opcode == active_id)
1002 .map(|a| a.symbol.clone())
1003 {
1004 if let Some(deal) = mapper::live_deal_desde_frame(&symbol, &frame.msg) {
1005 let _ = eventos.send(Event::LiveDeal(deal));
1006 }
1007 }
1008 }
1009 msg::COMMISSION_CHANGED => {
1010 let active_id = frame
1011 .msg
1012 .get("active_id")
1013 .and_then(|a| a.as_i64())
1014 .unwrap_or(0) as u32;
1015 let catalogo = catalogo.read().await;
1016 if let Some(symbol) = catalogo
1017 .iter()
1018 .find(|a| a.opcode == active_id)
1019 .map(|a| a.symbol.clone())
1020 {
1021 if let Some(cambio) = mapper::comision_desde_frame(&symbol, &frame.msg) {
1022 let _ = eventos.send(Event::CommissionChanged(cambio));
1023 }
1024 }
1025 }
1026 _ => {
1027 if let Some(evento) = mapper::evento_desde_frame(frame) {
1028 let _ = eventos.send(evento);
1029 }
1030 }
1031 }
1032}
1033
1034#[cfg(test)]
1035mod tests {
1036 use super::*;
1037 use crate::transport::websocket::WsFrame;
1038
1039 fn frame(name: &str, msg: Value) -> WsFrame {
1040 WsFrame {
1041 name: name.into(),
1042 msg,
1043 request_id: None,
1044 }
1045 }
1046
1047 struct CtxPrueba {
1048 ctx: Ctx,
1049 rx: broadcast::Receiver<Event>,
1050 resultados: Arc<RwLock<HashMap<String, OperationResult>>>,
1051 }
1052
1053 fn ctx() -> CtxPrueba {
1054 let (tx, rx) = broadcast::channel(64);
1055 let resultados = Arc::new(RwLock::new(HashMap::new()));
1056 CtxPrueba {
1057 ctx: Ctx {
1058 config: IqOptionConfig::default(),
1059 suscripciones: Arc::new(RwLock::new(Vec::new())),
1060 vivo: Arc::new(AtomicBool::new(true)),
1061 cortar: Arc::new(Notify::new()),
1062 abiertas: Arc::new(RwLock::new(HashSet::new())),
1063 router: Arc::new(RequestRouter::new()),
1064 estado: Arc::new(RwLock::new(Estado::default())),
1065 catalogo: Arc::new(RwLock::new(Vec::new())),
1066 sub_velas: Arc::new(RwLock::new(Vec::new())),
1067 eventos: tx,
1068 precios: broadcast::channel(64).0,
1069 resultados: resultados.clone(),
1070 digitales: Arc::new(RwLock::new(HashMap::new())),
1071 },
1072 rx,
1073 resultados,
1074 }
1075 }
1076
1077 #[tokio::test]
1080 async fn cache_no_se_pisa_con_el_segundo_canal() {
1081 let prueba = ctx();
1082 let ctx = prueba.ctx;
1083 let mut rx = prueba.rx;
1084 let resultados = prueba.resultados;
1085
1086 enrutar_evento(
1088 &frame(
1089 "option-closed",
1090 json!({"option_id": 14405260361i64, "result": "win", "amount": 1, "win_enrolled_amount": 1.83}),
1091 ),
1092 &ctx,
1093 )
1094 .await;
1095
1096 enrutar_evento(
1098 &frame(
1099 "socket-option-closed",
1100 json!({"id": 14405260361i64, "win": "win", "amount": 1000000}),
1101 ),
1102 &ctx,
1103 )
1104 .await;
1105
1106 let cache = resultados.read().await;
1108 let guardado = cache.get("14405260361").copied();
1109 assert_eq!(guardado, Some(OperationResult::Win(0.83)));
1110 drop(cache);
1111
1112 let ev = rx.try_recv().expect("debe haberse emitido un evento");
1114 match ev {
1115 Event::OrderClosed { id, result } => {
1116 assert_eq!(id, "14405260361");
1117 assert_eq!(result, OperationResult::Win(0.83));
1118 }
1119 otra => panic!("evento inesperado: {otra:?}"),
1120 }
1121 assert!(
1122 rx.try_recv().is_err(),
1123 "no debe emitirse un segundo OrderClosed"
1124 );
1125 }
1126
1127 #[test]
1129 fn registro_de_suscripciones_no_duplica_claves() {
1130 let mut lista = Vec::new();
1131 assert!(registrar_suscripcion(
1132 &mut lista,
1133 "velas:EURUSD",
1134 "subscribeMessage",
1135 &json!({"name": "candles-generated"})
1136 ));
1137 assert!(!registrar_suscripcion(
1138 &mut lista,
1139 "velas:EURUSD",
1140 "subscribeMessage",
1141 &json!({"name": "candles-generated"})
1142 ));
1143 assert_eq!(lista.len(), 1);
1144 assert_eq!(lista[0].clave, "velas:EURUSD");
1145 }
1146
1147 #[test]
1149 fn backoff_duplica_y_satura() {
1150 assert_eq!(siguiente_espera(0, 8_000), 1);
1151 assert_eq!(siguiente_espera(1, 8_000), 2);
1152 assert_eq!(siguiente_espera(4_000, 8_000), 8_000);
1153 assert_eq!(siguiente_espera(8_000, 8_000), 8_000);
1154 assert_eq!(siguiente_espera(8_000, 0), 1);
1155 }
1156
1157 #[test]
1159 fn reconciliacion_solo_rellena_ordenes_pendientes() {
1160 let posicion = |id: &str, pnl: Option<f64>| Position {
1161 id: id.into(),
1162 instrument_type: "turbo-option".into(),
1163 symbol: "EURUSD".into(),
1164 side: Side::Buy,
1165 amount: 1.0,
1166 open_price: Some(1.1),
1167 pnl,
1168 invested: Some(1.0),
1169 open_at: 1,
1170 close_at: Some(2),
1171 leverage: None,
1172 };
1173 let historial = PositionHistory {
1174 positions: vec![
1175 posicion("111", Some(0.83)),
1176 posicion("222", Some(-1.0)),
1177 posicion("333", Some(0.0)),
1178 posicion("999", Some(5.0)),
1179 posicion("111", Some(0.83)),
1180 ],
1181 offset: 0,
1182 total: Some(5),
1183 };
1184 let pendientes: HashSet<OrderId> = ["111", "222", "333"]
1185 .into_iter()
1186 .map(str::to_string)
1187 .collect();
1188
1189 let mut filas = reconciliar(&pendientes, &historial);
1190 filas.sort_by(|a, b| a.0.cmp(&b.0));
1191 assert_eq!(
1192 filas,
1193 vec![
1194 ("111".to_string(), OperationResult::Win(0.83)),
1195 ("222".to_string(), OperationResult::Loss(1.0)),
1196 ("333".to_string(), OperationResult::Equal(1.0)),
1197 ]
1198 );
1199 }
1200
1201 fn posicion_simulada(id: &str, pnl: f64) -> Position {
1203 Position {
1204 id: id.into(),
1205 instrument_type: "turbo-option".into(),
1206 symbol: "EURUSD".into(),
1207 side: Side::Buy,
1208 amount: 1.0,
1209 open_price: Some(1.1),
1210 pnl: Some(pnl),
1211 invested: Some(1.0),
1212 open_at: 1,
1213 close_at: Some(2),
1214 leverage: None,
1215 }
1216 }
1217
1218 fn historial_simulado(total: usize) -> Vec<Position> {
1219 (0..total)
1220 .map(|i| posicion_simulada(&i.to_string(), 0.5))
1221 .collect()
1222 }
1223
1224 struct PaginadorSimulado {
1225 posiciones: Vec<Position>,
1226 offsets: Vec<usize>,
1227 }
1228
1229 #[async_trait::async_trait]
1230 impl PaginadorHistorial for PaginadorSimulado {
1231 async fn pagina(&mut self, offset: usize) -> Result<PositionHistory, BrokerError> {
1232 self.offsets.push(offset);
1233 let posiciones = if offset >= self.posiciones.len() {
1234 Vec::new()
1235 } else {
1236 let fin = (offset + POSICIONES_POR_PAGINA).min(self.posiciones.len());
1237 self.posiciones[offset..fin].to_vec()
1238 };
1239 Ok(PositionHistory {
1240 positions: posiciones,
1241 offset,
1242 total: Some(self.posiciones.len()),
1243 })
1244 }
1245 }
1246
1247 #[tokio::test]
1249 async fn recorrido_multipagina_encuentra_en_la_tercera() {
1250 let mut fuente = PaginadorSimulado {
1251 posiciones: historial_simulado(250),
1252 offsets: Vec::new(),
1253 };
1254 let pendientes: HashSet<OrderId> = ["210", "245"].into_iter().map(str::to_string).collect();
1255
1256 let (encontrados, faltan, paginas) = recorrer_paginas(&mut fuente, &pendientes).await;
1257
1258 assert_eq!(fuente.offsets, vec![0, 100, 200]);
1259 assert_eq!(paginas, 3);
1260 assert!(faltan.is_empty(), "debieron encontrarse ambos cierres");
1261 assert_eq!(encontrados.len(), 2);
1262 }
1263
1264 #[tokio::test]
1266 async fn recorrido_corta_al_encontrar_todo() {
1267 let mut fuente = PaginadorSimulado {
1268 posiciones: historial_simulado(150),
1269 offsets: Vec::new(),
1270 };
1271 let pendientes: HashSet<OrderId> = ["7"].into_iter().map(str::to_string).collect();
1272
1273 let (encontrados, faltan, paginas) = recorrer_paginas(&mut fuente, &pendientes).await;
1274
1275 assert_eq!(fuente.offsets, vec![0]);
1276 assert_eq!(paginas, 1);
1277 assert!(faltan.is_empty());
1278 assert_eq!(encontrados.len(), 1);
1279 }
1280
1281 #[tokio::test]
1283 async fn recorrido_respeta_el_limite_de_paginas() {
1284 let mut fuente = PaginadorSimulado {
1285 posiciones: historial_simulado(POSICIONES_POR_PAGINA * PÁGINAS_RECONCILIACION),
1286 offsets: Vec::new(),
1287 };
1288 let pendientes: HashSet<OrderId> = ["999999"].into_iter().map(str::to_string).collect();
1289
1290 let (encontrados, faltan, paginas) = recorrer_paginas(&mut fuente, &pendientes).await;
1291
1292 assert_eq!(paginas, PÁGINAS_RECONCILIACION);
1293 assert_eq!(fuente.offsets.len(), PÁGINAS_RECONCILIACION);
1294 assert!(encontrados.is_empty());
1295 assert_eq!(faltan.len(), 1, "el pendiente debe seguir informado");
1296 }
1297
1298 #[test]
1300 fn solo_la_autenticacion_es_fatal() {
1301 assert!(es_fatal(&BrokerError::Authentication("rechazado".into())));
1302 assert!(!es_fatal(&BrokerError::Connection("cortado".into())));
1303 assert!(!es_fatal(&BrokerError::Timeout));
1304 }
1305}