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
600async fn reconciliar_pendientes(ws: &mut WsClient, ctx: &Ctx, plazo: std::time::Duration) {
606 let mut faltan = ctx.abiertas.read().await.clone();
607 if faltan.is_empty() {
608 return;
609 }
610
611 for pagina in 0..PÁGINAS_RECONCILIACION {
612 let offset = pagina * POSICIONES_POR_PAGINA;
613 let historial = match pedir_historial(ws, ctx, plazo, offset).await {
614 Ok(h) => h,
615 Err(e) => {
616 tracing::warn!(error = %e, offset, "sin historial: reconciliación incompleta");
617 return;
618 }
619 };
620 if historial.positions.is_empty() {
621 return;
622 }
623 let ultima_pagina = historial.positions.len() < POSICIONES_POR_PAGINA;
624
625 for (id, result) in reconciliar(&faltan, &historial) {
626 let nuevo = {
627 let mut cache = ctx.resultados.write().await;
628 if cache.contains_key(&id) {
629 false
630 } else {
631 cache.insert(id.clone(), result);
632 true
633 }
634 };
635 ctx.abiertas.write().await.remove(&id);
636 faltan.remove(&id);
637 if nuevo {
638 let _ = ctx.eventos.send(Event::OrderClosed { id, result });
639 }
640 }
641
642 if faltan.is_empty() {
643 return;
644 }
645 if ultima_pagina {
646 tracing::warn!(
647 pendientes = faltan.len(),
648 "cierres no encontrados en el historial"
649 );
650 return;
651 }
652 }
653 tracing::warn!(
654 pendientes = faltan.len(),
655 "reconciliación agotada sin coincidencias"
656 );
657}
658
659async fn pedir_historial(
661 ws: &mut WsClient,
662 ctx: &Ctx,
663 plazo: std::time::Duration,
664 offset: usize,
665) -> Result<PositionHistory, BrokerError> {
666 let balance_id = ctx
667 .estado
668 .read()
669 .await
670 .session
671 .as_ref()
672 .and_then(|s| s.balance_id);
673 let respuesta = solicitar_directo(
674 ws,
675 ctx,
676 msg::SEND_MESSAGE,
677 &json!({
678 "name": msg::PORTFOLIO_GET_HISTORY,
679 "body": {
680 "instrument_types": ["turbo-option", "binary-option", "digital-option"],
681 "limit": POSICIONES_POR_PAGINA,
682 "offset": offset,
683 "start": 0,
684 "end": 0,
685 "user_balance_id": balance_id
686 }
687 }),
688 plazo,
689 )
690 .await?;
691 mapper::historial_desde_positions(&respuesta, offset)
692 .ok_or_else(|| BrokerError::Rejected("historial sin positions".into()))
693}
694
695fn resultado_desde_posicion(p: &Position) -> Option<OperationResult> {
697 let pnl = p.pnl?;
698 Some(if pnl > 0.0 {
699 OperationResult::Win(pnl)
700 } else if pnl < 0.0 {
701 OperationResult::Loss(pnl.abs())
702 } else {
703 OperationResult::Equal(p.amount)
704 })
705}
706
707fn reconciliar(
712 pendientes: &HashSet<OrderId>,
713 historial: &PositionHistory,
714) -> Vec<(OrderId, OperationResult)> {
715 let mut vistos = HashSet::new();
716 historial
717 .positions
718 .iter()
719 .filter(|p| pendientes.contains(&p.id) && vistos.insert(p.id.clone()))
720 .filter_map(|p| resultado_desde_posicion(p).map(|r| (p.id.clone(), r)))
721 .collect()
722}
723
724async fn solicitar_directo(
729 ws: &mut WsClient,
730 ctx: &Ctx,
731 name: &str,
732 msg: &Value,
733 plazo: std::time::Duration,
734) -> Result<Value, BrokerError> {
735 let (rid, mut rx) = ctx.router.register("iq");
736 ws.enviar(name, msg, &rid).await?;
737 let limite = tokio::time::Instant::now() + plazo;
738 loop {
739 tokio::select! {
740 respuesta = &mut rx => {
741 return respuesta.map_err(|_| BrokerError::Internal("respuesta descartada".into()));
742 }
743 frame = ws.siguiente() => {
744 match frame {
745 Some(Ok(f)) => {
746 if f.request_id.as_deref() == Some(rid.as_str()) {
747 return Ok(f.msg);
748 }
749 if let Some(otro) = f.request_id.as_deref() {
750 let _ = ctx.router.deliver(Some(otro), f.msg.clone());
751 }
752 enrutar_evento(&f, ctx).await;
753 }
754 Some(Err(e)) => return Err(BrokerError::Transport(e)),
755 None => {
756 return Err(BrokerError::Connection(
757 "el socket se cerró durante la reautenticación".into(),
758 ))
759 }
760 }
761 }
762 _ = tokio::time::sleep_until(limite) => {
763 ctx.router.discard(&rid);
764 return Err(BrokerError::Timeout);
765 }
766 }
767 }
768}
769
770async fn enrutar_evento(frame: &crate::transport::websocket::WsFrame, ctx: &Ctx) {
772 let Ctx {
773 config: _,
774 suscripciones: _,
775 vivo: _,
776 cortar: _,
777 abiertas,
778 router: _,
779 estado,
780 catalogo,
781 sub_velas,
782 eventos,
783 precios,
784 resultados,
785 digitales,
786 } = ctx;
787 match frame.name.as_str() {
788 msg::TIME_SYNC => {
789 if let Some(ms) = frame.msg.as_i64() {
790 let ahora = std::time::SystemTime::now()
791 .duration_since(std::time::UNIX_EPOCH)
792 .map(|d| d.as_millis() as i64)
793 .unwrap_or(ms);
794 let mut e = estado.write().await;
795 if let Some(s) = e.session.as_mut() {
796 s.server_time_offset_ms = ms - ahora;
797 }
798 }
799 }
800 msg::PROFILE | msg::BALANCES => {
801 let balances = if frame.msg.is_array() {
802 mapper::balances_desde_lista(&frame.msg)
803 } else {
804 mapper::balances_desde_perfil(&frame.msg)
805 };
806 let mut e = estado.write().await;
807 if !balances.is_empty() {
808 e.balances = balances;
809 }
810 }
811 msg::BALANCE_CHANGED => {
812 if let Some(bal) = mapper::balance_desde_cambio(&frame.msg) {
813 let mut e = estado.write().await;
814 e.balances.retain(|b| b.id != bal.id);
815 e.balances.push(bal.clone());
816 let _ = eventos.send(Event::BalanceChanged(bal));
817 }
818 }
819 msg::CANDLE_GENERATED => {
820 let active_id = frame
821 .msg
822 .get("active_id")
823 .and_then(|a| a.as_u64())
824 .unwrap_or(0) as u32;
825 let catalogo = catalogo.read().await;
826 if let Some(symbol) = catalogo
827 .iter()
828 .find(|a| a.opcode == active_id)
829 .map(|a| a.symbol.clone())
830 {
831 if let Some(tick) = mapper::tick_desde_frame(&frame.msg) {
833 let _ = eventos.send(Event::PriceTick {
834 symbol: symbol.clone(),
835 tick,
836 });
837 }
838 if let Some((_, candle)) = mapper::vela_viva_unica(&frame.msg) {
839 let mut subs = sub_velas.write().await;
842 subs.retain(|s| !s.tx.is_closed());
843 for sub in subs.iter() {
844 if sub.symbol == symbol
845 && (sub.interval == 0 || sub.interval as i64 == candle.to - candle.from)
846 {
847 let _ = sub.tx.send(candle);
848 }
849 }
850 }
851 }
852 }
853 msg::CANDLES_GENERATED => {
854 let active_id = frame
855 .msg
856 .get("active_id")
857 .and_then(|a| a.as_u64())
858 .unwrap_or(0) as u32;
859 if active_id > 0 {
860 let catalogo = catalogo.read().await;
861 if let Some(symbol) = catalogo
862 .iter()
863 .find(|a| a.opcode == active_id)
864 .map(|a| a.symbol.clone())
865 {
866 if let Some(tick) = mapper::tick_desde_frame(&frame.msg) {
868 let _ = eventos.send(Event::PriceTick {
869 symbol: symbol.clone(),
870 tick,
871 });
872 }
873 let mut subs = sub_velas.write().await;
874 subs.retain(|s| !s.tx.is_closed());
875 for (size, candle) in mapper::velas_vivas_multi(&frame.msg) {
876 for sub in subs.iter() {
877 if sub.symbol == symbol && (sub.interval == 0 || sub.interval == size) {
878 let _ = sub.tx.send(candle);
879 }
880 }
881 }
882 }
883 }
884 }
885 msg::CLIENT_PRICE_GENERATED => {
886 let _ = precios.send(frame.msg.clone());
888 if let Some((active_id, payout)) = mapper::payout_price_splitter_con_id(&frame.msg) {
889 let catalogo = catalogo.read().await;
890 if let Some(asset) = catalogo.iter().find(|a| a.opcode == active_id) {
891 let payout = Payout {
892 symbol: asset.symbol.clone(),
893 ..payout
894 };
895 let _ = eventos.send(Event::PayoutChanged(payout));
896 }
897 }
898 }
899 msg::OPTION_OPENED => {
900 if let Some(operacion) = mapper::operacion_desde_apertura(&frame.msg) {
901 let _ = eventos.send(Event::OrderOpened(operacion));
902 }
903 }
904 msg::OPTION_CLOSED | msg::SOCKET_OPTION_CLOSED => {
905 let (id, result) = if frame.name == msg::OPTION_CLOSED {
906 (
907 frame.msg.get("option_id").map(|i| i.to_string()),
908 mapper::resultado_desde_cierre(&frame.msg),
909 )
910 } else {
911 (
912 frame.msg.get("id").map(|i| i.to_string()),
913 mapper::resultado_desde_socket_cerrado(&frame.msg),
914 )
915 };
916 if let (Some(id), Some(result)) = (id, result) {
917 let mut cache = resultados.write().await;
923 if !cache.contains_key(&id) {
924 cache.insert(id.clone(), result);
925 abiertas.write().await.remove(&id);
926 drop(cache);
927 let _ = eventos.send(Event::OrderClosed { id, result });
928 }
929 }
930 }
931 msg::POSITION_CHANGED => {
932 if let Some((instrument_id, result)) = mapper::cierre_digital_desde_position(&frame.msg)
933 {
934 let order_id = digitales.write().await.remove(&instrument_id);
935 if let Some(id) = order_id {
936 let mut cache = resultados.write().await;
937 if !cache.contains_key(&id) {
938 cache.insert(id.clone(), result);
939 abiertas.write().await.remove(&id);
940 drop(cache);
941 let _ = eventos.send(Event::OrderClosed { id, result });
942 }
943 }
944 }
945 }
946 msg::LIVE_DEAL | msg::LIVE_DEAL_BINARY => {
947 let active_id = frame
948 .msg
949 .get("active_id")
950 .or_else(|| frame.msg.get("instrument_active_id"))
951 .and_then(|a| a.as_i64())
952 .unwrap_or(0) as u32;
953 let catalogo = catalogo.read().await;
954 if let Some(symbol) = catalogo
955 .iter()
956 .find(|a| a.opcode == active_id)
957 .map(|a| a.symbol.clone())
958 {
959 if let Some(deal) = mapper::live_deal_desde_frame(&symbol, &frame.msg) {
960 let _ = eventos.send(Event::LiveDeal(deal));
961 }
962 }
963 }
964 msg::COMMISSION_CHANGED => {
965 let active_id = frame
966 .msg
967 .get("active_id")
968 .and_then(|a| a.as_i64())
969 .unwrap_or(0) as u32;
970 let catalogo = catalogo.read().await;
971 if let Some(symbol) = catalogo
972 .iter()
973 .find(|a| a.opcode == active_id)
974 .map(|a| a.symbol.clone())
975 {
976 if let Some(cambio) = mapper::comision_desde_frame(&symbol, &frame.msg) {
977 let _ = eventos.send(Event::CommissionChanged(cambio));
978 }
979 }
980 }
981 _ => {
982 if let Some(evento) = mapper::evento_desde_frame(frame) {
983 let _ = eventos.send(evento);
984 }
985 }
986 }
987}
988
989#[cfg(test)]
990mod tests {
991 use super::*;
992 use crate::transport::websocket::WsFrame;
993
994 fn frame(name: &str, msg: Value) -> WsFrame {
995 WsFrame {
996 name: name.into(),
997 msg,
998 request_id: None,
999 }
1000 }
1001
1002 struct CtxPrueba {
1003 ctx: Ctx,
1004 rx: broadcast::Receiver<Event>,
1005 resultados: Arc<RwLock<HashMap<String, OperationResult>>>,
1006 }
1007
1008 fn ctx() -> CtxPrueba {
1009 let (tx, rx) = broadcast::channel(64);
1010 let resultados = Arc::new(RwLock::new(HashMap::new()));
1011 CtxPrueba {
1012 ctx: Ctx {
1013 config: IqOptionConfig::default(),
1014 suscripciones: Arc::new(RwLock::new(Vec::new())),
1015 vivo: Arc::new(AtomicBool::new(true)),
1016 cortar: Arc::new(Notify::new()),
1017 abiertas: Arc::new(RwLock::new(HashSet::new())),
1018 router: Arc::new(RequestRouter::new()),
1019 estado: Arc::new(RwLock::new(Estado::default())),
1020 catalogo: Arc::new(RwLock::new(Vec::new())),
1021 sub_velas: Arc::new(RwLock::new(Vec::new())),
1022 eventos: tx,
1023 precios: broadcast::channel(64).0,
1024 resultados: resultados.clone(),
1025 digitales: Arc::new(RwLock::new(HashMap::new())),
1026 },
1027 rx,
1028 resultados,
1029 }
1030 }
1031
1032 #[tokio::test]
1035 async fn cache_no_se_pisa_con_el_segundo_canal() {
1036 let prueba = ctx();
1037 let ctx = prueba.ctx;
1038 let mut rx = prueba.rx;
1039 let resultados = prueba.resultados;
1040
1041 enrutar_evento(
1043 &frame(
1044 "option-closed",
1045 json!({"option_id": 14405260361i64, "result": "win", "amount": 1, "win_enrolled_amount": 1.83}),
1046 ),
1047 &ctx,
1048 )
1049 .await;
1050
1051 enrutar_evento(
1053 &frame(
1054 "socket-option-closed",
1055 json!({"id": 14405260361i64, "win": "win", "amount": 1000000}),
1056 ),
1057 &ctx,
1058 )
1059 .await;
1060
1061 let cache = resultados.read().await;
1063 let guardado = cache.get("14405260361").copied();
1064 assert_eq!(guardado, Some(OperationResult::Win(0.83)));
1065 drop(cache);
1066
1067 let ev = rx.try_recv().expect("debe haberse emitido un evento");
1069 match ev {
1070 Event::OrderClosed { id, result } => {
1071 assert_eq!(id, "14405260361");
1072 assert_eq!(result, OperationResult::Win(0.83));
1073 }
1074 otra => panic!("evento inesperado: {otra:?}"),
1075 }
1076 assert!(
1077 rx.try_recv().is_err(),
1078 "no debe emitirse un segundo OrderClosed"
1079 );
1080 }
1081
1082 #[test]
1084 fn registro_de_suscripciones_no_duplica_claves() {
1085 let mut lista = Vec::new();
1086 assert!(registrar_suscripcion(
1087 &mut lista,
1088 "velas:EURUSD",
1089 "subscribeMessage",
1090 &json!({"name": "candles-generated"})
1091 ));
1092 assert!(!registrar_suscripcion(
1093 &mut lista,
1094 "velas:EURUSD",
1095 "subscribeMessage",
1096 &json!({"name": "candles-generated"})
1097 ));
1098 assert_eq!(lista.len(), 1);
1099 assert_eq!(lista[0].clave, "velas:EURUSD");
1100 }
1101
1102 #[test]
1104 fn backoff_duplica_y_satura() {
1105 assert_eq!(siguiente_espera(0, 8_000), 1);
1106 assert_eq!(siguiente_espera(1, 8_000), 2);
1107 assert_eq!(siguiente_espera(4_000, 8_000), 8_000);
1108 assert_eq!(siguiente_espera(8_000, 8_000), 8_000);
1109 assert_eq!(siguiente_espera(8_000, 0), 1);
1110 }
1111
1112 #[test]
1114 fn reconciliacion_solo_rellena_ordenes_pendientes() {
1115 let posicion = |id: &str, pnl: Option<f64>| Position {
1116 id: id.into(),
1117 instrument_type: "turbo-option".into(),
1118 symbol: "EURUSD".into(),
1119 side: Side::Buy,
1120 amount: 1.0,
1121 open_price: Some(1.1),
1122 pnl,
1123 invested: Some(1.0),
1124 open_at: 1,
1125 close_at: Some(2),
1126 leverage: None,
1127 };
1128 let historial = PositionHistory {
1129 positions: vec![
1130 posicion("111", Some(0.83)),
1131 posicion("222", Some(-1.0)),
1132 posicion("333", Some(0.0)),
1133 posicion("999", Some(5.0)),
1134 posicion("111", Some(0.83)),
1135 ],
1136 offset: 0,
1137 total: Some(5),
1138 };
1139 let pendientes: HashSet<OrderId> = ["111", "222", "333"]
1140 .into_iter()
1141 .map(str::to_string)
1142 .collect();
1143
1144 let mut filas = reconciliar(&pendientes, &historial);
1145 filas.sort_by(|a, b| a.0.cmp(&b.0));
1146 assert_eq!(
1147 filas,
1148 vec![
1149 ("111".to_string(), OperationResult::Win(0.83)),
1150 ("222".to_string(), OperationResult::Loss(1.0)),
1151 ("333".to_string(), OperationResult::Equal(1.0)),
1152 ]
1153 );
1154 }
1155
1156 #[test]
1158 fn solo_la_autenticacion_es_fatal() {
1159 assert!(es_fatal(&BrokerError::Authentication("rechazado".into())));
1160 assert!(!es_fatal(&BrokerError::Connection("cortado".into())));
1161 assert!(!es_fatal(&BrokerError::Timeout));
1162 }
1163}