digdigdig3 0.1.19

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
//! # Bitget Endpoints
//!
//! URL'ы и endpoint enum для Bitget API.

use crate::core::types::AccountType;

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

/// URL'ы для Bitget API
#[derive(Debug, Clone)]
pub struct BitgetUrls {
    pub spot_rest: &'static str,
    pub futures_rest: &'static str,
    pub ws_public: &'static str,
    pub ws_private: &'static str,
}

impl BitgetUrls {
    /// Production URLs
    pub const MAINNET: Self = Self {
        spot_rest: "https://api.bitget.com",
        futures_rest: "https://api.bitget.com",
        ws_public: "wss://ws.bitget.com/v2/ws/public",
        ws_private: "wss://ws.bitget.com/v2/ws/private",
    };

    /// Demo / paper-trading URLs.
    ///
    /// Bitget demo trading ("simulated trading") uses the same REST base URLs
    /// as mainnet.  Authenticated REST requests must include the header
    /// `X-CHANNEL-API-CODE: paptrading`.  WebSocket connections use the
    /// dedicated `wspap.bitget.com` domain.
    pub const TESTNET: Self = Self {
        spot_rest: "https://api.bitget.com",
        futures_rest: "https://api.bitget.com",
        ws_public: "wss://wspap.bitget.com/v2/ws/public",
        ws_private: "wss://wspap.bitget.com/v2/ws/private",
    };

    /// Получить REST base URL для account type
    pub fn rest_url(&self, account_type: AccountType) -> &str {
        match account_type {
            AccountType::Spot | AccountType::Margin => self.spot_rest,
            AccountType::FuturesCross | AccountType::FuturesIsolated => self.futures_rest,
            _ => self.spot_rest,
        }
    }

    /// Получить WebSocket public URL
    pub fn ws_public_url(&self) -> String {
        self.ws_public.to_string()
    }

    /// Получить WebSocket private URL
    pub fn ws_private_url(&self) -> String {
        self.ws_private.to_string()
    }
}

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

/// Bitget API endpoints
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BitgetEndpoint {
    // === ОБЩИЕ ===
    Timestamp,

    // === SPOT MARKET DATA ===
    SpotPrice,
    SpotOrderbook,
    SpotKlines,
    SpotTicker,
    SpotAllTickers,
    SpotSymbols,

    // === SPOT TRADING ===
    SpotCreateOrder,
    SpotCancelOrder,
    SpotGetOrder,
    SpotOpenOrders,
    SpotAllOrders,

    // === SPOT ACCOUNT ===
    SpotAccounts,
    SpotAccountInfo,

    // === FUTURES MARKET DATA ===
    FuturesPrice,
    FuturesOrderbook,
    FuturesKlines,
    FuturesTicker,
    FuturesAllTickers,
    FuturesContracts,
    FundingRate,

    // === FUTURES TRADING ===
    FuturesCreateOrder,
    FuturesCancelOrder,
    FuturesGetOrder,
    FuturesOpenOrders,
    FuturesAllOrders,
    FuturesBatchPlaceOrders,
    FuturesBatchCancelOrders,
    FuturesCancelBySymbol,
    FuturesClosePositions,
    FuturesModifyOrder,
    FuturesPlanOrder,
    FuturesPosTpSl,

    // === FUTURES ACCOUNT ===
    FuturesAccount,
    FuturesAllAccounts,
    FuturesPositions,
    FuturesPosition,
    FuturesSetLeverage,
    FuturesSetMarginMode,
    FuturesSetMargin,

    // === FUTURES ALGO ===
    /// TWAP algorithmic order — `POST /api/v2/mix/order/place-twap-order`
    FuturesTwapOrder,

    // === SPOT EXTRA ===
    SpotBatchPlaceOrders,
    SpotBatchCancelOrders,
    SpotCancelBySymbol,
    SpotModifyOrder,
    SpotFills,

    // === COMMON ===
    TradeRate,
    VipFeeRate,

    // === TRANSFERS ===
    Transfer,                    // POST /api/v2/spot/wallet/transfer
    TransferHistory,             // GET  /api/v2/spot/account/transferRecords

    // === CUSTODIAL FUNDS ===
    DepositAddress,              // GET  /api/v2/spot/wallet/deposit-address
    Withdraw,                    // POST /api/v2/spot/wallet/withdrawal
    DepositHistory,              // GET  /api/v2/spot/wallet/deposit-records
    WithdrawHistory,             // GET  /api/v2/spot/wallet/withdrawal-records

    // === SUB ACCOUNTS ===
    SubAccountCreate,            // POST /api/v2/user/create-virtual-subaccount
    SubAccountList,              // GET  /api/v2/user/virtual-subaccount-list
    SubAccountTransfer,          // POST /api/v2/user/virtual-subaccount-transfer
    SubAccountAssets,            // GET  /api/v2/user/virtual-subaccount-assets

    // === EXTENDED ENDPOINTS ===
    /// GET /api/v2/spot/market/fills — recent public spot fills
    SpotRecentFills,
    /// GET /api/v2/spot/market/history-candles — historical candles beyond the standard window
    SpotHistoryCandles,
    /// GET /api/v2/mix/order/fill-history — futures fill/trade history (signed)
    FuturesFillHistory,
    /// GET /api/v2/mix/market/open-interest — futures open interest
    FuturesOpenInterest,
    /// GET /api/v2/mix/market/history-fund-rate — futures historical funding rates
    FuturesFundingRateHistory,
    /// GET /api/v2/mix/market/symbol-price — futures mark/index price
    FuturesSymbolPrice,
    /// GET /api/v2/spot/account/bills — spot account bill/ledger records
    SpotBills,
}

impl BitgetEndpoint {
    /// Получить путь endpoint'а (V2 API)
    pub fn path(&self) -> &'static str {
        match self {
            // Общие
            Self::Timestamp => "/api/v2/public/time",

            // Spot Market Data
            Self::SpotPrice => "/api/v2/spot/market/tickers",
            Self::SpotOrderbook => "/api/v2/spot/market/orderbook",
            Self::SpotKlines => "/api/v2/spot/market/candles",
            Self::SpotTicker => "/api/v2/spot/market/tickers",
            Self::SpotAllTickers => "/api/v2/spot/market/tickers",
            Self::SpotSymbols => "/api/v2/spot/public/symbols",

            // Spot Trading
            Self::SpotCreateOrder => "/api/v2/spot/trade/place-order",
            Self::SpotCancelOrder => "/api/v2/spot/trade/cancel-order",
            Self::SpotGetOrder => "/api/v2/spot/trade/orderInfo",
            Self::SpotOpenOrders => "/api/v2/spot/trade/unfilled-orders",
            Self::SpotAllOrders => "/api/v2/spot/trade/history-orders",

            // Spot Account
            Self::SpotAccounts => "/api/v2/spot/account/assets",
            Self::SpotAccountInfo => "/api/v2/spot/account/info",

            // Futures Market Data
            Self::FuturesPrice => "/api/v2/mix/market/ticker",
            Self::FuturesOrderbook => "/api/v2/mix/market/merge-depth",
            Self::FuturesKlines => "/api/v2/mix/market/candles",
            Self::FuturesTicker => "/api/v2/mix/market/ticker",
            Self::FuturesAllTickers => "/api/v2/mix/market/tickers",
            Self::FuturesContracts => "/api/v2/mix/market/contracts",
            Self::FundingRate => "/api/v2/mix/market/current-fund-rate",

            // Futures Trading
            Self::FuturesCreateOrder => "/api/v2/mix/order/place-order",
            Self::FuturesCancelOrder => "/api/v2/mix/order/cancel-order",
            Self::FuturesGetOrder => "/api/v2/mix/order/detail",
            Self::FuturesOpenOrders => "/api/v2/mix/order/orders-pending",
            Self::FuturesAllOrders => "/api/v2/mix/order/orders-history",
            Self::FuturesBatchPlaceOrders => "/api/v2/mix/order/batch-place-order",
            Self::FuturesBatchCancelOrders => "/api/v2/mix/order/batch-cancel-orders",
            Self::FuturesCancelBySymbol => "/api/v2/mix/order/cancel-all-orders",
            Self::FuturesClosePositions => "/api/v2/mix/order/close-positions",
            Self::FuturesModifyOrder => "/api/v2/mix/order/modify-order",
            Self::FuturesPlanOrder => "/api/v2/mix/order/place-plan-order",
            Self::FuturesPosTpSl => "/api/v2/mix/order/place-tpsl-order",

            // Futures Account
            Self::FuturesAccount => "/api/v2/mix/account/account",
            Self::FuturesAllAccounts => "/api/v2/mix/account/accounts",
            Self::FuturesPositions => "/api/v2/mix/position/all-position",
            Self::FuturesPosition => "/api/v2/mix/position/single-position",
            Self::FuturesSetLeverage => "/api/v2/mix/account/set-leverage",
            Self::FuturesSetMarginMode => "/api/v2/mix/account/set-margin-mode",
            Self::FuturesSetMargin => "/api/v2/mix/account/set-margin",

            // Futures Algo
            Self::FuturesTwapOrder => "/api/v2/mix/order/place-twap-order",

            // Spot Extra
            Self::SpotBatchPlaceOrders => "/api/v2/spot/trade/batch-orders",
            Self::SpotBatchCancelOrders => "/api/v2/spot/trade/batch-cancel-order",
            Self::SpotCancelBySymbol => "/api/v2/spot/trade/cancel-symbol-orders",
            Self::SpotModifyOrder => "/api/v2/spot/trade/modify-order",
            Self::SpotFills => "/api/v2/spot/trade/fills",

            // Common
            Self::TradeRate => "/api/v2/common/trade-rate",
            Self::VipFeeRate => "/api/v2/spot/market/vip-fee-rate",

            // Transfers
            Self::Transfer => "/api/v2/spot/wallet/transfer",
            Self::TransferHistory => "/api/v2/spot/account/transferRecords",

            // Custodial Funds
            Self::DepositAddress => "/api/v2/spot/wallet/deposit-address",
            Self::Withdraw => "/api/v2/spot/wallet/withdrawal",
            Self::DepositHistory => "/api/v2/spot/wallet/deposit-records",
            Self::WithdrawHistory => "/api/v2/spot/wallet/withdrawal-records",

            // Sub Accounts
            Self::SubAccountCreate => "/api/v2/user/create-virtual-subaccount",
            Self::SubAccountList => "/api/v2/user/virtual-subaccount-list",
            Self::SubAccountTransfer => "/api/v2/user/virtual-subaccount-transfer",
            Self::SubAccountAssets => "/api/v2/user/virtual-subaccount-assets",

            // Extended endpoints
            Self::SpotRecentFills => "/api/v2/spot/market/fills",
            Self::SpotHistoryCandles => "/api/v2/spot/market/history-candles",
            Self::FuturesFillHistory => "/api/v2/mix/order/fill-history",
            Self::FuturesOpenInterest => "/api/v2/mix/market/open-interest",
            Self::FuturesFundingRateHistory => "/api/v2/mix/market/history-fund-rate",
            Self::FuturesSymbolPrice => "/api/v2/mix/market/symbol-price",
            Self::SpotBills => "/api/v2/spot/account/bills",
        }
    }

    /// Требует ли endpoint авторизации
    pub fn requires_auth(&self) -> bool {
        match self {
            // Public endpoints
            Self::Timestamp
            | Self::SpotPrice
            | Self::SpotOrderbook
            | Self::SpotKlines
            | Self::SpotTicker
            | Self::SpotAllTickers
            | Self::SpotSymbols
            | Self::FuturesPrice
            | Self::FuturesOrderbook
            | Self::FuturesKlines
            | Self::FuturesTicker
            | Self::FuturesAllTickers
            | Self::FuturesContracts
            | Self::FundingRate
            | Self::SpotRecentFills
            | Self::SpotHistoryCandles
            | Self::FuturesOpenInterest
            | Self::FuturesFundingRateHistory
            | Self::FuturesSymbolPrice => false,

            // Private endpoints
            _ => true,
        }
    }

    /// HTTP метод для endpoint'а
    pub fn method(&self) -> &'static str {
        match self {
            Self::SpotCreateOrder
            | Self::SpotCancelOrder
            | Self::SpotBatchPlaceOrders
            | Self::SpotBatchCancelOrders
            | Self::SpotCancelBySymbol
            | Self::SpotModifyOrder
            | Self::FuturesCreateOrder
            | Self::FuturesCancelOrder
            | Self::FuturesBatchPlaceOrders
            | Self::FuturesBatchCancelOrders
            | Self::FuturesCancelBySymbol
            | Self::FuturesClosePositions
            | Self::FuturesModifyOrder
            | Self::FuturesPlanOrder
            | Self::FuturesPosTpSl
            | Self::FuturesTwapOrder
            | Self::FuturesSetLeverage
            | Self::FuturesSetMarginMode
            | Self::FuturesSetMargin
            | Self::Transfer
            | Self::Withdraw
            | Self::SubAccountCreate
            | Self::SubAccountTransfer => "POST",

            _ => "GET",
        }
    }
}

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

/// Форматирование символа для Bitget V2 API
///
/// # V2 Symbol Format (SIMPLIFIED)
/// V2 API uses plain symbol format without suffixes.
///
/// # Format
/// - All account types: `{BASE}{QUOTE}`
/// - Examples: `BTCUSDT`, `ETHUSDT`, `BTCUSD`
///
/// # Changes from V1
/// - V1: `BTCUSDT_SPBL` (spot), `BTCUSDT_UMCBL` (futures)
/// - V2: `BTCUSDT` (all types)
///
/// # Examples
/// - Spot: `BTCUSDT`, `ETHBTC`
/// - USDT Futures: `BTCUSDT`, `ETHUSDT`
/// - Coin Futures: `BTCUSD`, `ETHUSD`
pub fn format_symbol(base: &str, quote: &str, _account_type: AccountType) -> String {
    let base = base.to_uppercase();
    let quote = quote.to_uppercase();

    // V2 uses plain format for all account types
    format!("{}{}", base, quote)
}

/// Получить productType для futures API (V2 format)
///
/// # V2 Product Types
/// V2 API uses uppercase format with dashes:
/// - `USDT-FUTURES` - USDT-margined perpetual
/// - `COIN-FUTURES` - Coin-margined perpetual
/// - `USDC-FUTURES` - USDC-margined perpetual
///
/// # Changes from V1
/// - V1: `umcbl`, `dmcbl`, `cmcbl` (lowercase, no dashes)
/// - V2: `USDT-FUTURES`, `COIN-FUTURES`, `USDC-FUTURES` (uppercase with dashes)
pub fn get_product_type(quote: &str) -> &'static str {
    match quote.to_uppercase().as_str() {
        "USDT" => "USDT-FUTURES",
        "USD" => "COIN-FUTURES",
        "USDC" => "USDC-FUTURES",
        _ => "USDT-FUTURES", // Default to USDT-margined
    }
}

/// Маппинг интервала kline для Spot API
///
/// # Spot API Format
/// Parameter: `period` (string)
/// Values: `"1min"`, `"1h"`, `"1day"`, etc.
pub fn map_kline_interval(interval: &str) -> &'static str {
    match interval {
        "1m" => "1min",
        "3m" => "3min",
        "5m" => "5min",
        "15m" => "15min",
        "30m" => "30min",
        "1h" => "1h",
        "2h" => "2h",
        "4h" => "4h",
        "6h" => "6h",
        "12h" => "12h",
        "1d" => "1day",
        "1w" => "1week",
        "1M" => "1M",
        _ => "1h",
    }
}

/// Map kline interval to Futures granularity
///
/// # Futures API Format
/// Parameter: `granularity` (string)
/// Values: `"1m"`, `"1H"`, `"1D"`, etc.
///
/// # Differences from Spot
/// - Futures uses uppercase H, D, W, M
/// - Spot uses lowercase h, day, week
pub fn map_futures_granularity(interval: &str) -> &'static str {
    match interval {
        "1m" => "1m",
        "3m" => "3m",
        "5m" => "5m",
        "15m" => "15m",
        "30m" => "30m",
        "1h" => "1H",
        "2h" => "2H",
        "4h" => "4H",
        "6h" => "6H",
        "12h" => "12H",
        "1d" => "1D",
        "3d" => "3D",
        "1w" => "1W",
        "1M" => "1M",
        _ => "1H", // default 1 hour
    }
}