Skip to main content

cripsy_binary_api/broker/deriv/
session.rs

1//! Sesión del adaptador Deriv: WebSocket, OTP, router y supervisor.
2//!
3//! Arquitectura: una tarea posee el socket y atiende un `select!` entre la cola
4//! de salida y los mensajes entrantes. Las llamadas registran un `req_id`
5//! numérico y esperan su respuesta con plazo. La reconexión pide un **OTP
6//! nuevo** (el anterior es de un solo uso) y reproduce las suscripciones.
7
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13use futures_util::stream::{SplitSink, SplitStream};
14use futures_util::{SinkExt, StreamExt};
15use serde_json::{json, Value};
16use tokio::sync::{broadcast, mpsc, oneshot, watch, Notify, RwLock};
17use tokio::task::JoinHandle;
18use tokio_tungstenite::tungstenite::Message;
19use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
20
21use crate::broker::config::{AccountSelection, BrokerParams};
22use crate::broker::deriv::config::{DerivConfig, LimitesTasa};
23use crate::broker::deriv::protocol;
24use crate::broker::error::BrokerError;
25use crate::broker::session::Session;
26use crate::broker::trait_::{Broker, CandleStream, EventStream};
27use crate::domain::*;
28
29// ---------------------------------------------------------------------------
30// Tipos internos
31// ---------------------------------------------------------------------------
32
33type Ws = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
34type Escritor = SplitSink<Ws, Message>;
35type Lector = SplitStream<Ws>;
36
37/// Plazo por defecto de una petición.
38const PLAZO: Duration = Duration::from_secs(15);
39
40/// Granularidades de velas admitidas por Deriv.
41const GRANULARIDADES: [u64; 12] = [
42    60, 120, 180, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400,
43];
44
45/// Clase de presupuesto de tasa.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47enum Clase {
48    Trading,
49    Balance,
50    Cartera,
51    Resto,
52}
53
54/// Limitador por ventana deslizante (minuto y hora).
55struct Limitador {
56    cfg: LimitesTasa,
57    historial: Mutex<HashMap<Clase, VecDeque<Instant>>>,
58}
59
60impl Limitador {
61    fn new(cfg: LimitesTasa) -> Self {
62        Self {
63            cfg,
64            historial: Mutex::new(HashMap::new()),
65        }
66    }
67
68    fn cupo(&self, clase: Clase) -> (usize, usize) {
69        match clase {
70            Clase::Trading => (
71                self.cfg.trading_por_min as usize,
72                self.cfg.trading_por_hora as usize,
73            ),
74            Clase::Balance => (
75                self.cfg.balance_por_min as usize,
76                self.cfg.balance_por_hora as usize,
77            ),
78            Clase::Cartera => (
79                self.cfg.cartera_por_min as usize,
80                self.cfg.cartera_por_hora as usize,
81            ),
82            Clase::Resto => (
83                self.cfg.resto_por_min as usize,
84                self.cfg.resto_por_hora as usize,
85            ),
86        }
87    }
88
89    /// Espera hasta que haya hueco. Nunca falla: el objetivo es no recibir
90    /// `RateLimit` del bróker, no descartar trabajo.
91    async fn esperar(&self, clase: Clase) {
92        let (min, hora) = self.cupo(clase);
93        loop {
94            let espera = {
95                let ahora = Instant::now();
96                let mut guard = self.historial.lock().expect("limitador no envenenado");
97                let cola = guard.entry(clase).or_default();
98                while let Some(t) = cola.front() {
99                    if ahora.duration_since(*t) >= Duration::from_secs(3600) {
100                        cola.pop_front();
101                    } else {
102                        break;
103                    }
104                }
105                let en_minuto = cola
106                    .iter()
107                    .filter(|t| ahora.duration_since(**t) < Duration::from_secs(60))
108                    .count();
109                if en_minuto < min && cola.len() < hora {
110                    cola.push_back(ahora);
111                    None
112                } else if en_minuto >= min {
113                    let mas_viejo = cola
114                        .iter()
115                        .find(|t| ahora.duration_since(**t) < Duration::from_secs(60))
116                        .copied();
117                    mas_viejo.map(|t| {
118                        Duration::from_secs(60)
119                            .saturating_sub(ahora.duration_since(t))
120                            .max(Duration::from_millis(50))
121                    })
122                } else {
123                    Some(Duration::from_secs(5))
124                }
125            };
126            match espera {
127                None => return,
128                Some(d) => tokio::time::sleep(d).await,
129            }
130        }
131    }
132}
133
134/// Estado compartido entre el adaptador y la tarea del socket.
135struct Interna {
136    router: Mutex<HashMap<u64, oneshot::Sender<Value>>>,
137    contador: AtomicU64,
138    salida: mpsc::Sender<Value>,
139    vivo: AtomicBool,
140    activo: AtomicBool,
141    cortar: Notify,
142    eventos: broadcast::Sender<Event>,
143    estado: RwLock<Option<Session>>,
144    balance: RwLock<Option<Balance>>,
145    catalogo: RwLock<Vec<Asset>>,
146    resultados: RwLock<HashMap<OrderId, OperationResult>>,
147    abiertas: RwLock<HashSet<OrderId>>,
148    subs: RwLock<Vec<Value>>,
149    sub_velas: RwLock<HashMap<String, mpsc::Sender<Candle>>>,
150    limite: Limitador,
151    listo: watch::Sender<u64>,
152    /// Tipo de la cuenta resuelta por REST (Deriv usa prefijos nuevos).
153    tipo_cuenta: RwLock<AccountType>,
154    pausa_reconexion_segs: AtomicU64,
155    ultimo_error: Mutex<Option<String>>,
156}
157
158impl Interna {
159    fn siguiente_id(&self) -> u64 {
160        self.contador.fetch_add(1, Ordering::SeqCst) + 1
161    }
162
163    /// Envía y espera la respuesta correlacionada.
164    async fn solicitar(&self, msg: Value, plazo: Duration) -> Result<Value, BrokerError> {
165        if !self.vivo.load(Ordering::SeqCst) {
166            return Err(BrokerError::NotConnected);
167        }
168        let id = self.siguiente_id();
169        let mut msg = msg;
170        msg["req_id"] = json!(id);
171        let (tx, rx) = oneshot::channel();
172        self.router
173            .lock()
174            .expect("router no envenenado")
175            .insert(id, tx);
176        if self.salida.send(msg).await.is_err() {
177            self.router
178                .lock()
179                .expect("router no envenenado")
180                .remove(&id);
181            return Err(BrokerError::NotConnected);
182        }
183        match tokio::time::timeout(plazo, rx).await {
184            Ok(Ok(valor)) => interpretar(valor),
185            Ok(Err(_)) => Err(BrokerError::NotConnected),
186            Err(_) => {
187                self.router
188                    .lock()
189                    .expect("router no envenenado")
190                    .remove(&id);
191                Err(BrokerError::Timeout)
192            }
193        }
194    }
195
196    /// Registra una suscripción para reproducirla tras reconectar.
197    async fn registrar_sub(&self, msg: Value) {
198        let mut lista = self.subs.write().await;
199        if !lista.contains(&msg) {
200            lista.push(msg);
201        }
202    }
203}
204
205/// Error del bróker a partir del objeto `error` de un mensaje.
206fn error_de(e: &Value) -> BrokerError {
207    let code = e.get("code").and_then(Value::as_str).unwrap_or("Error");
208    let msg = e
209        .get("message")
210        .and_then(Value::as_str)
211        .unwrap_or("error del bróker");
212    match code {
213        "InvalidToken" | "Unauthorized" | "AuthorizationRequired" => {
214            BrokerError::Authentication(format!("deriv {code}: {msg}"))
215        }
216        _ => BrokerError::Rejected(format!("deriv {code}: {msg}")),
217    }
218}
219
220fn interpretar(valor: Value) -> Result<Value, BrokerError> {
221    match valor.get("error") {
222        Some(e) => Err(error_de(e)),
223        None => Ok(valor),
224    }
225}
226
227fn epoch_secs() -> i64 {
228    SystemTime::now()
229        .duration_since(UNIX_EPOCH)
230        .map(|d| d.as_secs() as i64)
231        .unwrap_or_default()
232}
233
234fn tipo_cuenta(id: &str, sel: AccountSelection) -> AccountType {
235    if id.starts_with("VRTC") || id.starts_with("VRT") || id.starts_with("DOT") {
236        AccountType::Practice
237    } else if id.starts_with("CR") || id.starts_with("ROT") {
238        AccountType::Real
239    } else {
240        match sel {
241            AccountSelection::Practice => AccountType::Practice,
242            AccountSelection::Real => AccountType::Real,
243            AccountSelection::Default => AccountType::Unknown,
244        }
245    }
246}
247
248/// Duración en la unidad más grande que divida exactamente.
249fn duracion(segundos: u64) -> (u64, &'static str) {
250    if segundos >= 86_400 && segundos % 86_400 == 0 {
251        (segundos / 86_400, "d")
252    } else if segundos >= 3_600 && segundos % 3_600 == 0 {
253        (segundos / 3_600, "h")
254    } else if segundos >= 60 && segundos % 60 == 0 {
255        (segundos / 60, "m")
256    } else {
257        (segundos.max(1), "s")
258    }
259}
260
261// ---------------------------------------------------------------------------
262// Adaptador
263// ---------------------------------------------------------------------------
264
265/// Adaptador Deriv.
266pub struct DerivBroker {
267    config: DerivConfig,
268    interna: Arc<Interna>,
269    tarea: Option<JoinHandle<()>>,
270}
271
272impl DerivBroker {
273    /// Construye el adaptador y espera la primera conexión.
274    pub async fn nuevo(config: DerivConfig) -> Result<Self, BrokerError> {
275        config.validar()?;
276        let capacidad = config.transport.cola_salida.clamp(16, 4096);
277        let (salida, salida_rx) = mpsc::channel::<Value>(capacidad);
278        let (listo, mut rx_listo) = watch::channel(0u64);
279        let (eventos, _) = broadcast::channel(512);
280
281        let interna = Arc::new(Interna {
282            router: Mutex::new(HashMap::new()),
283            contador: AtomicU64::new(0),
284            salida,
285            vivo: AtomicBool::new(false),
286            activo: AtomicBool::new(true),
287            cortar: Notify::new(),
288            eventos,
289            estado: RwLock::new(None),
290            balance: RwLock::new(None),
291            catalogo: RwLock::new(Vec::new()),
292            resultados: RwLock::new(HashMap::new()),
293            abiertas: RwLock::new(HashSet::new()),
294            subs: RwLock::new(Vec::new()),
295            sub_velas: RwLock::new(HashMap::new()),
296            limite: Limitador::new(config.limites),
297            listo,
298            tipo_cuenta: RwLock::new(AccountType::Unknown),
299            pausa_reconexion_segs: AtomicU64::new(0),
300            ultimo_error: Mutex::new(None),
301        });
302
303        let cfg = config.clone();
304        let interna_tarea = Arc::clone(&interna);
305        let tarea = tokio::spawn(async move {
306            bucle(interna_tarea, cfg, salida_rx).await;
307        });
308
309        let espera = tokio::time::timeout(Duration::from_secs(30), async {
310            while *rx_listo.borrow() == 0 {
311                if rx_listo.changed().await.is_err() {
312                    break;
313                }
314            }
315        })
316        .await;
317
318        if espera.is_err() || *rx_listo.borrow() == 0 {
319            tarea.abort();
320            let motivo = interna
321                .ultimo_error
322                .lock()
323                .expect("error no envenenado")
324                .clone()
325                .unwrap_or_else(|| "sin conexión con Deriv".to_string());
326            return Err(BrokerError::Connection(motivo));
327        }
328
329        Ok(Self {
330            config,
331            interna,
332            tarea: Some(tarea),
333        })
334    }
335
336    /// Configuración efectiva.
337    pub fn config(&self) -> &DerivConfig {
338        &self.config
339    }
340
341    /// ¿Es una sesión sin credenciales?
342    pub fn es_publico(&self) -> bool {
343        self.config.es_publico()
344    }
345
346    /// Fuerza la caída del socket (solo pruebas).
347    ///
348    /// El supervisor pide un OTP nuevo, reconecta y reproduce las
349    /// suscripciones; no cierra la sesión lógica.
350    #[doc(hidden)]
351    pub async fn simular_caida_de_conexion(&self) {
352        self.interna.cortar.notify_waiters();
353    }
354
355    /// Corta el socket y mantiene la reconexión pausada (`segundos`).
356    #[doc(hidden)]
357    pub async fn simular_caida_prolongada(&self, segundos: u64) {
358        self.interna
359            .pausa_reconexion_segs
360            .store(segundos, Ordering::SeqCst);
361        self.interna.cortar.notify_waiters();
362    }
363
364    /// Divisa de trabajo: la configurada o la del balance.
365    async fn divisa(&self) -> Result<String, BrokerError> {
366        if let Some(c) = &self.config.currency {
367            return Ok(c.clone());
368        }
369        // Sin credenciales no hay balance: Deriv cotiza en la divisa indicada.
370        if self.config.es_publico() {
371            return Ok("USD".to_string());
372        }
373        if let Some(b) = self.interna.balance.read().await.as_ref() {
374            return Ok(b.currency.clone());
375        }
376        let v = self.interna.solicitar(json!({"balance": 1}), PLAZO).await?;
377        let (_, currency, _) = protocol::balance(&v)
378            .ok_or_else(|| BrokerError::Internal("deriv: balance sin divisa".into()))?;
379        Ok(currency)
380    }
381
382    async fn activos_actualizados(&self) -> Result<Vec<Asset>, BrokerError> {
383        self.interna.limite.esperar(Clase::Resto).await;
384        let v = self
385            .interna
386            .solicitar(json!({"active_symbols": "full"}), PLAZO)
387            .await?;
388        let lista = protocol::activos(&v);
389        if lista.is_empty() {
390            return Err(BrokerError::Internal(
391                "deriv: active_symbols devolvió una lista vacía".into(),
392            ));
393        }
394        *self.interna.catalogo.write().await = lista.clone();
395        Ok(lista)
396    }
397}
398
399#[async_trait::async_trait]
400impl Broker for DerivBroker {
401    fn name(&self) -> &'static str {
402        "deriv"
403    }
404
405    async fn connect(params: BrokerParams) -> Result<Self, BrokerError> {
406        match params {
407            BrokerParams::Deriv(cfg) => Self::nuevo(cfg).await,
408            _ => Err(BrokerError::Internal(
409                "deriv: se esperaba BrokerParams::Deriv".into(),
410            )),
411        }
412    }
413
414    async fn disconnect(&mut self) -> Result<(), BrokerError> {
415        self.interna.activo.store(false, Ordering::SeqCst);
416        self.interna.cortar.notify_waiters();
417        if let Some(tarea) = self.tarea.take() {
418            tarea.abort();
419        }
420        self.interna.vivo.store(false, Ordering::SeqCst);
421        Ok(())
422    }
423
424    async fn is_connected(&self) -> bool {
425        self.interna.vivo.load(Ordering::SeqCst)
426    }
427
428    async fn session(&self) -> Result<Session, BrokerError> {
429        if let Some(s) = self.interna.estado.read().await.as_ref() {
430            return Ok(s.clone());
431        }
432        if !self.interna.vivo.load(Ordering::SeqCst) {
433            return Err(BrokerError::NotConnected);
434        }
435        let cuenta = self
436            .config
437            .account_id
438            .clone()
439            .unwrap_or_else(|| "public".to_string());
440        Ok(Session {
441            broker_name: "deriv".into(),
442            connected_at: epoch_secs(),
443            account_id: Some(cuenta.clone()),
444            balance_id: Some(protocol::id_surrogado(&cuenta)),
445            account_type: tipo_cuenta(&cuenta, self.config.account),
446            server_time_offset_ms: 0,
447        })
448    }
449
450    async fn get_balance(&self) -> Result<Balance, BrokerError> {
451        if self.config.es_publico() {
452            return Err(BrokerError::Authentication(
453                "deriv: el modo público no tiene cuenta; configura token y account_id".into(),
454            ));
455        }
456        self.interna.limite.esperar(Clase::Balance).await;
457        let v = self.interna.solicitar(json!({"balance": 1}), PLAZO).await?;
458        let (amount, currency, loginid) = protocol::balance(&v)
459            .ok_or_else(|| BrokerError::Internal("deriv: respuesta de balance sin datos".into()))?;
460        let id = if loginid.is_empty() {
461            self.config.account_id.clone().unwrap_or_default()
462        } else {
463            loginid
464        };
465        let tipo = match *self.interna.tipo_cuenta.read().await {
466            AccountType::Unknown => tipo_cuenta(&id, self.config.account),
467            conocido => conocido,
468        };
469        let balance = Balance {
470            amount,
471            currency,
472            account_type: tipo,
473            balance_id: protocol::id_surrogado(&id),
474        };
475        *self.interna.balance.write().await = Some(balance.clone());
476        Ok(balance)
477    }
478
479    async fn get_account_type(&self) -> Result<AccountType, BrokerError> {
480        Ok(self.session().await?.account_type)
481    }
482
483    async fn switch_account(&mut self, _kind: AccountType) -> Result<(), BrokerError> {
484        Err(BrokerError::Rejected(
485            "deriv: cambia account_id/account en DerivConfig y reconecta; \
486             el OTP está ligado a una cuenta concreta"
487                .into(),
488        ))
489    }
490
491    async fn list_assets(&self) -> Result<Vec<Asset>, BrokerError> {
492        let cache = self.interna.catalogo.read().await.clone();
493        if !cache.is_empty() {
494            return Ok(cache);
495        }
496        self.activos_actualizados().await
497    }
498
499    async fn asset_status(&self, symbol: &str) -> Result<MarketStatus, BrokerError> {
500        if let Some(a) = self
501            .interna
502            .catalogo
503            .read()
504            .await
505            .iter()
506            .find(|a| a.symbol == symbol)
507        {
508            return Ok(a.status);
509        }
510        let lista = self.activos_actualizados().await?;
511        lista
512            .iter()
513            .find(|a| a.symbol == symbol)
514            .map(|a| a.status)
515            .ok_or_else(|| BrokerError::Rejected(format!("deriv: símbolo desconocido {symbol}")))
516    }
517
518    async fn get_candles(&self, req: CandleRequest) -> Result<Vec<Candle>, BrokerError> {
519        if !GRANULARIDADES.contains(&req.interval) {
520            return Err(BrokerError::Rejected(format!(
521                "deriv: intervalo {} no admitido; válidos: {GRANULARIDADES:?}",
522                req.interval
523            )));
524        }
525        self.interna.limite.esperar(Clase::Resto).await;
526        let end = req
527            .end_time
528            .map(|t| t.to_string())
529            .unwrap_or_else(|| "latest".to_string());
530        let v = self
531            .interna
532            .solicitar(
533                json!({
534                    "ticks_history": req.symbol,
535                    "count": req.count.min(5000),
536                    "end": end,
537                    "style": "candles",
538                    "granularity": req.interval,
539                }),
540                PLAZO,
541            )
542            .await?;
543        Ok(protocol::velas(&v, req.interval))
544    }
545
546    async fn subscribe_candles(&self, req: CandleSubscribe) -> Result<CandleStream, BrokerError> {
547        if !GRANULARIDADES.contains(&req.interval) {
548            return Err(BrokerError::Rejected(format!(
549                "deriv: intervalo {} no admitido; válidos: {GRANULARIDADES:?}",
550                req.interval
551            )));
552        }
553        let clave = format!("{}|{}", req.symbol, req.interval);
554        let (tx, rx) = mpsc::channel::<Candle>(128);
555        self.interna.sub_velas.write().await.insert(clave, tx);
556        let msg = json!({
557            "ticks_history": req.symbol,
558            "count": 1,
559            "end": "latest",
560            "style": "candles",
561            "granularity": req.interval,
562            "subscribe": 1,
563        });
564        self.interna.registrar_sub(msg.clone()).await;
565        self.interna.limite.esperar(Clase::Resto).await;
566        self.interna.solicitar(msg, PLAZO).await?;
567        let stream = futures_util::stream::unfold(rx, |mut rx| async move {
568            rx.recv().await.map(|c| (Ok(c), rx))
569        });
570        Ok(Box::pin(stream))
571    }
572
573    async fn subscribe_ticks(&self, symbol: &str) -> Result<(), BrokerError> {
574        let msg = json!({"ticks": symbol, "subscribe": 1});
575        self.interna.registrar_sub(msg.clone()).await;
576        self.interna.limite.esperar(Clase::Resto).await;
577        self.interna.solicitar(msg, PLAZO).await?;
578        Ok(())
579    }
580
581    async fn get_position_history(
582        &self,
583        symbol: Option<&str>,
584        limit: usize,
585        offset: usize,
586    ) -> Result<PositionHistory, BrokerError> {
587        if self.config.es_publico() {
588            return Err(BrokerError::Authentication(
589                "deriv: el historial requiere credenciales".into(),
590            ));
591        }
592        self.interna.limite.esperar(Clase::Cartera).await;
593        let v = self
594            .interna
595            .solicitar(
596                json!({
597                    "profit_table": 1,
598                    "description": 1,
599                    "limit": limit.clamp(1, 100),
600                    "offset": offset,
601                    "sort": "DESC",
602                }),
603                PLAZO,
604            )
605            .await?;
606        let mut historial = protocol::posiciones(&v, offset);
607        if let Some(simbolo) = symbol {
608            historial.positions.retain(|p| p.symbol == simbolo);
609        }
610        Ok(historial)
611    }
612
613    async fn get_payout(
614        &self,
615        symbol: &str,
616        expiration_seconds: u64,
617    ) -> Result<Payout, BrokerError> {
618        let currency = self.divisa().await?;
619        let (duracion, unidad) = duracion(expiration_seconds.max(60));
620        self.interna.limite.esperar(Clase::Trading).await;
621        let v = self
622            .interna
623            .solicitar(
624                json!({
625                    "proposal": 1,
626                    "amount": self.config.stake_referencia,
627                    "basis": "stake",
628                    "contract_type": "CALL",
629                    "currency": currency,
630                    "underlying_symbol": symbol,
631                    "duration": duracion,
632                    "duration_unit": unidad,
633                }),
634                PLAZO,
635            )
636            .await;
637        match v {
638            Ok(valor) => {
639                let pct = protocol::payout_porcentaje(&valor, self.config.stake_referencia)
640                    .unwrap_or_default();
641                Ok(Payout {
642                    symbol: symbol.to_string(),
643                    expiration_seconds,
644                    profit_percent: pct,
645                    is_spot: false,
646                    strike: None,
647                    closed: false,
648                })
649            }
650            Err(BrokerError::Rejected(mensaje)) => Ok(Payout {
651                symbol: symbol.to_string(),
652                expiration_seconds,
653                profit_percent: 0.0,
654                is_spot: false,
655                strike: None,
656                closed: true,
657            })
658            .inspect(|_| {
659                tracing::warn!(
660                    mensaje,
661                    "deriv: propuesta rechazada, payout marcado cerrado"
662                );
663            }),
664            Err(e) => Err(e),
665        }
666    }
667
668    async fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
669        if self.config.es_publico() {
670            return Err(BrokerError::Authentication(
671                "deriv: operar requiere token con scope trade".into(),
672            ));
673        }
674        let currency = self.divisa().await?;
675        let tipo = match req.direction {
676            Direction::Call => "CALL",
677            Direction::Put => "PUT",
678        };
679        self.interna.limite.esperar(Clase::Trading).await;
680        let propuesta = self
681            .interna
682            .solicitar(
683                json!({
684                    "proposal": 1,
685                    "amount": req.amount,
686                    "basis": "stake",
687                    "contract_type": tipo,
688                    "currency": currency,
689                    "underlying_symbol": req.symbol,
690                    "duration": req.expiration_minutes,
691                    "duration_unit": "m",
692                }),
693                PLAZO,
694            )
695            .await?;
696        let id_propuesta = propuesta
697            .get("proposal")
698            .and_then(|p| p.get("id"))
699            .and_then(Value::as_str)
700            .ok_or_else(|| BrokerError::Internal("deriv: propuesta sin id".into()))?
701            .to_string();
702        let precio = propuesta
703            .get("proposal")
704            .and_then(|p| p.get("ask_price"))
705            .and_then(Value::as_f64)
706            .unwrap_or(req.amount);
707
708        let compra = self
709            .interna
710            .solicitar(json!({"buy": id_propuesta, "price": precio}), PLAZO)
711            .await?;
712        let contrato = compra
713            .get("buy")
714            .and_then(|b| b.get("contract_id"))
715            .and_then(Value::as_u64)
716            .ok_or_else(|| BrokerError::Internal("deriv: compra sin contract_id".into()))?;
717        let id = contrato.to_string();
718        self.interna.abiertas.write().await.insert(id.clone());
719        self.interna
720            .registrar_sub(json!({
721                "proposal_open_contract": 1,
722                "contract_id": contrato,
723                "subscribe": 1,
724            }))
725            .await;
726        let _ = self
727            .interna
728            .solicitar(
729                json!({"proposal_open_contract": 1, "contract_id": contrato, "subscribe": 1}),
730                PLAZO,
731            )
732            .await;
733        let _ = self.interna.eventos.send(Event::OrderOpened(Operation {
734            id: id.clone(),
735            symbol: req.symbol.clone(),
736            amount: req.amount,
737            direction: req.direction,
738            option_type: req.option_type,
739            status: OperationStatus::Open,
740            result: None,
741            payout_percent: protocol::payout_porcentaje(&propuesta, req.amount),
742            opened_at: epoch_secs(),
743            closed_at: None,
744        }));
745        Ok(id)
746    }
747
748    async fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
749        if self.config.es_publico() {
750            return Err(BrokerError::Authentication(
751                "deriv: vender requiere credenciales".into(),
752            ));
753        }
754        let contrato: u64 = order_id.parse().map_err(|_| {
755            BrokerError::Rejected(format!("deriv: contract_id inválido {order_id}"))
756        })?;
757        self.interna.limite.esperar(Clase::Trading).await;
758        self.interna
759            .solicitar(json!({"sell": contrato, "price": 0}), PLAZO)
760            .await?;
761        Ok(())
762    }
763
764    async fn get_operation_result(
765        &self,
766        order_id: &OrderId,
767    ) -> Result<OperationResult, BrokerError> {
768        Ok(self
769            .interna
770            .resultados
771            .read()
772            .await
773            .get(order_id)
774            .copied()
775            .unwrap_or(OperationResult::Pending))
776    }
777
778    async fn events(&self) -> Result<EventStream, BrokerError> {
779        let rx = self.interna.eventos.subscribe();
780        let stream = futures_util::stream::unfold(rx, |mut rx| async move {
781            match rx.recv().await {
782                Ok(evento) => Some((evento, rx)),
783                Err(broadcast::error::RecvError::Lagged(n)) => {
784                    Some((Event::EventsLost { count: n }, rx))
785                }
786                Err(broadcast::error::RecvError::Closed) => None,
787            }
788        });
789        Ok(Box::pin(stream))
790    }
791}
792
793// ---------------------------------------------------------------------------
794// Supervisor
795// ---------------------------------------------------------------------------
796
797/// URL de conexión: pública o un OTP nuevo.
798async fn url_de_conexion(
799    config: &DerivConfig,
800    interna: &Arc<Interna>,
801) -> Result<String, BrokerError> {
802    let Some(token) = config.token.as_ref() else {
803        return Ok(config.public_ws_url.clone());
804    };
805
806    let http = reqwest::Client::builder()
807        .timeout(Duration::from_secs(
808            config.transport.request_timeout_secs.max(5),
809        ))
810        .build()
811        .map_err(|e| BrokerError::Internal(format!("deriv: cliente http: {e}")))?;
812
813    let (cuenta, tipo) = resolver_cuenta(&http, config, token).await?;
814    *interna.tipo_cuenta.write().await = tipo;
815
816    let url = format!(
817        "{}/trading/v1/options/accounts/{}/otp",
818        config.base_url.trim_end_matches('/'),
819        cuenta
820    );
821    let mut peticion = http
822        .post(url)
823        .header("Authorization", format!("Bearer {token}"));
824    if let Some(app) = &config.app_id {
825        peticion = peticion.header("Deriv-App-ID", app);
826    }
827    let resp = peticion
828        .send()
829        .await
830        .map_err(|e| BrokerError::Connection(format!("deriv otp: {e}")))?;
831    let estado = resp.status();
832    let texto = resp.text().await.unwrap_or_default();
833    if !estado.is_success() {
834        let detalle: String = texto.chars().take(300).collect();
835        return Err(match estado.as_u16() {
836            401 | 403 => BrokerError::Authentication(format!(
837                "deriv otp {estado}: {} (el token necesita scope trade)",
838                detalle.trim()
839            )),
840            _ => BrokerError::Connection(format!("deriv otp {estado}: {}", detalle.trim())),
841        });
842    }
843    let valor: Value = serde_json::from_str(&texto)
844        .map_err(|e| BrokerError::Internal(format!("deriv otp: respuesta no JSON: {e}")))?;
845    valor
846        .get("data")
847        .and_then(|d| d.get("url"))
848        .and_then(Value::as_str)
849        .map(str::to_string)
850        .ok_or_else(|| BrokerError::Connection("deriv otp: respuesta sin url".into()))
851}
852
853/// Resuelve la cuenta del token y su tipo (`demo`/`real`).
854async fn resolver_cuenta(
855    http: &reqwest::Client,
856    config: &DerivConfig,
857    token: &str,
858) -> Result<(String, AccountType), BrokerError> {
859    let url = format!(
860        "{}/trading/v1/options/accounts",
861        config.base_url.trim_end_matches('/')
862    );
863    let mut peticion = http
864        .get(url)
865        .header("Authorization", format!("Bearer {token}"));
866    if let Some(app) = &config.app_id {
867        peticion = peticion.header("Deriv-App-ID", app);
868    }
869    let resp = peticion
870        .send()
871        .await
872        .map_err(|e| BrokerError::Connection(format!("deriv cuentas: {e}")))?;
873    let estado = resp.status();
874    let texto = resp.text().await.unwrap_or_default();
875    if !estado.is_success() {
876        let detalle: String = texto.chars().take(300).collect();
877        return Err(match estado.as_u16() {
878            401 | 403 => {
879                BrokerError::Authentication(format!("deriv cuentas {estado}: {}", detalle.trim()))
880            }
881            _ => BrokerError::Connection(format!("deriv cuentas {estado}: {}", detalle.trim())),
882        });
883    }
884    let valor: Value = serde_json::from_str(&texto)
885        .map_err(|e| BrokerError::Internal(format!("deriv cuentas: respuesta no JSON: {e}")))?;
886    // La API devuelve `data` como lista; se acepta también `data.accounts`
887    // por compatibilidad con la forma documentada en algunos ejemplos.
888    let lista = valor
889        .get("data")
890        .and_then(|d| {
891            if d.is_array() {
892                Some(d)
893            } else {
894                d.get("accounts")
895            }
896        })
897        .and_then(Value::as_array)
898        .ok_or_else(|| BrokerError::Connection("deriv cuentas: respuesta sin lista".into()))?;
899
900    let quiere_demo = !matches!(config.account, AccountSelection::Real);
901    let mut elegida: Option<(String, AccountType)> = None;
902
903    for c in lista {
904        let id = match c.get("account_id").and_then(Value::as_str) {
905            Some(id) if !id.is_empty() => id,
906            _ => continue,
907        };
908        let tipo = match c.get("account_type").and_then(Value::as_str) {
909            Some("demo") | Some("virtual") => AccountType::Practice,
910            Some("real") => AccountType::Real,
911            _ => {
912                let virtual_ = c
913                    .get("is_virtual")
914                    .and_then(Value::as_bool)
915                    .unwrap_or(false);
916                if virtual_ {
917                    AccountType::Practice
918                } else {
919                    tipo_cuenta(id, config.account)
920                }
921            }
922        };
923        if config.account_id.as_deref() == Some(id) {
924            return Ok((id.to_string(), tipo));
925        }
926        let es_demo = matches!(tipo, AccountType::Practice);
927        if elegida.is_none() && es_demo == quiere_demo {
928            elegida = Some((id.to_string(), tipo));
929        }
930    }
931
932    if let Some(configurada) = &config.account_id {
933        return Ok((configurada.clone(), AccountType::Unknown));
934    }
935    elegida.ok_or_else(|| {
936        BrokerError::Authentication(format!(
937            "deriv: el token no tiene cuenta {}",
938            if quiere_demo { "demo" } else { "real" }
939        ))
940    })
941}
942
943async fn enviar_json(sink: &mut Escritor, msg: Value) -> Result<(), BrokerError> {
944    sink.send(Message::Text(msg.to_string()))
945        .await
946        .map_err(|e| BrokerError::Connection(e.to_string()))
947}
948
949/// Bucle del supervisor: conecta, inicializa, atiende y reconecta.
950async fn bucle(interna: Arc<Interna>, config: DerivConfig, mut salida: mpsc::Receiver<Value>) {
951    let base = config.transport.backoff_base_ms.max(200);
952    let maximo = config.transport.backoff_max_ms.max(base);
953    let mut backoff = base;
954    let mut reconexiones = 0u32;
955    let mut caido_en: Option<Instant> = None;
956
957    while interna.activo.load(Ordering::SeqCst) {
958        let url = match url_de_conexion(&config, &interna).await {
959            Ok(u) => u,
960            Err(e) => {
961                *interna.ultimo_error.lock().expect("error no envenenado") = Some(e.to_string());
962                if matches!(e, BrokerError::Authentication(_)) {
963                    tracing::error!(error = %e, "deriv: credenciales rechazadas, no se reintenta");
964                    break;
965                }
966                tracing::warn!(error = %e, "deriv: sin URL de conexión; reintento");
967                tokio::time::sleep(Duration::from_millis(backoff)).await;
968                backoff = backoff.saturating_mul(2).min(maximo);
969                continue;
970            }
971        };
972
973        let ws = match connect_async(&url).await {
974            Ok((ws, _)) => ws,
975            Err(e) => {
976                tracing::warn!(error = %e, "deriv: conexión ws fallida");
977                tokio::time::sleep(Duration::from_millis(backoff)).await;
978                backoff = backoff.saturating_mul(2).min(maximo);
979                continue;
980            }
981        };
982
983        let (mut sink, mut stream) = ws.split();
984        interna.vivo.store(true, Ordering::SeqCst);
985
986        match inicializar(&interna, &mut sink, &mut stream).await {
987            Ok(()) => {}
988            Err(e) => {
989                tracing::warn!(error = %e, "deriv: inicialización fallida");
990                interna.vivo.store(false, Ordering::SeqCst);
991                let _ = sink.close().await;
992                tokio::time::sleep(Duration::from_millis(backoff)).await;
993                backoff = backoff.saturating_mul(2).min(maximo);
994                continue;
995            }
996        }
997
998        let generacion = (*interna.listo.borrow()).wrapping_add(1);
999        let _ = interna.listo.send(generacion);
1000        backoff = base;
1001
1002        if reconexiones > 0 {
1003            let _ = interna.eventos.send(Event::Reconnected {
1004                intentos: reconexiones,
1005                downtime_ms: caido_en
1006                    .map(|t| t.elapsed().as_millis() as u64)
1007                    .unwrap_or(0),
1008            });
1009        }
1010
1011        for sub in interna.subs.read().await.iter().cloned() {
1012            let mut sub = sub;
1013            sub["req_id"] = json!(interna.siguiente_id());
1014            if let Err(e) = enviar_json(&mut sink, sub).await {
1015                tracing::warn!(error = %e, "deriv: replay de suscripción fallido");
1016            }
1017        }
1018
1019        {
1020            let rec = Arc::clone(&interna);
1021            tokio::spawn(async move {
1022                reconciliar(&rec).await;
1023            });
1024        }
1025        let motivo = bucle_socket(&interna, &mut sink, &mut stream, &mut salida).await;
1026        caido_en = Some(Instant::now());
1027        interna.vivo.store(false, Ordering::SeqCst);
1028        interna.router.lock().expect("router no envenenado").clear();
1029        let _ = interna.eventos.send(Event::Disconnected {
1030            motivo: motivo.clone(),
1031        });
1032        tracing::warn!(motivo, "deriv: conexión perdida");
1033
1034        if !interna.activo.load(Ordering::SeqCst) {
1035            break;
1036        }
1037        reconexiones += 1;
1038        let pausa = interna.pausa_reconexion_segs.swap(0, Ordering::SeqCst);
1039        if pausa > 0 {
1040            tracing::warn!(pausa, "deriv: reconexión pausada para prueba");
1041            tokio::time::sleep(Duration::from_secs(pausa)).await;
1042        }
1043        tokio::time::sleep(Duration::from_millis(backoff)).await;
1044        backoff = backoff.saturating_mul(2).min(maximo);
1045    }
1046}
1047
1048/// Primera petición de la conexión: hora del servidor y balance.
1049async fn inicializar(
1050    interna: &Arc<Interna>,
1051    sink: &mut Escritor,
1052    stream: &mut Lector,
1053) -> Result<(), BrokerError> {
1054    let id = interna.siguiente_id();
1055    enviar_json(sink, json!({"time": 1, "req_id": id})).await?;
1056    let tiempo = leer_hasta(stream, id, Duration::from_secs(10)).await?;
1057    let servidor = tiempo
1058        .get("time")
1059        .and_then(Value::as_i64)
1060        .unwrap_or_default();
1061    let offset_ms = (servidor - epoch_secs()) * 1000;
1062
1063    let mut cuenta = String::from("public");
1064    let mut balance = None;
1065
1066    if interna.activo.load(Ordering::SeqCst) {
1067        let id = interna.siguiente_id();
1068        enviar_json(sink, json!({"balance": 1, "subscribe": 1, "req_id": id})).await?;
1069        if let Ok(valor) = leer_hasta(stream, id, Duration::from_secs(10)).await {
1070            if let Some((amount, currency, loginid)) = protocol::balance(&valor) {
1071                if !loginid.is_empty() {
1072                    cuenta = loginid;
1073                }
1074                balance = Some(Balance {
1075                    amount,
1076                    currency,
1077                    account_type: AccountType::Unknown,
1078                    balance_id: protocol::id_surrogado(&cuenta),
1079                });
1080            }
1081        }
1082    }
1083
1084    if let Some(b) = balance {
1085        *interna.balance.write().await = Some(b);
1086    }
1087
1088    let sesion = Session {
1089        broker_name: "deriv".into(),
1090        connected_at: epoch_secs(),
1091        account_id: Some(cuenta.clone()),
1092        balance_id: Some(protocol::id_surrogado(&cuenta)),
1093        account_type: *interna.tipo_cuenta.read().await,
1094        server_time_offset_ms: offset_ms,
1095    };
1096    *interna.estado.write().await = Some(sesion);
1097    Ok(())
1098}
1099
1100/// Lee del socket hasta la respuesta con `id`.
1101async fn leer_hasta(stream: &mut Lector, id: u64, plazo: Duration) -> Result<Value, BrokerError> {
1102    let fin = tokio::time::Instant::now() + plazo;
1103    loop {
1104        let restante = fin.saturating_duration_since(tokio::time::Instant::now());
1105        if restante.is_zero() {
1106            return Err(BrokerError::Timeout);
1107        }
1108        match tokio::time::timeout(restante, stream.next()).await {
1109            Err(_) => return Err(BrokerError::Timeout),
1110            Ok(None) => return Err(BrokerError::NotConnected),
1111            Ok(Some(Err(e))) => return Err(BrokerError::Connection(e.to_string())),
1112            Ok(Some(Ok(Message::Text(texto)))) => {
1113                if let Ok(valor) = serde_json::from_str::<Value>(&texto) {
1114                    if valor.get("req_id").and_then(Value::as_u64) == Some(id) {
1115                        return interpretar(valor);
1116                    }
1117                }
1118            }
1119            Ok(Some(Ok(Message::Close(_)))) => return Err(BrokerError::NotConnected),
1120            Ok(Some(Ok(_))) => {}
1121        }
1122    }
1123}
1124
1125/// Atiende el socket hasta que se cierra. Devuelve el motivo.
1126async fn bucle_socket(
1127    interna: &Arc<Interna>,
1128    sink: &mut Escritor,
1129    stream: &mut Lector,
1130    salida: &mut mpsc::Receiver<Value>,
1131) -> String {
1132    loop {
1133        tokio::select! {
1134            Some(msg) = salida.recv() => {
1135                if let Err(e) = enviar_json(sink, msg).await {
1136                    return e.to_string();
1137                }
1138            }
1139            frame = stream.next() => {
1140                match frame {
1141                    Some(Ok(Message::Text(texto))) => procesar(interna, &texto).await,
1142                    Some(Ok(Message::Ping(datos))) => {
1143                        let _ = sink.send(Message::Pong(datos)).await;
1144                    }
1145                    Some(Ok(Message::Close(_))) | None => return "socket cerrado".into(),
1146                    Some(Err(e)) => return e.to_string(),
1147                    _ => {}
1148                }
1149            }
1150            _ = interna.cortar.notified() => {
1151                let _ = sink.close().await;
1152                return "cierre solicitado".into();
1153            }
1154        }
1155    }
1156}
1157
1158/// Entrega respuestas y trata mensajes de suscripción.
1159async fn procesar(interna: &Arc<Interna>, texto: &str) {
1160    let Ok(valor) = serde_json::from_str::<Value>(texto) else {
1161        return;
1162    };
1163
1164    if let Some(id) = valor.get("req_id").and_then(Value::as_u64) {
1165        let espera = interna
1166            .router
1167            .lock()
1168            .expect("router no envenenado")
1169            .remove(&id);
1170        if let Some(tx) = espera {
1171            let _ = tx.send(valor.clone());
1172        }
1173    }
1174
1175    match valor.get("msg_type").and_then(Value::as_str).unwrap_or("") {
1176        "ohlc" => {
1177            let eco = valor.get("echo_req").cloned().unwrap_or(Value::Null);
1178            let symbol = eco
1179                .get("ticks_history")
1180                .and_then(Value::as_str)
1181                .unwrap_or_default();
1182            let intervalo = eco.get("granularity").and_then(Value::as_u64).unwrap_or(60);
1183            if let Some(vela) = protocol::vela_ohlc(&valor, intervalo) {
1184                let clave = format!("{symbol}|{intervalo}");
1185                let emisor = interna.sub_velas.read().await.get(&clave).cloned();
1186                if let Some(tx) = emisor {
1187                    let _ = tx.send(vela).await;
1188                }
1189            }
1190        }
1191        "proposal_open_contract" => {
1192            if let Some((id, resultado)) = protocol::resultado_contrato(&valor) {
1193                registrar_cierre(interna, &id, resultado).await;
1194            }
1195        }
1196        "tick" => {
1197            if let Some(t) = valor.get("tick") {
1198                let symbol = t
1199                    .get("symbol")
1200                    .and_then(Value::as_str)
1201                    .or_else(|| valor.pointer("/echo_req/ticks").and_then(Value::as_str))
1202                    .unwrap_or_default()
1203                    .to_string();
1204                let price = t.get("quote").and_then(Value::as_f64).unwrap_or_default();
1205                let epoch = t.get("epoch").and_then(Value::as_i64).unwrap_or_default();
1206                let _ = interna.eventos.send(Event::PriceTick {
1207                    symbol,
1208                    tick: PriceTick {
1209                        price,
1210                        bid: t.get("bid").and_then(Value::as_f64),
1211                        ask: t.get("ask").and_then(Value::as_f64),
1212                        at_ms: epoch * 1000,
1213                    },
1214                });
1215            }
1216        }
1217        "balance" => {
1218            if let Some((amount, currency, loginid)) = protocol::balance(&valor) {
1219                let balance = Balance {
1220                    amount,
1221                    currency,
1222                    account_type: tipo_cuenta(&loginid, AccountSelection::Default),
1223                    balance_id: protocol::id_surrogado(&loginid),
1224                };
1225                *interna.balance.write().await = Some(balance.clone());
1226                let _ = interna.eventos.send(Event::BalanceChanged(AccountBalance {
1227                    id: balance.balance_id,
1228                    currency: balance.currency.clone(),
1229                    amount: balance.amount,
1230                    account_type: balance.account_type,
1231                    hold_amount: None,
1232                    bonus_amount: None,
1233                    enrolled_amount: None,
1234                    has_deposits: None,
1235                }));
1236            }
1237        }
1238        _ => {}
1239    }
1240}
1241
1242/// Registra un cierre una sola vez (los eventos y la reconciliación pueden
1243/// observar el mismo contrato).
1244async fn registrar_cierre(interna: &Arc<Interna>, id: &str, resultado: OperationResult) {
1245    if interna.resultados.read().await.contains_key(id) {
1246        return;
1247    }
1248    interna
1249        .resultados
1250        .write()
1251        .await
1252        .insert(id.to_string(), resultado);
1253    interna.abiertas.write().await.remove(id);
1254    let _ = interna.eventos.send(Event::OrderClosed {
1255        id: id.to_string(),
1256        result: resultado,
1257    });
1258}
1259
1260/// Recupera cierres ocurridos sin conexión: contrato puntual y, si ya no está
1261/// en el POC activo, historial paginado. No reenvía órdenes ni duplica eventos.
1262async fn reconciliar(interna: &Arc<Interna>) {
1263    let abiertas: Vec<OrderId> = interna.abiertas.read().await.iter().cloned().collect();
1264    if abiertas.is_empty() {
1265        return;
1266    }
1267    tracing::info!(pendientes = abiertas.len(), "deriv: reconciliando cierres");
1268
1269    for id in &abiertas {
1270        let Ok(contrato) = id.parse::<u64>() else {
1271            continue;
1272        };
1273        let Ok(valor) = interna
1274            .solicitar(
1275                json!({"proposal_open_contract": 1, "contract_id": contrato}),
1276                PLAZO,
1277            )
1278            .await
1279        else {
1280            continue;
1281        };
1282        if let Some((cid, resultado)) = protocol::resultado_contrato(&valor) {
1283            registrar_cierre(interna, &cid, resultado).await;
1284        }
1285    }
1286
1287    let mut offset = 0usize;
1288    for _ in 0..10 {
1289        if interna.abiertas.read().await.is_empty() {
1290            break;
1291        }
1292        let Ok(valor) = interna
1293            .solicitar(
1294                json!({"profit_table": 1, "description": 1, "limit": 100, "offset": offset}),
1295                PLAZO,
1296            )
1297            .await
1298        else {
1299            break;
1300        };
1301        let pagina = protocol::posiciones(&valor, offset);
1302        if pagina.positions.is_empty() {
1303            break;
1304        }
1305        for posicion in &pagina.positions {
1306            if !interna.abiertas.read().await.contains(&posicion.id) {
1307                continue;
1308            }
1309            let resultado = match posicion.pnl {
1310                Some(x) if x > 0.0 => OperationResult::Win(x),
1311                Some(x) if x < 0.0 => OperationResult::Loss(x.abs()),
1312                Some(_) => OperationResult::Equal(0.0),
1313                None => continue,
1314            };
1315            registrar_cierre(interna, &posicion.id, resultado).await;
1316        }
1317        offset += 100;
1318    }
1319}
1320
1321#[cfg(test)]
1322mod tests {
1323    use super::*;
1324
1325    #[test]
1326    fn duracion_usa_la_unidad_mayor_exacta() {
1327        assert_eq!(duracion(60), (1, "m"));
1328        assert_eq!(duracion(300), (5, "m"));
1329        assert_eq!(duracion(3600), (1, "h"));
1330        assert_eq!(duracion(86400), (1, "d"));
1331        assert_eq!(duracion(45), (45, "s"));
1332    }
1333
1334    #[test]
1335    fn tipo_cuenta_por_prefijo() {
1336        assert_eq!(
1337            tipo_cuenta("VRTC123", AccountSelection::Real),
1338            AccountType::Practice
1339        );
1340        assert_eq!(
1341            tipo_cuenta("CR456", AccountSelection::Practice),
1342            AccountType::Real
1343        );
1344        assert_eq!(
1345            tipo_cuenta("X", AccountSelection::Default),
1346            AccountType::Unknown
1347        );
1348    }
1349
1350    #[test]
1351    fn error_invalid_token_es_autenticacion() {
1352        let e = error_de(&json!({"code": "InvalidToken", "message": "bad"}));
1353        assert!(matches!(e, BrokerError::Authentication(_)));
1354    }
1355
1356    #[test]
1357    fn error_de_validacion_es_rechazo() {
1358        let e = error_de(&json!({"code": "InputValidationFailed", "message": "falta"}));
1359        assert!(matches!(e, BrokerError::Rejected(_)));
1360    }
1361}