1use 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
29type Ws = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
34type Escritor = SplitSink<Ws, Message>;
35type Lector = SplitStream<Ws>;
36
37const PLAZO: Duration = Duration::from_secs(15);
39
40const GRANULARIDADES: [u64; 12] = [
42 60, 120, 180, 300, 600, 900, 1800, 3600, 7200, 14400, 28800, 86400,
43];
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47enum Clase {
48 Trading,
49 Balance,
50 Cartera,
51 Resto,
52}
53
54struct 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 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
134struct 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_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 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 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
205fn 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
248fn 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
261fn contrato_de(opcion: OptionType) -> Option<&'static str> {
266 match opcion {
267 OptionType::Binary => Some("CALL"),
268 OptionType::Digital | OptionType::Blitz => None,
269 }
270}
271
272pub struct DerivBroker {
278 config: DerivConfig,
279 interna: Arc<Interna>,
280 tarea: Option<JoinHandle<()>>,
281}
282
283impl DerivBroker {
284 pub async fn nuevo(config: DerivConfig) -> Result<Self, BrokerError> {
286 config.validar()?;
287 let capacidad = config.transport.cola_salida.clamp(16, 4096);
288 let (salida, salida_rx) = mpsc::channel::<Value>(capacidad);
289 let (listo, mut rx_listo) = watch::channel(0u64);
290 let (eventos, _) = broadcast::channel(512);
291
292 let interna = Arc::new(Interna {
293 router: Mutex::new(HashMap::new()),
294 contador: AtomicU64::new(0),
295 salida,
296 vivo: AtomicBool::new(false),
297 activo: AtomicBool::new(true),
298 cortar: Notify::new(),
299 eventos,
300 estado: RwLock::new(None),
301 balance: RwLock::new(None),
302 catalogo: RwLock::new(Vec::new()),
303 resultados: RwLock::new(HashMap::new()),
304 abiertas: RwLock::new(HashSet::new()),
305 subs: RwLock::new(Vec::new()),
306 sub_velas: RwLock::new(HashMap::new()),
307 limite: Limitador::new(config.limites),
308 listo,
309 tipo_cuenta: RwLock::new(AccountType::Unknown),
310 pausa_reconexion_segs: AtomicU64::new(0),
311 ultimo_error: Mutex::new(None),
312 });
313
314 let cfg = config.clone();
315 let interna_tarea = Arc::clone(&interna);
316 let tarea = tokio::spawn(async move {
317 bucle(interna_tarea, cfg, salida_rx).await;
318 });
319
320 let espera = tokio::time::timeout(Duration::from_secs(30), async {
321 while *rx_listo.borrow() == 0 {
322 if rx_listo.changed().await.is_err() {
323 break;
324 }
325 }
326 })
327 .await;
328
329 if espera.is_err() || *rx_listo.borrow() == 0 {
330 tarea.abort();
331 let motivo = interna
332 .ultimo_error
333 .lock()
334 .expect("error no envenenado")
335 .clone()
336 .unwrap_or_else(|| "sin conexión con Deriv".to_string());
337 return Err(BrokerError::Connection(motivo));
338 }
339
340 Ok(Self {
341 config,
342 interna,
343 tarea: Some(tarea),
344 })
345 }
346
347 pub fn config(&self) -> &DerivConfig {
349 &self.config
350 }
351
352 pub fn es_publico(&self) -> bool {
354 self.config.es_publico()
355 }
356
357 #[doc(hidden)]
362 pub async fn simular_caida_de_conexion(&self) {
363 self.interna.cortar.notify_waiters();
364 }
365
366 #[doc(hidden)]
368 pub async fn simular_caida_prolongada(&self, segundos: u64) {
369 self.interna
370 .pausa_reconexion_segs
371 .store(segundos, Ordering::SeqCst);
372 self.interna.cortar.notify_waiters();
373 }
374
375 async fn divisa(&self) -> Result<String, BrokerError> {
377 if let Some(c) = &self.config.currency {
378 return Ok(c.clone());
379 }
380 if self.config.es_publico() {
382 return Ok("USD".to_string());
383 }
384 if let Some(b) = self.interna.balance.read().await.as_ref() {
385 return Ok(b.currency.clone());
386 }
387 let v = self.interna.solicitar(json!({"balance": 1}), PLAZO).await?;
388 let (_, currency, _) = protocol::balance(&v)
389 .ok_or_else(|| BrokerError::Internal("deriv: balance sin divisa".into()))?;
390 Ok(currency)
391 }
392
393 async fn activos_actualizados(&self) -> Result<Vec<Asset>, BrokerError> {
394 self.interna.limite.esperar(Clase::Resto).await;
395 let v = self
396 .interna
397 .solicitar(json!({"active_symbols": "full"}), PLAZO)
398 .await?;
399 let lista = protocol::activos(&v);
400 if lista.is_empty() {
401 return Err(BrokerError::Internal(
402 "deriv: active_symbols devolvió una lista vacía".into(),
403 ));
404 }
405 *self.interna.catalogo.write().await = lista.clone();
406 Ok(lista)
407 }
408}
409
410#[async_trait::async_trait]
411impl Broker for DerivBroker {
412 fn name(&self) -> &'static str {
413 "deriv"
414 }
415
416 async fn connect(params: BrokerParams) -> Result<Self, BrokerError> {
417 match params {
418 BrokerParams::Deriv(cfg) => Self::nuevo(cfg).await,
419 _ => Err(BrokerError::Internal(
420 "deriv: se esperaba BrokerParams::Deriv".into(),
421 )),
422 }
423 }
424
425 async fn disconnect(&mut self) -> Result<(), BrokerError> {
426 self.interna.activo.store(false, Ordering::SeqCst);
427 self.interna.cortar.notify_waiters();
428 if let Some(tarea) = self.tarea.take() {
429 tarea.abort();
430 }
431 self.interna.vivo.store(false, Ordering::SeqCst);
432 Ok(())
433 }
434
435 async fn is_connected(&self) -> bool {
436 self.interna.vivo.load(Ordering::SeqCst)
437 }
438
439 async fn session(&self) -> Result<Session, BrokerError> {
440 if let Some(s) = self.interna.estado.read().await.as_ref() {
441 return Ok(s.clone());
442 }
443 if !self.interna.vivo.load(Ordering::SeqCst) {
444 return Err(BrokerError::NotConnected);
445 }
446 let cuenta = self
447 .config
448 .account_id
449 .clone()
450 .unwrap_or_else(|| "public".to_string());
451 Ok(Session {
452 broker_name: "deriv".into(),
453 connected_at: epoch_secs(),
454 account_id: Some(cuenta.clone()),
455 balance_id: Some(protocol::id_surrogado(&cuenta)),
456 account_type: tipo_cuenta(&cuenta, self.config.account),
457 server_time_offset_ms: 0,
458 })
459 }
460
461 async fn get_balance(&self) -> Result<Balance, BrokerError> {
462 if self.config.es_publico() {
463 return Err(BrokerError::Authentication(
464 "deriv: el modo público no tiene cuenta; configura token y account_id".into(),
465 ));
466 }
467 self.interna.limite.esperar(Clase::Balance).await;
468 let v = self.interna.solicitar(json!({"balance": 1}), PLAZO).await?;
469 let (amount, currency, loginid) = protocol::balance(&v)
470 .ok_or_else(|| BrokerError::Internal("deriv: respuesta de balance sin datos".into()))?;
471 let id = if loginid.is_empty() {
472 self.config.account_id.clone().unwrap_or_default()
473 } else {
474 loginid
475 };
476 let tipo = match *self.interna.tipo_cuenta.read().await {
477 AccountType::Unknown => tipo_cuenta(&id, self.config.account),
478 conocido => conocido,
479 };
480 let balance = Balance {
481 amount,
482 currency,
483 account_type: tipo,
484 balance_id: protocol::id_surrogado(&id),
485 };
486 *self.interna.balance.write().await = Some(balance.clone());
487 Ok(balance)
488 }
489
490 async fn get_account_type(&self) -> Result<AccountType, BrokerError> {
491 Ok(self.session().await?.account_type)
492 }
493
494 async fn switch_account(&mut self, _kind: AccountType) -> Result<(), BrokerError> {
495 Err(BrokerError::Rejected(
496 "deriv: cambia account_id/account en DerivConfig y reconecta; \
497 el OTP está ligado a una cuenta concreta"
498 .into(),
499 ))
500 }
501
502 async fn list_assets(&self) -> Result<Vec<Asset>, BrokerError> {
503 let cache = self.interna.catalogo.read().await.clone();
504 if !cache.is_empty() {
505 return Ok(cache);
506 }
507 self.activos_actualizados().await
508 }
509
510 async fn asset_status(&self, symbol: &str) -> Result<MarketStatus, BrokerError> {
511 if let Some(a) = self
512 .interna
513 .catalogo
514 .read()
515 .await
516 .iter()
517 .find(|a| a.symbol == symbol)
518 {
519 return Ok(a.status);
520 }
521 let lista = self.activos_actualizados().await?;
522 lista
523 .iter()
524 .find(|a| a.symbol == symbol)
525 .map(|a| a.status)
526 .ok_or_else(|| BrokerError::Rejected(format!("deriv: símbolo desconocido {symbol}")))
527 }
528
529 async fn get_candles(&self, req: CandleRequest) -> Result<Vec<Candle>, BrokerError> {
530 if !GRANULARIDADES.contains(&req.interval) {
531 return Err(BrokerError::Rejected(format!(
532 "deriv: intervalo {} no admitido; válidos: {GRANULARIDADES:?}",
533 req.interval
534 )));
535 }
536 self.interna.limite.esperar(Clase::Resto).await;
537 let end = req
538 .end_time
539 .map(|t| t.to_string())
540 .unwrap_or_else(|| "latest".to_string());
541 let v = self
542 .interna
543 .solicitar(
544 json!({
545 "ticks_history": req.symbol,
546 "count": req.count.min(5000),
547 "end": end,
548 "style": "candles",
549 "granularity": req.interval,
550 }),
551 PLAZO,
552 )
553 .await?;
554 Ok(protocol::velas(&v, req.interval))
555 }
556
557 async fn subscribe_candles(&self, req: CandleSubscribe) -> Result<CandleStream, BrokerError> {
558 if !GRANULARIDADES.contains(&req.interval) {
559 return Err(BrokerError::Rejected(format!(
560 "deriv: intervalo {} no admitido; válidos: {GRANULARIDADES:?}",
561 req.interval
562 )));
563 }
564 let clave = format!("{}|{}", req.symbol, req.interval);
565 let (tx, rx) = mpsc::channel::<Candle>(128);
566 self.interna.sub_velas.write().await.insert(clave, tx);
567 let msg = json!({
568 "ticks_history": req.symbol,
569 "count": 1,
570 "end": "latest",
571 "style": "candles",
572 "granularity": req.interval,
573 "subscribe": 1,
574 });
575 self.interna.registrar_sub(msg.clone()).await;
576 self.interna.limite.esperar(Clase::Resto).await;
577 self.interna.solicitar(msg, PLAZO).await?;
578 let stream = futures_util::stream::unfold(rx, |mut rx| async move {
579 rx.recv().await.map(|c| (Ok(c), rx))
580 });
581 Ok(Box::pin(stream))
582 }
583
584 async fn subscribe_ticks(&self, symbol: &str) -> Result<(), BrokerError> {
585 let msg = json!({"ticks": symbol, "subscribe": 1});
586 self.interna.registrar_sub(msg.clone()).await;
587 self.interna.limite.esperar(Clase::Resto).await;
588 self.interna.solicitar(msg, PLAZO).await?;
589 Ok(())
590 }
591
592 async fn get_position_history(
593 &self,
594 symbol: Option<&str>,
595 limit: usize,
596 offset: usize,
597 ) -> Result<PositionHistory, BrokerError> {
598 if self.config.es_publico() {
599 return Err(BrokerError::Authentication(
600 "deriv: el historial requiere credenciales".into(),
601 ));
602 }
603 self.interna.limite.esperar(Clase::Cartera).await;
604 let v = self
605 .interna
606 .solicitar(
607 json!({
608 "profit_table": 1,
609 "description": 1,
610 "limit": limit.clamp(1, 100),
611 "offset": offset,
612 "sort": "DESC",
613 }),
614 PLAZO,
615 )
616 .await?;
617 let mut historial = protocol::posiciones(&v, offset);
618 if let Some(simbolo) = symbol {
619 historial.positions.retain(|p| p.symbol == simbolo);
620 }
621 Ok(historial)
622 }
623
624 async fn get_payout(
625 &self,
626 symbol: &str,
627 expiration_seconds: u64,
628 ) -> Result<Payout, BrokerError> {
629 let currency = self.divisa().await?;
630 let (duracion, unidad) = duracion(expiration_seconds.max(60));
631 self.interna.limite.esperar(Clase::Trading).await;
632 let v = self
633 .interna
634 .solicitar(
635 json!({
636 "proposal": 1,
637 "amount": self.config.stake_referencia,
638 "basis": "stake",
639 "contract_type": "CALL",
640 "currency": currency,
641 "underlying_symbol": symbol,
642 "duration": duracion,
643 "duration_unit": unidad,
644 }),
645 PLAZO,
646 )
647 .await;
648 match v {
649 Ok(valor) => {
650 let pct = protocol::payout_porcentaje(&valor, self.config.stake_referencia)
651 .unwrap_or_default();
652 Ok(Payout {
653 symbol: symbol.to_string(),
654 expiration_seconds,
655 profit_percent: pct,
656 is_spot: false,
657 strike: None,
658 closed: false,
659 })
660 }
661 Err(BrokerError::Rejected(mensaje)) => Ok(Payout {
662 symbol: symbol.to_string(),
663 expiration_seconds,
664 profit_percent: 0.0,
665 is_spot: false,
666 strike: None,
667 closed: true,
668 })
669 .inspect(|_| {
670 tracing::warn!(
671 mensaje,
672 "deriv: propuesta rechazada, payout marcado cerrado"
673 );
674 }),
675 Err(e) => Err(e),
676 }
677 }
678
679 async fn quote_payout(
680 &self,
681 symbol: &str,
682 option_type: OptionType,
683 expiration_seconds: u64,
684 amount: f64,
685 ) -> Result<PayoutQuote, BrokerError> {
686 if !amount.is_finite() || amount <= 0.0 {
687 return Err(BrokerError::Domain(DomainError::InvalidAmount(format!(
688 "deriv: amount debe ser positivo, recibido {amount}"
689 ))));
690 }
691 if expiration_seconds == 0 {
692 return Err(BrokerError::Rejected(
693 "deriv: expiration_seconds debe ser positivo".into(),
694 ));
695 }
696 let Some(contract_type) = contrato_de(option_type) else {
697 return Ok(PayoutQuote::unavailable(
698 symbol,
699 option_type,
700 expiration_seconds,
701 ));
702 };
703
704 let currency = self.divisa().await?;
705 let (duracion, unidad) = duracion(expiration_seconds);
706 self.interna.limite.esperar(Clase::Trading).await;
707 let valor = self
708 .interna
709 .solicitar(
710 json!({
711 "proposal": 1,
712 "amount": amount,
713 "basis": "stake",
714 "contract_type": contract_type,
715 "currency": currency,
716 "underlying_symbol": symbol,
717 "duration": duracion,
718 "duration_unit": unidad,
719 }),
720 PLAZO,
721 )
722 .await?;
723
724 let Some(profit_percent) = protocol::payout_porcentaje(&valor, amount) else {
725 return Ok(PayoutQuote::unavailable(
726 symbol,
727 option_type,
728 expiration_seconds,
729 ));
730 };
731
732 Ok(PayoutQuote {
733 symbol: symbol.to_string(),
734 option_type,
735 expiration_seconds,
736 profit_percent: Some(profit_percent),
737 min_amount: None,
738 max_amount: None,
739 available: true,
740 captured_at: epoch_secs(),
741 })
742 }
743
744 async fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError> {
745 if self.config.es_publico() {
746 return Err(BrokerError::Authentication(
747 "deriv: operar requiere token con scope trade".into(),
748 ));
749 }
750 let currency = self.divisa().await?;
751 let tipo = match req.direction {
752 Direction::Call => "CALL",
753 Direction::Put => "PUT",
754 };
755 self.interna.limite.esperar(Clase::Trading).await;
756 let propuesta = self
757 .interna
758 .solicitar(
759 json!({
760 "proposal": 1,
761 "amount": req.amount,
762 "basis": "stake",
763 "contract_type": tipo,
764 "currency": currency,
765 "underlying_symbol": req.symbol,
766 "duration": req.expiration_minutes,
767 "duration_unit": "m",
768 }),
769 PLAZO,
770 )
771 .await?;
772 let id_propuesta = propuesta
773 .get("proposal")
774 .and_then(|p| p.get("id"))
775 .and_then(Value::as_str)
776 .ok_or_else(|| BrokerError::Internal("deriv: propuesta sin id".into()))?
777 .to_string();
778 let precio = propuesta
779 .get("proposal")
780 .and_then(|p| p.get("ask_price"))
781 .and_then(Value::as_f64)
782 .unwrap_or(req.amount);
783
784 let compra = self
785 .interna
786 .solicitar(json!({"buy": id_propuesta, "price": precio}), PLAZO)
787 .await?;
788 let contrato = compra
789 .get("buy")
790 .and_then(|b| b.get("contract_id"))
791 .and_then(Value::as_u64)
792 .ok_or_else(|| BrokerError::Internal("deriv: compra sin contract_id".into()))?;
793 let id = contrato.to_string();
794 self.interna.abiertas.write().await.insert(id.clone());
795 self.interna
796 .registrar_sub(json!({
797 "proposal_open_contract": 1,
798 "contract_id": contrato,
799 "subscribe": 1,
800 }))
801 .await;
802 let _ = self
803 .interna
804 .solicitar(
805 json!({"proposal_open_contract": 1, "contract_id": contrato, "subscribe": 1}),
806 PLAZO,
807 )
808 .await;
809 let _ = self.interna.eventos.send(Event::OrderOpened(Operation {
810 id: id.clone(),
811 symbol: req.symbol.clone(),
812 amount: req.amount,
813 direction: req.direction,
814 option_type: req.option_type,
815 status: OperationStatus::Open,
816 result: None,
817 payout_percent: protocol::payout_porcentaje(&propuesta, req.amount),
818 opened_at: epoch_secs(),
819 closed_at: None,
820 }));
821 Ok(id)
822 }
823
824 async fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError> {
825 if self.config.es_publico() {
826 return Err(BrokerError::Authentication(
827 "deriv: vender requiere credenciales".into(),
828 ));
829 }
830 let contrato: u64 = order_id.parse().map_err(|_| {
831 BrokerError::Rejected(format!("deriv: contract_id inválido {order_id}"))
832 })?;
833 self.interna.limite.esperar(Clase::Trading).await;
834 self.interna
835 .solicitar(json!({"sell": contrato, "price": 0}), PLAZO)
836 .await?;
837 Ok(())
838 }
839
840 async fn get_operation_result(
841 &self,
842 order_id: &OrderId,
843 ) -> Result<OperationResult, BrokerError> {
844 Ok(self
845 .interna
846 .resultados
847 .read()
848 .await
849 .get(order_id)
850 .copied()
851 .unwrap_or(OperationResult::Pending))
852 }
853
854 async fn events(&self) -> Result<EventStream, BrokerError> {
855 let rx = self.interna.eventos.subscribe();
856 let stream = futures_util::stream::unfold(rx, |mut rx| async move {
857 match rx.recv().await {
858 Ok(evento) => Some((evento, rx)),
859 Err(broadcast::error::RecvError::Lagged(n)) => {
860 Some((Event::EventsLost { count: n }, rx))
861 }
862 Err(broadcast::error::RecvError::Closed) => None,
863 }
864 });
865 Ok(Box::pin(stream))
866 }
867}
868
869async fn url_de_conexion(
875 config: &DerivConfig,
876 interna: &Arc<Interna>,
877) -> Result<String, BrokerError> {
878 let Some(token) = config.token.as_ref() else {
879 return Ok(config.public_ws_url.clone());
880 };
881
882 let http = reqwest::Client::builder()
883 .timeout(Duration::from_secs(
884 config.transport.request_timeout_secs.max(5),
885 ))
886 .build()
887 .map_err(|e| BrokerError::Internal(format!("deriv: cliente http: {e}")))?;
888
889 let (cuenta, tipo) = resolver_cuenta(&http, config, token).await?;
890 *interna.tipo_cuenta.write().await = tipo;
891
892 let url = format!(
893 "{}/trading/v1/options/accounts/{}/otp",
894 config.base_url.trim_end_matches('/'),
895 cuenta
896 );
897 let mut peticion = http
898 .post(url)
899 .header("Authorization", format!("Bearer {token}"));
900 if let Some(app) = &config.app_id {
901 peticion = peticion.header("Deriv-App-ID", app);
902 }
903 let resp = peticion
904 .send()
905 .await
906 .map_err(|e| BrokerError::Connection(format!("deriv otp: {e}")))?;
907 let estado = resp.status();
908 let texto = resp.text().await.unwrap_or_default();
909 if !estado.is_success() {
910 let detalle: String = texto.chars().take(300).collect();
911 return Err(match estado.as_u16() {
912 401 | 403 => BrokerError::Authentication(format!(
913 "deriv otp {estado}: {} (el token necesita scope trade)",
914 detalle.trim()
915 )),
916 _ => BrokerError::Connection(format!("deriv otp {estado}: {}", detalle.trim())),
917 });
918 }
919 let valor: Value = serde_json::from_str(&texto)
920 .map_err(|e| BrokerError::Internal(format!("deriv otp: respuesta no JSON: {e}")))?;
921 valor
922 .get("data")
923 .and_then(|d| d.get("url"))
924 .and_then(Value::as_str)
925 .map(str::to_string)
926 .ok_or_else(|| BrokerError::Connection("deriv otp: respuesta sin url".into()))
927}
928
929async fn resolver_cuenta(
931 http: &reqwest::Client,
932 config: &DerivConfig,
933 token: &str,
934) -> Result<(String, AccountType), BrokerError> {
935 let url = format!(
936 "{}/trading/v1/options/accounts",
937 config.base_url.trim_end_matches('/')
938 );
939 let mut peticion = http
940 .get(url)
941 .header("Authorization", format!("Bearer {token}"));
942 if let Some(app) = &config.app_id {
943 peticion = peticion.header("Deriv-App-ID", app);
944 }
945 let resp = peticion
946 .send()
947 .await
948 .map_err(|e| BrokerError::Connection(format!("deriv cuentas: {e}")))?;
949 let estado = resp.status();
950 let texto = resp.text().await.unwrap_or_default();
951 if !estado.is_success() {
952 let detalle: String = texto.chars().take(300).collect();
953 return Err(match estado.as_u16() {
954 401 | 403 => {
955 BrokerError::Authentication(format!("deriv cuentas {estado}: {}", detalle.trim()))
956 }
957 _ => BrokerError::Connection(format!("deriv cuentas {estado}: {}", detalle.trim())),
958 });
959 }
960 let valor: Value = serde_json::from_str(&texto)
961 .map_err(|e| BrokerError::Internal(format!("deriv cuentas: respuesta no JSON: {e}")))?;
962 let lista = valor
965 .get("data")
966 .and_then(|d| {
967 if d.is_array() {
968 Some(d)
969 } else {
970 d.get("accounts")
971 }
972 })
973 .and_then(Value::as_array)
974 .ok_or_else(|| BrokerError::Connection("deriv cuentas: respuesta sin lista".into()))?;
975
976 let quiere_demo = !matches!(config.account, AccountSelection::Real);
977 let mut elegida: Option<(String, AccountType)> = None;
978
979 for c in lista {
980 let id = match c.get("account_id").and_then(Value::as_str) {
981 Some(id) if !id.is_empty() => id,
982 _ => continue,
983 };
984 let tipo = match c.get("account_type").and_then(Value::as_str) {
985 Some("demo") | Some("virtual") => AccountType::Practice,
986 Some("real") => AccountType::Real,
987 _ => {
988 let virtual_ = c
989 .get("is_virtual")
990 .and_then(Value::as_bool)
991 .unwrap_or(false);
992 if virtual_ {
993 AccountType::Practice
994 } else {
995 tipo_cuenta(id, config.account)
996 }
997 }
998 };
999 if config.account_id.as_deref() == Some(id) {
1000 return Ok((id.to_string(), tipo));
1001 }
1002 let es_demo = matches!(tipo, AccountType::Practice);
1003 if elegida.is_none() && es_demo == quiere_demo {
1004 elegida = Some((id.to_string(), tipo));
1005 }
1006 }
1007
1008 if let Some(configurada) = &config.account_id {
1009 return Ok((configurada.clone(), AccountType::Unknown));
1010 }
1011 elegida.ok_or_else(|| {
1012 BrokerError::Authentication(format!(
1013 "deriv: el token no tiene cuenta {}",
1014 if quiere_demo { "demo" } else { "real" }
1015 ))
1016 })
1017}
1018
1019async fn enviar_json(sink: &mut Escritor, msg: Value) -> Result<(), BrokerError> {
1020 sink.send(Message::Text(msg.to_string()))
1021 .await
1022 .map_err(|e| BrokerError::Connection(e.to_string()))
1023}
1024
1025async fn bucle(interna: Arc<Interna>, config: DerivConfig, mut salida: mpsc::Receiver<Value>) {
1027 let base = config.transport.backoff_base_ms.max(200);
1028 let maximo = config.transport.backoff_max_ms.max(base);
1029 let mut backoff = base;
1030 let mut reconexiones = 0u32;
1031 let mut caido_en: Option<Instant> = None;
1032
1033 while interna.activo.load(Ordering::SeqCst) {
1034 let url = match url_de_conexion(&config, &interna).await {
1035 Ok(u) => u,
1036 Err(e) => {
1037 *interna.ultimo_error.lock().expect("error no envenenado") = Some(e.to_string());
1038 if matches!(e, BrokerError::Authentication(_)) {
1039 tracing::error!(error = %e, "deriv: credenciales rechazadas, no se reintenta");
1040 break;
1041 }
1042 tracing::warn!(error = %e, "deriv: sin URL de conexión; reintento");
1043 tokio::time::sleep(Duration::from_millis(backoff)).await;
1044 backoff = backoff.saturating_mul(2).min(maximo);
1045 continue;
1046 }
1047 };
1048
1049 let ws = match connect_async(&url).await {
1050 Ok((ws, _)) => ws,
1051 Err(e) => {
1052 tracing::warn!(error = %e, "deriv: conexión ws fallida");
1053 tokio::time::sleep(Duration::from_millis(backoff)).await;
1054 backoff = backoff.saturating_mul(2).min(maximo);
1055 continue;
1056 }
1057 };
1058
1059 let (mut sink, mut stream) = ws.split();
1060 interna.vivo.store(true, Ordering::SeqCst);
1061
1062 match inicializar(&interna, &mut sink, &mut stream).await {
1063 Ok(()) => {}
1064 Err(e) => {
1065 tracing::warn!(error = %e, "deriv: inicialización fallida");
1066 interna.vivo.store(false, Ordering::SeqCst);
1067 let _ = sink.close().await;
1068 tokio::time::sleep(Duration::from_millis(backoff)).await;
1069 backoff = backoff.saturating_mul(2).min(maximo);
1070 continue;
1071 }
1072 }
1073
1074 let generacion = (*interna.listo.borrow()).wrapping_add(1);
1075 let _ = interna.listo.send(generacion);
1076 backoff = base;
1077
1078 if reconexiones > 0 {
1079 let _ = interna.eventos.send(Event::Reconnected {
1080 intentos: reconexiones,
1081 downtime_ms: caido_en
1082 .map(|t| t.elapsed().as_millis() as u64)
1083 .unwrap_or(0),
1084 });
1085 }
1086
1087 for sub in interna.subs.read().await.iter().cloned() {
1088 let mut sub = sub;
1089 sub["req_id"] = json!(interna.siguiente_id());
1090 if let Err(e) = enviar_json(&mut sink, sub).await {
1091 tracing::warn!(error = %e, "deriv: replay de suscripción fallido");
1092 }
1093 }
1094
1095 {
1096 let rec = Arc::clone(&interna);
1097 tokio::spawn(async move {
1098 reconciliar(&rec).await;
1099 });
1100 }
1101 let motivo = bucle_socket(&interna, &mut sink, &mut stream, &mut salida).await;
1102 caido_en = Some(Instant::now());
1103 interna.vivo.store(false, Ordering::SeqCst);
1104 interna.router.lock().expect("router no envenenado").clear();
1105 let _ = interna.eventos.send(Event::Disconnected {
1106 motivo: motivo.clone(),
1107 });
1108 tracing::warn!(motivo, "deriv: conexión perdida");
1109
1110 if !interna.activo.load(Ordering::SeqCst) {
1111 break;
1112 }
1113 reconexiones += 1;
1114 let pausa = interna.pausa_reconexion_segs.swap(0, Ordering::SeqCst);
1115 if pausa > 0 {
1116 tracing::warn!(pausa, "deriv: reconexión pausada para prueba");
1117 tokio::time::sleep(Duration::from_secs(pausa)).await;
1118 }
1119 tokio::time::sleep(Duration::from_millis(backoff)).await;
1120 backoff = backoff.saturating_mul(2).min(maximo);
1121 }
1122}
1123
1124async fn inicializar(
1126 interna: &Arc<Interna>,
1127 sink: &mut Escritor,
1128 stream: &mut Lector,
1129) -> Result<(), BrokerError> {
1130 let id = interna.siguiente_id();
1131 enviar_json(sink, json!({"time": 1, "req_id": id})).await?;
1132 let tiempo = leer_hasta(stream, id, Duration::from_secs(10)).await?;
1133 let servidor = tiempo
1134 .get("time")
1135 .and_then(Value::as_i64)
1136 .unwrap_or_default();
1137 let offset_ms = (servidor - epoch_secs()) * 1000;
1138
1139 let mut cuenta = String::from("public");
1140 let mut balance = None;
1141
1142 if interna.activo.load(Ordering::SeqCst) {
1143 let id = interna.siguiente_id();
1144 enviar_json(sink, json!({"balance": 1, "subscribe": 1, "req_id": id})).await?;
1145 if let Ok(valor) = leer_hasta(stream, id, Duration::from_secs(10)).await {
1146 if let Some((amount, currency, loginid)) = protocol::balance(&valor) {
1147 if !loginid.is_empty() {
1148 cuenta = loginid;
1149 }
1150 balance = Some(Balance {
1151 amount,
1152 currency,
1153 account_type: AccountType::Unknown,
1154 balance_id: protocol::id_surrogado(&cuenta),
1155 });
1156 }
1157 }
1158 }
1159
1160 if let Some(b) = balance {
1161 *interna.balance.write().await = Some(b);
1162 }
1163
1164 let sesion = Session {
1165 broker_name: "deriv".into(),
1166 connected_at: epoch_secs(),
1167 account_id: Some(cuenta.clone()),
1168 balance_id: Some(protocol::id_surrogado(&cuenta)),
1169 account_type: *interna.tipo_cuenta.read().await,
1170 server_time_offset_ms: offset_ms,
1171 };
1172 *interna.estado.write().await = Some(sesion);
1173 Ok(())
1174}
1175
1176async fn leer_hasta(stream: &mut Lector, id: u64, plazo: Duration) -> Result<Value, BrokerError> {
1178 let fin = tokio::time::Instant::now() + plazo;
1179 loop {
1180 let restante = fin.saturating_duration_since(tokio::time::Instant::now());
1181 if restante.is_zero() {
1182 return Err(BrokerError::Timeout);
1183 }
1184 match tokio::time::timeout(restante, stream.next()).await {
1185 Err(_) => return Err(BrokerError::Timeout),
1186 Ok(None) => return Err(BrokerError::NotConnected),
1187 Ok(Some(Err(e))) => return Err(BrokerError::Connection(e.to_string())),
1188 Ok(Some(Ok(Message::Text(texto)))) => {
1189 if let Ok(valor) = serde_json::from_str::<Value>(&texto) {
1190 if valor.get("req_id").and_then(Value::as_u64) == Some(id) {
1191 return interpretar(valor);
1192 }
1193 }
1194 }
1195 Ok(Some(Ok(Message::Close(_)))) => return Err(BrokerError::NotConnected),
1196 Ok(Some(Ok(_))) => {}
1197 }
1198 }
1199}
1200
1201async fn bucle_socket(
1203 interna: &Arc<Interna>,
1204 sink: &mut Escritor,
1205 stream: &mut Lector,
1206 salida: &mut mpsc::Receiver<Value>,
1207) -> String {
1208 loop {
1209 tokio::select! {
1210 Some(msg) = salida.recv() => {
1211 if let Err(e) = enviar_json(sink, msg).await {
1212 return e.to_string();
1213 }
1214 }
1215 frame = stream.next() => {
1216 match frame {
1217 Some(Ok(Message::Text(texto))) => procesar(interna, &texto).await,
1218 Some(Ok(Message::Ping(datos))) => {
1219 let _ = sink.send(Message::Pong(datos)).await;
1220 }
1221 Some(Ok(Message::Close(_))) | None => return "socket cerrado".into(),
1222 Some(Err(e)) => return e.to_string(),
1223 _ => {}
1224 }
1225 }
1226 _ = interna.cortar.notified() => {
1227 let _ = sink.close().await;
1228 return "cierre solicitado".into();
1229 }
1230 }
1231 }
1232}
1233
1234async fn procesar(interna: &Arc<Interna>, texto: &str) {
1236 let Ok(valor) = serde_json::from_str::<Value>(texto) else {
1237 return;
1238 };
1239
1240 if let Some(id) = valor.get("req_id").and_then(Value::as_u64) {
1241 let espera = interna
1242 .router
1243 .lock()
1244 .expect("router no envenenado")
1245 .remove(&id);
1246 if let Some(tx) = espera {
1247 let _ = tx.send(valor.clone());
1248 }
1249 }
1250
1251 match valor.get("msg_type").and_then(Value::as_str).unwrap_or("") {
1252 "ohlc" => {
1253 let eco = valor.get("echo_req").cloned().unwrap_or(Value::Null);
1254 let symbol = eco
1255 .get("ticks_history")
1256 .and_then(Value::as_str)
1257 .unwrap_or_default();
1258 let intervalo = eco.get("granularity").and_then(Value::as_u64).unwrap_or(60);
1259 if let Some(vela) = protocol::vela_ohlc(&valor, intervalo) {
1260 let clave = format!("{symbol}|{intervalo}");
1261 let emisor = interna.sub_velas.read().await.get(&clave).cloned();
1262 if let Some(tx) = emisor {
1263 let _ = tx.send(vela).await;
1264 }
1265 }
1266 }
1267 "proposal_open_contract" => {
1268 if let Some((id, resultado)) = protocol::resultado_contrato(&valor) {
1269 registrar_cierre(interna, &id, resultado).await;
1270 }
1271 }
1272 "tick" => {
1273 if let Some(t) = valor.get("tick") {
1274 let symbol = t
1275 .get("symbol")
1276 .and_then(Value::as_str)
1277 .or_else(|| valor.pointer("/echo_req/ticks").and_then(Value::as_str))
1278 .unwrap_or_default()
1279 .to_string();
1280 let price = t.get("quote").and_then(Value::as_f64).unwrap_or_default();
1281 let epoch = t.get("epoch").and_then(Value::as_i64).unwrap_or_default();
1282 let _ = interna.eventos.send(Event::PriceTick {
1283 symbol,
1284 tick: PriceTick {
1285 price,
1286 bid: t.get("bid").and_then(Value::as_f64),
1287 ask: t.get("ask").and_then(Value::as_f64),
1288 at_ms: epoch * 1000,
1289 },
1290 });
1291 }
1292 }
1293 "balance" => {
1294 if let Some((amount, currency, loginid)) = protocol::balance(&valor) {
1295 let balance = Balance {
1296 amount,
1297 currency,
1298 account_type: tipo_cuenta(&loginid, AccountSelection::Default),
1299 balance_id: protocol::id_surrogado(&loginid),
1300 };
1301 *interna.balance.write().await = Some(balance.clone());
1302 let _ = interna.eventos.send(Event::BalanceChanged(AccountBalance {
1303 id: balance.balance_id,
1304 currency: balance.currency.clone(),
1305 amount: balance.amount,
1306 account_type: balance.account_type,
1307 hold_amount: None,
1308 bonus_amount: None,
1309 enrolled_amount: None,
1310 has_deposits: None,
1311 }));
1312 }
1313 }
1314 _ => {}
1315 }
1316}
1317
1318async fn registrar_cierre(interna: &Arc<Interna>, id: &str, resultado: OperationResult) {
1321 if interna.resultados.read().await.contains_key(id) {
1322 return;
1323 }
1324 interna
1325 .resultados
1326 .write()
1327 .await
1328 .insert(id.to_string(), resultado);
1329 interna.abiertas.write().await.remove(id);
1330 let _ = interna.eventos.send(Event::OrderClosed {
1331 id: id.to_string(),
1332 result: resultado,
1333 });
1334}
1335
1336async fn reconciliar(interna: &Arc<Interna>) {
1339 let abiertas: Vec<OrderId> = interna.abiertas.read().await.iter().cloned().collect();
1340 if abiertas.is_empty() {
1341 return;
1342 }
1343 tracing::info!(pendientes = abiertas.len(), "deriv: reconciliando cierres");
1344
1345 for id in &abiertas {
1346 let Ok(contrato) = id.parse::<u64>() else {
1347 continue;
1348 };
1349 let Ok(valor) = interna
1350 .solicitar(
1351 json!({"proposal_open_contract": 1, "contract_id": contrato}),
1352 PLAZO,
1353 )
1354 .await
1355 else {
1356 continue;
1357 };
1358 if let Some((cid, resultado)) = protocol::resultado_contrato(&valor) {
1359 registrar_cierre(interna, &cid, resultado).await;
1360 }
1361 }
1362
1363 let mut offset = 0usize;
1364 for _ in 0..10 {
1365 if interna.abiertas.read().await.is_empty() {
1366 break;
1367 }
1368 let Ok(valor) = interna
1369 .solicitar(
1370 json!({"profit_table": 1, "description": 1, "limit": 100, "offset": offset}),
1371 PLAZO,
1372 )
1373 .await
1374 else {
1375 break;
1376 };
1377 let pagina = protocol::posiciones(&valor, offset);
1378 if pagina.positions.is_empty() {
1379 break;
1380 }
1381 for posicion in &pagina.positions {
1382 if !interna.abiertas.read().await.contains(&posicion.id) {
1383 continue;
1384 }
1385 let resultado = match posicion.pnl {
1386 Some(x) if x > 0.0 => OperationResult::Win(x),
1387 Some(x) if x < 0.0 => OperationResult::Loss(x.abs()),
1388 Some(_) => OperationResult::Equal(0.0),
1389 None => continue,
1390 };
1391 registrar_cierre(interna, &posicion.id, resultado).await;
1392 }
1393 offset += 100;
1394 }
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399 use super::*;
1400
1401 #[test]
1402 fn duracion_usa_la_unidad_mayor_exacta() {
1403 assert_eq!(duracion(60), (1, "m"));
1404 assert_eq!(duracion(300), (5, "m"));
1405 assert_eq!(duracion(3600), (1, "h"));
1406 assert_eq!(duracion(86400), (1, "d"));
1407 assert_eq!(duracion(45), (45, "s"));
1408 }
1409
1410 #[test]
1411 fn tipo_cuenta_por_prefijo() {
1412 assert_eq!(
1413 tipo_cuenta("VRTC123", AccountSelection::Real),
1414 AccountType::Practice
1415 );
1416 assert_eq!(
1417 tipo_cuenta("CR456", AccountSelection::Practice),
1418 AccountType::Real
1419 );
1420 assert_eq!(
1421 tipo_cuenta("X", AccountSelection::Default),
1422 AccountType::Unknown
1423 );
1424 }
1425
1426 #[test]
1427 fn contrato_de_solo_traduce_rise_fall() {
1428 assert_eq!(contrato_de(OptionType::Binary), Some("CALL"));
1429 assert_eq!(contrato_de(OptionType::Digital), None);
1430 assert_eq!(contrato_de(OptionType::Blitz), None);
1431 }
1432
1433 #[test]
1434 fn error_invalid_token_es_autenticacion() {
1435 let e = error_de(&json!({"code": "InvalidToken", "message": "bad"}));
1436 assert!(matches!(e, BrokerError::Authentication(_)));
1437 }
1438
1439 #[test]
1440 fn error_de_validacion_es_rechazo() {
1441 let e = error_de(&json!({"code": "InputValidationFailed", "message": "falta"}));
1442 assert!(matches!(e, BrokerError::Rejected(_)));
1443 }
1444}