Skip to main content

cripsy_binary_api/broker/deriv/
protocol.rs

1//! Traducción entre el JSON de Deriv y el dominio del crate.
2//!
3//! Reglas: nada de datos inventados. Lo que Deriv no publica (volumen de
4//! velas, `opcode`, id numérico de balance) queda ausente o documentado como
5//! sustituto explícito.
6
7use serde_json::Value;
8
9use crate::domain::{
10    Asset, AssetClass, AssetExtras, Candle, Direction, MarketStatus, OperationResult, OrderId,
11    Position, PositionHistory, Side,
12};
13
14/// Cuenta numérica estable a partir del id de cuenta de Deriv.
15///
16/// Deriv identifica cuentas con cadenas (`CR…`, `VRTC…`); el dominio usa `i64`.
17/// Hasta que el contrato admita cadenas (0.3.x), este valor es un **sustituto
18/// determinista**, no un identificador del bróker.
19pub fn id_surrogado(account_id: &str) -> i64 {
20    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
21    for byte in account_id.as_bytes() {
22        hash ^= u64::from(*byte);
23        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
24    }
25    (hash & 0x7fff_ffff_ffff_ffff) as i64
26}
27
28/// Clase de activo a partir de `market`/`underlying_symbol_type`.
29pub fn clase_de(market: &str, tipo: &str) -> AssetClass {
30    let m = market.to_ascii_lowercase();
31    let t = tipo.to_ascii_lowercase();
32    if m.contains("synthetic") || t.contains("stockindex") {
33        AssetClass::Index
34    } else if m.contains("forex") || t.contains("forex") {
35        AssetClass::Forex
36    } else if m.contains("crypto") || t.contains("crypto") {
37        AssetClass::Crypto
38    } else if m.contains("commodit") || t.contains("commodit") || m.contains("metal") {
39        AssetClass::Commodity
40    } else if m.contains("index") || m.contains("indices") {
41        AssetClass::Index
42    } else {
43        AssetClass::Cfd
44    }
45}
46
47fn estado(v: &Value) -> MarketStatus {
48    if v.get("is_trading_suspended").and_then(Value::as_u64) == Some(1) {
49        MarketStatus::Suspended
50    } else if v.get("exchange_is_open").and_then(Value::as_u64) == Some(1) {
51        MarketStatus::Open
52    } else {
53        MarketStatus::Closed
54    }
55}
56
57fn precision(pip: f64) -> Option<u32> {
58    if pip > 0.0 && pip < 1.0 {
59        Some((-pip.log10()).round() as u32)
60    } else if pip >= 1.0 {
61        Some(0)
62    } else {
63        None
64    }
65}
66
67/// Activos desde una respuesta `active_symbols`.
68pub fn activos(valor: &Value) -> Vec<Asset> {
69    let Some(lista) = valor.get("active_symbols").and_then(Value::as_array) else {
70        return Vec::new();
71    };
72    lista
73        .iter()
74        .filter_map(|v| {
75            let symbol = v.get("underlying_symbol")?.as_str()?.to_string();
76            let name = v
77                .get("underlying_symbol_name")
78                .and_then(Value::as_str)
79                .unwrap_or(&symbol)
80                .to_string();
81            let market = v.get("market").and_then(Value::as_str).unwrap_or("");
82            let tipo = v
83                .get("underlying_symbol_type")
84                .and_then(Value::as_str)
85                .unwrap_or("");
86            let pip = v.get("pip_size").and_then(Value::as_f64);
87            Some(Asset {
88                symbol,
89                name,
90                class: clase_de(market, tipo),
91                // Deriv no publica identificador numérico: 0 documentado.
92                opcode: 0,
93                status: estado(v),
94                payout_percent: None,
95                sector: v
96                    .get("submarket")
97                    .and_then(Value::as_str)
98                    .map(str::to_string),
99                schedule: None,
100                extras: Some(AssetExtras {
101                    precision: pip.and_then(precision),
102                    provider: v
103                        .get("subgroup")
104                        .and_then(Value::as_str)
105                        .map(str::to_string),
106                    ..AssetExtras::default()
107                }),
108            })
109        })
110        .collect()
111}
112
113/// Velas desde una respuesta `candles`.
114pub fn velas(valor: &Value, intervalo: u64) -> Vec<Candle> {
115    let Some(lista) = valor.get("candles").and_then(Value::as_array) else {
116        return Vec::new();
117    };
118    lista
119        .iter()
120        .filter_map(|v| {
121            let from = v.get("epoch").and_then(Value::as_i64)?;
122            Some(Candle {
123                from,
124                to: from + intervalo as i64,
125                open: v.get("open").and_then(Value::as_f64)?,
126                close: v.get("close").and_then(Value::as_f64)?,
127                high: v.get("high").and_then(Value::as_f64)?,
128                low: v.get("low").and_then(Value::as_f64)?,
129                // Deriv no publica volumen en el histórico de velas.
130                volume: None,
131            })
132        })
133        .collect()
134}
135
136/// Vela individual de un mensaje `ohlc`.
137pub fn vela_ohlc(valor: &Value, intervalo: u64) -> Option<Candle> {
138    let v = valor.get("ohlc")?;
139    let from = v.get("open_time")?.as_i64()?;
140    Some(Candle {
141        from,
142        to: from + intervalo as i64,
143        open: v.get("open")?.as_f64()?,
144        close: v.get("close")?.as_f64()?,
145        high: v.get("high")?.as_f64()?,
146        low: v.get("low")?.as_f64()?,
147        volume: None,
148    })
149}
150
151/// `(importe, divisa, id de cuenta)` desde una respuesta `balance`.
152pub fn balance(valor: &Value) -> Option<(f64, String, String)> {
153    let b = valor.get("balance")?;
154    Some((
155        b.get("balance")?.as_f64()?,
156        b.get("currency")?.as_str()?.to_string(),
157        b.get("loginid")
158            .and_then(Value::as_str)
159            .unwrap_or_default()
160            .to_string(),
161    ))
162}
163
164/// Porcentaje de payout a partir de una propuesta.
165///
166/// Deriv cotiza por importe: `profit_percent` depende del stake, no es un dato
167/// de catálogo.
168pub fn payout_porcentaje(propuesta: &Value, stake: f64) -> Option<f64> {
169    let payout = propuesta.get("proposal")?.get("payout")?.as_f64()?;
170    if stake <= 0.0 {
171        return None;
172    }
173    Some((payout / stake - 1.0) * 100.0)
174}
175
176fn direccion_de(contract_type: &str) -> Direction {
177    if contract_type.eq_ignore_ascii_case("PUT") {
178        Direction::Put
179    } else {
180        Direction::Call
181    }
182}
183
184/// Posiciones desde `profit_table` (cierres) o `portfolio` (abiertas).
185///
186/// La forma exacta de `profit_table` está pendiente de verificación en vivo:
187/// el parser acepta `profit_table.transactions` y `transactions`.
188pub fn posiciones(valor: &Value, offset: usize) -> PositionHistory {
189    let lista = valor
190        .get("profit_table")
191        .and_then(|p| p.get("transactions"))
192        .or_else(|| valor.get("transactions"))
193        .and_then(Value::as_array)
194        .cloned()
195        .unwrap_or_default();
196
197    let posiciones: Vec<Position> = lista
198        .iter()
199        .filter_map(|v| {
200            let id = v
201                .get("contract_id")
202                .and_then(|x| x.as_i64().map(|n| n.to_string()))
203                .or_else(|| {
204                    v.get("contract_id")
205                        .and_then(Value::as_str)
206                        .map(str::to_string)
207                })?;
208            let contrato = v
209                .get("contract_type")
210                .and_then(Value::as_str)
211                .unwrap_or("CALL");
212            let symbol = v
213                .get("underlying_symbol")
214                .or_else(|| v.get("symbol"))
215                .and_then(Value::as_str)
216                .unwrap_or("")
217                .to_string();
218            let compra = v.get("buy_price").and_then(num);
219            let venta = v.get("sell_price").and_then(num);
220            // `profit_table` no publica `profit`: el resultado se deriva de la
221            // venta y la compra, y queda marcado como dato derivado.
222            let derivado = match (compra, venta) {
223                (Some(c), Some(s)) => Some(s - c),
224                _ => None,
225            };
226            let pnl = v.get("profit").and_then(num).or(derivado);
227            let inicio = v
228                .get("purchase_time")
229                .or_else(|| v.get("date_start"))
230                .and_then(Value::as_i64)
231                .unwrap_or(0);
232            let fin = v
233                .get("sell_time")
234                .or_else(|| v.get("date_settlement"))
235                .and_then(Value::as_i64);
236            Some(Position {
237                id,
238                instrument_type: contrato.to_string(),
239                symbol,
240                side: direccion_de(contrato).into(),
241                amount: compra.unwrap_or(0.0),
242                open_price: v
243                    .get("entry_spot")
244                    .and_then(|s| s.as_str().and_then(|x| x.parse().ok())),
245                pnl,
246                invested: compra,
247                open_at: inicio,
248                close_at: fin,
249                leverage: None,
250            })
251        })
252        .collect();
253
254    PositionHistory {
255        positions: posiciones,
256        offset,
257        // `profit_table.count` es el tamaño de la página, no el total.
258        total: None,
259    }
260}
261
262/// Número que puede venir como JSON numérico o como cadena.
263fn num(v: &Value) -> Option<f64> {
264    v.as_f64()
265        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
266}
267
268impl From<Direction> for Side {
269    fn from(d: Direction) -> Self {
270        match d {
271            Direction::Call => Side::Buy,
272            Direction::Put => Side::Sell,
273        }
274    }
275}
276
277/// Resultado terminal de un `proposal_open_contract`.
278pub fn resultado_contrato(valor: &Value) -> Option<(OrderId, OperationResult)> {
279    let poc = valor.get("proposal_open_contract")?;
280    let id = poc
281        .get("contract_id")?
282        .to_string()
283        .trim_matches('"')
284        .to_string();
285    let status = poc.get("status").and_then(Value::as_str).unwrap_or("");
286    let profit = poc.get("profit").and_then(|p| {
287        p.as_f64()
288            .or_else(|| p.as_str().and_then(|s| s.parse::<f64>().ok()))
289    });
290    let resultado = match status {
291        "won" => OperationResult::Win(profit.unwrap_or_default()),
292        "lost" => OperationResult::Loss(profit.map(f64::abs).unwrap_or_default()),
293        "sold" => match profit.unwrap_or_default() {
294            p if p > 0.0 => OperationResult::Win(p),
295            p if p < 0.0 => OperationResult::Loss(p.abs()),
296            _ => OperationResult::Equal(0.0),
297        },
298        "cancelled" => return None,
299        _ => return None,
300    };
301    Some((id, resultado))
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use serde_json::json;
308
309    #[test]
310    fn id_surrogado_es_estable_y_positivo() {
311        let a = id_surrogado("VRTC123456");
312        assert_eq!(a, id_surrogado("VRTC123456"));
313        assert!(a > 0);
314        assert_ne!(a, id_surrogado("VRTC654321"));
315    }
316
317    #[test]
318    fn mapea_activos_reales() {
319        let v = json!({"active_symbols":[{
320            "underlying_symbol":"R_100","underlying_symbol_name":"Volatility 100 Index",
321            "market":"synthetic_index","underlying_symbol_type":"stockindex",
322            "pip_size":0.01,"exchange_is_open":1,"is_trading_suspended":0,
323            "submarket":"random_index","subgroup":"synthetics"}]});
324        let lista = activos(&v);
325        assert_eq!(lista.len(), 1);
326        assert_eq!(lista[0].symbol, "R_100");
327        assert_eq!(lista[0].class, AssetClass::Index);
328        assert_eq!(lista[0].status, MarketStatus::Open);
329        assert_eq!(lista[0].extras.as_ref().unwrap().precision, Some(2));
330    }
331
332    #[test]
333    fn mapea_velas_sin_volumen() {
334        let v = json!({"candles":[{"epoch":100,"open":1.0,"high":1.3,"low":0.9,"close":1.2}]});
335        let c = velas(&v, 60);
336        assert_eq!(c.len(), 1);
337        assert_eq!(c[0].to, 160);
338        assert!(c[0].volume.is_none());
339        assert!(c[0].is_consistent());
340    }
341
342    #[test]
343    fn resultado_por_estado() {
344        let ganada =
345            json!({"proposal_open_contract":{"contract_id":1,"status":"won","profit":0.95}});
346        assert_eq!(
347            resultado_contrato(&ganada),
348            Some(("1".into(), OperationResult::Win(0.95)))
349        );
350        let perdida =
351            json!({"proposal_open_contract":{"contract_id":2,"status":"lost","profit":-1.0}});
352        assert_eq!(
353            resultado_contrato(&perdida),
354            Some(("2".into(), OperationResult::Loss(1.0)))
355        );
356        let abierta = json!({"proposal_open_contract":{"contract_id":3,"status":"open"}});
357        assert!(resultado_contrato(&abierta).is_none());
358    }
359
360    #[test]
361    fn payout_es_porcentaje_del_stake() {
362        let v = json!({"proposal":{"payout":1.95}});
363        assert!((payout_porcentaje(&v, 1.0).unwrap() - 95.0).abs() < 1e-9);
364        assert!((payout_porcentaje(&v, 2.0).unwrap() - (-2.5)).abs() < 1e-9);
365    }
366}