Skip to main content

cripsy_binary_api/broker/iq_option/
mapper.rs

1//! Mapeo dominio ↔ protocolo IQ Option.
2
3use serde_json::Value;
4
5use crate::broker::config::AccountSelection;
6use crate::broker::session::Session;
7use crate::domain::*;
8use crate::transport::websocket::WsFrame;
9
10use super::endpoints::ASSET_NAME_PREFIX;
11
12/// Quita el prefijo `front.` de los nombres del bróker.
13pub fn simbolo_desde_nombre(nombre: &str) -> String {
14    nombre
15        .strip_prefix(ASSET_NAME_PREFIX)
16        .unwrap_or(nombre)
17        .to_string()
18}
19
20/// Convierte `balance type` del bróker en `AccountType`.
21pub fn tipo_de_cuenta(balance_type: i64) -> AccountType {
22    match balance_type {
23        1 => AccountType::Real,
24        4 => AccountType::Practice,
25        // Un tipo desconocido NO se interpreta como cuenta real: se marca como
26        // desconocido y se registra para poder diagnosticarlo.
27        otro => {
28            tracing::warn!(balance_type = otro, "tipo de cuenta no reconocido");
29            AccountType::Unknown
30        }
31    }
32}
33
34/// Payout en porcentaje a partir de la comisión del catálogo.
35pub fn payout_de_comision(comision: f64) -> f64 {
36    (100.0 - comision).max(0.0)
37}
38
39/// Parsea los grupos `binary`/`turbo`/`blitz` del inicializador.
40pub fn catalogo_desde_init(msg: &Value) -> Vec<Asset> {
41    // `groups` mapea group_id -> nombre de sector ("front.forex").
42    let grupos: std::collections::HashMap<String, String> = msg
43        .get("groups")
44        .and_then(|g| g.as_object())
45        .map(|m| {
46            m.iter()
47                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
48                .collect()
49        })
50        .unwrap_or_default();
51    let mut activos = Vec::new();
52    for (grupo, clase) in [
53        ("binary", AssetClass::Binary),
54        ("turbo", AssetClass::Turbo),
55        ("blitz", AssetClass::Blitz),
56        ("digital", AssetClass::Digital),
57    ] {
58        let Some(actives) = msg
59            .pointer(&format!("/{grupo}/actives"))
60            .and_then(|a| a.as_object())
61        else {
62            continue;
63        };
64        for (id, a) in actives {
65            let Some(opcode) = id.parse::<u32>().ok() else {
66                continue;
67            };
68            let nombre = a.get("name").and_then(|n| n.as_str()).unwrap_or_default();
69            if nombre.is_empty() {
70                continue;
71            }
72            let comision = a
73                .pointer("/option/profit/commission")
74                .and_then(|c| c.as_f64());
75            let payout_percent = comision.map(payout_de_comision);
76            let habilitado = a.get("enabled").and_then(|e| e.as_bool()).unwrap_or(false);
77            let suspendido = a
78                .get("is_suspended")
79                .and_then(|e| e.as_bool())
80                .unwrap_or(false);
81            // Estado declarado por el bróker; el horario se evalúa a consulta con
82            // `Asset::is_open_by_schedule` usando la hora del servidor.
83            let status = if !habilitado || suspendido {
84                MarketStatus::Closed
85            } else {
86                MarketStatus::Open
87            };
88            let schedule = a
89                .get("schedule")
90                .and_then(|s| s.as_array())
91                .map(|ventanas| {
92                    ventanas
93                        .iter()
94                        .filter_map(|v| {
95                            let abierta = v.as_array()?;
96                            Some(ScheduleWindow {
97                                open: abierta.first()?.as_i64()?,
98                                close: abierta.get(1)?.as_i64()?,
99                            })
100                        })
101                        .collect::<Vec<_>>()
102                });
103            let expiration_times = a
104                .pointer("/option/expiration_times")
105                .and_then(|e| e.as_array())
106                .map(|v| v.iter().filter_map(|s| s.as_u64()).collect::<Vec<_>>());
107            let rollovers = a.get("rollovers").and_then(|r| r.as_array()).map(|v| {
108                v.iter()
109                    .filter_map(|r| {
110                        Some(RolloverParams {
111                            deadtime: r.get("deadtime")?.as_u64()? as u32,
112                            limit: r.get("limit")?.as_u64()? as u32,
113                            offset: r.get("offset")?.as_u64()? as u32,
114                            offset_from_expiration: r.get("offset_from_expiration")?.as_u64()?
115                                as u32,
116                            expiration_size: r.get("expiration_size")?.as_u64()? as u32,
117                        })
118                    })
119                    .collect::<Vec<_>>()
120            });
121            let min_amount = a
122                .pointer("/minmax/min")
123                .and_then(|m| m.as_f64())
124                .or_else(|| a.get("minimal_bet").and_then(|m| m.as_f64()));
125            let max_amount = a
126                .pointer("/minmax/max")
127                .and_then(|m| m.as_f64())
128                .or_else(|| a.get("maximal_bet").and_then(|m| m.as_f64()));
129            let extras = AssetExtras {
130                expiration_times_secs: expiration_times,
131                rollovers,
132                min_amount,
133                max_amount,
134                provider: a
135                    .get("provider")
136                    .and_then(|p| p.as_str())
137                    .map(str::to_string),
138                exchange: a
139                    .get("exchange")
140                    .and_then(|e| e.as_str())
141                    .map(str::to_string),
142                start_time: a.get("start_time").and_then(|t| t.as_i64()),
143                buyback_deadtime: a
144                    .get("buyback_deadtime")
145                    .and_then(|d| d.as_u64())
146                    .map(|d| d as u32),
147                deadtime: a.get("deadtime").and_then(|d| d.as_u64()).map(|d| d as u32),
148                is_buyback: a.get("is_buyback").and_then(|b| b.as_bool()),
149                top_traders_enabled: a.get("top_traders_enabled").and_then(|b| b.as_bool()),
150                precision: a
151                    .get("precision")
152                    .and_then(|p| p.as_u64())
153                    .map(|p| p as u32),
154                minimal_bet: a.get("minimal_bet").and_then(|m| m.as_f64()),
155                maximal_bet: a.get("maximal_bet").and_then(|m| m.as_f64()),
156            };
157            // Sector: `groups` mapea group_id -> nombre ("front.forex").
158            // Sector: `groups` mapea group_id -> nombre ("front.forex").
159            // El `group_id` puede venir como string o como número.
160            let sector = a
161                .get("group_id")
162                .and_then(|g| {
163                    g.as_str()
164                        .map(str::to_string)
165                        .or_else(|| g.as_i64().map(|i| i.to_string()))
166                })
167                .and_then(|gid| grupos.get(&gid).map(|s| s.as_str()))
168                .map(simbolo_desde_nombre);
169            let _ = comision; // la comisión se consulta vía el catálogo del bróker
170            activos.push(Asset {
171                symbol: simbolo_desde_nombre(nombre),
172                name: nombre.to_string(),
173                class: clase,
174                opcode,
175                status,
176                payout_percent,
177                sector,
178                schedule,
179                extras: Some(extras),
180            });
181        }
182    }
183    activos
184}
185
186/// Parsea una vela del histórico (`get-candles` / `quotes-history.get-candles`).
187///
188/// Campos: `from`,`to`,`open`,`close`,`max`,`min`,`volume`,`at` (ns).
189pub fn vela_desde_json(v: &Value) -> Option<Candle> {
190    Some(Candle {
191        from: v.get("from")?.as_i64()?,
192        to: v.get("to")?.as_i64()?,
193        open: v.get("open")?.as_f64()?,
194        close: v.get("close")?.as_f64()?,
195        high: v.get("max").and_then(|m| m.as_f64())?,
196        low: v.get("min").and_then(|m| m.as_f64())?,
197        volume: v.get("volume").and_then(|x| x.as_f64()),
198    })
199}
200
201/// `expired` de blitz: el bróker exige el valor ALINEADO al múltiplo de la
202/// duración (verificado en vivo 2026-10-27; valores desalineados reciben
203/// `active is suspended`).
204pub fn expiracion_blitz_alineada(ahora: i64, duracion_segs: u64) -> i64 {
205    let d = duracion_segs as i64;
206    (ahora / d + 1) * d
207}
208
209/// Tiempo de expiración de binarias/turbo (réplica de la lógica del bróker).
210/// Devuelve `(expirado, indice)`. Los primeros 5 candidatos son de minuto
211/// (turbo); el índice decide `option_type_id`: <5 → 3 (turbo), ≥5 → 1 (binary).
212pub fn tiempo_de_expiracion(ahora: i64, duracion_min: u64) -> (i64, usize) {
213    let minuto_base = ahora - ahora % 60;
214    let mut candidatos: Vec<i64> = Vec::new();
215
216    // Turbo: siguientes 5 minutos hábiles.
217    let mut t = if minuto_base + 60 - ahora > 30 {
218        minuto_base + 60
219    } else {
220        minuto_base + 120
221    };
222    for _ in 0..5 {
223        candidatos.push(t);
224        t += 60;
225    }
226
227    // Binary: cuartos de hora con margen de 5 minutos.
228    let mut exp = minuto_base;
229    let mut idx = 0;
230    while idx < 50 {
231        if (exp / 60) % 15 == 0 && exp - ahora > 60 * 5 {
232            candidatos.push(exp);
233            idx += 1;
234        }
235        exp += 60;
236    }
237
238    let objetivo = (60 * duracion_min) as i64;
239    candidatos
240        .into_iter()
241        .enumerate()
242        .min_by_key(|(_, t)| (*t - ahora - objetivo).abs())
243        .map(|(i, t)| (t, i))
244        .unwrap_or((ahora + 60 * duracion_min as i64, 0))
245}
246
247/// Payout digital en vivo desde `price-splitter.client-price-generated`.
248///
249/// Payout digital en vivo desde `price-splitter.client-price-generated`.
250///
251/// `call` paga con `bid`; `put` paga con `ask`: `ProfitPercent = (100-precio)*100/precio`.
252pub fn payout_price_splitter(msg: &Value, direction: Direction) -> Option<Payout> {
253    let prices = msg.get("prices")?.as_array()?;
254    // La entrada spot se marca con strike = SPT (el resto son strikes numéricos).
255    let primero = prices
256        .iter()
257        .find(|p| p.get("strike").and_then(|s| s.as_str()) == Some("SPT"))
258        .or_else(|| prices.first())?;
259    let precio = match direction {
260        Direction::Call => primero.pointer("/call/bid").and_then(|v| v.as_f64())?,
261        Direction::Put => primero.pointer("/put/ask").and_then(|v| v.as_f64())?,
262    };
263    if precio <= 0.0 {
264        return None;
265    }
266    Some(Payout {
267        symbol: msg
268            .get("asset_id")
269            .and_then(|a| a.as_i64())
270            .map(|a| a.to_string())
271            .unwrap_or_default(),
272        expiration_seconds: msg.get("period").and_then(|p| p.as_u64()).unwrap_or(0),
273        profit_percent: (100.0 - precio) * 100.0 / precio,
274        is_spot: true,
275        strike: None,
276        closed: false,
277    })
278}
279
280/// `instrument_id` digital por dirección y periodo (segundos) del price-splitter.
281pub fn instrumento_digital(msg: &Value, periodo_segs: u64, direction: Direction) -> Option<String> {
282    if msg.get("period").and_then(|p| p.as_u64()) != Some(periodo_segs) {
283        return None;
284    }
285    let prices = msg.get("prices")?.as_array()?;
286    let primero = prices
287        .iter()
288        .find(|p| p.get("strike").and_then(|s| s.as_str()) == Some("SPT"))
289        .or_else(|| prices.first())?;
290    match direction {
291        Direction::Call => primero
292            .pointer("/call/symbol")
293            .and_then(|s| s.as_str())
294            .map(str::to_string),
295        Direction::Put => primero
296            .pointer("/put/symbol")
297            .and_then(|s| s.as_str())
298            .map(str::to_string),
299    }
300}
301
302/// Construye una `Operation` desde el mensaje `option-opened`.
303pub fn operacion_desde_apertura(msg: &Value) -> Option<Operation> {
304    let id = msg.get("option_id")?.to_string();
305    let direction = match msg.get("direction").and_then(|d| d.as_str())? {
306        "call" => Direction::Call,
307        "put" => Direction::Put,
308        _ => return None,
309    };
310    let option_type = match msg.get("option_type").and_then(|t| t.as_str()) {
311        Some("blitz") => OptionType::Blitz,
312        Some(_) => OptionType::Binary,
313        None => OptionType::Binary,
314    };
315    Some(Operation {
316        id,
317        symbol: msg
318            .get("active")
319            .and_then(|a| a.as_str())
320            .unwrap_or_default()
321            .to_string(),
322        amount: msg.get("amount").and_then(|a| a.as_f64()).unwrap_or(0.0),
323        direction,
324        option_type,
325        status: OperationStatus::Open,
326        result: None,
327        // El bróker envía el CRÉDITO TOTAL (p. ej. 183 = 100 + 83): normalizamos
328        // al payout neto (verificado en vivo; observación del informe 2026-10-31).
329        payout_percent: msg
330            .get("profit_percent")
331            .and_then(|p| p.as_f64())
332            .map(|p| (p - 100.0).max(0.0)),
333        opened_at: msg
334            .get("open_time")
335            .and_then(|t| t.as_i64())
336            .unwrap_or_default(),
337        closed_at: None,
338    })
339}
340
341/// Ventana de expiración de minivela válida (`to` en el cierre de una vela).
342pub fn cierre_de_vela_cerrada(ahora_segs: i64, size_segs: i64, margen_segs: i64) -> i64 {
343    (ahora_segs / size_segs) * size_segs - margen_segs
344}
345
346/// Redondeo monetario a 6 decimales (evita ruido de punto flotante).
347pub fn redondear_dinero(v: f64) -> f64 {
348    (v * 1e6).round() / 1e6
349}
350
351/// Resultado neto a partir del mensaje de cierre (`option-closed`).
352///
353/// `win_enrolled_amount`/`profit_amount` son el CRÉDITO TOTAL (stake + ganancia).
354pub fn resultado_desde_cierre(msg: &Value) -> Option<OperationResult> {
355    let resultado = msg.get("result").and_then(|r| r.as_str())?;
356    let stake = redondear_dinero(msg.get("amount").and_then(|a| a.as_f64()).unwrap_or(0.0));
357    let credito = redondear_dinero(
358        msg.get("win_enrolled_amount")
359            .or_else(|| msg.get("profit_amount"))
360            .and_then(|v| v.as_f64())
361            .unwrap_or(0.0),
362    );
363    match resultado {
364        // Un `win` SIN crédito es un mensaje incompleto (verificado en Blitz:
365        // `socket-option-closed` puede llegar sin `win_amount`): se descarta
366        // para no pisar el resultado bueno (informe 2026-10-31).
367        "win" | "won" => {
368            if credito > 0.0 {
369                Some(OperationResult::Win(redondear_dinero(credito - stake)))
370            } else {
371                None
372            }
373        }
374        "loose" | "lose" | "lost" => Some(OperationResult::Loss(stake)),
375        "equal" => Some(OperationResult::Equal(stake)),
376        // Cierre manual (venta anticipada/buyback): el bróker marca
377        // `result: "default"` y el crédito real viaja en profit_amount.
378        "default" | "sold" => {
379            let venta = msg
380                .get("profit_amount")
381                .and_then(|p| p.as_f64())
382                .or_else(|| msg.get("win_enrolled_amount").and_then(|w| w.as_f64()))
383                .unwrap_or(0.0);
384            let neto = redondear_dinero(venta - stake);
385            if neto > 0.0 {
386                Some(OperationResult::Win(neto))
387            } else if neto < 0.0 {
388                Some(OperationResult::Loss(-neto))
389            } else {
390                Some(OperationResult::Equal(stake))
391            }
392        }
393        _ => None,
394    }
395}
396
397/// Parsea los balances del mensaje `profile` (`/balances[]`).
398pub fn balances_desde_perfil(perfil: &Value) -> Vec<AccountBalance> {
399    let mut salida = Vec::new();
400    if let Some(lista) = perfil.get("balances").and_then(|b| b.as_array()) {
401        for b in lista {
402            if let (Some(id), Some(tipo), Some(monto)) = (
403                b.get("id").and_then(|i| i.as_i64()),
404                b.get("type").and_then(|t| t.as_i64()),
405                b.get("amount").and_then(|a| a.as_f64()),
406            ) {
407                salida.push(AccountBalance {
408                    id,
409                    currency: b
410                        .get("currency")
411                        .and_then(|c| c.as_str())
412                        .unwrap_or("USD")
413                        .to_string(),
414                    amount: monto,
415                    account_type: tipo_de_cuenta(tipo),
416                    hold_amount: b.get("hold_amount").and_then(|v| v.as_f64()),
417                    bonus_amount: b.get("bonus_amount").and_then(|v| v.as_f64()),
418                    enrolled_amount: b.get("enrolled_amount").and_then(|v| v.as_f64()),
419                    has_deposits: b.get("has_deposits").and_then(|v| v.as_bool()),
420                });
421            }
422        }
423    }
424    salida
425}
426
427/// Parsea una lista directa de balances (respuesta al mensaje `balances`).
428pub fn balances_desde_lista(lista: &Value) -> Vec<AccountBalance> {
429    let mut salida = Vec::new();
430    if let Some(items) = lista.as_array() {
431        for b in items {
432            if let (Some(id), Some(tipo)) = (
433                b.get("id").and_then(|i| i.as_i64()),
434                b.get("type").and_then(|t| t.as_i64()),
435            ) {
436                salida.push(AccountBalance {
437                    id,
438                    currency: b
439                        .get("currency")
440                        .and_then(|c| c.as_str())
441                        .unwrap_or("USD")
442                        .to_string(),
443                    amount: b.get("amount").and_then(|a| a.as_f64()).unwrap_or(0.0),
444                    account_type: tipo_de_cuenta(tipo),
445                    hold_amount: b.get("hold_amount").and_then(|v| v.as_f64()),
446                    bonus_amount: b.get("bonus_amount").and_then(|v| v.as_f64()),
447                    enrolled_amount: b.get("enrolled_amount").and_then(|v| v.as_f64()),
448                    has_deposits: b.get("has_deposits").and_then(|v| v.as_bool()),
449                });
450            }
451        }
452    }
453    salida
454}
455
456/// Construye la `Session` y los balances desde el perfil, eligiendo la cuenta.
457///
458/// Sin selección explícita se prefiere la demo (type 4), igual que la web.
459pub fn sesion_desde_perfil(
460    perfil: &Value,
461    seleccion: &AccountSelection,
462) -> Option<(Session, Vec<AccountBalance>)> {
463    let balances = balances_desde_perfil(perfil);
464    if balances.is_empty() {
465        return None;
466    }
467    let elegido = match seleccion {
468        AccountSelection::Practice => balances
469            .iter()
470            .find(|b| b.account_type == AccountType::Practice),
471        AccountSelection::Real => balances
472            .iter()
473            .find(|b| b.account_type == AccountType::Real),
474        AccountSelection::Default => balances
475            .iter()
476            .find(|b| b.account_type == AccountType::Practice)
477            .or_else(|| balances.first()),
478    }
479    .cloned()?;
480    Some((
481        Session {
482            broker_name: "iq_option".into(),
483            connected_at: std::time::SystemTime::now()
484                .duration_since(std::time::UNIX_EPOCH)
485                .map(|d| d.as_secs() as i64)
486                .unwrap_or_default(),
487            account_id: perfil
488                .get("user_id")
489                .and_then(|u| u.as_i64())
490                .map(|u| u.to_string()),
491            balance_id: Some(elegido.id),
492            account_type: elegido.account_type,
493            server_time_offset_ms: 0,
494        },
495        balances,
496    ))
497}
498
499/// Parsea un `balance-changed` (mensaje `current_balance`).
500pub fn balance_desde_cambio(msg: &Value) -> Option<AccountBalance> {
501    let bal = msg.get("current_balance")?;
502    Some(AccountBalance {
503        id: bal.get("id").and_then(|i| i.as_i64())?,
504        currency: bal
505            .get("currency")
506            .and_then(|c| c.as_str())
507            .unwrap_or("USD")
508            .to_string(),
509        amount: bal.get("amount").and_then(|a| a.as_f64()).unwrap_or(0.0),
510        account_type: tipo_de_cuenta(bal.get("type").and_then(|t| t.as_i64()).unwrap_or(1)),
511        hold_amount: bal.get("hold_amount").and_then(|v| v.as_f64()),
512        bonus_amount: bal.get("bonus_amount").and_then(|v| v.as_f64()),
513        enrolled_amount: bal.get("enrolled_amount").and_then(|v| v.as_f64()),
514        has_deposits: bal.get("has_deposits").and_then(|v| v.as_bool()),
515    })
516}
517
518/// Vela viva de `candle-generated` (mensaje de tamaño único): campos en `msg`.
519pub fn vela_viva_unica(msg: &Value) -> Option<(u32, Candle)> {
520    let active_id = msg.get("active_id").and_then(|a| a.as_u64())? as u32;
521    let size = msg.get("size").and_then(|s| s.as_u64()).unwrap_or(0);
522    let precio = msg.get("value").and_then(|v| v.as_f64());
523    let mut candle = vela_desde_json_live(msg, precio)?;
524    if candle.volume.is_none() {
525        candle.volume = None;
526    }
527    candle.to = candle.from + size as i64;
528    Some((active_id, candle))
529}
530
531/// Vela de un mensaje vivo donde `close` puede faltar (vela en curso):
532/// se usa el precio actual del mensaje (`value`) como cierre.
533pub fn vela_desde_json_live(vela: &Value, precio_actual: Option<f64>) -> Option<Candle> {
534    Some(Candle {
535        from: vela.get("from")?.as_i64()?,
536        to: vela.get("to")?.as_i64()?,
537        open: vela.get("open")?.as_f64()?,
538        close: vela
539            .get("close")
540            .and_then(|c| c.as_f64())
541            .or(precio_actual)?,
542        high: vela.get("max")?.as_f64()?,
543        low: vela.get("min")?.as_f64()?,
544        volume: vela.get("volume").and_then(|x| x.as_f64()),
545    })
546}
547
548/// Velas vivas de `candles-generated` (multi-tamaño): `msg.candles` por tamaño.
549pub fn velas_vivas_multi(msg: &Value) -> Vec<(u64, Candle)> {
550    let mut salida = Vec::new();
551    let Some(actives) = msg.get("candles").and_then(|c| c.as_object()) else {
552        return salida;
553    };
554    let precio = msg.get("value").and_then(|v| v.as_f64()).or_else(|| {
555        let bid = msg.get("bid").and_then(|v| v.as_f64())?;
556        let ask = msg.get("ask").and_then(|v| v.as_f64())?;
557        Some((bid + ask) / 2.0)
558    });
559    for (size, vela) in actives {
560        if let Some(candle) = vela_desde_json_live(vela, precio) {
561            let size = size.parse::<u64>().unwrap_or(0);
562            salida.push((size, candle));
563        }
564    }
565    salida
566}
567
568/// Cierre de posición digital desde `position-changed` (`portfolio`).
569///
570/// El mensaje no trae `order_ids`: se correlaciona por `instrument_id` contra
571/// las órdenes digitales abiertas (las guarda la sesión al comprar).
572/// `close_reason = expired` trae `close_profit` = crédito TOTAL
573/// (neto = close_profit - invest); `default` trae `pnl_realized` ya neto.
574pub fn cierre_digital_desde_position(msg: &Value) -> Option<(String, OperationResult)> {
575    if msg.get("instrument_type").and_then(|t| t.as_str()) != Some("digital-option") {
576        return None;
577    }
578    let raw = msg.get("raw_event")?;
579    if raw.get("status").and_then(|s| s.as_str()) != Some("closed") {
580        return None;
581    }
582    let instrument_id = msg
583        .get("instrument_id")
584        .and_then(|i| i.as_str())?
585        .to_string();
586    let numero = |v: Option<&Value>| -> Option<f64> {
587        v.and_then(|x| {
588            x.as_f64()
589                .or_else(|| x.as_str().and_then(|s| s.parse::<f64>().ok()))
590        })
591    };
592    let reason = raw
593        .get("close_reason")
594        .and_then(|r| r.as_str())
595        .unwrap_or("expired");
596    let result = if reason == "expired" {
597        let close = numero(raw.get("close_profit").or_else(|| msg.get("close_profit")))?;
598        let invest = numero(
599            raw.get("invest")
600                .or_else(|| raw.get("buy_amount"))
601                .or_else(|| msg.get("invest")),
602        )?;
603        let diff = redondear_dinero(close - invest);
604        if diff > 0.0 {
605            OperationResult::Win(diff)
606        } else if diff == 0.0 {
607            OperationResult::Equal(invest)
608        } else {
609            OperationResult::Loss(-diff)
610        }
611    } else {
612        let pnl = numero(raw.get("pnl_realized").or_else(|| msg.get("pnl_realized")))?;
613        if pnl >= 0.0 {
614            OperationResult::Win(redondear_dinero(pnl))
615        } else {
616            OperationResult::Loss(redondear_dinero(-pnl))
617        }
618    };
619    Some((instrument_id, result))
620}
621/// Convierte un frame del stream en un evento de dominio cuando aplica./// Resultado desde `socket-option-closed`: `amount` va en micro-unidades (1e6);
622/// `sum` es el stake legible y `win_amount` el crédito total.
623pub fn resultado_desde_socket_cerrado(msg: &Value) -> Option<OperationResult> {
624    let win = msg.get("win").and_then(|w| w.as_str())?;
625    let stake = redondear_dinero(
626        msg.get("sum")
627            .and_then(|s| s.as_f64())
628            .or_else(|| {
629                msg.get("amount")
630                    .and_then(|a| a.as_f64())
631                    .map(|a| a / 1_000_000.0)
632            })
633            .unwrap_or(0.0),
634    );
635    let credito = redondear_dinero(
636        msg.get("win_amount")
637            .and_then(|w| w.as_f64())
638            .unwrap_or(0.0),
639    );
640    match win {
641        // Igual que `resultado_desde_cierre`: `win` sin crédito = mensaje
642        // incompleto; se descarta en lugar de inventar Win(0.0).
643        "win" | "won" => {
644            if credito > 0.0 {
645                Some(OperationResult::Win(redondear_dinero(credito - stake)))
646            } else {
647                None
648            }
649        }
650        "equal" => Some(OperationResult::Equal(stake)),
651        _ => Some(OperationResult::Loss(stake)),
652    }
653}
654
655/// `(asset_id, Payout)` desde `price-splitter.client-price-generated` (call).
656pub fn payout_price_splitter_con_id(msg: &Value) -> Option<(u32, Payout)> {
657    let asset_id = msg.get("asset_id").and_then(|a| a.as_u64())? as u32;
658    let payout = payout_price_splitter(msg, Direction::Call)?;
659    Some((asset_id, payout))
660}
661
662/// Tick de precio desde un mensaje de stream (`candles-generated` /
663/// `candle-generated`): el precio spot viaja en `value`/`bid`/`ask`, con `at`
664/// en NANOSEGUNDOS. Densidad medida en vivo: ~3 ticks/s por activo, sin límite
665/// de caudal por conexión (20 activos = 61 msg/s).
666pub fn tick_desde_frame(msg: &Value) -> Option<PriceTick> {
667    let price = msg.get("value").and_then(|v| v.as_f64())?;
668    let at_ns = msg.get("at").and_then(|a| a.as_i64()).unwrap_or(0);
669    Some(PriceTick {
670        price,
671        bid: msg.get("bid").and_then(|b| b.as_f64()),
672        ask: msg.get("ask").and_then(|a| a.as_f64()),
673        at_ms: at_ns / 1_000_000,
674    })
675}
676
677/// Interpreta la respuesta de `trading-signals.get-technical-indicators`.
678///
679/// Si el bróker soporta el activo devuelve Ok(indicadores) con el `indicators`
680/// del mensaje; si no, Err con el mensaje textual del bróker
681/// (observado: `Active is not supported: active id 'X'`, status 4150).
682pub fn indicadores_desde_respuesta(
683    msg: &Value,
684    symbol: &str,
685) -> Result<TechnicalIndicators, String> {
686    match msg.get("indicators") {
687        Some(indicadores) => Ok(TechnicalIndicators {
688            symbol: symbol.to_string(),
689            indicators: indicadores.clone(),
690        }),
691        None => Err(msg
692            .get("message")
693            .and_then(|m| m.as_str())
694            .unwrap_or("el bróker no devolvió indicadores")
695            .to_string()),
696    }
697}
698
699/// Live-deal (operación de un tercero) desde el canal del mismo nombre.
700/// Forma defensiva: el bróker no documenta el payload completo.
701pub fn live_deal_desde_frame(simbolo: &str, msg: &Value) -> Option<LiveDeal> {
702    let option_type = match msg.get("option_type").and_then(|t| t.as_str()) {
703        Some("digital-option") => OptionType::Digital,
704        _ => OptionType::Binary,
705    };
706    let direction = match msg.get("direction").and_then(|d| d.as_str()) {
707        Some("put") => Direction::Put,
708        _ => Direction::Call,
709    };
710    Some(LiveDeal {
711        symbol: simbolo.to_string(),
712        option_type,
713        direction,
714        amount: msg.get("amount").and_then(|a| a.as_f64()).unwrap_or(0.0),
715        created_at: msg
716            .get("created_at")
717            .and_then(|c| c.as_i64())
718            .unwrap_or_default(),
719        user_id: msg
720            .get("user_id")
721            .and_then(|u| u.as_i64())
722            .map(|u| u.to_string()),
723    })
724}
725
726/// Comisión cambiada desde el canal `commission-changed`.
727pub fn comision_desde_frame(simbolo: &str, msg: &Value) -> Option<CommissionChange> {
728    Some(CommissionChange {
729        symbol: simbolo.to_string(),
730        instrument_type: msg
731            .get("instrument_type")
732            .and_then(|t| t.as_str())
733            .unwrap_or_default()
734            .to_string(),
735        commission_value: msg.pointer("/commission/value").and_then(|c| c.as_f64()),
736    })
737}
738
739/// Query GraphQL del perfil de activo (verificada en vivo 2026-10-29). El
740/// esquema del bróker ya no acepta los fragmentos Stock/CryptoCurrency sobre
741/// `FinInfo`; esta versión mínima funciona para todo tipo de activo.
742pub const QUERY_ASSET_PROFILE: &str = "query GetAssetProfileInfo($activeId:ActiveID!, $locale: LocaleName){\n active(id: $activeId) {\n id\n name(source: TradeRoom, locale: $locale)\n ticker\n charts { dtd { change } m1 { change } y1 { change } ytd { change } }\n }\n }";
743
744/// Parsea la respuesta de `get-financial-information` (GraphQL).
745pub fn perfil_desde_financial(simbolo: &str, msg: &Value) -> Result<AssetProfile, String> {
746    let activo = msg
747        .pointer("/data/active")
748        .ok_or("sin data.active (ver errors del broker)")?;
749    let numero = |v: Option<&Value>| v.and_then(|x| x.as_f64());
750    Ok(AssetProfile {
751        symbol: simbolo.to_string(),
752        broker_name: activo
753            .get("name")
754            .and_then(|n| n.as_str())
755            .unwrap_or_default()
756            .to_string(),
757        ticker: activo
758            .get("ticker")
759            .and_then(|t| t.as_str())
760            .unwrap_or_default()
761            .to_string(),
762        change_dtd: numero(activo.pointer("/charts/dtd/change")),
763        change_m1: numero(activo.pointer("/charts/m1/change")),
764        change_y1: numero(activo.pointer("/charts/y1/change")),
765        change_ytd: numero(activo.pointer("/charts/ytd/change")),
766    })
767}
768
769/// Historial de posiciones desde `portfolio.get-history-positions`
770/// (`msg.positions[]`): posiciones cerradas con PnL realizado.
771pub fn historial_desde_positions(msg: &Value, offset: usize) -> Option<PositionHistory> {
772    let lista = msg.get("positions")?.as_array()?;
773    let numero = |v: Option<&Value>| v.and_then(|x| x.as_f64());
774    let posiciones: Vec<Position> = lista
775        .iter()
776        .map(|p| Position {
777            id: p
778                .get("external_id")
779                .or_else(|| p.get("id"))
780                .and_then(|i| i.as_i64())
781                .map(|i| i.to_string())
782                .unwrap_or_default(),
783            instrument_type: p
784                .get("instrument_type")
785                .and_then(|t| t.as_str())
786                .unwrap_or("digital-option")
787                .to_string(),
788            symbol: p
789                .get("active_name")
790                .and_then(|n| n.as_str())
791                .map(simbolo_desde_nombre)
792                .unwrap_or_default(),
793            side: match p.get("direction").and_then(|d| d.as_str()) {
794                Some("put") => Side::Sell,
795                _ => Side::Buy,
796            },
797            amount: p
798                .get("invest")
799                .and_then(|a| a.as_f64())
800                .or_else(|| numero(p.get("buy_amount")))
801                .unwrap_or(0.0),
802            open_price: p.get("open_quote").and_then(|q| q.as_f64()),
803            pnl: p
804                .get("close_profit")
805                .and_then(|c| c.as_f64())
806                .map(|c| c - p.get("invest").and_then(|i| i.as_f64()).unwrap_or(0.0)),
807            invested: p.get("invest").and_then(|i| i.as_f64()),
808            open_at: p
809                .get("open_time")
810                .and_then(|t| t.as_i64())
811                .unwrap_or_default(),
812            close_at: p.get("close_time").and_then(|t| t.as_i64()),
813            leverage: None,
814        })
815        .collect();
816    let total = msg
817        .get("total")
818        .and_then(|t| t.as_u64())
819        .map(|t| t as usize);
820    Some(PositionHistory {
821        positions: posiciones,
822        offset,
823        total,
824    })
825}
826
827/// Convierte un frame del stream en un evento de dominio cuando aplica.
828pub fn evento_desde_frame(frame: &WsFrame) -> Option<Event> {
829    match frame.name.as_str() {
830        super::endpoints::msg::TRADERS_MOOD_CHANGED => {
831            let symbol = frame
832                .msg
833                .get("asset_id")
834                .and_then(|a| a.as_i64())
835                .map(|id| id.to_string())?;
836            let call_percent = frame.msg.get("value").and_then(|v| v.as_f64())? * 100.0;
837            Some(Event::TradersMoodChanged {
838                symbol,
839                call_percent,
840            })
841        }
842        _ => None,
843    }
844}
845
846#[cfg(test)]
847mod tests {
848    use super::*;
849    use serde_json::json;
850
851    #[test]
852    fn quita_prefijo_front() {
853        assert_eq!(simbolo_desde_nombre("front.EURUSD"), "EURUSD");
854        assert_eq!(simbolo_desde_nombre("EURUSD"), "EURUSD");
855        assert_eq!(simbolo_desde_nombre("front.ETHUSD-OTC"), "ETHUSD-OTC");
856    }
857
858    #[test]
859    fn payout_desde_comision() {
860        assert_eq!(payout_de_comision(18.0), 82.0);
861        assert_eq!(payout_de_comision(14.0), 86.0);
862    }
863
864    #[test]
865    fn tipo_de_cuenta_desde_type() {
866        assert_eq!(tipo_de_cuenta(4), AccountType::Practice);
867        assert_eq!(tipo_de_cuenta(1), AccountType::Real);
868        // Un tipo no documentado nunca se degrada a `Real`.
869        assert_eq!(tipo_de_cuenta(7), AccountType::Unknown);
870        assert_eq!(tipo_de_cuenta(0), AccountType::Unknown);
871    }
872
873    #[test]
874    fn catalogo_parsea_tres_grupos() {
875        let init = json!({
876            "binary": { "actives": {
877                "76": { "name": "front.EURUSD-OTC", "enabled": true, "option": { "profit": { "commission": 12 } },
878                        "schedule": [[100, 200]], "minmax": {"min": 1, "max": 5000} } } },
879            "turbo": { "actives": {
880                "1": { "name": "front.XAUUSD", "enabled": true, "option": { "profit": { "commission": 30 } } } } },
881            "blitz": { "actives": {
882                "2250": { "name": "front.USDZAR-OTC", "enabled": true,
883                          "option": { "profit": { "commission": 13 }, "expiration_times": [30, 60] },
884                          "rollovers": [{"deadtime": 7, "limit": 5, "offset": 0, "offset_from_expiration": 30, "expiration_size": 30}],
885                          "minmax": {"min": 1, "max": 20000} } } }
886        });
887        let activos = catalogo_desde_init(&init);
888        assert_eq!(activos.len(), 3);
889        let eur = activos.iter().find(|a| a.symbol == "EURUSD-OTC").unwrap();
890        assert_eq!(eur.class, AssetClass::Binary);
891        assert_eq!(eur.opcode, 76);
892        assert!(eur.schedule.is_some());
893        let blitz = activos
894            .iter()
895            .find(|a| a.class == AssetClass::Blitz)
896            .unwrap();
897        let extras = blitz.extras.as_ref().unwrap();
898        assert_eq!(extras.expiration_times_secs, Some(vec![30, 60]));
899        assert!(extras.rollovers.is_some());
900        assert_eq!(extras.max_amount, Some(20000.0));
901    }
902
903    #[test]
904    fn catalogo_expone_sector_y_metadatos() {
905        // Payload real observado: groups + campos por activo que nadie leía.
906        let init = json!({
907            "groups": { "1": "front.forex", "16": "front.crypto currencies" },
908            "turbo": { "actives": {
909                "76": {
910                    "name": "front.EURUSD-OTC", "enabled": true, "group_id": "1",
911                    "provider": "OTC", "exchange": "front.exchange_eurusdotc",
912                    "start_time": 1406941845, "buyback_deadtime": 10, "deadtime": 30,
913                    "is_buyback": true, "top_traders_enabled": true, "precision": 6,
914                    "minimal_bet": 1, "maximal_bet": 20000,
915                    "option": { "profit": { "commission": 14 } }
916                }
917            } }
918        });
919        let activos = catalogo_desde_init(&init);
920        let eur = activos.iter().find(|a| a.symbol == "EURUSD-OTC").unwrap();
921        assert_eq!(eur.sector.as_deref(), Some("forex"));
922        let extras = eur.extras.as_ref().expect("extras");
923        assert_eq!(extras.provider.as_deref(), Some("OTC"));
924        assert_eq!(extras.buyback_deadtime, Some(10));
925        assert_eq!(extras.deadtime, Some(30));
926        assert_eq!(extras.is_buyback, Some(true));
927        assert_eq!(extras.start_time, Some(1406941845));
928        assert_eq!(extras.precision, Some(6));
929        assert_eq!(extras.maximal_bet, Some(20000.0));
930    }
931
932    #[test]
933    fn historial_desde_positions_calcula_pnl_neto() {
934        // Payload real observado (cuenta demo).
935        let msg = json!({
936            "positions": [{
937                "active_id": 1380, "active_name": "front.USDZAR-OTC",
938                "close_profit": 0, "close_reason": "expired",                 "close_time": 1793065260000i64,
939                "open_time": 1793065200000i64,
940                "external_id": 20328564504i64, "invest": 1, "instrument_type": "digital-option",
941                "open_quote": 16.5, "pnl": -1
942            }],
943            "total": 1
944        });
945        let h = historial_desde_positions(&msg, 0).unwrap();
946        assert_eq!(h.total, Some(1));
947        let p = &h.positions[0];
948        assert_eq!(p.id, "20328564504");
949        assert_eq!(p.symbol, "USDZAR-OTC");
950        assert_eq!(p.pnl, Some(-1.0));
951        assert_eq!(p.invested, Some(1.0));
952    }
953
954    #[test]
955    fn balances_con_campos_de_riesgo() {
956        let perfil = json!({ "balances": [{
957            "id": 5, "type": 4, "amount": 100.5, "currency": "USD",
958            "hold_amount": 3, "bonus_amount": 1.5, "enrolled_amount": 2,
959            "has_deposits": true
960        }] });
961        let b = balances_desde_perfil(&perfil);
962        assert_eq!(b[0].hold_amount, Some(3.0));
963        assert_eq!(b[0].bonus_amount, Some(1.5));
964        assert_eq!(b[0].enrolled_amount, Some(2.0));
965        assert_eq!(b[0].has_deposits, Some(true));
966    }
967
968    #[test]
969    fn live_deal_desde_frame_basico() {
970        // Forma defensiva: el bróker no documenta el payload completo.
971        let msg = json!({
972            "active_id": 76, "option_type": "binary-option",
973            "direction": "put", "amount": 25, "created_at": 1793416554, "user_id": 991
974        });
975        let deal = live_deal_desde_frame("EURUSD-OTC", &msg).unwrap();
976        assert_eq!(deal.symbol, "EURUSD-OTC");
977        assert_eq!(deal.option_type, OptionType::Binary);
978        assert_eq!(deal.direction, Direction::Put);
979        assert_eq!(deal.amount, 25.0);
980        assert_eq!(deal.user_id.as_deref(), Some("991"));
981    }
982
983    #[test]
984    fn comision_desde_frame_extrae_valor() {
985        // Forma verificada contra el bróker.
986        let msg = json!({
987            "instrument_type": "digital-option", "active_id": 76,
988            "commission": { "value": 13 }
989        });
990        let c = comision_desde_frame("EURUSD-OTC", &msg).unwrap();
991        assert_eq!(c.symbol, "EURUSD-OTC");
992        assert_eq!(c.instrument_type, "digital-option");
993        assert_eq!(c.commission_value, Some(13.0));
994    }
995
996    #[test]
997    fn sector_ausente_es_none() {
998        let init = json!({
999            "groups": { "1": "front.forex" },
1000            "turbo": { "actives": { "76": { "name": "front.X", "enabled": true, "group_id": "99" } } }
1001        });
1002        let activos = catalogo_desde_init(&init);
1003        assert!(activos[0].sector.is_none());
1004    }
1005
1006    #[test]
1007    fn vela_desde_json_parsea() {
1008        let v = json!({"from": 100, "to": 160, "open": 1.1, "close": 1.2, "max": 1.3, "min": 1.05, "volume": 7, "at": "1792927902000000000"});
1009        let c = vela_desde_json(&v).unwrap();
1010        assert_eq!(c.high, 1.3);
1011        assert_eq!(c.low, 1.05);
1012        assert_eq!(c.volume, Some(7.0));
1013        assert!(vela_desde_json(&json!({"from": 1})).is_none());
1014    }
1015
1016    #[test]
1017    fn cierre_de_vela_cerrada_redondea() {
1018        // 1792927907 → suelo(1792927907/60)*60 = 1792927860; -90 → 1792927770
1019        assert_eq!(cierre_de_vela_cerrada(1792927907, 60, 90), 1792927770);
1020    }
1021
1022    #[test]
1023    fn expiracion_blitz_alineada_redondea() {
1024        // 1793064502 con 30s → 1793064510 (múltiplo de 30 siguiente).
1025        assert_eq!(expiracion_blitz_alineada(1793064502, 30), 1793064510);
1026        // Ya alineado → salta al siguiente múltiplo.
1027        assert_eq!(expiracion_blitz_alineada(1793064510, 30), 1793064540);
1028        // 900s alinea a múltiplos de 900.
1029        assert_eq!(expiracion_blitz_alineada(1793064502, 900), 1793064600);
1030    }
1031
1032    #[test]
1033    fn tiempo_de_expiracion_redondea() {
1034        // 999_999_960 es múltiplo de 60; ahora = segundo 07 de ese minuto.
1035        // Margen >30 s → primer candidato turbo = minuto + 60 = 1_000_000_020.
1036        let (exp, idx) = tiempo_de_expiracion(999_999_967, 1);
1037        assert_eq!(exp, 1_000_000_020);
1038        assert!(idx < 5, "1 minuto cae en el bloque turbo");
1039        // 30 minutos busca cuarto de hora: índice >= 5.
1040        let (exp30, idx30) = tiempo_de_expiracion(999_999_967, 30);
1041        assert!(idx30 >= 5, "30 minuto cae en el bloque binary");
1042        assert!(exp30 > 999_999_967);
1043        // Segundo 55 del minuto: margen <= 30 → primer candidato = minuto + 120.
1044        let (exp55, _) = tiempo_de_expiracion(1_000_000_015, 1);
1045        assert_eq!(exp55, 1_000_000_080);
1046    }
1047
1048    #[test]
1049    fn indicadores_desde_respuesta_ok_y_error() {
1050        // Respuesta con indicadores (forma libre del bróker).
1051        let ok = json!({"indicators": [{"name": "SMA", "values": [1.0, 2.0]}]});
1052        let r = indicadores_desde_respuesta(&ok, "EURUSD").unwrap();
1053        assert_eq!(r.symbol, "EURUSD");
1054        assert_eq!(r.indicators, json!([{"name": "SMA", "values": [1.0, 2.0]}]));
1055
1056        // Respuesta real de rechazo (verificado en vivo 2026-10-27).
1057        let err = json!({"message": "Active is not supported: active id '1380'"});
1058        let e = indicadores_desde_respuesta(&err, "USDZAR-OTC").unwrap_err();
1059        assert!(
1060            e.contains("not supported"),
1061            "mensaje del bróker preservado: {e}"
1062        );
1063    }
1064
1065    #[test]
1066    fn win_sin_credito_no_es_cierre() {
1067        // Informe 2026-10-31: socket-option-closed de Blitz con win pero sin
1068        // win_amount: debe descartarse, no inventar Win(0.0).
1069        let opt = json!({ "result": "win", "amount": 1, "win_enrolled_amount": 0 });
1070        assert_eq!(resultado_desde_cierre(&opt), None);
1071        let sock = json!({ "win": "win", "amount": 1000000 });
1072        assert_eq!(resultado_desde_socket_cerrado(&sock), None);
1073    }
1074
1075    #[test]
1076    fn win_con_credito_funciona() {
1077        let opt = json!({ "result": "win", "amount": 1, "win_enrolled_amount": 1.83 });
1078        assert_eq!(
1079            resultado_desde_cierre(&opt),
1080            Some(OperationResult::Win(0.83))
1081        );
1082        let sock = json!({ "win": "win", "amount": 1000000, "sum": 1, "win_amount": 1.83 });
1083        assert_eq!(
1084            resultado_desde_socket_cerrado(&sock),
1085            Some(OperationResult::Win(0.83))
1086        );
1087    }
1088
1089    #[test]
1090    fn payout_percent_de_apertura_es_credito_total() {
1091        // Observación secundaria del informe: option-opened.profit_percent
1092        // llega como 183 (crédito total) para un payout de 83.
1093        let msg = json!({
1094            "option_id": 1, "direction": "call", "option_type": "blitz",
1095            "amount": 1, "profit_percent": 183, "open_time": 1793416554
1096        });
1097        let op = operacion_desde_apertura(&msg).unwrap();
1098        assert_eq!(op.payout_percent, Some(83.0));
1099    }
1100
1101    #[test]
1102    fn tick_desde_frame_extrae_precio() {
1103        // Payload real: `at` en nanosegundos, precio en `value`.
1104        let msg = json!({
1105            "active_id": 1380, "at": 1793067441904000000i64, "value": 16.599655,
1106            "bid": 16.599515, "ask": 16.599895, "phase": "T"
1107        });
1108        let tick = tick_desde_frame(&msg).unwrap();
1109        assert_eq!(tick.price, 16.599655);
1110        assert_eq!(tick.at_ms, 1793067441904);
1111        assert_eq!(tick.ask, Some(16.599895));
1112        assert!(tick_desde_frame(&json!({"active_id": 1})).is_none());
1113    }
1114
1115    #[test]
1116    fn velas_vivas_multi_sin_close_usa_value() {
1117        // Payload real observado: las entas en curso no traen `close`.
1118        let msg = json!({
1119            "active_id": 1380,
1120            "bid": 16.5781,
1121            "ask": 16.5783,
1122            "value": 16.5782,
1123            "phase": "T",
1124            "candles": {
1125                "1": {"from": 1792927915, "id": 193276907, "max": 16.578285, "min": 16.578095,
1126                      "open": 16.578285, "phase": "T", "to": 1792927916, "volume": 0},
1127                "60": {"from": 1792927860, "id": 1611212, "max": 16.582745, "min": 16.577935,
1128                       "open": 16.581445, "phase": "T", "to": 1792927920, "volume": 0}
1129            }
1130        });
1131        let velas = velas_vivas_multi(&msg);
1132        assert_eq!(velas.len(), 2);
1133        let (size_1, vela_1) = velas.iter().find(|(s, _)| *s == 1).unwrap();
1134        assert_eq!(*size_1, 1);
1135        assert_eq!(vela_1.close, 16.5782);
1136        assert!(vela_1.is_consistent());
1137    }
1138
1139    #[test]
1140    fn perfil_desde_financial_graphql() {
1141        // Respuesta real verificada en vivo (query mínima sin fragmentos).
1142        let msg = json!({ "data": { "active": {
1143            "id": 1, "name": "EUR/USD", "ticker": "EURUSD",
1144            "charts": {
1145                "dtd": { "change": -0.1598 }, "m1": { "change": -1.9 },
1146                "y1": { "change": -3.97 }, "ytd": { "change": -4.97 }
1147            }
1148        } } });
1149        let p = perfil_desde_financial("EURUSD", &msg).unwrap();
1150        assert_eq!(p.broker_name, "EUR/USD");
1151        assert_eq!(p.ticker, "EURUSD");
1152        assert_eq!(p.change_dtd, Some(-0.1598));
1153        assert_eq!(p.change_ytd, Some(-4.97));
1154    }
1155
1156    #[test]
1157    fn perfil_sin_data_es_error() {
1158        let msg = json!({ "data": null, "errors": [{"message": "x"}] });
1159        assert!(perfil_desde_financial("EURUSD", &msg).is_err());
1160    }
1161
1162    #[test]
1163    fn cierre_por_venta_anticipada() {
1164        // Venta anticipada: `result: "default"` con el crédito en profit_amount.
1165        let msg = json!({
1166            "result": "default", "amount": 1,
1167            "profit_amount": 0.83, "win_enrolled_amount": 0.83
1168        });
1169        assert_eq!(
1170            resultado_desde_cierre(&msg),
1171            Some(OperationResult::Loss(0.17))
1172        );
1173        // Venta con ganancia.
1174        let msg2 = json!({ "result": "default", "amount": 1, "profit_amount": 1.2 });
1175        assert_eq!(
1176            resultado_desde_cierre(&msg2),
1177            Some(OperationResult::Win(0.2))
1178        );
1179    }
1180
1181    #[test]
1182    fn resultado_neto_desde_cierre() {
1183        // Evidencia real: crédito 1.85, stake 1 → neto 0.85
1184        let msg = json!({"result": "win", "amount": 1, "win_enrolled_amount": 1.85});
1185        let r = resultado_desde_cierre(&msg).unwrap();
1186        assert_eq!(r, OperationResult::Win(0.85));
1187        let msg2 = json!({"result": "loose", "amount": 1});
1188        assert_eq!(
1189            resultado_desde_cierre(&msg2),
1190            Some(OperationResult::Loss(1.0))
1191        );
1192        let msg3 = json!({"result": "equal", "amount": 1});
1193        assert_eq!(
1194            resultado_desde_cierre(&msg3),
1195            Some(OperationResult::Equal(1.0))
1196        );
1197    }
1198}