Skip to main content

cripsy_binary_api/broker/deriv/
config.rs

1//! Configuración del adaptador Deriv.
2//!
3//! El token **nunca** se serializa ni se imprime: `Debug` lo redacta y
4//! `serde` lo omite. Un `BrokerParams` serializado no transporta credenciales.
5
6use serde::{Deserialize, Serialize};
7
8use crate::broker::config::{AccountSelection, TransportConfig};
9use crate::broker::error::BrokerError;
10
11/// Cupos de peticiones por clase de presupuesto.
12///
13/// Deriv comparte el cupo entre llamadas del mismo grupo (proposal, buy y sell
14/// comparten 360/min). Por defecto se usa el 80 % de lo documentado para dejar
15/// margen a reconexiones.
16#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
17pub struct LimitesTasa {
18    /// Fracción del cupo documentado que se permite usar (0.1 - 1.0).
19    pub porcentaje: f64,
20    pub trading_por_min: u32,
21    pub trading_por_hora: u32,
22    pub balance_por_min: u32,
23    pub balance_por_hora: u32,
24    pub cartera_por_min: u32,
25    pub cartera_por_hora: u32,
26    pub resto_por_min: u32,
27    pub resto_por_hora: u32,
28}
29
30impl Default for LimitesTasa {
31    fn default() -> Self {
32        let p = 0.8;
33        Self {
34            porcentaje: p,
35            trading_por_min: (360.0 * p) as u32,
36            trading_por_hora: (14_400.0 * p) as u32,
37            balance_por_min: (100.0 * p) as u32,
38            balance_por_hora: (2_000.0 * p) as u32,
39            cartera_por_min: (30.0 * p) as u32,
40            cartera_por_hora: (1_500.0 * p) as u32,
41            resto_por_min: (220.0 * p) as u32,
42            resto_por_hora: (14_400.0 * p) as u32,
43        }
44    }
45}
46
47/// Configuración del adaptador Deriv.
48///
49/// Dos modos:
50/// - **Público** (sin `token`): solo mercado, sin cuenta ni órdenes.
51/// - **Autenticado** (`token` + `account_id`): OTP, balance y ejecución.
52#[derive(Clone, PartialEq, Serialize, Deserialize)]
53pub struct DerivConfig {
54    /// PAT o access token OAuth. Nunca se serializa ni se imprime.
55    #[serde(default, skip_serializing)]
56    pub token: Option<String>,
57    /// App ID de la aplicación (obligatorio con PAT).
58    pub app_id: Option<String>,
59    /// Cuenta sobre la que se opera (`CR…`, `VRTC…`). Si falta, se elige la
60    /// primera del tipo pedido en `account`.
61    pub account_id: Option<String>,
62    pub base_url: String,
63    pub public_ws_url: String,
64    pub account: AccountSelection,
65    /// Divisa para propuestas; si falta se usa la del balance.
66    pub currency: Option<String>,
67    /// Importe de referencia para cotizar payout (Deriv cotiza por importe).
68    pub stake_referencia: f64,
69    pub transport: TransportConfig,
70    pub limites: LimitesTasa,
71}
72
73impl Default for DerivConfig {
74    fn default() -> Self {
75        Self {
76            token: None,
77            app_id: None,
78            account_id: None,
79            base_url: "https://api.derivws.com".into(),
80            public_ws_url: "wss://api.derivws.com/trading/v1/options/ws/public".into(),
81            account: AccountSelection::Practice,
82            currency: None,
83            stake_referencia: 1.0,
84            transport: TransportConfig::default(),
85            limites: LimitesTasa::default(),
86        }
87    }
88}
89
90impl DerivConfig {
91    /// Configuración de solo mercado público (sin credenciales).
92    pub fn publico() -> Self {
93        Self::default()
94    }
95
96    /// ¿Opera sin credenciales?
97    pub fn es_publico(&self) -> bool {
98        self.token.is_none()
99    }
100
101    /// Valida la configuración antes de abrir red.
102    pub fn validar(&self) -> Result<(), BrokerError> {
103        if self.base_url.trim().is_empty() {
104            return Err(BrokerError::Internal("deriv: base_url vacía".into()));
105        }
106        if !self.public_ws_url.starts_with("wss://") {
107            return Err(BrokerError::Internal(
108                "deriv: public_ws_url debe ser wss://".into(),
109            ));
110        }
111        if let Some(token) = &self.token {
112            if token.trim().is_empty() {
113                return Err(BrokerError::Authentication(
114                    "deriv: token vacío; usa None para el modo público".into(),
115                ));
116            }
117        }
118        if self.stake_referencia <= 0.0 {
119            return Err(BrokerError::Internal(
120                "deriv: stake_referencia debe ser positivo".into(),
121            ));
122        }
123        if !(0.05..=1.0).contains(&self.limites.porcentaje) {
124            return Err(BrokerError::Internal(
125                "deriv: limites.porcentaje fuera de 0.05..=1.0".into(),
126            ));
127        }
128        Ok(())
129    }
130}
131
132impl std::fmt::Debug for DerivConfig {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        let token = match &self.token {
135            Some(t) if !t.is_empty() => format!("<redactado:{}chars>", t.len()),
136            Some(_) => "<vacío>".to_string(),
137            None => "<ninguno>".to_string(),
138        };
139        f.debug_struct("DerivConfig")
140            .field("token", &token)
141            .field("app_id", &self.app_id.as_deref().map(|_| "<presente>"))
142            .field("account_id", &self.account_id)
143            .field("base_url", &self.base_url)
144            .field("public_ws_url", &self.public_ws_url)
145            .field("account", &self.account)
146            .field("currency", &self.currency)
147            .field("stake_referencia", &self.stake_referencia)
148            .field("transport", &self.transport)
149            .field("limites", &self.limites)
150            .finish()
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn debug_no_filtra_el_token() {
160        let cfg = DerivConfig {
161            token: Some("pat_secreto_123".into()),
162            app_id: Some("12345".into()),
163            ..DerivConfig::default()
164        };
165        let texto = format!("{cfg:?}");
166        assert!(!texto.contains("pat_secreto_123"));
167        assert!(texto.contains("redactado"));
168    }
169
170    #[test]
171    fn serde_omite_el_token() {
172        let cfg = DerivConfig {
173            token: Some("pat_secreto_123".into()),
174            ..DerivConfig::default()
175        };
176        let json = serde_json::to_string(&cfg).unwrap();
177        assert!(!json.contains("pat_secreto_123"));
178        assert!(!json.contains("token"));
179    }
180
181    #[test]
182    fn publico_no_requiere_token() {
183        assert!(DerivConfig::publico().es_publico());
184        assert!(DerivConfig::publico().validar().is_ok());
185    }
186
187    #[test]
188    fn token_vacio_es_error() {
189        let cfg = DerivConfig {
190            token: Some("   ".into()),
191            ..DerivConfig::default()
192        };
193        assert!(matches!(cfg.validar(), Err(BrokerError::Authentication(_))));
194    }
195
196    #[test]
197    fn cupos_por_defecto_bajo_el_limite() {
198        let l = LimitesTasa::default();
199        assert!(l.trading_por_min < 360);
200        assert!(l.cartera_por_min < 30);
201    }
202}