Skip to main content

bybit/
api.rs

1use crate::account::AccountManager;
2use crate::asset::AssetManager;
3use crate::client::Client;
4use crate::config::Config;
5use crate::general::General;
6use crate::market::MarketData;
7use crate::position::PositionManager;
8use crate::trade::Trader;
9use crate::ws::Stream;
10
11pub enum API {
12    Market(Market),
13    Trade(Trade),
14    Position(Position),
15    Account(Account),
16    Asset(Asset),
17    SpotLeverage(SpotLeverage),
18    SpotMargin(SpotMargin),
19}
20/// Bybit Endpoints
21#[derive(Debug, PartialEq)]
22pub enum WebsocketAPI {
23    PublicSpot,
24    PublicLinear,
25    PublicInverse,
26    PublicOption,
27    PublicSpread,
28    PublicRFQ,
29    Private,
30    TradeStream,
31    PublicMiscStatus,
32}
33
34#[derive(Clone)]
35pub enum Public {
36    Spot,
37    Linear,
38    Inverse,
39}
40
41pub enum Market {
42    Time,
43    Kline,
44    MarkPriceKline,
45    IndexPriceKline,
46    PremiumIndexPriceKline,
47    InstrumentsInfo,
48    OrderBook,
49    RPIOrderbook,
50    Ticker,
51    FundingRate,
52    RecentTrades,
53    OpenInterest,
54    HistoricalVolatility,
55    Insurance,
56    RiskLimit,
57    DeliveryPrice,
58    NewDeliveryPrice,
59    LongShortRatio,
60    SystemStatus,
61    ADLAlert,
62    FeeGroupInfo,
63    OrderPriceLimit,
64}
65
66pub enum Trade {
67    Place,
68    Amend,
69    Cancel,
70    OpenOrders,
71    CancelAll,
72    History,
73    TradeHistory,
74    BatchPlace,
75    BatchAmend,
76    BatchCancel,
77    SpotBorrowCheck,
78    SetDisconnectCancelall,
79    PreCheck,
80}
81
82pub enum Position {
83    Information,
84    SetLeverage,
85    SetRiskLimit,
86    SetTradingStop,
87    SwitchIsolated,
88    SwitchMode,
89    SetAutoaddMargin,
90    AddorReduceMargin,
91    ClosedPnl,
92    GetClosedOptionsPositions,
93    ConfirmPendingMmr,
94    MovePosition,
95    MovePositionHistory,
96}
97
98pub enum Account {
99    Balance,
100    UpgradetoUTA,
101    BorrowHistory,
102    RepayLiability,
103    SetCollateral,
104    BatchSetCollateral,
105    CollateralInfo,
106    CoinGreeks,
107    FeeRate,
108    Information,
109    TransactionLog,
110    SetMarginMode,
111    SMPGroupID,
112    SetSpotHedging,
113}
114
115pub enum Asset {
116    CoinExchangeRecord,
117    DeliveryRecord,
118    SettlementRecord,
119    Intertransfer,
120    QueryTransferList,
121    SaveTransferSubmember,
122    UniversalTransfer,
123    QueryUniversalTransferList,
124    QueryTransferCoinList,
125    QueryTransferSubmemberList,
126    QueryAccountCoinBalance,
127    QuerySingleAccountCoinBalance,
128    QueryAssetInfo,
129    QueryAllowedList,
130    QueryRecord,
131    QuerySubMemberRecord,
132    QueryInternalRecord,
133    QueryAddress,
134    QueryInfo,
135    QueryAsset,
136    Withdraw,
137    CancelWithdraw,
138    Deposit,
139    QuerySubmemberAddress,
140    OrderRecord,
141    WithdrawableAmount,
142    SetDepositAccount,
143    QueryWithdrawalAddress,
144    QueryWithdrawalRecord,
145    QueryVaspList,
146}
147
148pub enum SpotLeverage {
149    Info,
150    Marketinfo,
151    Purchase,
152    Redeem,
153    OrderRecord,
154}
155
156pub enum SpotMargin {
157    SwitchMode,
158    SetLeverage,
159    MarginCoinInfo,
160    State,
161    BorrowableCoin,
162    LoanInfo,
163    LoanAccountInfo,
164    Borrow,
165    Repay,
166    BorrowOrderDetail,
167    RepayOrderDetail,
168    ClassicMarginToggle,
169}
170
171impl AsRef<str> for API {
172    fn as_ref(&self) -> &str {
173        match self {
174            API::Market(route) => match route {
175                Market::Time => "/v5/market/time",
176                Market::Insurance => "/v5/market/insurance",
177                Market::Kline => "/v5/market/kline",
178                Market::MarkPriceKline => "/v5/market/mark-price-kline",
179                Market::IndexPriceKline => "/v5/market/index-price-kline",
180                Market::PremiumIndexPriceKline => "/v5/market/premium-index-price-kline",
181                Market::InstrumentsInfo => "/v5/market/instruments-info",
182                Market::OrderBook => "/v5/market/orderbook",
183                Market::RPIOrderbook => "/v5/market/rpi_orderbook",
184                Market::Ticker => "/v5/market/tickers",
185                Market::RecentTrades => "/v5/market/recent-trade",
186                Market::FundingRate => "/v5/market/funding/history",
187                Market::OpenInterest => "/v5/market/open-interest",
188                Market::HistoricalVolatility => "/v5/market/historical-volatility",
189                Market::RiskLimit => "/v5/market/risk-limit",
190                Market::DeliveryPrice => "/v5/market/delivery-price",
191                Market::NewDeliveryPrice => "/v5/market/new-delivery-price",
192                Market::LongShortRatio => "/v5/market/account-ratio",
193                Market::SystemStatus => "/v5/system/status",
194                Market::ADLAlert => "/v5/market/adlAlert",
195                Market::FeeGroupInfo => "/v5/market/fee-group-info",
196                Market::OrderPriceLimit => "/v5/market/price-limit",
197            },
198            API::Trade(route) => match route {
199                Trade::Place => "/v5/order/create",
200                Trade::Amend => "/v5/order/amend",
201                Trade::Cancel => "/v5/order/cancel",
202                Trade::OpenOrders => "/v5/order/realtime",
203                Trade::CancelAll => "/v5/order/cancel-all",
204                Trade::History => "/v5/order/history",
205                Trade::TradeHistory => "/v5/execution/list",
206                Trade::BatchPlace => "/v5/order/create-batch",
207                Trade::BatchAmend => "/v5/order/amend-batch",
208                Trade::BatchCancel => "/v5/order/cancel-batch",
209                Trade::SpotBorrowCheck => "/v5/order/spot-borrow-check",
210                Trade::SetDisconnectCancelall => "/v5/order/disconnected-cancel-all",
211                Trade::PreCheck => "/v5/order/pre-check",
212            },
213            API::Position(route) => match route {
214                Position::Information => "/v5/position/list",
215                Position::SetLeverage => "/v5/position/set-leverage",
216                Position::SwitchIsolated => "/v5/position/switch-isolated",
217                Position::SwitchMode => "/v5/position/switch-mode",
218                Position::SetRiskLimit => "/v5/position/set-risk-limit",
219                Position::SetTradingStop => "/v5/position/trading-stop",
220                Position::SetAutoaddMargin => "/v5/position/set-auto-add-margin",
221                Position::AddorReduceMargin => "/v5/position/add-margin",
222                Position::ClosedPnl => "/v5/position/closed-pnl",
223                Position::GetClosedOptionsPositions => "/v5/position/get-closed-positions",
224                Position::ConfirmPendingMmr => "/v5/position/confirm-pending-mmr",
225                Position::MovePosition => "/v5/position/move-positions",
226                Position::MovePositionHistory => "/v5/position/move-history",
227            },
228            API::Account(route) => match route {
229                Account::Balance => "/v5/account/wallet-balance",
230                Account::UpgradetoUTA => "/v5/account/upgrade-to-uta",
231                Account::BorrowHistory => "/v5/account/borrow-history",
232                Account::RepayLiability => "/v5/account/quick-repayment",
233                Account::SetCollateral => "/v5/account/set-collateral-switch",
234                Account::BatchSetCollateral => "/v5/account/set-collateral-switch-batch",
235                Account::CollateralInfo => "/v5/account/collateral-info",
236                Account::CoinGreeks => "/v5/asset/coin-greeks",
237                Account::FeeRate => "/v5/account/fee-rate",
238                Account::Information => "/v5/account/info",
239                Account::TransactionLog => "/v5/account/transaction-log",
240                Account::SMPGroupID => "/v5/account/smp-group",
241                Account::SetMarginMode => "/v5/aaccount/set-margin-mode",
242                Account::SetSpotHedging => "/v5/account/set-hedging-mode",
243            },
244            API::Asset(route) => match route {
245                Asset::CoinExchangeRecord => "/v5/asset/exchange/order-record",
246                Asset::DeliveryRecord => "/v5/asset/delivery-record",
247                Asset::SettlementRecord => "/v5/asset/settlement-record",
248                Asset::QueryAssetInfo => "/v5/asset/transfer/query-asset-info",
249                Asset::QueryAccountCoinBalance => "/v5/asset/transfer/query-account-coins-balance",
250                Asset::QuerySingleAccountCoinBalance => {
251                    "/v5/asset/transfer/query-account-coin-balance"
252                }
253                Asset::QueryTransferCoinList => "/v5/asset/transfer/query-transfer-coin-list",
254                Asset::Intertransfer => "/v5/asset/transfer/inter-transfer",
255                Asset::QueryTransferList => "/v5/asset/transfer/query-inter-transfer-list",
256                Asset::QueryTransferSubmemberList => "/v5/asset/transfer/query-sub-member-list",
257                Asset::UniversalTransfer => "/v5/asset/transfer/universal-transfer",
258                Asset::QueryUniversalTransferList => {
259                    "/v5/asset/transfer/query-universal-transfer-list"
260                }
261                Asset::QueryAllowedList => "/v5/asset/deposit/query-allowed-list",
262                Asset::Withdraw => "/v5/asset/withdraw/create",
263                Asset::CancelWithdraw => "/v5/asset/withdraw/cancel",
264                Asset::QueryInfo => "/v5/asset/coin/query-info",
265                Asset::QueryRecord => "/v5/asset/deposit/query-record",
266                Asset::QueryWithdrawalAddress => "/v5/asset/withdraw/query-address",
267                Asset::QueryWithdrawalRecord => "/v5/asset/withdraw/query-record",
268                Asset::QueryVaspList => "/v5/asset/withdraw/vasp/list",
269                Asset::QuerySubMemberRecord => "/v5/asset/deposit/query-sub-member-record",
270                Asset::QueryInternalRecord => "/v5/asset/deposit/query-internal-record",
271                Asset::QueryAddress => "/v5/asset/deposit/query-address",
272                Asset::QuerySubmemberAddress => "/v5/asset/deposit/query-sub-member-address",
273                Asset::WithdrawableAmount => "/v5/asset/withdraw/withdrawable-amount",
274                Asset::SetDepositAccount => "/v5/asset/deposit/deposit-to-account",
275                _ => {
276                    todo!("Asset route not implemented");
277                }
278            },
279            API::SpotLeverage(route) => match route {
280                SpotLeverage::Info => "/v5/spot-lever-token/info",
281                SpotLeverage::Marketinfo => "v5/spot-lever-token/reference",
282                SpotLeverage::Purchase => "/v5/spot-lever-token/purchase",
283                SpotLeverage::Redeem => "/v5/spot-lever-token/redeem",
284                SpotLeverage::OrderRecord => "/v5/spot-lever-token/order-record",
285            },
286            API::SpotMargin(route) => match route {
287                SpotMargin::SwitchMode => "/v5/spot-margin-trade/switch-mode",
288                SpotMargin::SetLeverage => "/v5/spot-margin-trade/set-leverage",
289                SpotMargin::State => "/v5/spot-margin-trade/state",
290                SpotMargin::MarginCoinInfo => "/v5/spot-cross-margin-trade/pledge-token",
291                SpotMargin::BorrowableCoin => "/v5/spot-cross-margin-trade/borrow-token",
292                SpotMargin::LoanInfo => "/v5/spot-cross-margin-trade/loan",
293                SpotMargin::LoanAccountInfo => "/v5/spot-cross-margin-trade/account",
294                SpotMargin::Borrow => "/v5/spot-cross-margin-trade/loan",
295                SpotMargin::Repay => "/v5/spot-cross-margin-trade/repay",
296                SpotMargin::BorrowOrderDetail => "/v5/spot-cross-margin-trade/orders",
297                SpotMargin::RepayOrderDetail => "/v5/spot-cross-margin-trade/repay-history",
298                SpotMargin::ClassicMarginToggle => "/v5/spot-cross-margin-trade/switch",
299            },
300        }
301    }
302}
303
304impl AsRef<str> for WebsocketAPI {
305    fn as_ref(&self) -> &str {
306        match self {
307            WebsocketAPI::PublicSpot => "/public/spot",
308            WebsocketAPI::PublicLinear => "/public/linear",
309            WebsocketAPI::PublicInverse => "/public/inverse",
310            WebsocketAPI::PublicOption => "/public/option",
311            WebsocketAPI::PublicRFQ => "/public/rfq",
312            WebsocketAPI::PublicSpread => "/public/spread",
313            WebsocketAPI::Private => "/private",
314            WebsocketAPI::TradeStream => "/trade",
315            WebsocketAPI::PublicMiscStatus => "/public/misc/status",
316        }
317    }
318}
319
320/// A trait that all modules must implement to be a Bybit API client module.
321///
322/// This trait provides two methods to create a new instance of the module,
323/// one with default configuration and one with custom configuration.
324pub trait Bybit {
325    /// Creates a new instance of the module with default configuration.
326    ///
327    /// # Parameters
328    ///
329    /// * `api_key`: The API key to be used for the module.
330    /// * `secret_key`: The secret key to be used for the module.
331    ///
332    /// # Returns
333    ///
334    /// A new instance of the module.
335    fn new(api_key: Option<String>, secret_key: Option<String>) -> Self;
336
337    /// Creates a new instance of the module with custom configuration.
338    ///
339    /// # Parameters
340    ///
341    /// * `config`: The custom configuration to be used for the module.
342    /// * `api_key`: The API key to be used for the module.
343    /// * `secret_key`: The secret key to be used for the module.
344    ///
345    /// # Returns
346    ///
347    /// A new instance of the module.
348    fn new_with_config(
349        config: &Config,
350        api_key: Option<String>,
351        secret_key: Option<String>,
352    ) -> Self;
353}
354
355impl Bybit for General {
356    fn new(api_key: Option<String>, secret_key: Option<String>) -> General {
357        Self::new_with_config(&Config::default(), api_key, secret_key)
358    }
359
360    fn new_with_config(
361        config: &Config,
362        api_key: Option<String>,
363        secret_key: Option<String>,
364    ) -> General {
365        General {
366            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
367        }
368    }
369}
370
371impl Bybit for MarketData {
372    fn new(api_key: Option<String>, secret_key: Option<String>) -> MarketData {
373        Self::new_with_config(&Config::default(), api_key, secret_key)
374    }
375    fn new_with_config(
376        config: &Config,
377        api_key: Option<String>,
378        secret_key: Option<String>,
379    ) -> MarketData {
380        MarketData {
381            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
382            recv_window: config.recv_window,
383        }
384    }
385}
386
387impl Bybit for Trader {
388    fn new(api_key: Option<String>, secret_key: Option<String>) -> Trader {
389        Self::new_with_config(&Config::default(), api_key, secret_key)
390    }
391    fn new_with_config(
392        config: &Config,
393        api_key: Option<String>,
394        secret_key: Option<String>,
395    ) -> Trader {
396        Trader {
397            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
398            recv_window: config.recv_window,
399        }
400    }
401}
402impl Bybit for PositionManager {
403    fn new(api_key: Option<String>, secret_key: Option<String>) -> PositionManager {
404        Self::new_with_config(&Config::default(), api_key, secret_key)
405    }
406    fn new_with_config(
407        config: &Config,
408        api_key: Option<String>,
409        secret_key: Option<String>,
410    ) -> PositionManager {
411        PositionManager {
412            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
413            recv_window: config.recv_window,
414        }
415    }
416}
417
418impl Bybit for AccountManager {
419    fn new(api_key: Option<String>, secret_key: Option<String>) -> AccountManager {
420        Self::new_with_config(&Config::default(), api_key, secret_key)
421    }
422    fn new_with_config(
423        config: &Config,
424        api_key: Option<String>,
425        secret_key: Option<String>,
426    ) -> AccountManager {
427        AccountManager {
428            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
429            recv_window: config.recv_window,
430        }
431    }
432}
433
434impl Bybit for AssetManager {
435    fn new(api_key: Option<String>, secret_key: Option<String>) -> AssetManager {
436        Self::new_with_config(&Config::default(), api_key, secret_key)
437    }
438    fn new_with_config(
439        config: &Config,
440        api_key: Option<String>,
441        secret_key: Option<String>,
442    ) -> AssetManager {
443        AssetManager {
444            client: Client::new(api_key, secret_key, config.rest_api_endpoint.to_string()),
445            recv_window: config.recv_window,
446        }
447    }
448}
449
450impl Bybit for Stream {
451    fn new(api_key: Option<String>, secret_key: Option<String>) -> Stream {
452        Self::new_with_config(&Config::default(), api_key, secret_key)
453    }
454
455    fn new_with_config(
456        config: &Config,
457        api_key: Option<String>,
458        secret_key: Option<String>,
459    ) -> Stream {
460        Stream {
461            client: Client::new(api_key, secret_key, config.ws_endpoint.to_string()),
462        }
463    }
464}