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