Skip to main content

cripsy_binary_api/broker/iq_option/
client.rs

1//! Implementación del contrato `Broker` para IQ Option.
2
3use async_trait::async_trait;
4use futures_util::stream::unfold;
5use serde_json::json;
6use tokio::sync::mpsc;
7
8use crate::broker::config::BrokerParams;
9use crate::broker::error::BrokerError;
10use crate::broker::iq_option::endpoints::{msg, option_type_id};
11use crate::broker::iq_option::mapper;
12use crate::broker::iq_option::session::IqOptionBroker;
13use crate::broker::session::Session;
14use crate::broker::trait_::{Broker, CandleStream, EventStream};
15use crate::domain::*;
16
17#[async_trait]
18impl Broker for IqOptionBroker {
19    fn name(&self) -> &'static str {
20        "iq_option"
21    }
22
23    async fn connect(params: BrokerParams) -> Result<Self, BrokerError>
24    where
25        Self: Sized,
26    {
27        Self::nuevo(params).await
28    }
29
30    async fn disconnect(&mut self) -> Result<(), BrokerError> {
31        self.cerrar_salida();
32        let mut estado = self.estado.write().await;
33        estado.conectado = false;
34        Ok(())
35    }
36
37    async fn is_connected(&self) -> bool {
38        self.estado.read().await.conectado
39    }
40
41    async fn session(&self) -> Result<Session, BrokerError> {
42        self.estado_lectura()
43            .await
44            .session
45            .clone()
46            .ok_or_else(|| BrokerError::Internal("sesión no inicializada".into()))
47    }
48
49    // -------- Cuenta y balance --------
50
51    async fn get_balance(&self) -> Result<Balance, BrokerError> {
52        let estado = self.estado_lectura().await;
53        let balance_id = estado
54            .session
55            .as_ref()
56            .and_then(|s| s.balance_id)
57            .ok_or_else(|| BrokerError::Rejected("sesión sin balance activo".into()))?;
58        let bal = estado
59            .balances
60            .iter()
61            .find(|b| b.id == balance_id)
62            .cloned()
63            .ok_or_else(|| BrokerError::Rejected("balance activo no encontrado".into()))?;
64        Ok(Balance {
65            amount: bal.amount,
66            currency: bal.currency,
67            account_type: bal.account_type,
68            balance_id: bal.id,
69        })
70    }
71
72    async fn get_account_type(&self) -> Result<AccountType, BrokerError> {
73        self.estado_lectura()
74            .await
75            .session
76            .as_ref()
77            .map(|s| s.account_type)
78            .ok_or_else(|| BrokerError::Internal("sesión no inicializada".into()))
79    }
80
81    async fn switch_account(&mut self, kind: AccountType) -> Result<(), BrokerError> {
82        // `api_profile_changebalance` (WS) + refresco de balances (`get-balances`).
83        let balance_id = {
84            let estado = self.estado_lectura().await;
85            estado
86                .balances
87                .iter()
88                .find(|b| b.account_type == kind)
89                .map(|b| b.id)
90                .ok_or_else(|| BrokerError::Rejected(format!("no hay cuenta {kind:?}")))?
91        };
92        self.enviar_sin_espera(
93            "api_profile_changebalance",
94            &json!({ "balance_id": balance_id }),
95        )
96        .await?;
97
98        // Si el refresco falla, el cambio NO se da por hecho: el error se
99        // propaga y la sesión conserva la cuenta anterior.
100        let lista = self
101            .solicitar(msg::GET_BALANCES, &json!({}), "balances")
102            .await?;
103        let balances = mapper::balances_desde_lista(&lista);
104        if balances.is_empty() {
105            return Err(BrokerError::Rejected(
106                "el bróker no devolvió balances tras el cambio de cuenta".into(),
107            ));
108        }
109        if !balances.iter().any(|b| b.id == balance_id) {
110            return Err(BrokerError::Rejected(format!(
111                "el bróker no confirmó el balance {balance_id}"
112            )));
113        }
114        let mut estado = self.estado.write().await;
115        estado.balances = balances;
116        if let Some(s) = estado.session.as_mut() {
117            s.balance_id = Some(balance_id);
118            s.account_type = kind;
119        }
120        Ok(())
121    }
122
123    // -------- Activos y mercado --------
124
125    async fn list_assets(&self) -> Result<Vec<Asset>, BrokerError> {
126        Ok(self.catalogo.read().await.clone())
127    }
128
129    async fn asset_status(&self, symbol: &str) -> Result<MarketStatus, BrokerError> {
130        let catalogo = self.catalogo.read().await;
131        catalogo
132            .iter()
133            .find(|a| a.symbol == symbol)
134            .map(|a| a.status)
135            .ok_or_else(|| {
136                BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
137                    symbol.into(),
138                ))
139            })
140    }
141
142    // -------- Velas --------
143
144    async fn get_candles(&self, req: CandleRequest) -> Result<Vec<Candle>, BrokerError> {
145        let catalogo = self.catalogo.read().await;
146        let active_id = catalogo
147            .iter()
148            .find(|a| a.symbol == req.symbol)
149            .map(|a| a.opcode)
150            .ok_or_else(|| {
151                BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
152                    req.symbol.clone(),
153                ))
154            })?;
155        drop(catalogo);
156
157        let ahora = self.hora_servidor_segs().await;
158        // El bróker solo devuelve velas CERRADAS: `to` = cierre de vela cerrada.
159        let to = req
160            .end_time
161            .unwrap_or_else(|| mapper::cierre_de_vela_cerrada(ahora, req.interval as i64, 90));
162        let respuesta = self
163            .solicitar(
164                msg::SEND_MESSAGE,
165                &json!({
166                    "name": msg::QUOTES_HISTORY_GET_CANDLES,
167                    "version": "2.0",
168                    "body": {
169                        "active_id": active_id,
170                        "size": req.interval,
171                        "count": req.count,
172                        "split_normalization": true,
173                        "to": to
174                    }
175                }),
176                msg::CANDLES,
177            )
178            .await?;
179        let velas = respuesta
180            .get("candles")
181            .and_then(|c| c.as_array())
182            .map(|lista| lista.iter().filter_map(mapper::vela_desde_json).collect())
183            .unwrap_or_default();
184        Ok(velas)
185    }
186
187    async fn subscribe_candles(&self, req: CandleSubscribe) -> Result<CandleStream, BrokerError> {
188        let catalogo = self.catalogo.read().await;
189        let active_id = catalogo
190            .iter()
191            .find(|a| a.symbol == req.symbol)
192            .map(|a| a.opcode)
193            .ok_or_else(|| {
194                BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
195                    req.symbol.clone(),
196                ))
197            })?;
198        drop(catalogo);
199
200        // Stream multi-tamaño: un único canal por símbolo con el tamaño pedido
201        // (0 = todos los tamaños).
202        self.suscribir(
203            &format!("velas:{}", req.symbol),
204            msg::SUBSCRIBE_MESSAGE,
205            &json!({
206                "name": msg::CANDLES_GENERATED,
207                "params": { "routingFilters": { "active_id": active_id.to_string() } }
208            }),
209        )
210        .await?;
211
212        // Canal por suscripción. Al soltar el `CandleStream` el receptor queda
213        // cerrado y la suscripción se retira en el siguiente despacho de velas
214        // (`sub_velas.retain`): no hay API de baja explícita. El canal es
215        // ilimitado, así que el consumidor debe drenarlo.
216        let (tx, rx) = mpsc::unbounded_channel::<Candle>();
217        self.sub_velas
218            .write()
219            .await
220            .push(crate::broker::iq_option::session::SubVelas {
221                symbol: req.symbol.clone(),
222                interval: req.interval,
223                tx,
224            });
225        let stream = unfold(rx, |mut rx| async move {
226            rx.recv().await.map(|c| (Ok::<Candle, BrokerError>(c), rx))
227        });
228        Ok(Box::pin(stream))
229    }
230
231    // -------- Payout --------
232
233    async fn get_payout(
234        &self,
235        symbol: &str,
236        expiration_seconds: u64,
237    ) -> Result<Payout, BrokerError> {
238        let catalogo = self.catalogo.read().await;
239        let asset = catalogo
240            .iter()
241            .find(|a| a.symbol == symbol)
242            .ok_or_else(|| {
243                BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
244                    symbol.into(),
245                ))
246            })?;
247        let profit_percent = asset.payout_percent.unwrap_or(0.0);
248        // El payout digital en vivo (price-splitter) se añade en la Fase 5.
249        Ok(Payout {
250            symbol: symbol.to_string(),
251            expiration_seconds,
252            profit_percent,
253            is_spot: asset.class == AssetClass::Digital,
254            strike: None,
255            closed: asset.status == MarketStatus::Closed,
256        })
257    }
258
259    async fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
260        // Mensaje `sell-options` v2.0 con la lista de ids (verificado contra
261        // el canal del bróker; el bróker confirma con `sold-options`).
262        let id_num = order_id
263            .parse::<i64>()
264            .map_err(|_| BrokerError::Rejected(format!("id de orden no numerico: {order_id}")))?;
265        let respuesta = self
266            .solicitar(
267                msg::SEND_MESSAGE,
268                &json!({
269                    "name": msg::SELL_OPTIONS,
270                    "version": "2.0",
271                    "body": { "options_ids": [id_num] }
272                }),
273                msg::SOLD_OPTIONS,
274            )
275            .await?;
276        // El broker responde con el detalle de la venta o con error.
277        if respuesta.get("message").is_some() {
278            return Err(BrokerError::Rejected(
279                respuesta
280                    .get("message")
281                    .and_then(|m| m.as_str())
282                    .unwrap_or("venta rechazada")
283                    .to_string(),
284            ));
285        }
286        Ok(())
287    }
288
289    async fn get_position_history(
290        &self,
291        symbol: Option<&str>,
292        limit: usize,
293        offset: usize,
294    ) -> Result<PositionHistory, BrokerError> {
295        let balance_id = self
296            .estado_lectura()
297            .await
298            .session
299            .as_ref()
300            .and_then(|s| s.balance_id);
301        let limit = limit.min(100) as u64;
302        let respuesta = self
303            .solicitar(
304                msg::SEND_MESSAGE,
305                &json!({
306                    "name": msg::PORTFOLIO_GET_HISTORY,
307                    "body": {
308                        "instrument_types": ["turbo-option", "binary-option", "digital-option"],
309                        "limit": limit,
310                        "offset": offset as u64,
311                        "start": 0,
312                        "end": 0,
313                        "user_balance_id": balance_id
314                    }
315                }),
316                msg::HISTORY_POSITIONS,
317            )
318            .await?;
319        let historial = mapper::historial_desde_positions(&respuesta, offset)
320            .ok_or_else(|| BrokerError::Rejected("respuesta sin positions".into()))?;
321        if let Some(simbolo) = symbol {
322            if historial.positions.iter().all(|p| p.symbol != simbolo) {
323                return Err(BrokerError::Domain(
324                    crate::domain::error::DomainError::OperationNotFound(format!(
325                        "sin historial para {simbolo}"
326                    )),
327                ));
328            }
329        }
330        Ok(historial)
331    }
332    async fn get_technical_indicators(
333        &self,
334        symbol: &str,
335    ) -> Result<TechnicalIndicators, BrokerError> {
336        let asset_id = {
337            let catalogo = self.catalogo.read().await;
338            catalogo
339                .iter()
340                .find(|a| a.symbol == symbol)
341                .map(|a| a.opcode)
342                .ok_or_else(|| {
343                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
344                        symbol.into(),
345                    ))
346                })?
347        };
348        // Mensaje: `trading-signals.get-technical-indicators` v1.0, body {id}.
349        // El `id` DEBE ser entero (string → INVALID_SCHEMA). Respuesta:
350        // `technical-indicators` con `msg.indicators`, o `msg.message` de error.
351        let respuesta = self
352            .solicitar(
353                msg::SEND_MESSAGE,
354                &json!({
355                    "name": msg::TECHNICAL_INDICATORS,
356                    "version": "1.0",
357                    "body": { "id": asset_id }
358                }),
359                msg::TECHNICAL_INDICATORS_RESPONSE,
360            )
361            .await?;
362        mapper::indicadores_desde_respuesta(&respuesta, symbol).map_err(BrokerError::Rejected)
363    }
364
365    // -------- Órdenes --------
366
367    async fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError> {
368        let asset_id = {
369            let catalogo = self.catalogo.read().await;
370            catalogo
371                .iter()
372                .find(|a| a.symbol == symbol)
373                .map(|a| a.opcode)
374                .ok_or_else(|| {
375                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
376                        symbol.into(),
377                    ))
378                })?
379        };
380        // GraphQL: el broker responde `financial-information` con data.active.
381        let respuesta = self
382            .solicitar(
383                msg::SEND_MESSAGE,
384                &json!({
385                    "name": msg::GET_FINANCIAL_INFORMATION,
386                    "version": "1.0",
387                    "body": {
388                        "query": mapper::QUERY_ASSET_PROFILE,
389                        "operationName": "GetAssetProfileInfo",
390                        "variables": { "activeId": asset_id }
391                    }
392                }),
393                msg::FINANCIAL_INFORMATION,
394            )
395            .await?;
396        mapper::perfil_desde_financial(symbol, &respuesta).map_err(BrokerError::Rejected)
397    }
398    async fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError> {
399        let active_id = {
400            let catalogo = self.catalogo.read().await;
401            catalogo
402                .iter()
403                .find(|a| a.symbol == symbol)
404                .map(|a| a.opcode)
405                .ok_or_else(|| {
406                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
407                        symbol.into(),
408                    ))
409                })?
410        };
411        // Ambos canales: el agregado y el específico de binarias.
412        self.suscribir(
413            &format!("live-deals:{symbol}"),
414            msg::SUBSCRIBE_MESSAGE,
415            &json!({
416                "name": msg::LIVE_DEAL,
417                "version": "1.0",
418                "params": { "routingFilters": { "instrument_active_id": active_id } }
419            }),
420        )
421        .await?;
422        self.suscribir(
423            &format!("live-deals-bin:{symbol}"),
424            msg::SUBSCRIBE_MESSAGE,
425            &json!({
426                "name": msg::LIVE_DEAL_BINARY,
427                "version": "1.0",
428                "params": { "routingFilters": { "active_id": active_id, "option_type": "binary-option" } }
429            }),
430        )
431        .await?;
432        Ok(())
433    }
434
435    async fn subscribe_commission_changes(&self) -> Result<(), BrokerError> {
436        // Los tres tipos de opción: el bróker emite por instrumento.
437        for instrumento in ["binary-option", "turbo-option", "digital-option"] {
438            self.suscribir(
439                &format!("comision:{instrumento}"),
440                msg::SUBSCRIBE_MESSAGE,
441                &json!({
442                    "name": msg::COMMISSION_CHANGED,
443                    "version": "1.0",
444                    "params": { "routingFilters": { "instrument_type": instrumento } }
445                }),
446            )
447            .await?;
448        }
449        Ok(())
450    }
451    async fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
452        // BLITZ tiene su propia petición (duración en segundos y payout): se
453        // delega en `buy_blitz` para no transportar segundos en
454        // `expiration_minutes`.
455        if req.option_type == OptionType::Blitz {
456            let payout = {
457                let catalogo = self.catalogo.read().await;
458                catalogo
459                    .iter()
460                    .find(|a| a.symbol == req.symbol && a.class == AssetClass::Blitz)
461                    .and_then(|a| a.payout_percent)
462                    .unwrap_or(0.0)
463            };
464            return self
465                .buy_blitz(BuyBlitzRequest {
466                    symbol: req.symbol,
467                    amount: req.amount,
468                    direction: req.direction,
469                    expiration_size_secs: req.expiration_minutes,
470                    profit_percent: payout,
471                })
472                .await;
473        }
474
475        let asset = {
476            let catalogo = self.catalogo.read().await;
477            catalogo
478                .iter()
479                .find(|a| {
480                    a.symbol == req.symbol
481                        && (a.class == AssetClass::Binary || a.class == AssetClass::Turbo)
482                })
483                .cloned()
484        }
485        .ok_or_else(|| {
486            BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
487                req.symbol.clone(),
488            ))
489        })?;
490
491        if asset.status == MarketStatus::Closed {
492            return Err(BrokerError::Domain(
493                crate::domain::error::DomainError::MarketClosed(req.symbol),
494            ));
495        }
496        if let Some(extras) = &asset.extras {
497            if let Some(min) = extras.min_amount {
498                if req.amount < min {
499                    return Err(BrokerError::Domain(
500                        crate::domain::error::DomainError::InvalidAmount(format!("mínimo {min}")),
501                    ));
502                }
503            }
504        }
505
506        let mut body = json!({
507            "active_id": asset.opcode,
508            "user_balance_id": self.estado_lectura().await.session.as_ref()
509                .and_then(|s| s.balance_id),
510            "price": req.amount,
511            "direction": match req.direction { Direction::Call => "call", Direction::Put => "put" }
512        });
513
514        // Clásica v1.0: expiración por tabla de minutos/cuartos de hora.
515        let (expired, idx) =
516            mapper::tiempo_de_expiracion(self.hora_servidor_segs().await, req.expiration_minutes);
517        body["expired"] = json!(expired);
518        body["option_type_id"] = json!(if idx < 5 {
519            option_type_id::TURBO
520        } else {
521            option_type_id::BINARY
522        });
523
524        let (version, esperada) = ("1.0", msg::BUY_COMPLETE);
525        match self
526            .solicitar(
527                msg::SEND_MESSAGE,
528                &json!({ "name": msg::OPEN_OPTION, "version": version, "body": body }),
529                esperada,
530            )
531            .await
532        {
533            Ok(respuesta) => {
534                let id = respuesta
535                    .get("id")
536                    .and_then(|i| i.as_i64())
537                    .or_else(|| respuesta.pointer("/result/id").and_then(|i| i.as_i64()))
538                    .ok_or_else(|| {
539                        BrokerError::Rejected(
540                            respuesta
541                                .get("message")
542                                .and_then(|m| m.as_str())
543                                .unwrap_or("respuesta sin id de orden")
544                                .to_string(),
545                        )
546                    })?;
547                // Base de la reconciliación: hasta que llegue un cierre.
548                self.abiertas.write().await.insert(id.to_string());
549                Ok(id.to_string())
550            }
551            Err(e) => Err(e),
552        }
553    }
554
555    async fn buy_blitz(&self, req: BuyBlitzRequest) -> Result<OrderId, BrokerError> {
556        // El blitz se resuelve contra el grupo blitz del catálogo, cuyos
557        // metadatos (duraciones en segundos, rollovers) son propios.
558        let asset = {
559            let catalogo = self.catalogo.read().await;
560            catalogo
561                .iter()
562                .find(|a| a.symbol == req.symbol && a.class == AssetClass::Blitz)
563                .cloned()
564        }
565        .ok_or_else(|| {
566            BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
567                req.symbol.clone(),
568            ))
569        })?;
570
571        if asset.status == MarketStatus::Closed {
572            return Err(BrokerError::Domain(
573                crate::domain::error::DomainError::MarketClosed(req.symbol),
574            ));
575        }
576        let extras = asset
577            .extras
578            .as_ref()
579            .ok_or_else(|| BrokerError::Rejected("activo sin metadata de blitz".into()))?;
580        if let Some(min) = extras.min_amount {
581            if req.amount < min {
582                return Err(BrokerError::Domain(
583                    crate::domain::error::DomainError::InvalidAmount(format!("mínimo {min}")),
584                ));
585            }
586        }
587
588        // Duraciones admitidas: `option.expiration_times` ∪ `rollovers[].expiration_size`.
589        let mut permitidos = extras.expiration_times_secs.clone().unwrap_or_default();
590        for r in extras.rollovers.as_ref().into_iter().flatten() {
591            let s = r.expiration_size as u64;
592            if !permitidos.contains(&s) {
593                permitidos.push(s);
594            }
595        }
596        permitidos.sort_unstable();
597        let secs = req.expiration_size_secs;
598        if !permitidos.is_empty() && !permitidos.contains(&secs) {
599            return Err(BrokerError::Rejected(format!(
600                "duración {secs}s no admitida; admite {permitidos:?}"
601            )));
602        }
603
604        // Payout: el de la petición si viene informado; si no, el del catálogo.
605        let payout = if req.profit_percent > 0.0 {
606            req.profit_percent
607        } else {
608            asset.payout_percent.unwrap_or(0.0)
609        };
610
611        let body = json!({
612            "active_id": asset.opcode,
613            "user_balance_id": self.estado_lectura().await.session.as_ref()
614                .and_then(|s| s.balance_id),
615            "price": req.amount,
616            "direction": match req.direction { Direction::Call => "call", Direction::Put => "put" },
617            // `expired` debe quedar alineado al múltiplo de la duración.
618            "expired": mapper::expiracion_blitz_alineada(self.hora_servidor_segs().await, secs),
619            "expiration_size": secs,
620            // El bróker exige entero (rechaza "86.0").
621            "profit_percent": payout.round() as i64,
622            "option_type_id": option_type_id::BLITZ,
623        });
624
625        let respuesta = self
626            .solicitar(
627                msg::SEND_MESSAGE,
628                &json!({ "name": msg::OPEN_OPTION, "version": "2.0", "body": body }),
629                msg::OPTION,
630            )
631            .await?;
632        let id = respuesta
633            .get("id")
634            .and_then(|i| i.as_i64())
635            .or_else(|| respuesta.pointer("/result/id").and_then(|i| i.as_i64()))
636            .ok_or_else(|| {
637                BrokerError::Rejected(
638                    respuesta
639                        .get("message")
640                        .and_then(|m| m.as_str())
641                        .unwrap_or("respuesta sin id de orden blitz")
642                        .to_string(),
643                )
644            })?;
645        self.abiertas.write().await.insert(id.to_string());
646        Ok(id.to_string())
647    }
648
649    async fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError> {
650        let (asset_id, periodo) = {
651            let catalogo = self.catalogo.read().await;
652            let asset = catalogo
653                .iter()
654                .find(|a| a.symbol == req.symbol)
655                .ok_or_else(|| {
656                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
657                        req.symbol.clone(),
658                    ))
659                })?;
660            if asset.status == MarketStatus::Closed {
661                return Err(BrokerError::Domain(
662                    crate::domain::error::DomainError::MarketClosed(req.symbol),
663                ));
664            }
665            (asset.opcode, req.duration_minutes * 60)
666        };
667
668        // Suscripción price-splitter (payout + instrument_id en vivo).
669        self.suscribir(
670            &format!("splitter:{asset_id}"),
671            msg::SUBSCRIBE_MESSAGE,
672            &json!({
673                "name": msg::PRICE_SPLITTER,
674                "version": "1.0",
675                "params": { "routingFilters": { "instrument_type": "digital-option", "asset_id": asset_id } }
676            }),
677        )
678        .await?;
679        let mut rx = self.precios.subscribe();
680
681        // Espera el mensaje del periodo pedido: instrumento SPOT (strike "SPT")
682        // e instrument_index del MISMO mensaje (evita carreras de rollover).
683        let (instrument_id, asset_id_json, instrument_index) = loop {
684            let msg = tokio::time::timeout(std::time::Duration::from_secs(15), rx.recv())
685                .await
686                .map_err(|_| BrokerError::Timeout)?
687                .map_err(|e| BrokerError::Internal(format!("canal de precios cerrado: {e}")))?;
688            if msg.get("period").and_then(|p| p.as_u64()) != Some(periodo) {
689                continue;
690            }
691            if let Some(prices) = msg.pointer("/prices").and_then(|p| p.as_array()) {
692                let spot = prices
693                    .iter()
694                    .find(|p| p.get("strike").and_then(|s| s.as_str()) == Some("SPT"));
695                if let Some(spot) = spot {
696                    let campo = match req.direction {
697                        Direction::Call => "/call/symbol",
698                        Direction::Put => "/put/symbol",
699                    };
700                    if let Some(simbolo) = spot.pointer(campo).and_then(|s| s.as_str()) {
701                        let idx = msg
702                            .get("instrument_index")
703                            .and_then(|i| i.as_i64())
704                            .unwrap_or(0);
705                        let aid = msg.get("asset_id").cloned().unwrap_or(json!(asset_id));
706                        break (simbolo.to_string(), aid, idx);
707                    }
708                }
709            }
710        };
711        let balance_id = self
712            .estado_lectura()
713            .await
714            .session
715            .as_ref()
716            .and_then(|s| s.balance_id);
717        match self
718            .solicitar(
719                msg::SEND_MESSAGE,
720                &json!({
721                    "name": msg::PLACE_DIGITAL_OPTION,
722                    // v2.0 verificada en vivo: amount como STRING, con asset_id e
723                    // instrument_index del mismo mensaje de price-splitter.
724                    "version": "2.0",
725                    "body": {
726                        "user_balance_id": balance_id,
727                        "instrument_id": instrument_id,
728                        "asset_id": asset_id_json,
729                        "instrument_index": instrument_index,
730                        "amount": format!("{:.2}", req.amount)
731                    }
732                }),
733                msg::DIGITAL_OPTION_PLACED,
734            )
735            .await
736        {
737            Ok(respuesta) => {
738                let id = respuesta
739                    .get("id")
740                    .and_then(|i| i.as_i64())
741                    .ok_or_else(|| {
742                        BrokerError::Rejected(
743                            respuesta
744                                .get("message")
745                                .and_then(|m| m.as_str())
746                                .unwrap_or("respuesta sin id de orden digital")
747                                .to_string(),
748                        )
749                    })?;
750                // Correlación para `position-changed`: instrumento → id de orden.
751                self.digitales
752                    .write()
753                    .await
754                    .insert(instrument_id.clone(), id.to_string());
755                self.abiertas.write().await.insert(id.to_string());
756                Ok(id.to_string())
757            }
758            Err(e) => Err(e),
759        }
760    }
761
762    /// Lee el resultado de la caché local, alimentada por los eventos de
763    /// cierre (`option-closed`, `socket-option-closed`, `position-changed`).
764    ///
765    /// **No hace ninguna petición al bróker**: si el cierre aún no ha llegado
766    /// por eventos, devuelve `OperationResult::Pending`.
767    async fn get_operation_result(
768        &self,
769        order_id: &OrderId,
770    ) -> Result<OperationResult, BrokerError> {
771        let cache = self.resultados.read().await;
772        Ok(cache
773            .get(order_id)
774            .copied()
775            .unwrap_or(OperationResult::Pending))
776    }
777
778    // -------- Eventos --------
779
780    async fn events(&self) -> Result<EventStream, BrokerError> {
781        let rx = self.eventos.subscribe();
782        let stream = unfold(rx, |mut rx| async move {
783            match rx.recv().await {
784                Ok(ev) => Some((ev, rx)),
785                // Pérdida de continuidad: se informa y el stream continúa, en
786                // vez de cerrarse como si la sesión hubiera terminado.
787                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
788                    Some((Event::EventsLost { count: n }, rx))
789                }
790                Err(tokio::sync::broadcast::error::RecvError::Closed) => None,
791            }
792        });
793        Ok(Box::pin(stream))
794    }
795}