digdigdig3 0.3.16

Unified async Rust API for 47 exchange connectors (REST + WebSocket). The core layer — pure ExchangeHub + connectors. Higher-level builder, persistence, replay, OB tracker live in `digdigdig3-station`.
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
//! # MEXC Endpoints
//!
//! URL structures and endpoint enum for MEXC Spot API.

use crate::core::types::{AccountType, Symbol};

// ═══════════════════════════════════════════════════════════════════════════════
// URLs
// ═══════════════════════════════════════════════════════════════════════════════

/// URL endpoints for MEXC API
pub struct MexcUrls;

impl MexcUrls {
    /// Get REST API base URL for spot trading
    pub fn base_url() -> &'static str {
        "https://api.mexc.com"
    }

    /// Get REST API base URL for futures trading
    pub fn futures_base_url() -> &'static str {
        "https://contract.mexc.com"
    }

    /// Get WebSocket URL for spot trading
    ///
    /// # Note
    /// The old endpoint `wss://wbs.mexc.com/ws` was deprecated in August 2025.
    /// New endpoint supports both JSON and Protobuf formats.
    pub fn ws_url() -> &'static str {
        "wss://wbs-api.mexc.com/ws"
    }

    /// Get WebSocket URL for futures trading
    pub fn futures_ws_url() -> &'static str {
        "wss://contract.mexc.com/edge"
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ENDPOINTS
// ═══════════════════════════════════════════════════════════════════════════════

/// MEXC API endpoints (Spot + Futures)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MexcEndpoint {
    // === SPOT MARKET DATA ===
    Ping,             // GET /api/v3/ping
    ServerTime,       // GET /api/v3/time
    ExchangeInfo,     // GET /api/v3/exchangeInfo
    Orderbook,        // GET /api/v3/depth
    RecentTrades,     // GET /api/v3/trades
    Klines,           // GET /api/v3/klines
    Ticker24hr,       // GET /api/v3/ticker/24hr
    TickerPrice,      // GET /api/v3/ticker/price
    BookTicker,       // GET /api/v3/ticker/bookTicker
    AvgPrice,         // GET /api/v3/avgPrice

    // === SPOT ACCOUNT ===
    Account,          // GET /api/v3/account
    MyTrades,         // GET /api/v3/myTrades
    TradeFee,         // GET /api/v3/tradeFee

    // === SPOT TRADING ===
    PlaceOrder,       // POST /api/v3/order
    TestOrder,        // POST /api/v3/order/test
    CancelOrder,      // DELETE /api/v3/order
    CancelAllOrders,  // DELETE /api/v3/openOrders
    QueryOrder,       // GET /api/v3/order
    OpenOrders,       // GET /api/v3/openOrders
    AllOrders,        // GET /api/v3/allOrders

    // === BATCH ORDERS ===
    BatchOrders,          // POST /api/v3/batchOrders

    // === BATCH ORDERS ===
    BatchOrdersCancel,    // DELETE /api/v3/batchOrders (unused placeholder)

    // === TRANSFERS ===
    Transfer,                  // POST /api/v3/capital/transfer
    TransferHistory,           // GET  /api/v3/capital/transfer

    // === CUSTODIAL FUNDS ===
    DepositAddress,            // GET  /api/v3/capital/deposit/address
    Withdraw,                  // POST /api/v3/capital/withdraw
    DepositHistory,            // GET  /api/v3/capital/deposit/hisrec
    WithdrawHistory,           // GET  /api/v3/capital/withdraw/history

    // === SUB ACCOUNTS ===
    SubAccountCreate,          // POST /api/v3/sub-account/virtualSubAccount
    SubAccountList,            // GET  /api/v3/sub-account/list
    SubAccountTransfer,        // POST /api/v3/capital/sub-account/universalTransfer
    SubAccountAssets,          // GET  /api/v3/sub-account/assets

    // === FUTURES MARKET DATA ===
    FuturesPing,          // GET /api/v1/contract/ping
    FuturesTicker,        // GET /api/v1/contract/ticker
    FuturesOrderbook,     // GET /api/v1/contract/depth/{symbol}
    FuturesKlines,        // GET /api/v1/contract/kline/{symbol}
    FuturesRecentTrades,  // GET /api/v1/contract/deals/{symbol}
    FuturesContractInfo,  // GET /api/v1/contract/detail

    // === EXTENDED ENDPOINTS ===
    /// GET /api/v1/contract/index_price/{symbol} — index and mark price
    FuturesMarkPrice,
    /// GET /api/v1/contract/funding_rate/{symbol} — current funding rate
    /// TODO: verify exact path against live MEXC contract API
    FuturesFundingRate,
    /// GET /api/v1/contract/open_interest/{symbol} — open interest for a contract
    /// TODO: verify exact path against live MEXC contract API
    FuturesOpenInterest,

    // === DERIVED KLINE ENDPOINTS (contract API) ===
    /// GET /api/v1/contract/kline/fair_price/{symbol} — mark/fair price klines
    /// Params: interval, start (Unix seconds), end (Unix seconds)
    /// Max 2000 per request. vol/amount always 0.0.
    FuturesFairPriceKlines,
    /// GET /api/v1/contract/kline/index_price/{symbol} — index price klines
    /// Same params and limits as FuturesFairPriceKlines.
    FuturesIndexPriceKlines,
    /// GET /api/v1/contract/funding_rate/history — historical funding rates
    /// Params: symbol, page_num (default 1), page_size (default 20, max 1000)
    /// No date filter — pagination only.
    FuturesFundingRateHistory,
}

impl MexcEndpoint {
    /// Get endpoint path (without symbol parameter for futures)
    pub fn path(&self) -> &'static str {
        match self {
            // Spot Market Data
            Self::Ping => "/api/v3/ping",
            Self::ServerTime => "/api/v3/time",
            Self::ExchangeInfo => "/api/v3/exchangeInfo",
            Self::Orderbook => "/api/v3/depth",
            Self::RecentTrades => "/api/v3/trades",
            Self::Klines => "/api/v3/klines",
            Self::Ticker24hr => "/api/v3/ticker/24hr",
            Self::TickerPrice => "/api/v3/ticker/price",
            Self::BookTicker => "/api/v3/ticker/bookTicker",
            Self::AvgPrice => "/api/v3/avgPrice",

            // Spot Account
            Self::Account => "/api/v3/account",
            Self::MyTrades => "/api/v3/myTrades",
            Self::TradeFee => "/api/v3/tradeFee",

            // Spot Trading
            Self::PlaceOrder => "/api/v3/order",
            Self::TestOrder => "/api/v3/order/test",
            Self::CancelOrder => "/api/v3/order",
            Self::CancelAllOrders => "/api/v3/openOrders",
            Self::QueryOrder => "/api/v3/order",
            Self::OpenOrders => "/api/v3/openOrders",
            Self::AllOrders => "/api/v3/allOrders",
            Self::BatchOrders => "/api/v3/batchOrders",
            Self::BatchOrdersCancel => "/api/v3/batchOrders",

            // Transfers
            Self::Transfer => "/api/v3/capital/transfer",
            Self::TransferHistory => "/api/v3/capital/transfer",

            // Custodial Funds
            Self::DepositAddress => "/api/v3/capital/deposit/address",
            Self::Withdraw => "/api/v3/capital/withdraw",
            Self::DepositHistory => "/api/v3/capital/deposit/hisrec",
            Self::WithdrawHistory => "/api/v3/capital/withdraw/history",

            // Sub Accounts
            Self::SubAccountCreate => "/api/v3/sub-account/virtualSubAccount",
            Self::SubAccountList => "/api/v3/sub-account/list",
            Self::SubAccountTransfer => "/api/v3/capital/sub-account/universalTransfer",
            Self::SubAccountAssets => "/api/v3/sub-account/assets",

            // Futures Market Data
            Self::FuturesPing => "/api/v1/contract/ping",
            Self::FuturesTicker => "/api/v1/contract/ticker",
            Self::FuturesOrderbook => "/api/v1/contract/depth", // Symbol added as path param
            Self::FuturesKlines => "/api/v1/contract/kline",     // Symbol added as path param
            Self::FuturesRecentTrades => "/api/v1/contract/deals", // Symbol added as path param
            Self::FuturesContractInfo => "/api/v1/contract/detail",

            // Extended endpoints
            Self::FuturesMarkPrice => "/api/v1/contract/index_price", // Append /{symbol}
            Self::FuturesFundingRate => "/api/v1/contract/funding_rate", // Append /{symbol}
            Self::FuturesOpenInterest => "/api/v1/contract/open_interest", // Append /{symbol}

            // Derived kline endpoints
            Self::FuturesFairPriceKlines => "/api/v1/contract/kline/fair_price", // Append /{symbol}
            Self::FuturesIndexPriceKlines => "/api/v1/contract/kline/index_price", // Append /{symbol}
            Self::FuturesFundingRateHistory => "/api/v1/contract/funding_rate/history",
        }
    }

    /// Get HTTP method for endpoint
    pub fn method(&self) -> &'static str {
        match self {
            // POST requests
            Self::PlaceOrder
            | Self::TestOrder
            | Self::BatchOrders
            | Self::Transfer
            | Self::Withdraw
            | Self::SubAccountCreate
            | Self::SubAccountTransfer => "POST",

            // DELETE requests
            Self::CancelOrder
            | Self::CancelAllOrders
            | Self::BatchOrdersCancel => "DELETE",

            // GET requests (default)
            _ => "GET",
        }
    }

    /// Check if endpoint requires authentication
    pub fn is_private(&self) -> bool {
        match self {
            // Public spot endpoints
            Self::Ping
            | Self::ServerTime
            | Self::ExchangeInfo
            | Self::Orderbook
            | Self::RecentTrades
            | Self::Klines
            | Self::Ticker24hr
            | Self::TickerPrice
            | Self::BookTicker
            | Self::AvgPrice
            // Public futures endpoints
            | Self::FuturesPing
            | Self::FuturesTicker
            | Self::FuturesOrderbook
            | Self::FuturesKlines
            | Self::FuturesRecentTrades
            | Self::FuturesContractInfo
            | Self::FuturesMarkPrice
            | Self::FuturesFundingRate
            | Self::FuturesOpenInterest
            | Self::FuturesFairPriceKlines
            | Self::FuturesIndexPriceKlines
            | Self::FuturesFundingRateHistory => false,

            // Private endpoints
            _ => true,
        }
    }

    /// Check if endpoint is for futures
    pub fn is_futures(&self) -> bool {
        matches!(
            self,
            Self::FuturesPing
            | Self::FuturesTicker
            | Self::FuturesOrderbook
            | Self::FuturesKlines
            | Self::FuturesRecentTrades
            | Self::FuturesContractInfo
            | Self::FuturesMarkPrice
            | Self::FuturesFundingRate
            | Self::FuturesOpenInterest
            | Self::FuturesFairPriceKlines
            | Self::FuturesIndexPriceKlines
            | Self::FuturesFundingRateHistory
        )
    }

    /// Check if endpoint is a transfer/funds/subaccount endpoint (always spot base URL)
    pub fn is_capital(&self) -> bool {
        matches!(
            self,
            Self::Transfer
            | Self::TransferHistory
            | Self::DepositAddress
            | Self::Withdraw
            | Self::DepositHistory
            | Self::WithdrawHistory
            | Self::SubAccountCreate
            | Self::SubAccountList
            | Self::SubAccountTransfer
            | Self::SubAccountAssets
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SYMBOL FORMATTING
// ═══════════════════════════════════════════════════════════════════════════════

/// Format symbol for MEXC API
///
/// # Format
/// - Spot: `BTCUSDT` (no separator)
/// - Futures: `BTC_USDT` (underscore separator)
///
/// # Examples
/// ```
/// use connectors_v5::exchanges::mexc::format_symbol;
/// use connectors_v5::core::types::{Symbol, AccountType};
///
/// let symbol = Symbol::new("BTC", "USDT");
/// assert_eq!(format_symbol(&symbol, AccountType::Spot), "BTCUSDT");
/// ```
pub fn format_symbol(symbol: &Symbol, account_type: AccountType) -> String {
    match account_type {
        AccountType::Spot | AccountType::Margin => {
            // Spot: concatenated without separator
            format!("{}{}", symbol.base.to_uppercase(), symbol.quote.to_uppercase())
        },
        AccountType::FuturesCross | AccountType::FuturesIsolated => {
            // Futures: underscore separator
            format!("{}_{}", symbol.base.to_uppercase(), symbol.quote.to_uppercase())
        },
        _ => {
            // Unsupported account types default to spot format
            format!("{}{}", symbol.base.to_uppercase(), symbol.quote.to_uppercase())
        },
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WEBSOCKET CHANNEL NAMES (Protobuf format)
// ═══════════════════════════════════════════════════════════════════════════════

/// WebSocket channel helpers for MEXC's protobuf-based WS API.
///
/// Since August 2025, MEXC WebSocket uses protobuf encoding exclusively.
/// All channel names must include the `.pb` suffix.
pub struct MexcWsChannels;

impl MexcWsChannels {
    /// Mini ticker for a single symbol (protobuf).
    /// Example: `spot@public.miniTicker.v3.api.pb@BTCUSDT@UTC+0`
    pub fn mini_ticker(symbol: &str) -> String {
        format!("spot@public.miniTicker.v3.api.pb@{}@UTC+0", symbol)
    }

    /// Aggregated deals (trades) for a symbol (protobuf, 100ms batching).
    /// Example: `spot@public.aggre.deals.v3.api.pb@100ms@BTCUSDT`
    pub fn aggre_deals(symbol: &str) -> String {
        format!("spot@public.aggre.deals.v3.api.pb@100ms@{}", symbol)
    }

    /// Aggregated depth for a symbol (protobuf, 100ms batching).
    /// Example: `spot@public.aggre.depth.v3.api.pb@100ms@BTCUSDT`
    pub fn aggre_depth(symbol: &str) -> String {
        format!("spot@public.aggre.depth.v3.api.pb@100ms@{}", symbol)
    }

    /// Limit depth (orderbook snapshot) for a symbol (protobuf).
    /// Example: `spot@public.limit.depth.v3.api.pb@BTCUSDT@5`
    pub fn limit_depth(symbol: &str, levels: u32) -> String {
        format!("spot@public.limit.depth.v3.api.pb@{}@{}", symbol, levels)
    }

    /// Kline/candlestick for a symbol (protobuf).
    /// Example: `spot@public.kline.v3.api.pb@BTCUSDT@1m`
    pub fn kline(symbol: &str, interval: &str) -> String {
        format!("spot@public.kline.v3.api.pb@{}@{}", symbol, interval)
    }

    /// Book ticker for a single symbol (protobuf).
    /// Example: `spot@public.bookTicker.v3.api.pb@BTCUSDT`
    pub fn book_ticker(symbol: &str) -> String {
        format!("spot@public.bookTicker.v3.api.pb@{}", symbol)
    }

    /// Futures funding rate channel name (informational).
    ///
    /// Subscription to this channel must be sent on `wss://contract.mexc.com/edge`
    /// (JSON frames), NOT on the spot protobuf endpoint. Use `MexcWebSocket::start_futures_ws()`.
    ///
    /// Subscription message format:
    /// `{"method":"sub.funding.rate","param":{"symbol":"<symbol>"}}`
    ///
    /// Push event channel: `push.funding.rate`
    pub fn futures_funding_rate(_symbol: &str) -> &'static str {
        "push.funding.rate"
    }

    // MEXC does not publish a public liquidation stream — confirmed in API docs.
}

/// Map kline interval to MEXC format
///
/// # MEXC Interval Format
/// - Minutes: `1m`, `5m`, `15m`, `30m`, `60m`
/// - Hours: `4h`, `8h`
/// - Day: `1d`
/// - Week: `1w`
/// - Month: `1M`
///
/// # Examples
/// ```
/// use connectors_v5::exchanges::mexc::map_kline_interval;
///
/// assert_eq!(map_kline_interval("1m"), "1m");
/// assert_eq!(map_kline_interval("1h"), "60m");
/// assert_eq!(map_kline_interval("1d"), "1d");
/// ```
pub fn map_kline_interval(interval: &str) -> &'static str {
    match interval {
        "1m" => "1m",
        "5m" => "5m",
        "15m" => "15m",
        "30m" => "30m",
        "1h" => "60m",
        "4h" => "4h",
        "8h" => "8h",
        "1d" => "1d",
        "1w" => "1w",
        "1M" => "1M",
        _ => "1h", // default to 1 hour
    }
}