digdigdig3 0.1.29

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! # MOEX ISS Connector Implementation
//!
//! Implementation of core traits for MOEX Moscow Exchange ISS API.

use async_trait::async_trait;
use reqwest::Client;
use std::collections::HashMap;

use crate::core::types::{
    AccountType, Balance, ExchangeError, ExchangeId, ExchangeResult, Kline, Order, OrderBook,
    Position, Price, Symbol, Ticker, AccountInfo, FundingRate, SymbolInfo,
    OrderRequest, CancelRequest, OrderHistoryFilter, PlaceOrderResponse, FeeInfo,
    BalanceQuery, PositionQuery, PositionModification,
    MarketDataCapabilities, TradingCapabilities, AccountCapabilities,
};
use crate::core::traits::{ExchangeIdentity, MarketData, Trading, Account, Positions};

use super::endpoints::{MoexEndpoint, MoexEndpoints, format_symbol, map_interval, default_stock_params};
use super::auth::MoexAuth;
use super::parser::MoexParser;

// ═══════════════════════════════════════════════════════════════════════════════
// MOEX CONNECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// MOEX ISS connector
///
/// This connector provides access to Moscow Exchange market data via the ISS API.
/// It is a **data-only provider** and does not support trading operations.
pub struct MoexConnector {
    client: Client,
    auth: MoexAuth,
    endpoints: MoexEndpoints,
}

impl MoexConnector {
    /// Create new MOEX connector with authentication
    pub fn new(auth: MoexAuth) -> Self {
        Self {
            client: Client::new(),
            auth,
            endpoints: MoexEndpoints::default(),
        }
    }

    /// Create public MOEX connector (no authentication, 15-min delay)
    pub fn new_public() -> Self {
        Self::new(MoexAuth::public())
    }

    /// Create connector from environment variables
    pub fn from_env() -> Self {
        Self::new(MoexAuth::from_env())
    }

    /// Internal: Make GET request
    async fn get(
        &self,
        endpoint: MoexEndpoint,
        path_params: &[(&str, &str)],
        query_params: HashMap<String, String>,
    ) -> ExchangeResult<serde_json::Value> {
        let path = endpoint.build_path(path_params);
        let url = format!("{}{}", self.endpoints.rest_base, path);

        // Add authentication headers
        let mut headers = HashMap::new();
        self.auth.sign_headers(&mut headers);

        // Build request
        let mut request = self.client.get(&url);

        // Add headers
        for (key, value) in headers {
            request = request.header(key, value);
        }

        // Add query params
        if !query_params.is_empty() {
            request = request.query(&query_params);
        }

        // Send request
        let response = request
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        // Check status
        let status = response.status();
        if !status.is_success() {
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: format!("HTTP {}", status),
            });
        }

        // Parse JSON
        response
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: ExchangeIdentity
// ═══════════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for MoexConnector {
    fn exchange_name(&self) -> &'static str {
        "MOEX"
    }

    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::Moex
    }

    fn is_testnet(&self) -> bool {
        false
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        // MOEX ISS is data-only, but conceptually supports these markets
        vec![AccountType::Spot] // Can be extended for futures data
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: MarketData
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl MarketData for MoexConnector {
    /// Get current price
    async fn get_price(
        &self,
        symbol: Symbol,
        _account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let (engine, market, board) = default_stock_params();
        let security = format_symbol(&symbol);

        let path_params = &[
            ("engine", engine),
            ("market", market),
            ("board", board),
            ("security", &security),
        ];

        let response = self
            .get(MoexEndpoint::BoardSecurityData, path_params, HashMap::new())
            .await?;

        MoexParser::parse_price(&response)
            .map_err(ExchangeError::Parse)
    }

    /// Get orderbook
    ///
    /// Note: Requires paid subscription for real-time orderbook data
    async fn get_orderbook(
        &self,
        symbol: Symbol,
        _depth: Option<u16>,
        _account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        let (engine, market, _board) = default_stock_params();
        let security = format_symbol(&symbol);

        let path_params = &[
            ("engine", engine),
            ("market", market),
            ("security", &security),
        ];

        let response = self
            .get(MoexEndpoint::SecurityOrderbook, path_params, HashMap::new())
            .await?;

        MoexParser::parse_orderbook(&response)
            .map_err(ExchangeError::Parse)
    }

    /// Get klines/candles
    async fn get_klines(
        &self,
        symbol: Symbol,
        interval: &str,
        limit: Option<u16>,
        _account_type: AccountType,
        _end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let (engine, market, board) = default_stock_params();
        let security = format_symbol(&symbol);
        let moex_interval = map_interval(interval);

        let path_params = &[
            ("engine", engine),
            ("market", market),
            ("board", board),
            ("security", &security),
        ];

        let mut query_params = HashMap::new();
        query_params.insert("interval".to_string(), moex_interval.to_string());

        // MOEX requires 'from' parameter for candles
        // Default to last 7 days if not specified
        let from_date = chrono::Utc::now() - chrono::Duration::days(7);
        query_params.insert("from".to_string(), from_date.format("%Y-%m-%d").to_string());

        if let Some(lim) = limit {
            // MOEX doesn't have explicit limit, but we can use 'till' to control range
            // For simplicity, just note the limitation
            query_params.insert("limit".to_string(), lim.to_string());
        }

        let response = self
            .get(MoexEndpoint::BoardCandles, path_params, query_params)
            .await?;

        MoexParser::parse_klines(&response)
            .map_err(ExchangeError::Parse)
    }

    /// Get 24h ticker
    async fn get_ticker(
        &self,
        symbol: Symbol,
        _account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let (engine, market, board) = default_stock_params();
        let security = format_symbol(&symbol);

        let path_params = &[
            ("engine", engine),
            ("market", market),
            ("board", board),
            ("security", &security),
        ];

        let response = self
            .get(MoexEndpoint::BoardSecurityData, path_params, HashMap::new())
            .await?;

        MoexParser::parse_ticker(&response, &security)
            .map_err(ExchangeError::Parse)
    }

    /// Ping server
    async fn ping(&self) -> ExchangeResult<()> {
        // MOEX doesn't have a dedicated ping endpoint
        // Use lightweight engines endpoint instead
        self.get(MoexEndpoint::Engines, &[], HashMap::new())
            .await
            .map(|_| ())
    }

    fn market_data_capabilities(&self, _account_type: AccountType) -> MarketDataCapabilities {
        MarketDataCapabilities {
            has_ping: true,
            has_price: true,
            has_ticker: true,
            // Orderbook endpoint exists but requires a paid real-time subscription.
            // The REST snapshot is available for authenticated users; we mark it true
            // since the connector implements the call and returns data when authorized.
            has_orderbook: true,
            has_klines: true,
            has_exchange_info: true,
            // SecurityTrades endpoint exists in the API but the MarketData trait
            // method get_recent_trades is not implemented for this connector.
            has_recent_trades: false,
            // MOEX ISS candle intervals (integer-minute codes via map_interval):
            // 1 min, 10 min, 1 hour, 1 day, 1 week, 1 month, 1 quarter.
            supported_intervals: &["1m", "10m", "1h", "1d", "1w", "1M", "1Q"],
            // MOEX candles endpoint uses date ranges instead of a count limit.
            // No numeric per-request limit is enforced by the API.
            max_kline_limit: None,
            // MOEX STOMP WebSocket supports kline (candle) streaming
            has_ws_klines: true,
            // MOEX STOMP WebSocket supports trade streaming
            has_ws_trades: true,
            // MOEX STOMP WebSocket supports orderbook streaming
            has_ws_orderbook: true,
            // MOEX STOMP WebSocket supports ticker streaming
            has_ws_ticker: true,
        }
    }

    /// Get exchange info — returns listed securities from MOEX
    ///
    /// Delegates to the same MarketSecurities endpoint used by `get_symbols()`
    /// which reliably returns all actively-trading instruments on the stock/shares market.
    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        let (engine, market, _) = default_stock_params();

        let path_params = &[
            ("engine", engine),
            ("market", market),
        ];

        let response = self
            .get(MoexEndpoint::MarketSecurities, path_params, HashMap::new())
            .await?;

        let symbols = MoexParser::parse_symbols(&response)
            .map_err(ExchangeError::Parse)?;

        let infos = symbols.into_iter().map(|sec_id| SymbolInfo {
            symbol: sec_id.clone(),
            base_asset: sec_id,
            quote_asset: "RUB".to_string(),
            status: "TRADING".to_string(),
            price_precision: 2,
            quantity_precision: 0,
            min_quantity: Some(1.0),
            max_quantity: None,
            tick_size: None,
            step_size: Some(1.0),
            min_notional: None,
            account_type,
        }).collect();

        Ok(infos)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Trading (UnsupportedOperation - MOEX ISS is data-only)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Trading for MoexConnector {
    async fn place_order(&self, _req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - trading not supported. Use MOEX WebAPI for trading.".to_string()
        ))
    }

    async fn cancel_order(&self, _req: CancelRequest) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - trading not supported. Use MOEX WebAPI for trading.".to_string()
        ))
    }

    async fn get_order(
        &self,
        _symbol: &str,
        _order_id: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - trading not supported. Use MOEX WebAPI for trading.".to_string()
        ))
    }

    async fn get_open_orders(
        &self,
        _symbol: Option<&str>,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - trading not supported. Use MOEX WebAPI for trading.".to_string()
        ))
    }

    async fn get_order_history(
        &self,
        _filter: OrderHistoryFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - trading not supported. Use MOEX WebAPI for trading.".to_string()
        ))
    }

    fn trading_capabilities(&self, _account_type: AccountType) -> TradingCapabilities {
        TradingCapabilities::none()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Account (UnsupportedOperation - MOEX ISS is data-only)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for MoexConnector {
    async fn get_balance(&self, _query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - account operations not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    
    }

    async fn get_account_info(&self, _account_type: AccountType) -> ExchangeResult<AccountInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - account operations not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    }

    async fn get_fees(&self, _symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - account operations not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    }

    fn account_capabilities(&self, _account_type: AccountType) -> AccountCapabilities {
        AccountCapabilities::none()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRAIT: Positions (UnsupportedOperation - MOEX ISS is data-only)
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Positions for MoexConnector {
    async fn get_positions(&self, _query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - position tracking not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    }

    async fn get_funding_rate(
        &self,
        _symbol: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - position tracking not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    }

    async fn modify_position(&self, _req: PositionModification) -> ExchangeResult<()> {
        Err(ExchangeError::UnsupportedOperation(
            "MOEX ISS is a data provider - position tracking not supported. Use MOEX WebAPI or broker API.".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXTENDED METHODS (MOEX-specific, not from traits)
// ═══════════════════════════════════════════════════════════════════════════════

impl MoexConnector {
    /// Get list of all symbols/securities
    pub async fn get_symbols(&self) -> ExchangeResult<Vec<String>> {
        let (engine, market, _) = default_stock_params();

        let path_params = &[
            ("engine", engine),
            ("market", market),
        ];

        let response = self
            .get(MoexEndpoint::MarketSecurities, path_params, HashMap::new())
            .await?;

        MoexParser::parse_symbols(&response)
            .map_err(ExchangeError::Parse)
    }

    /// Get list of all trading engines
    pub async fn get_engines(&self) -> ExchangeResult<serde_json::Value> {
        self.get(MoexEndpoint::Engines, &[], HashMap::new())
            .await
    }

    /// Get markets for a specific engine
    pub async fn get_markets(&self, engine: &str) -> ExchangeResult<serde_json::Value> {
        let path_params = &[("engine", engine)];
        self.get(MoexEndpoint::EngineMarkets, path_params, HashMap::new())
            .await
    }

    /// Get security information
    pub async fn get_security_info(&self, security: &str) -> ExchangeResult<serde_json::Value> {
        let path_params = &[("security", security)];
        self.get(MoexEndpoint::SecurityInfo, path_params, HashMap::new())
            .await
    }

    /// Get market turnovers
    pub async fn get_turnovers(&self) -> ExchangeResult<serde_json::Value> {
        self.get(MoexEndpoint::Turnovers, &[], HashMap::new())
            .await
    }

    /// Check if connector has real-time access
    pub fn has_realtime_access(&self) -> bool {
        self.auth.is_authenticated()
    }
}