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