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