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
333    // -------- Órdenes --------
334
335    async fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
336        // BLITZ tiene su propia petición (duración en segundos y payout): se
337        // delega en `buy_blitz` para no transportar segundos en
338        // `expiration_minutes`.
339        if req.option_type == OptionType::Blitz {
340            let payout = {
341                let catalogo = self.catalogo.read().await;
342                catalogo
343                    .iter()
344                    .find(|a| a.symbol == req.symbol && a.class == AssetClass::Blitz)
345                    .and_then(|a| a.payout_percent)
346                    .unwrap_or(0.0)
347            };
348            return self
349                .buy_blitz(BuyBlitzRequest {
350                    symbol: req.symbol,
351                    amount: req.amount,
352                    direction: req.direction,
353                    expiration_size_secs: req.expiration_minutes,
354                    profit_percent: payout,
355                })
356                .await;
357        }
358
359        let asset = {
360            let catalogo = self.catalogo.read().await;
361            catalogo
362                .iter()
363                .find(|a| {
364                    a.symbol == req.symbol
365                        && (a.class == AssetClass::Binary || a.class == AssetClass::Turbo)
366                })
367                .cloned()
368        }
369        .ok_or_else(|| {
370            BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
371                req.symbol.clone(),
372            ))
373        })?;
374
375        if asset.status == MarketStatus::Closed {
376            return Err(BrokerError::Domain(
377                crate::domain::error::DomainError::MarketClosed(req.symbol),
378            ));
379        }
380        if let Some(extras) = &asset.extras {
381            if let Some(min) = extras.min_amount {
382                if req.amount < min {
383                    return Err(BrokerError::Domain(
384                        crate::domain::error::DomainError::InvalidAmount(format!("mínimo {min}")),
385                    ));
386                }
387            }
388        }
389
390        let mut body = json!({
391            "active_id": asset.opcode,
392            "user_balance_id": self.estado_lectura().await.session.as_ref()
393                .and_then(|s| s.balance_id),
394            "price": req.amount,
395            "direction": match req.direction { Direction::Call => "call", Direction::Put => "put" }
396        });
397
398        // Clásica v1.0: expiración por tabla de minutos/cuartos de hora.
399        let (expired, idx) =
400            mapper::tiempo_de_expiracion(self.hora_servidor_segs().await, req.expiration_minutes);
401        body["expired"] = json!(expired);
402        body["option_type_id"] = json!(if idx < 5 {
403            option_type_id::TURBO
404        } else {
405            option_type_id::BINARY
406        });
407
408        let (version, esperada) = ("1.0", msg::BUY_COMPLETE);
409        match self
410            .solicitar(
411                msg::SEND_MESSAGE,
412                &json!({ "name": msg::OPEN_OPTION, "version": version, "body": body }),
413                esperada,
414            )
415            .await
416        {
417            Ok(respuesta) => {
418                let id = respuesta
419                    .get("id")
420                    .and_then(|i| i.as_i64())
421                    .or_else(|| respuesta.pointer("/result/id").and_then(|i| i.as_i64()))
422                    .ok_or_else(|| {
423                        BrokerError::Rejected(
424                            respuesta
425                                .get("message")
426                                .and_then(|m| m.as_str())
427                                .unwrap_or("respuesta sin id de orden")
428                                .to_string(),
429                        )
430                    })?;
431                // Base de la reconciliación: hasta que llegue un cierre.
432                self.abiertas.write().await.insert(id.to_string());
433                Ok(id.to_string())
434            }
435            Err(e) => Err(e),
436        }
437    }
438
439    /// Lee el resultado de la caché local, alimentada por los eventos de
440    /// cierre (`option-closed`, `socket-option-closed`, `position-changed`).
441    ///
442    /// **No hace ninguna petición al bróker**: si el cierre aún no ha llegado
443    /// por eventos, devuelve `OperationResult::Pending`.
444    async fn get_operation_result(
445        &self,
446        order_id: &OrderId,
447    ) -> Result<OperationResult, BrokerError> {
448        let cache = self.resultados.read().await;
449        Ok(cache
450            .get(order_id)
451            .copied()
452            .unwrap_or(OperationResult::Pending))
453    }
454
455    // -------- Eventos --------
456
457    async fn events(&self) -> Result<EventStream, BrokerError> {
458        let rx = self.eventos.subscribe();
459        let stream = unfold(rx, |mut rx| async move {
460            match rx.recv().await {
461                Ok(ev) => Some((ev, rx)),
462                // Pérdida de continuidad: se informa y el stream continúa, en
463                // vez de cerrarse como si la sesión hubiera terminado.
464                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
465                    Some((Event::EventsLost { count: n }, rx))
466                }
467                Err(tokio::sync::broadcast::error::RecvError::Closed) => None,
468            }
469        });
470        Ok(Box::pin(stream))
471    }
472}
473
474impl IqOptionBroker {
475    pub async fn get_technical_indicators(
476        &self,
477        symbol: &str,
478    ) -> Result<TechnicalIndicators, BrokerError> {
479        let asset_id = {
480            let catalogo = self.catalogo.read().await;
481            catalogo
482                .iter()
483                .find(|a| a.symbol == symbol)
484                .map(|a| a.opcode)
485                .ok_or_else(|| {
486                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
487                        symbol.into(),
488                    ))
489                })?
490        };
491        // Mensaje: `trading-signals.get-technical-indicators` v1.0, body {id}.
492        // El `id` DEBE ser entero (string → INVALID_SCHEMA). Respuesta:
493        // `technical-indicators` con `msg.indicators`, o `msg.message` de error.
494        let respuesta = self
495            .solicitar(
496                msg::SEND_MESSAGE,
497                &json!({
498                    "name": msg::TECHNICAL_INDICATORS,
499                    "version": "1.0",
500                    "body": { "id": asset_id }
501                }),
502                msg::TECHNICAL_INDICATORS_RESPONSE,
503            )
504            .await?;
505        mapper::indicadores_desde_respuesta(&respuesta, symbol).map_err(BrokerError::Rejected)
506    }
507
508    pub async fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError> {
509        let asset_id = {
510            let catalogo = self.catalogo.read().await;
511            catalogo
512                .iter()
513                .find(|a| a.symbol == symbol)
514                .map(|a| a.opcode)
515                .ok_or_else(|| {
516                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
517                        symbol.into(),
518                    ))
519                })?
520        };
521        // GraphQL: el broker responde `financial-information` con data.active.
522        let respuesta = self
523            .solicitar(
524                msg::SEND_MESSAGE,
525                &json!({
526                    "name": msg::GET_FINANCIAL_INFORMATION,
527                    "version": "1.0",
528                    "body": {
529                        "query": mapper::QUERY_ASSET_PROFILE,
530                        "operationName": "GetAssetProfileInfo",
531                        "variables": { "activeId": asset_id }
532                    }
533                }),
534                msg::FINANCIAL_INFORMATION,
535            )
536            .await?;
537        mapper::perfil_desde_financial(symbol, &respuesta).map_err(BrokerError::Rejected)
538    }
539
540    pub async fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError> {
541        let active_id = {
542            let catalogo = self.catalogo.read().await;
543            catalogo
544                .iter()
545                .find(|a| a.symbol == symbol)
546                .map(|a| a.opcode)
547                .ok_or_else(|| {
548                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
549                        symbol.into(),
550                    ))
551                })?
552        };
553        // Ambos canales: el agregado y el específico de binarias.
554        self.suscribir(
555            &format!("live-deals:{symbol}"),
556            msg::SUBSCRIBE_MESSAGE,
557            &json!({
558                "name": msg::LIVE_DEAL,
559                "version": "1.0",
560                "params": { "routingFilters": { "instrument_active_id": active_id } }
561            }),
562        )
563        .await?;
564        self.suscribir(
565            &format!("live-deals-bin:{symbol}"),
566            msg::SUBSCRIBE_MESSAGE,
567            &json!({
568                "name": msg::LIVE_DEAL_BINARY,
569                "version": "1.0",
570                "params": { "routingFilters": { "active_id": active_id, "option_type": "binary-option" } }
571            }),
572        )
573        .await?;
574        Ok(())
575    }
576
577    pub async fn subscribe_commission_changes(&self) -> Result<(), BrokerError> {
578        // Los tres tipos de opción: el bróker emite por instrumento.
579        for instrumento in ["binary-option", "turbo-option", "digital-option"] {
580            self.suscribir(
581                &format!("comision:{instrumento}"),
582                msg::SUBSCRIBE_MESSAGE,
583                &json!({
584                    "name": msg::COMMISSION_CHANGED,
585                    "version": "1.0",
586                    "params": { "routingFilters": { "instrument_type": instrumento } }
587                }),
588            )
589            .await?;
590        }
591        Ok(())
592    }
593
594    pub async fn buy_blitz(&self, req: BuyBlitzRequest) -> Result<OrderId, BrokerError> {
595        // El blitz se resuelve contra el grupo blitz del catálogo, cuyos
596        // metadatos (duraciones en segundos, rollovers) son propios.
597        let asset = {
598            let catalogo = self.catalogo.read().await;
599            catalogo
600                .iter()
601                .find(|a| a.symbol == req.symbol && a.class == AssetClass::Blitz)
602                .cloned()
603        }
604        .ok_or_else(|| {
605            BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
606                req.symbol.clone(),
607            ))
608        })?;
609
610        if asset.status == MarketStatus::Closed {
611            return Err(BrokerError::Domain(
612                crate::domain::error::DomainError::MarketClosed(req.symbol),
613            ));
614        }
615        let extras = asset
616            .extras
617            .as_ref()
618            .ok_or_else(|| BrokerError::Rejected("activo sin metadata de blitz".into()))?;
619        if let Some(min) = extras.min_amount {
620            if req.amount < min {
621                return Err(BrokerError::Domain(
622                    crate::domain::error::DomainError::InvalidAmount(format!("mínimo {min}")),
623                ));
624            }
625        }
626
627        // Duraciones admitidas: `option.expiration_times` ∪ `rollovers[].expiration_size`.
628        let mut permitidos = extras.expiration_times_secs.clone().unwrap_or_default();
629        for r in extras.rollovers.as_ref().into_iter().flatten() {
630            let s = r.expiration_size as u64;
631            if !permitidos.contains(&s) {
632                permitidos.push(s);
633            }
634        }
635        permitidos.sort_unstable();
636        let secs = req.expiration_size_secs;
637        if !permitidos.is_empty() && !permitidos.contains(&secs) {
638            return Err(BrokerError::Rejected(format!(
639                "duración {secs}s no admitida; admite {permitidos:?}"
640            )));
641        }
642
643        // Payout: el de la petición si viene informado; si no, el del catálogo.
644        let payout = if req.profit_percent > 0.0 {
645            req.profit_percent
646        } else {
647            asset.payout_percent.unwrap_or(0.0)
648        };
649
650        let body = json!({
651            "active_id": asset.opcode,
652            "user_balance_id": self.estado_lectura().await.session.as_ref()
653                .and_then(|s| s.balance_id),
654            "price": req.amount,
655            "direction": match req.direction { Direction::Call => "call", Direction::Put => "put" },
656            // `expired` debe quedar alineado al múltiplo de la duración.
657            "expired": mapper::expiracion_blitz_alineada(self.hora_servidor_segs().await, secs),
658            "expiration_size": secs,
659            // El bróker exige entero (rechaza "86.0").
660            "profit_percent": payout.round() as i64,
661            "option_type_id": option_type_id::BLITZ,
662        });
663
664        let respuesta = self
665            .solicitar(
666                msg::SEND_MESSAGE,
667                &json!({ "name": msg::OPEN_OPTION, "version": "2.0", "body": body }),
668                msg::OPTION,
669            )
670            .await?;
671        let id = respuesta
672            .get("id")
673            .and_then(|i| i.as_i64())
674            .or_else(|| respuesta.pointer("/result/id").and_then(|i| i.as_i64()))
675            .ok_or_else(|| {
676                BrokerError::Rejected(
677                    respuesta
678                        .get("message")
679                        .and_then(|m| m.as_str())
680                        .unwrap_or("respuesta sin id de orden blitz")
681                        .to_string(),
682                )
683            })?;
684        self.abiertas.write().await.insert(id.to_string());
685        Ok(id.to_string())
686    }
687
688    pub async fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError> {
689        let (asset_id, periodo) = {
690            let catalogo = self.catalogo.read().await;
691            let asset = catalogo
692                .iter()
693                .find(|a| a.symbol == req.symbol)
694                .ok_or_else(|| {
695                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
696                        req.symbol.clone(),
697                    ))
698                })?;
699            if asset.status == MarketStatus::Closed {
700                return Err(BrokerError::Domain(
701                    crate::domain::error::DomainError::MarketClosed(req.symbol),
702                ));
703            }
704            (asset.opcode, req.duration_minutes * 60)
705        };
706
707        // Suscripción price-splitter (payout + instrument_id en vivo).
708        self.suscribir(
709            &format!("splitter:{asset_id}"),
710            msg::SUBSCRIBE_MESSAGE,
711            &json!({
712                "name": msg::PRICE_SPLITTER,
713                "version": "1.0",
714                "params": { "routingFilters": { "instrument_type": "digital-option", "asset_id": asset_id } }
715            }),
716        )
717        .await?;
718        let mut rx = self.precios.subscribe();
719
720        // Espera el mensaje del periodo pedido: instrumento SPOT (strike "SPT")
721        // e instrument_index del MISMO mensaje (evita carreras de rollover).
722        let (instrument_id, asset_id_json, instrument_index) = loop {
723            let msg = tokio::time::timeout(std::time::Duration::from_secs(15), rx.recv())
724                .await
725                .map_err(|_| BrokerError::Timeout)?
726                .map_err(|e| BrokerError::Internal(format!("canal de precios cerrado: {e}")))?;
727            if msg.get("period").and_then(|p| p.as_u64()) != Some(periodo) {
728                continue;
729            }
730            if let Some(prices) = msg.pointer("/prices").and_then(|p| p.as_array()) {
731                let spot = prices
732                    .iter()
733                    .find(|p| p.get("strike").and_then(|s| s.as_str()) == Some("SPT"));
734                if let Some(spot) = spot {
735                    let campo = match req.direction {
736                        Direction::Call => "/call/symbol",
737                        Direction::Put => "/put/symbol",
738                    };
739                    if let Some(simbolo) = spot.pointer(campo).and_then(|s| s.as_str()) {
740                        let idx = msg
741                            .get("instrument_index")
742                            .and_then(|i| i.as_i64())
743                            .unwrap_or(0);
744                        let aid = msg.get("asset_id").cloned().unwrap_or(json!(asset_id));
745                        break (simbolo.to_string(), aid, idx);
746                    }
747                }
748            }
749        };
750        let balance_id = self
751            .estado_lectura()
752            .await
753            .session
754            .as_ref()
755            .and_then(|s| s.balance_id);
756        match self
757            .solicitar(
758                msg::SEND_MESSAGE,
759                &json!({
760                    "name": msg::PLACE_DIGITAL_OPTION,
761                    // v2.0 verificada en vivo: amount como STRING, con asset_id e
762                    // instrument_index del mismo mensaje de price-splitter.
763                    "version": "2.0",
764                    "body": {
765                        "user_balance_id": balance_id,
766                        "instrument_id": instrument_id,
767                        "asset_id": asset_id_json,
768                        "instrument_index": instrument_index,
769                        "amount": format!("{:.2}", req.amount)
770                    }
771                }),
772                msg::DIGITAL_OPTION_PLACED,
773            )
774            .await
775        {
776            Ok(respuesta) => {
777                let id = respuesta
778                    .get("id")
779                    .and_then(|i| i.as_i64())
780                    .ok_or_else(|| {
781                        BrokerError::Rejected(
782                            respuesta
783                                .get("message")
784                                .and_then(|m| m.as_str())
785                                .unwrap_or("respuesta sin id de orden digital")
786                                .to_string(),
787                        )
788                    })?;
789                // Correlación para `position-changed`: instrumento → id de orden.
790                self.digitales
791                    .write()
792                    .await
793                    .insert(instrument_id.clone(), id.to_string());
794                self.abiertas.write().await.insert(id.to_string());
795                Ok(id.to_string())
796            }
797            Err(e) => Err(e),
798        }
799    }
800}