cripsy_binary_api/broker/trait_.rs
1//! Trait `Broker`: interfaz común async (object-safe vía `async_trait`).
2
3use async_trait::async_trait;
4use futures_core::Stream;
5
6use crate::domain::{
7 AccountType, Asset, AssetProfile, Balance, BuyBinaryRequest, BuyBlitzRequest,
8 BuyDigitalRequest, Candle, CandleRequest, CandleSubscribe, Event, MarketStatus,
9 OperationResult, OptionType, OrderId, Payout, PositionHistory, TechnicalIndicators,
10};
11
12use super::config::BrokerParams;
13use super::error::BrokerError;
14use super::session::Session;
15
16/// Stream async de velas.
17pub type CandleStream = std::pin::Pin<Box<dyn Stream<Item = Result<Candle, BrokerError>> + Send>>;
18
19/// Stream async de eventos del ciclo de vida.
20pub type EventStream = std::pin::Pin<Box<dyn Stream<Item = Event> + Send>>;
21
22/// Contrato que todo adaptador de bróker cumple.
23///
24/// Diseño type-erased a propósito: sin associated types para que
25/// `Box<dyn Broker>` y `MultiBroker` compilen (ver `docs/01_introduccion.es.md`).
26#[async_trait]
27pub trait Broker: Send + Sync {
28 /// Nombre estable del adaptador, p. ej. `iq_option`.
29 fn name(&self) -> &'static str;
30
31 /// Constructor de la sesión: autentica y deja el bróker operativo.
32 async fn connect(params: BrokerParams) -> Result<Self, BrokerError>
33 where
34 Self: Sized;
35
36 async fn disconnect(&mut self) -> Result<(), BrokerError>;
37 async fn is_connected(&self) -> bool;
38
39 /// Metadatos de la sesión activa (copia: la sesión se actualiza en caliente).
40 async fn session(&self) -> Result<Session, BrokerError>;
41
42 // -------- Cuenta y balance --------
43
44 async fn get_balance(&self) -> Result<Balance, BrokerError>;
45 async fn get_account_type(&self) -> Result<AccountType, BrokerError>;
46 async fn switch_account(&mut self, kind: AccountType) -> Result<(), BrokerError>;
47
48 // -------- Activos y mercado --------
49
50 async fn list_assets(&self) -> Result<Vec<Asset>, BrokerError>;
51 async fn asset_status(&self, symbol: &str) -> Result<MarketStatus, BrokerError>;
52
53 // -------- Velas --------
54
55 async fn get_candles(&self, req: CandleRequest) -> Result<Vec<Candle>, BrokerError>;
56 async fn subscribe_candles(&self, req: CandleSubscribe) -> Result<CandleStream, BrokerError>;
57
58 /// Historial de posiciones cerradas (cartera): para analítica de cuenta.
59 /// `limit` ≤ 100 por página, `offset` para paginar.
60 async fn get_position_history(
61 &self,
62 symbol: Option<&str>,
63 limit: usize,
64 offset: usize,
65 ) -> Result<PositionHistory, BrokerError>;
66
67 // -------- Payout --------
68
69 /// Payout **publicado en el catálogo** para el activo.
70 ///
71 /// `expiration_seconds` se devuelve en el resultado pero no altera la
72 /// consulta: no se pide una cotización por expiración ni por strike. Los
73 /// cambios en vivo llegan por `Event::PayoutChanged`.
74 async fn get_payout(
75 &self,
76 symbol: &str,
77 expiration_seconds: u64,
78 ) -> Result<Payout, BrokerError>;
79
80 // -------- Indicadores técnicos del bróker --------
81
82 /// Indicadores técnicos que el bróker envía para un activo (`trading-signals`).
83 /// No calcula nada: transporta lo que el bróker entregue; si no soporta el
84 /// activo devuelve `BrokerError::Rejected` con el mensaje del bróker.
85 async fn get_technical_indicators(
86 &self,
87 symbol: &str,
88 ) -> Result<TechnicalIndicators, BrokerError>;
89
90 /// Perfil fundamental del activo (nombre del bróker, ticker y variaciones
91 /// dtd/m1/y1/ytd) vía el endpoint GraphQL del bróker.
92 async fn get_asset_profile(&self, symbol: &str) -> Result<AssetProfile, BrokerError>;
93
94 /// Suscribe el stream de operaciones de terceros (`live-deal`) para un
95 /// activo. Los deals llegan por `Event::LiveDeal`.
96 async fn subscribe_live_deals(&self, symbol: &str) -> Result<(), BrokerError>;
97
98 /// Suscribe los cambios de comisión por tipo de instrumento. Llegan por
99 /// `Event::CommissionChanged`.
100 async fn subscribe_commission_changes(&self) -> Result<(), BrokerError>;
101
102 // -------- Órdenes --------
103
104 /// Compra clásica (turbo o binary según la duración).
105 ///
106 /// BLITZ tiene su propia petición: [`Broker::buy_blitz`].
107 async fn buy_binary(&self, req: BuyBinaryRequest) -> Result<OrderId, BrokerError>;
108
109 /// Compra BLITZ: duración en segundos y payout explícito (protocolo v2).
110 async fn buy_blitz(&self, req: BuyBlitzRequest) -> Result<OrderId, BrokerError>;
111
112 /// Compra digital spot: el bróker elige el strike a precio actual.
113 async fn buy_digital_spot(&self, req: BuyDigitalRequest) -> Result<OrderId, BrokerError>;
114
115 /// Venta anticipada (buyback) de una orden abierta. El bróker la admite
116 /// dentro de la ventana `buyback_deadtime` del activo; si la orden ya no
117 /// es vendible responde con su mensaje de rechazo.
118 async fn sell_option(&self, order_id: &OrderId) -> Result<(), BrokerError>;
119
120 /// Resultado leído de la caché local (alimentada por `events()`).
121 ///
122 /// No consulta al bróker: devuelve `OperationResult::Pending` mientras el
123 /// cierre no haya llegado por eventos.
124 async fn get_operation_result(
125 &self,
126 order_id: &OrderId,
127 ) -> Result<OperationResult, BrokerError>;
128
129 // -------- Eventos --------
130
131 /// Stream de eventos (cierres, balances, payouts en vivo, velas suscritas).
132 async fn events(&self) -> Result<EventStream, BrokerError>;
133}
134
135/// Marcador de compilación: el trait es `Send + Sync` por contrato.
136const fn _assert_broker_bounds<T: Broker + Send + Sync>() {}
137
138/// Tipo de opción por defecto del MVP.
139pub const MVP_OPTION_TYPES: &[OptionType] = &[OptionType::Binary, OptionType::Digital];