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 se consulta por `quote_payout`; este método
253        // conserva el valor del catálogo por compatibilidad.
254        Ok(Payout {
255            symbol: symbol.to_string(),
256            expiration_seconds,
257            profit_percent,
258            is_spot: asset.class == AssetClass::Digital,
259            strike: None,
260            closed: asset.status == MarketStatus::Closed,
261        })
262    }
263
264    /// Cotización viva por expiración y tipo de opción.
265    ///
266    /// IQ Option publica el payout digital en
267    /// `price-splitter.client-price-generated`: la entrada `SPT` es el spot y
268    /// `call.bid` el precio con el que se calcula el payout de CALL. El canal
269    /// se verificó en vivo con la cuenta; no hubo frames equivalentes para
270    /// `instrument-quotes-generated` (binary/turbo/blitz). Por eso esos tipos
271    /// devuelven `available: false` en vez de reutilizar el payout del
272    /// catálogo, que no es una cotización por expiración.
273    async fn quote_payout(
274        &self,
275        symbol: &str,
276        option_type: OptionType,
277        expiration_seconds: u64,
278        amount: f64,
279    ) -> Result<PayoutQuote, BrokerError> {
280        if expiration_seconds == 0 {
281            return Err(BrokerError::Rejected(
282                "iq_option: expiration_seconds debe ser positivo".into(),
283            ));
284        }
285
286        let asset = {
287            let catalogo = self.catalogo.read().await;
288            catalogo
289                .iter()
290                .find(|a| a.symbol == symbol)
291                .cloned()
292                .ok_or_else(|| {
293                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
294                        symbol.into(),
295                    ))
296                })?
297        };
298
299        // `amount` no altera el precio digital de IQ; se conserva por contrato.
300        let _ = amount;
301
302        if option_type != OptionType::Digital || asset.status == MarketStatus::Closed {
303            return Ok(PayoutQuote::unavailable(
304                symbol,
305                option_type,
306                expiration_seconds,
307            ));
308        }
309
310        self.suscribir(
311            &format!("splitter:{}", asset.opcode),
312            msg::SUBSCRIBE_MESSAGE,
313            &json!({
314                "name": msg::PRICE_SPLITTER,
315                "version": "1.0",
316                "params": { "routingFilters": { "instrument_type": "digital-option", "asset_id": asset.opcode } }
317            }),
318        )
319        .await?;
320
321        let mut precios = self.precios.subscribe();
322        // Mismo plazo que la compra digital: si el bróker no publica el periodo,
323        // la respuesta correcta es “sin cotización”, no un payout inventado.
324        let plazo = std::time::Duration::from_secs(15);
325        let limite = tokio::time::Instant::now() + plazo;
326        loop {
327            let restante = limite.saturating_duration_since(tokio::time::Instant::now());
328            if restante.is_zero() {
329                return Ok(PayoutQuote::unavailable(
330                    symbol,
331                    option_type,
332                    expiration_seconds,
333                ));
334            }
335            let mensaje = match tokio::time::timeout(restante, precios.recv()).await {
336                Err(_) => {
337                    return Ok(PayoutQuote::unavailable(
338                        symbol,
339                        option_type,
340                        expiration_seconds,
341                    ))
342                }
343                Ok(Ok(mensaje)) => mensaje,
344                Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => continue,
345                Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) => {
346                    return Err(BrokerError::Internal(
347                        "iq_option: canal de precios cerrado".into(),
348                    ))
349                }
350            };
351
352            if mensaje.get("asset_id").and_then(|v| v.as_u64()) != Some(u64::from(asset.opcode))
353                || mensaje.get("period").and_then(|v| v.as_u64()) != Some(expiration_seconds)
354            {
355                continue;
356            }
357
358            let Some(payout) = mapper::payout_price_splitter(&mensaje, Direction::Call) else {
359                continue;
360            };
361            let extras = asset.extras.as_ref();
362            return Ok(PayoutQuote {
363                symbol: symbol.to_string(),
364                option_type,
365                expiration_seconds,
366                profit_percent: Some(payout.profit_percent),
367                min_amount: extras.and_then(|e| e.min_amount),
368                max_amount: extras.and_then(|e| e.max_amount),
369                available: true,
370                captured_at: self.hora_servidor_segs().await,
371            });
372        }
373    }
374
375    async fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
376        // Mensaje `sell-options` v2.0 con la lista de ids (verificado contra
377        // el canal del bróker; el bróker confirma con `sold-options`).
378        let id_num = order_id
379            .parse::<i64>()
380            .map_err(|_| BrokerError::Rejected(format!("id de orden no numerico: {order_id}")))?;
381        let respuesta = self
382            .solicitar(
383                msg::SEND_MESSAGE,
384                &json!({
385                    "name": msg::SELL_OPTIONS,
386                    "version": "2.0",
387                    "body": { "options_ids": [id_num] }
388                }),
389                msg::SOLD_OPTIONS,
390            )
391            .await?;
392        // El broker responde con el detalle de la venta o con error.
393        if respuesta.get("message").is_some() {
394            return Err(BrokerError::Rejected(
395                respuesta
396                    .get("message")
397                    .and_then(|m| m.as_str())
398                    .unwrap_or("venta rechazada")
399                    .to_string(),
400            ));
401        }
402        Ok(())
403    }
404
405    async fn get_position_history(
406        &self,
407        symbol: Option<&str>,
408        limit: usize,
409        offset: usize,
410    ) -> Result<PositionHistory, BrokerError> {
411        let balance_id = self
412            .estado_lectura()
413            .await
414            .session
415            .as_ref()
416            .and_then(|s| s.balance_id);
417        let limit = limit.min(100) as u64;
418        let respuesta = self
419            .solicitar(
420                msg::SEND_MESSAGE,
421                &json!({
422                    "name": msg::PORTFOLIO_GET_HISTORY,
423                    "body": {
424                        "instrument_types": ["turbo-option", "binary-option", "digital-option"],
425                        "limit": limit,
426                        "offset": offset as u64,
427                        "start": 0,
428                        "end": 0,
429                        "user_balance_id": balance_id
430                    }
431                }),
432                msg::HISTORY_POSITIONS,
433            )
434            .await?;
435        let historial = mapper::historial_desde_positions(&respuesta, offset)
436            .ok_or_else(|| BrokerError::Rejected("respuesta sin positions".into()))?;
437        if let Some(simbolo) = symbol {
438            if historial.positions.iter().all(|p| p.symbol != simbolo) {
439                return Err(BrokerError::Domain(
440                    crate::domain::error::DomainError::OperationNotFound(format!(
441                        "sin historial para {simbolo}"
442                    )),
443                ));
444            }
445        }
446        Ok(historial)
447    }
448
449    // -------- Órdenes --------
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    /// Lee el resultado de la caché local, alimentada por los eventos de
556    /// cierre (`option-closed`, `socket-option-closed`, `position-changed`).
557    ///
558    /// **No hace ninguna petición al bróker**: si el cierre aún no ha llegado
559    /// por eventos, devuelve `OperationResult::Pending`.
560    async fn get_operation_result(
561        &self,
562        order_id: &OrderId,
563    ) -> Result<OperationResult, BrokerError> {
564        let cache = self.resultados.read().await;
565        Ok(cache
566            .get(order_id)
567            .copied()
568            .unwrap_or(OperationResult::Pending))
569    }
570
571    // -------- Eventos --------
572
573    async fn events(&self) -> Result<EventStream, BrokerError> {
574        let rx = self.eventos.subscribe();
575        let stream = unfold(rx, |mut rx| async move {
576            match rx.recv().await {
577                Ok(ev) => Some((ev, rx)),
578                // Pérdida de continuidad: se informa y el stream continúa, en
579                // vez de cerrarse como si la sesión hubiera terminado.
580                Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
581                    Some((Event::EventsLost { count: n }, rx))
582                }
583                Err(tokio::sync::broadcast::error::RecvError::Closed) => None,
584            }
585        });
586        Ok(Box::pin(stream))
587    }
588}
589
590impl IqOptionBroker {
591    pub async fn get_technical_indicators(
592        &self,
593        symbol: &str,
594    ) -> Result<TechnicalIndicators, BrokerError> {
595        let asset_id = {
596            let catalogo = self.catalogo.read().await;
597            catalogo
598                .iter()
599                .find(|a| a.symbol == symbol)
600                .map(|a| a.opcode)
601                .ok_or_else(|| {
602                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
603                        symbol.into(),
604                    ))
605                })?
606        };
607        // Mensaje: `trading-signals.get-technical-indicators` v1.0, body {id}.
608        // El `id` DEBE ser entero (string → INVALID_SCHEMA). Respuesta:
609        // `technical-indicators` con `msg.indicators`, o `msg.message` de error.
610        let respuesta = self
611            .solicitar(
612                msg::SEND_MESSAGE,
613                &json!({
614                    "name": msg::TECHNICAL_INDICATORS,
615                    "version": "1.0",
616                    "body": { "id": asset_id }
617                }),
618                msg::TECHNICAL_INDICATORS_RESPONSE,
619            )
620            .await?;
621        mapper::indicadores_desde_respuesta(&respuesta, symbol).map_err(BrokerError::Rejected)
622    }
623
624    pub async fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError> {
625        let asset_id = {
626            let catalogo = self.catalogo.read().await;
627            catalogo
628                .iter()
629                .find(|a| a.symbol == symbol)
630                .map(|a| a.opcode)
631                .ok_or_else(|| {
632                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
633                        symbol.into(),
634                    ))
635                })?
636        };
637        // GraphQL: el broker responde `financial-information` con data.active.
638        let respuesta = self
639            .solicitar(
640                msg::SEND_MESSAGE,
641                &json!({
642                    "name": msg::GET_FINANCIAL_INFORMATION,
643                    "version": "1.0",
644                    "body": {
645                        "query": mapper::QUERY_ASSET_PROFILE,
646                        "operationName": "GetAssetProfileInfo",
647                        "variables": { "activeId": asset_id }
648                    }
649                }),
650                msg::FINANCIAL_INFORMATION,
651            )
652            .await?;
653        mapper::perfil_desde_financial(symbol, &respuesta).map_err(BrokerError::Rejected)
654    }
655
656    pub async fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError> {
657        let active_id = {
658            let catalogo = self.catalogo.read().await;
659            catalogo
660                .iter()
661                .find(|a| a.symbol == symbol)
662                .map(|a| a.opcode)
663                .ok_or_else(|| {
664                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
665                        symbol.into(),
666                    ))
667                })?
668        };
669        // Ambos canales: el agregado y el específico de binarias.
670        self.suscribir(
671            &format!("live-deals:{symbol}"),
672            msg::SUBSCRIBE_MESSAGE,
673            &json!({
674                "name": msg::LIVE_DEAL,
675                "version": "1.0",
676                "params": { "routingFilters": { "instrument_active_id": active_id } }
677            }),
678        )
679        .await?;
680        self.suscribir(
681            &format!("live-deals-bin:{symbol}"),
682            msg::SUBSCRIBE_MESSAGE,
683            &json!({
684                "name": msg::LIVE_DEAL_BINARY,
685                "version": "1.0",
686                "params": { "routingFilters": { "active_id": active_id, "option_type": "binary-option" } }
687            }),
688        )
689        .await?;
690        Ok(())
691    }
692
693    pub async fn subscribe_commission_changes(&self) -> Result<(), BrokerError> {
694        // Los tres tipos de opción: el bróker emite por instrumento.
695        for instrumento in ["binary-option", "turbo-option", "digital-option"] {
696            self.suscribir(
697                &format!("comision:{instrumento}"),
698                msg::SUBSCRIBE_MESSAGE,
699                &json!({
700                    "name": msg::COMMISSION_CHANGED,
701                    "version": "1.0",
702                    "params": { "routingFilters": { "instrument_type": instrumento } }
703                }),
704            )
705            .await?;
706        }
707        Ok(())
708    }
709
710    pub async fn buy_blitz(&self, req: BuyBlitzRequest) -> Result<OrderId, BrokerError> {
711        // El blitz se resuelve contra el grupo blitz del catálogo, cuyos
712        // metadatos (duraciones en segundos, rollovers) son propios.
713        let asset = {
714            let catalogo = self.catalogo.read().await;
715            catalogo
716                .iter()
717                .find(|a| a.symbol == req.symbol && a.class == AssetClass::Blitz)
718                .cloned()
719        }
720        .ok_or_else(|| {
721            BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
722                req.symbol.clone(),
723            ))
724        })?;
725
726        if asset.status == MarketStatus::Closed {
727            return Err(BrokerError::Domain(
728                crate::domain::error::DomainError::MarketClosed(req.symbol),
729            ));
730        }
731        let extras = asset
732            .extras
733            .as_ref()
734            .ok_or_else(|| BrokerError::Rejected("activo sin metadata de blitz".into()))?;
735        if let Some(min) = extras.min_amount {
736            if req.amount < min {
737                return Err(BrokerError::Domain(
738                    crate::domain::error::DomainError::InvalidAmount(format!("mínimo {min}")),
739                ));
740            }
741        }
742
743        // Duraciones admitidas: `option.expiration_times` ∪ `rollovers[].expiration_size`.
744        let mut permitidos = extras.expiration_times_secs.clone().unwrap_or_default();
745        for r in extras.rollovers.as_ref().into_iter().flatten() {
746            let s = r.expiration_size as u64;
747            if !permitidos.contains(&s) {
748                permitidos.push(s);
749            }
750        }
751        permitidos.sort_unstable();
752        let secs = req.expiration_size_secs;
753        if !permitidos.is_empty() && !permitidos.contains(&secs) {
754            return Err(BrokerError::Rejected(format!(
755                "duración {secs}s no admitida; admite {permitidos:?}"
756            )));
757        }
758
759        // Payout: el de la petición si viene informado; si no, el del catálogo.
760        let payout = if req.profit_percent > 0.0 {
761            req.profit_percent
762        } else {
763            asset.payout_percent.unwrap_or(0.0)
764        };
765
766        let body = json!({
767            "active_id": asset.opcode,
768            "user_balance_id": self.estado_lectura().await.session.as_ref()
769                .and_then(|s| s.balance_id),
770            "price": req.amount,
771            "direction": match req.direction { Direction::Call => "call", Direction::Put => "put" },
772            // `expired` debe quedar alineado al múltiplo de la duración.
773            "expired": mapper::expiracion_blitz_alineada(self.hora_servidor_segs().await, secs),
774            "expiration_size": secs,
775            // El bróker exige entero (rechaza "86.0").
776            "profit_percent": payout.round() as i64,
777            "option_type_id": option_type_id::BLITZ,
778        });
779
780        let respuesta = self
781            .solicitar(
782                msg::SEND_MESSAGE,
783                &json!({ "name": msg::OPEN_OPTION, "version": "2.0", "body": body }),
784                msg::OPTION,
785            )
786            .await?;
787        let id = respuesta
788            .get("id")
789            .and_then(|i| i.as_i64())
790            .or_else(|| respuesta.pointer("/result/id").and_then(|i| i.as_i64()))
791            .ok_or_else(|| {
792                BrokerError::Rejected(
793                    respuesta
794                        .get("message")
795                        .and_then(|m| m.as_str())
796                        .unwrap_or("respuesta sin id de orden blitz")
797                        .to_string(),
798                )
799            })?;
800        self.abiertas.write().await.insert(id.to_string());
801        Ok(id.to_string())
802    }
803
804    pub async fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError> {
805        let (asset_id, periodo) = {
806            let catalogo = self.catalogo.read().await;
807            let asset = catalogo
808                .iter()
809                .find(|a| a.symbol == req.symbol)
810                .ok_or_else(|| {
811                    BrokerError::Domain(crate::domain::error::DomainError::AssetNotFound(
812                        req.symbol.clone(),
813                    ))
814                })?;
815            if asset.status == MarketStatus::Closed {
816                return Err(BrokerError::Domain(
817                    crate::domain::error::DomainError::MarketClosed(req.symbol),
818                ));
819            }
820            (asset.opcode, req.duration_minutes * 60)
821        };
822
823        // Suscripción price-splitter (payout + instrument_id en vivo).
824        self.suscribir(
825            &format!("splitter:{asset_id}"),
826            msg::SUBSCRIBE_MESSAGE,
827            &json!({
828                "name": msg::PRICE_SPLITTER,
829                "version": "1.0",
830                "params": { "routingFilters": { "instrument_type": "digital-option", "asset_id": asset_id } }
831            }),
832        )
833        .await?;
834        let mut rx = self.precios.subscribe();
835
836        // Espera el mensaje del periodo pedido: instrumento SPOT (strike "SPT")
837        // e instrument_index del MISMO mensaje (evita carreras de rollover).
838        let (instrument_id, asset_id_json, instrument_index) = loop {
839            let msg = tokio::time::timeout(std::time::Duration::from_secs(15), rx.recv())
840                .await
841                .map_err(|_| BrokerError::Timeout)?
842                .map_err(|e| BrokerError::Internal(format!("canal de precios cerrado: {e}")))?;
843            if msg.get("period").and_then(|p| p.as_u64()) != Some(periodo) {
844                continue;
845            }
846            if let Some(prices) = msg.pointer("/prices").and_then(|p| p.as_array()) {
847                let spot = prices
848                    .iter()
849                    .find(|p| p.get("strike").and_then(|s| s.as_str()) == Some("SPT"));
850                if let Some(spot) = spot {
851                    let campo = match req.direction {
852                        Direction::Call => "/call/symbol",
853                        Direction::Put => "/put/symbol",
854                    };
855                    if let Some(simbolo) = spot.pointer(campo).and_then(|s| s.as_str()) {
856                        let idx = msg
857                            .get("instrument_index")
858                            .and_then(|i| i.as_i64())
859                            .unwrap_or(0);
860                        let aid = msg.get("asset_id").cloned().unwrap_or(json!(asset_id));
861                        break (simbolo.to_string(), aid, idx);
862                    }
863                }
864            }
865        };
866        let balance_id = self
867            .estado_lectura()
868            .await
869            .session
870            .as_ref()
871            .and_then(|s| s.balance_id);
872        match self
873            .solicitar(
874                msg::SEND_MESSAGE,
875                &json!({
876                    "name": msg::PLACE_DIGITAL_OPTION,
877                    // v2.0 verificada en vivo: amount como STRING, con asset_id e
878                    // instrument_index del mismo mensaje de price-splitter.
879                    "version": "2.0",
880                    "body": {
881                        "user_balance_id": balance_id,
882                        "instrument_id": instrument_id,
883                        "asset_id": asset_id_json,
884                        "instrument_index": instrument_index,
885                        "amount": format!("{:.2}", req.amount)
886                    }
887                }),
888                msg::DIGITAL_OPTION_PLACED,
889            )
890            .await
891        {
892            Ok(respuesta) => {
893                let id = respuesta
894                    .get("id")
895                    .and_then(|i| i.as_i64())
896                    .ok_or_else(|| {
897                        BrokerError::Rejected(
898                            respuesta
899                                .get("message")
900                                .and_then(|m| m.as_str())
901                                .unwrap_or("respuesta sin id de orden digital")
902                                .to_string(),
903                        )
904                    })?;
905                // Correlación para `position-changed`: instrumento → id de orden.
906                self.digitales
907                    .write()
908                    .await
909                    .insert(instrument_id.clone(), id.to_string());
910                self.abiertas.write().await.insert(id.to_string());
911                Ok(id.to_string())
912            }
913            Err(e) => Err(e),
914        }
915    }
916}