lib.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. use std::collections::{BTreeMap, HashMap};
  2. use std::fmt;
  3. use std::fmt::Formatter;
  4. use std::io::{Error};
  5. use async_trait::async_trait;
  6. use rust_decimal::Decimal;
  7. use global::trace_stack::TraceStack;
  8. use crate::exchange::ExchangeEnum;
  9. // 引入工具模块
  10. pub mod utils;
  11. // 引入exchange模块
  12. pub mod exchange;
  13. pub mod handle_info;
  14. // 引入binance模块
  15. mod binance_swap;
  16. mod binance_spot;
  17. pub mod binance_handle;
  18. // 引入gate模块
  19. mod gate_swap;
  20. mod gate_spot;
  21. pub mod gate_handle;
  22. mod kucoin_swap;
  23. pub mod kucoin_handle;
  24. mod okx_swap;
  25. pub mod okx_handle;
  26. mod bitget_spot;
  27. pub mod bitget_spot_handle;
  28. /// 持仓模式枚举
  29. /// - `Both`:单持仓方向
  30. /// - `LONG`:多仓
  31. /// - `SHORT`:空仓
  32. #[derive(Debug, Clone, PartialEq, Eq)]
  33. pub enum PositionModeEnum {
  34. Both,
  35. Long,
  36. Short,
  37. }
  38. /// OrderCommand结构体(下单指令)
  39. /// - `cancel(HashMap<String, Vec<String>)`: 取消订单指令 `{"order_name": [c_id, o_id]}`;
  40. /// - `check(HashMap<String, Vec<String>>)`: balance挂单的冻结数量 `{"order_name": [数量,方向,价格,c_id]}`;
  41. /// - `limits_open(HashMap<String, Vec<String>>)`: 总计交易币数量 `{"order_name": [c_id, o_id]}`;
  42. /// - `limits_close(HashMap<String, Vec<String>>)`: 可用交易币数量 `{"order_name": [c_id, o_id]}`;
  43. #[derive(Debug, Clone, PartialEq, Eq)]
  44. pub struct OrderCommand {
  45. // 取消订单指令,数据结构例子:
  46. pub cancel: HashMap<String, Vec<String>>,
  47. // 检验指令,数据结构例子:(暂没找到例子)
  48. pub check: HashMap<String, Vec<String>>,
  49. // 限开指令,数据结构例子:(暂没找到例子)
  50. pub limits_open: HashMap<String, Vec<String>>,
  51. // 限收指令,数据结构例子:(暂没找到例子)
  52. pub limits_close: HashMap<String, Vec<String>>,
  53. }
  54. impl OrderCommand {
  55. pub fn new() -> OrderCommand {
  56. OrderCommand {
  57. cancel: Default::default(),
  58. check: Default::default(),
  59. limits_open: Default::default(),
  60. limits_close: Default::default(),
  61. }
  62. }
  63. pub fn is_not_empty(&self) -> bool {
  64. let is_empty = self.limits_close.is_empty() && self.limits_open.is_empty() && self.cancel.is_empty() && self.check.is_empty();
  65. if is_empty { false } else { true }
  66. }
  67. }
  68. impl fmt::Display for OrderCommand {
  69. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  70. write!(f, "订单触发数据: cancel: {:?}, check: {:?}, limits_open: {:?}, limits_close: {:?}",
  71. self.cancel,
  72. self.check,
  73. self.limits_open,
  74. self.limits_close
  75. )
  76. }
  77. }
  78. /// Account结构体(账户信息)
  79. /// - `balance(Decimal)`: 总计计价币数量;
  80. /// - `available_balance(Decimal)`: 可用计价币数量;
  81. /// - `frozen_balance(Decimal)`: balance挂单的冻结数量
  82. /// - `stocks(Decimal)`: 总计交易币数量
  83. /// - `available_stocks(Decimal)`: 可用交易币数量
  84. /// - `frozen_stocks(Decimal)`: stocks挂单的冻结数量
  85. #[derive(Debug, Clone, PartialEq, Eq)]
  86. pub struct Account {
  87. pub balance: Decimal,
  88. pub available_balance: Decimal,
  89. pub frozen_balance: Decimal,
  90. pub stocks: Decimal,
  91. pub available_stocks: Decimal,
  92. pub frozen_stocks: Decimal,
  93. }
  94. impl Account {
  95. pub fn new() -> Account {
  96. Account {
  97. balance: Default::default(),
  98. available_balance: Default::default(),
  99. frozen_balance: Default::default(),
  100. stocks: Default::default(),
  101. available_stocks: Default::default(),
  102. frozen_stocks: Default::default(),
  103. }
  104. }
  105. }
  106. /// Depth结构体(市场深度)
  107. /// - `time(i64)`: 深度更新时间戳(ms);
  108. /// - `asks(Vec<MarketOrder>)`: 卖方深度列表;
  109. /// - `bids(Vec<MarketOrder>)`: 买方深度列表;
  110. #[derive(Debug, Clone, PartialEq, Eq)]
  111. pub struct Depth {
  112. pub time: i64,
  113. pub asks: Vec<MarketOrder>,
  114. pub bids: Vec<MarketOrder>,
  115. }
  116. impl Depth {
  117. pub fn new() -> Depth {
  118. Depth {
  119. time: 0,
  120. asks: vec![],
  121. bids: vec![],
  122. }
  123. }
  124. }
  125. /// 特殊Depth结构体(市场深度)
  126. /// - `name<String>`: 平台信息;
  127. /// - `depth(Vec<Decimal>)`: 深度信息;
  128. /// - `ticker(SpecialTicker)`: 市场行情;
  129. #[derive(Debug, Clone, PartialEq, Eq)]
  130. pub struct SpecialDepth {
  131. pub name: String,
  132. pub depth: Vec<Decimal>,
  133. pub ticker: SpecialTicker,
  134. }
  135. impl SpecialDepth {
  136. pub fn new() -> SpecialDepth {
  137. SpecialDepth {
  138. name: "".to_string(),
  139. depth: vec![],
  140. ticker: SpecialTicker::new(),
  141. }
  142. }
  143. }
  144. /// 特殊Ticker结构体(市场行情)
  145. /// - `sell(Decimal)`: 卖一价
  146. /// - `buy(Decimal)`: 买一价
  147. /// - `mid_price(Decimal)`: 平均价
  148. #[derive(Debug, Clone, PartialEq, Eq)]
  149. pub struct SpecialTicker {
  150. pub sell: Decimal,
  151. pub buy: Decimal,
  152. pub mid_price: Decimal,
  153. }
  154. impl SpecialTicker {
  155. pub fn new() -> SpecialTicker {
  156. SpecialTicker {
  157. sell: Default::default(),
  158. buy: Default::default(),
  159. mid_price: Default::default(),
  160. }
  161. }
  162. }
  163. /// MarketOrder结构体(市场深度单)
  164. /// - `price(Decimal)`: 价格
  165. /// - `amount(Decimal)`: 数量
  166. #[derive(Debug, Clone, PartialEq, Eq)]
  167. pub struct MarketOrder {
  168. pub price: Decimal,
  169. pub amount: Decimal,
  170. }
  171. impl MarketOrder {
  172. pub fn new() -> MarketOrder {
  173. MarketOrder {
  174. price: Default::default(),
  175. amount: Default::default(),
  176. }
  177. }
  178. }
  179. /// Record结构体(标准的OHLC结构)
  180. /// - `time(i64)`: 时间戳;
  181. /// - `open(Decimal)`: 开盘价;
  182. /// - `high(Decimal)`: 最高价;
  183. /// - `low(Decimal):` 最低价;
  184. /// - `close(Decimal)`: 收盘价;
  185. /// - `volume(Decimal)`: 交易量;
  186. #[derive(Debug, Clone, PartialEq, Eq)]
  187. pub struct Record {
  188. pub time: i64,
  189. pub open: Decimal,
  190. pub high: Decimal,
  191. pub low: Decimal,
  192. pub close: Decimal,
  193. pub volume: Decimal,
  194. }
  195. impl Record {
  196. pub fn new() -> Record {
  197. Record {
  198. time: 0,
  199. open: Default::default(),
  200. high: Default::default(),
  201. low: Default::default(),
  202. close: Default::default(),
  203. volume: Default::default(),
  204. }
  205. }
  206. }
  207. /// 特殊Order结构体(订单)
  208. /// - `name<String>`: 平台信息;
  209. /// - `order<Vec<Order>>`: 订单信息数组;
  210. #[derive(Debug, Clone, PartialEq, Eq)]
  211. pub struct SpecialOrder {
  212. pub name: String,
  213. pub order: Vec<Order>,
  214. }
  215. impl SpecialOrder {
  216. pub fn new() -> SpecialOrder {
  217. SpecialOrder {
  218. name: "".to_string(),
  219. order: vec![],
  220. }
  221. }
  222. }
  223. /// Order结构体(订单)
  224. /// - `id(String)`: 交易单唯一标识
  225. /// - `custom_id(String)`: 自定义Id
  226. /// - `price(Decimal)`: 下单价格
  227. /// - `amount(Decimal)`: 下单数量
  228. /// - `deal_amount(Decimal)`: 成交数量
  229. /// - `avg_price(Decimal)`: 成交均价
  230. /// - `status(String)`: 订单状态
  231. /// - `order_type(String)`: 订单类型
  232. #[derive(Debug, Clone, PartialEq, Eq)]
  233. pub struct Order {
  234. pub id: String,
  235. pub custom_id: String,
  236. pub price: Decimal,
  237. pub amount: Decimal,
  238. pub deal_amount: Decimal,
  239. pub avg_price: Decimal,
  240. pub status: String,
  241. pub order_type: String,
  242. pub trace_stack: TraceStack,
  243. }
  244. impl Order {
  245. pub fn new() -> Order {
  246. Order {
  247. id: "".to_string(),
  248. custom_id: "".to_string(),
  249. price: Default::default(),
  250. amount: Default::default(),
  251. deal_amount: Default::default(),
  252. avg_price: Default::default(),
  253. status: "".to_string(),
  254. order_type: "".to_string(),
  255. trace_stack: TraceStack::default(),
  256. }
  257. }
  258. }
  259. /// Ticker结构体(市场行情)
  260. /// - `time(i64)`: 毫秒级别时间戳
  261. /// - `high(Decimal)`: 最高价
  262. /// - `low(Decimal)`: 最低价
  263. /// - `sell(Decimal)`: 卖一价
  264. /// - `buy(Decimal)`: 买一价
  265. /// - `last(Decimal)`: 最后成交价
  266. /// - `volume(Decimal)`: 最近成交量
  267. #[derive(Debug, Clone, PartialEq, Eq)]
  268. pub struct Ticker {
  269. pub time: i64,
  270. pub high: Decimal,
  271. pub low: Decimal,
  272. pub sell: Decimal,
  273. pub buy: Decimal,
  274. pub last: Decimal,
  275. pub volume: Decimal,
  276. }
  277. impl Ticker {
  278. pub fn new() -> Ticker {
  279. Ticker {
  280. time: 0,
  281. high: Default::default(),
  282. low: Default::default(),
  283. sell: Default::default(),
  284. buy: Default::default(),
  285. last: Default::default(),
  286. volume: Default::default(),
  287. }
  288. }
  289. }
  290. /// Market结构体(交易品种的市场信息)
  291. /// - `symbol(String)`: 交易对
  292. /// - `base_asset(String)`: 交易币
  293. /// - `quote_asset(String)`: 计价币
  294. /// - `tick_size(Decimal)`: 价格最小变动数值
  295. /// - `amount_size(Decimal)`: 下单量最小变动数值
  296. /// - `price_precision(Decimal)`: 价格精度
  297. /// - `amount_precision(Decimal)`: 下单量精度
  298. /// - `min_qty(Decimal)`: 最小下单量
  299. /// - `max_qty(Decimal)`: 最大下单量
  300. /// - `min_notional(Decimal)`: 最小下单金额
  301. /// - `max_notional(Decimal)`: 最大下单金额
  302. /// - `ct_val(Decimal)`: 合约价值
  303. #[derive(Debug, Clone, PartialEq, Eq)]
  304. pub struct Market {
  305. pub symbol: String,
  306. pub base_asset: String,
  307. pub quote_asset: String,
  308. pub tick_size: Decimal,
  309. pub amount_size: Decimal,
  310. pub price_precision: Decimal,
  311. pub amount_precision: Decimal,
  312. pub min_qty: Decimal,
  313. pub max_qty: Decimal,
  314. pub min_notional: Decimal,
  315. pub max_notional: Decimal,
  316. pub ct_val: Decimal,
  317. }
  318. impl Market {
  319. pub fn new() -> Market {
  320. Market {
  321. symbol: "".to_string(),
  322. base_asset: "".to_string(),
  323. quote_asset: "".to_string(),
  324. tick_size: Default::default(),
  325. amount_size: Default::default(),
  326. price_precision: Default::default(),
  327. amount_precision: Default::default(),
  328. min_qty: Default::default(),
  329. max_qty: Default::default(),
  330. min_notional: Default::default(),
  331. max_notional: Default::default(),
  332. ct_val: Default::default(),
  333. }
  334. }
  335. }
  336. /// Position结构体(仓位信息)
  337. /// - `symbol(String)`: 币对
  338. /// - `margin_level(String)`: 持仓杆杠大小
  339. /// - `amount(String)`: 持仓量
  340. /// - `frozen_amount(String)`: 仓位冻结量
  341. /// - `price(Decimal)`: 持仓均价
  342. /// - `profit(Decimal)`: 持仓浮动盈亏
  343. /// - `position_mode(PositionModeEnum)`: 持仓模式
  344. /// - `margin(Decimal)`: 仓位占用的保证金
  345. #[derive(Debug, Clone, PartialEq, Eq)]
  346. pub struct Position {
  347. pub symbol: String,
  348. pub margin_level: Decimal,
  349. pub amount: Decimal,
  350. pub frozen_amount: Decimal,
  351. pub price: Decimal,
  352. pub profit: Decimal,
  353. pub position_mode: PositionModeEnum,
  354. pub margin: Decimal,
  355. }
  356. impl Position {
  357. pub fn new() -> Position {
  358. Position {
  359. symbol: "".to_string(),
  360. margin_level: Default::default(),
  361. amount: Default::default(),
  362. frozen_amount: Default::default(),
  363. price: Default::default(),
  364. profit: Default::default(),
  365. position_mode: PositionModeEnum::Both,
  366. margin: Default::default(),
  367. }
  368. }
  369. }
  370. /// 交易所统一方法接口
  371. ///
  372. /// 使用方法前需实例化
  373. /// ```rust
  374. /// use std::collections::BTreeMap;
  375. /// use standard::exchange::{Exchange, ExchangeEnum};
  376. ///
  377. /// let mut params:BTreeMap<String,String> = BTreeMap::new();
  378. /// params.insert("access_key".to_string(), "your_access_key".to_string());
  379. /// params.insert("access_key".to_string(), "your_secret_key".to_string());
  380. /// let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  381. /// ```
  382. /// 获取当前交易所交易模式
  383. /// - fn get_self_exchange(&self) -> ExchangeEnum;
  384. /// ```rust
  385. /// # use std::collections::BTreeMap;
  386. /// # use standard::exchange::{Exchange, ExchangeEnum};
  387. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  388. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  389. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  390. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  391. ///
  392. /// exchange.get_self_exchange();
  393. /// ```
  394. /// 获取当前是否使用高速模式
  395. /// - fn get_self_is_colo(&self) -> bool;
  396. /// ```rust
  397. /// # use std::collections::BTreeMap;
  398. /// # use standard::exchange::{Exchange, ExchangeEnum};
  399. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  400. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  401. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  402. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  403. ///
  404. /// exchange.get_self_is_colo();
  405. /// ```
  406. /// 获取当前是否使用登录
  407. /// - fn get_self_is_login(&self) -> bool;
  408. /// ```rust
  409. /// # use std::collections::BTreeMap;
  410. /// # use standard::exchange::{Exchange, ExchangeEnum};
  411. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  412. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  413. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  414. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  415. ///
  416. /// exchange.get_self_is_login();
  417. /// ```
  418. /// 获取登录params信息
  419. /// - fn get_self_params(&self) -> BTreeMap<String, String>;
  420. /// ```rust
  421. /// # use std::collections::BTreeMap;
  422. /// # use standard::exchange::{Exchange, ExchangeEnum};
  423. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  424. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  425. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  426. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  427. ///
  428. /// exchange.get_self_params();
  429. /// ```
  430. /// 获取账号信息
  431. /// - async fn get_account(&self, symbol: &str) -> Result<Account, Error>;
  432. /// ```rust
  433. /// # use std::collections::BTreeMap;
  434. /// # use standard::exchange::{Exchange, ExchangeEnum};
  435. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  436. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  437. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  438. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  439. ///
  440. /// exchange.get_account()
  441. /// ```
  442. /// 订阅账号信息
  443. /// ```rust
  444. /// # use std::collections::BTreeMap;
  445. /// # use standard::exchange::{Exchange, ExchangeEnum};
  446. /// # let mut params:BTreeMap<String,String> = BTreeMap::new();
  447. /// # params.insert("access_key".to_string(), "your_access_key".to_string());
  448. /// # params.insert("access_key".to_string(), "your_secret_key".to_string());
  449. /// # let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params);
  450. ///
  451. /// exchange.subscribe_account();
  452. /// ```
  453. #[async_trait]
  454. pub trait Platform {
  455. fn clone_box(&self) -> Box<dyn Platform + Send + Sync>;
  456. // 获取当前交易所交易模式
  457. fn get_self_exchange(&self) -> ExchangeEnum;
  458. // 获取交易对
  459. fn get_self_symbol(&self) -> String;
  460. // 获取当前是否使用高速模式
  461. fn get_self_is_colo(&self) -> bool;
  462. // 获取登录params信息
  463. fn get_self_params(&self) -> BTreeMap<String, String>;
  464. // 获取market信息
  465. fn get_self_market(&self) -> Market;
  466. // 获取请求时间
  467. fn get_request_delays(&self) -> Vec<i64>;
  468. // 获取请求平均时间
  469. fn get_request_avg_delay(&self) -> Decimal;
  470. // 获取请求最大时间
  471. fn get_request_max_delay(&self) -> i64;
  472. // 获取服务器时间
  473. async fn get_server_time(&mut self) -> Result<String, Error>;
  474. // 获取账号信息
  475. async fn get_account(&mut self) -> Result<Account, Error>;
  476. // 获取持仓信息
  477. async fn get_position(&mut self) -> Result<Vec<Position>, Error>;
  478. // 获取所有持仓
  479. async fn get_positions(&mut self) -> Result<Vec<Position>, Error>;
  480. // 获取市场行情
  481. async fn get_ticker(&mut self) -> Result<Ticker, Error>;
  482. // 获取市场行情自定义交易对
  483. async fn get_ticker_symbol(&mut self, symbol: String) -> Result<Ticker, Error>;
  484. // 查询所有的市场信息
  485. async fn get_market(&mut self) -> Result<Market, Error>;
  486. // 查询所有的市场信息自定义交易对
  487. async fn get_market_symbol(&mut self, symbol: String) -> Result<Market, Error>;
  488. // 查询订单详情
  489. async fn get_order_detail(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error>;
  490. // 获取订单列表
  491. async fn get_orders_list(&mut self, status: &str) -> Result<Vec<Order>, Error>;
  492. // 下单接口
  493. async fn take_order(&mut self, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error>;
  494. // 下单接口自定义交易对
  495. async fn take_order_symbol(&mut self, symbol: String, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error>;
  496. // 撤销订单
  497. async fn cancel_order(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error>;
  498. // 批量撤销订单
  499. async fn cancel_orders(&mut self) -> Result<Vec<Order>, Error>;
  500. // 设置持仓模式
  501. async fn set_dual_mode(&mut self, coin: &str, is_dual_mode: bool) -> Result<String, Error>;
  502. // 更新双持仓模式下杠杆
  503. async fn set_dual_leverage(&mut self, leverage: &str) -> Result<String, Error>;
  504. // 设置自动追加保证金
  505. async fn set_auto_deposit_status(&mut self, status: bool) -> Result<String, Error>;
  506. // 交易账户互转
  507. async fn wallet_transfers(&mut self, coin: &str, from: &str, to: &str, amount: Decimal) -> Result<String, Error>;
  508. // 指令下单
  509. async fn command_order(&mut self, order_command: OrderCommand, trace_stack: TraceStack);
  510. }