use std::collections::{BTreeMap, HashMap}; use std::fmt; use std::fmt::Formatter; use std::io::{Error}; use async_trait::async_trait; use rust_decimal::Decimal; use serde_json::Value; use tokio::time::Instant; use global::trace_stack::TraceStack; use crate::exchange::ExchangeEnum; // 引入工具模块 pub mod utils; // 引入exchange模块 pub mod exchange; pub mod handle_info; // 引入binance模块 mod binance_swap; mod binance_spot; pub mod binance_swap_handle; pub mod binance_spot_handle; // 引入gate模块 mod gate_swap; mod gate_spot; pub mod gate_swap_handle; mod kucoin_swap; pub mod kucoin_handle; mod okx_swap; pub mod okx_handle; mod bitget_spot; pub mod bitget_spot_handle; mod kucoin_spot; pub mod kucoin_spot_handle; mod bybit_swap; mod bybit_swap_handle; mod bitget_swap; mod bitget_swap_handle; /// 持仓模式枚举 /// - `Both`:单持仓方向 /// - `LONG`:多仓 /// - `SHORT`:空仓 #[derive(Debug, Clone, PartialEq, Eq)] pub enum PositionModeEnum { Both, Long, Short, } /// OrderCommand结构体(下单指令) /// - `cancel(HashMap)`: 取消订单指令 `{"order_name": [c_id, o_id]}`; /// - `check(HashMap>)`: balance挂单的冻结数量 `{"order_name": [数量,方向,价格,c_id]}`; /// - `limits_open(HashMap>)`: 总计交易币数量 `{"order_name": [c_id, o_id]}`; /// - `limits_close(HashMap>)`: 可用交易币数量 `{"order_name": [c_id, o_id]}`; #[derive(Debug, Clone, PartialEq, Eq)] pub struct OrderCommand { // 取消订单指令,数据结构例子: pub cancel: HashMap>, // 检验指令,数据结构例子:(暂没找到例子) pub check: HashMap>, // 限开指令,数据结构例子:(暂没找到例子) pub limits_open: HashMap>, // 限收指令,数据结构例子:(暂没找到例子) pub limits_close: HashMap>, } impl OrderCommand { pub fn new() -> OrderCommand { OrderCommand { cancel: Default::default(), check: Default::default(), limits_open: Default::default(), limits_close: Default::default(), } } pub fn is_not_empty(&self) -> bool { let is_empty = self.limits_close.is_empty() && self.limits_open.is_empty() && self.cancel.is_empty() && self.check.is_empty(); if is_empty { false } else { true } } } impl fmt::Display for OrderCommand { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "订单触发数据: cancel: {:?}, check: {:?}, limits_open: {:?}, limits_close: {:?}", self.cancel, self.check, self.limits_open, self.limits_close ) } } /// Account结构体(账户信息) /// - `coin(String)`: 货币; /// - `balance(Decimal)`: 总计计价币数量; /// - `available_balance(Decimal)`: 可用计价币数量; /// - `frozen_balance(Decimal)`: balance挂单的冻结数量 /// - `stocks(Decimal)`: 总计交易币数量 /// - `available_stocks(Decimal)`: 可用交易币数量 /// - `frozen_stocks(Decimal)`: stocks挂单的冻结数量 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Account { pub coin: String, pub balance: Decimal, pub available_balance: Decimal, pub frozen_balance: Decimal, pub stocks: Decimal, pub available_stocks: Decimal, pub frozen_stocks: Decimal, } impl Account { pub fn new() -> Account { Account { coin: "".to_string(), balance: Default::default(), available_balance: Default::default(), frozen_balance: Default::default(), stocks: Default::default(), available_stocks: Default::default(), frozen_stocks: Default::default(), } } } /// Depth结构体(市场深度) /// - `time(i64)`: 深度更新时间戳(ms); /// - `asks(Vec)`: 卖方深度列表; /// - `bids(Vec)`: 买方深度列表; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Depth { pub time: i64, pub asks: Vec, pub bids: Vec, } impl Depth { pub fn new() -> Depth { Depth { time: 0, asks: vec![], bids: vec![], } } } /// 特殊Depth结构体(市场深度) /// - `name`: 平台信息; /// - `depth(Vec)`: 深度信息; /// - `ticker(SpecialTicker)`: 市场行情; /// - `t(Decimal)`: 数据更新id /// - `create_at(i64)`: 数据生成时间 #[derive(Debug, Clone, PartialEq, Eq)] pub struct SpecialDepth { pub name: String, pub depth: Vec, pub ticker: SpecialTicker, pub t: Decimal, pub create_at: i64, } impl SpecialDepth { pub fn new() -> SpecialDepth { SpecialDepth { name: "".to_string(), depth: vec![], ticker: SpecialTicker::new(), t: Default::default(), create_at: 0, } } } /// 特殊Ticker结构体(市场行情) /// - `sell(Decimal)`: 卖一价 /// - `buy(Decimal)`: 买一价 /// - `mid_price(Decimal)`: 平均价 /// - `t(Decimal)`: 数据更新id /// - `create_at(i64)`: 数据生成时间 #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct SpecialTicker { pub sell: Decimal, pub buy: Decimal, pub mid_price: Decimal, pub t: Decimal, pub create_at: i64 } impl SpecialTicker { pub fn new() -> SpecialTicker { SpecialTicker { sell: Default::default(), buy: Default::default(), mid_price: Default::default(), t: Default::default(), create_at: 0, } } } /// MarketOrder结构体(市场深度单) /// - `price(Decimal)`: 价格 /// - `amount(Decimal)`: 数量 #[derive(Debug, Clone, PartialEq, Eq)] pub struct MarketOrder { pub price: Decimal, pub amount: Decimal, } impl MarketOrder { pub fn new() -> MarketOrder { MarketOrder { price: Default::default(), amount: Default::default(), } } } /// Record结构体(标准的OHLC结构) /// - `time(i64)`: 时间戳; /// - `open(Decimal)`: 开盘价; /// - `high(Decimal)`: 最高价; /// - `low(Decimal):` 最低价; /// - `close(Decimal)`: 收盘价; /// - `volume(Decimal)`: 交易量; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Record { pub time: i64, pub open: Decimal, pub high: Decimal, pub low: Decimal, pub close: Decimal, pub volume: Decimal, } impl Record { pub fn new() -> Record { Record { time: 0, open: Default::default(), high: Default::default(), low: Default::default(), close: Default::default(), volume: Default::default(), } } } /// 特殊Order结构体(订单) /// - `name`: 平台信息; /// - `order>`: 订单信息数组; #[derive(Debug, Clone, PartialEq, Eq)] pub struct SpecialOrder { pub name: String, pub order: Vec, } impl SpecialOrder { pub fn new() -> SpecialOrder { SpecialOrder { name: "".to_string(), order: vec![], } } } /// Order结构体(订单) /// - `id(String)`: 交易单唯一标识 /// - `custom_id(String)`: 自定义Id /// - `price(Decimal)`: 下单价格 /// - `amount(Decimal)`: 下单数量 /// - `deal_amount(Decimal)`: 成交数量 /// - `avg_price(Decimal)`: 成交均价 /// - `status(String)`: 订单状态 /// - `order_type(String)`: 订单类型 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Order { pub id: String, pub custom_id: String, pub price: Decimal, pub amount: Decimal, pub deal_amount: Decimal, pub avg_price: Decimal, pub status: String, pub order_type: String, pub trace_stack: TraceStack, } impl Order { pub fn new() -> Order { Order { id: "".to_string(), custom_id: "".to_string(), price: Default::default(), amount: Default::default(), deal_amount: Default::default(), avg_price: Default::default(), status: "".to_string(), order_type: "".to_string(), trace_stack: TraceStack::new(0, Instant::now()), } } } /// Ticker结构体(市场行情) /// - `time(i64)`: 毫秒级别时间戳 /// - `high(Decimal)`: 最高价 /// - `low(Decimal)`: 最低价 /// - `sell(Decimal)`: 卖一价 /// - `buy(Decimal)`: 买一价 /// - `last(Decimal)`: 最后成交价 /// - `volume(Decimal)`: 最近成交量 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Ticker { pub time: i64, pub high: Decimal, pub low: Decimal, pub sell: Decimal, pub buy: Decimal, pub last: Decimal, pub volume: Decimal, } impl Ticker { pub fn new() -> Ticker { Ticker { time: 0, high: Default::default(), low: Default::default(), sell: Default::default(), buy: Default::default(), last: Default::default(), volume: Default::default(), } } } /// Market结构体(交易品种的市场信息) /// - `symbol(String)`: 交易对 /// - `base_asset(String)`: 交易币 /// - `quote_asset(String)`: 计价币 /// - `tick_size(Decimal)`: 价格最小变动数值 /// - `amount_size(Decimal)`: 下单量最小变动数值 /// - `price_precision(Decimal)`: 价格精度 /// - `amount_precision(Decimal)`: 下单量精度 /// - `min_qty(Decimal)`: 最小下单量 /// - `max_qty(Decimal)`: 最大下单量 /// - `min_notional(Decimal)`: 最小下单金额 /// - `max_notional(Decimal)`: 最大下单金额 /// - `ct_val(Decimal)`: 合约价值 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Market { pub symbol: String, pub base_asset: String, pub quote_asset: String, pub tick_size: Decimal, pub amount_size: Decimal, pub price_precision: Decimal, pub amount_precision: Decimal, pub min_qty: Decimal, pub max_qty: Decimal, pub min_notional: Decimal, pub max_notional: Decimal, pub ct_val: Decimal, } impl Market { pub fn new() -> Market { Market { symbol: "".to_string(), base_asset: "".to_string(), quote_asset: "".to_string(), tick_size: Default::default(), amount_size: Default::default(), price_precision: Default::default(), amount_precision: Default::default(), min_qty: Default::default(), max_qty: Default::default(), min_notional: Default::default(), max_notional: Default::default(), ct_val: Default::default(), } } } /// Position结构体(仓位信息) /// - `symbol(String)`: 币对 /// - `margin_level(Decimal)`: 持仓杆杠大小 /// - `amount(Decimal)`: 持仓量 /// - `frozen_amount(Decimal)`: 仓位冻结量 /// - `price(Decimal)`: 持仓均价 /// - `profit(Decimal)`: 持仓浮动盈亏 /// - `position_mode(PositionModeEnum)`: 持仓模式 /// - `margin(Decimal)`: 仓位占用的保证金 #[derive(Debug, Clone, PartialEq, Eq)] pub struct Position { pub symbol: String, pub margin_level: Decimal, pub amount: Decimal, pub frozen_amount: Decimal, pub price: Decimal, pub profit: Decimal, pub position_mode: PositionModeEnum, pub margin: Decimal, } impl Position { pub fn new() -> Position { Position { symbol: "".to_string(), margin_level: Default::default(), amount: Default::default(), frozen_amount: Default::default(), price: Default::default(), profit: Default::default(), position_mode: PositionModeEnum::Both, margin: Default::default(), } } } /// 交易所统一方法接口 /// /// 使用方法前需实例化 /// ```rust /// use std::collections::BTreeMap; /// use standard::exchange::{Exchange, ExchangeEnum}; /// /// let mut params:BTreeMap = BTreeMap::new(); /// params.insert("access_key".to_string(), "your_access_key".to_string()); /// params.insert("access_key".to_string(), "your_secret_key".to_string()); /// // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// ``` /// 获取当前交易所交易模式 /// - fn get_self_exchange(&self) -> ExchangeEnum; /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.get_self_exchange(); /// ``` /// 获取当前是否使用高速模式 /// - fn get_self_is_colo(&self) -> bool; /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.get_self_is_colo(); /// ``` /// 获取当前是否使用登录 /// - fn get_self_is_login(&self) -> bool; /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.get_self_is_login(); /// ``` /// 获取登录params信息 /// - fn get_self_params(&self) -> BTreeMap; /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.get_self_params(); /// ``` /// 获取账号信息 /// - async fn get_account(&self, symbol: &str) -> Result; /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.get_account() /// ``` /// 订阅账号信息 /// ```rust /// # use std::collections::BTreeMap; /// # use standard::exchange::{Exchange, ExchangeEnum}; /// # let mut params:BTreeMap = BTreeMap::new(); /// # params.insert("access_key".to_string(), "your_access_key".to_string()); /// # params.insert("access_key".to_string(), "your_secret_key".to_string()); /// # // let exchange = Exchange::new(ExchangeEnum::BinanceSwap, "BTC_USDT".to_string(), true, params); /// /// // exchange.subscribe_account(); /// ``` #[async_trait] pub trait Platform { fn clone_box(&self) -> Box; // 获取当前交易所交易模式 fn get_self_exchange(&self) -> ExchangeEnum; // 获取交易对 fn get_self_symbol(&self) -> String; // 获取当前是否使用高速模式 fn get_self_is_colo(&self) -> bool; // 获取登录params信息 fn get_self_params(&self) -> BTreeMap; // 获取market信息 fn get_self_market(&self) -> Market; // 获取请求时间 fn get_request_delays(&self) -> Vec; // 获取请求平均时间 fn get_request_avg_delay(&self) -> Decimal; // 获取请求最大时间 fn get_request_max_delay(&self) -> i64; // 获取服务器时间 async fn get_server_time(&mut self) -> Result; // 获取账号信息 async fn get_account(&mut self) -> Result; // 获取现货账号信息 async fn get_spot_account(&mut self) -> Result, Error>; // 获取持仓信息 async fn get_position(&mut self) -> Result, Error>; // 获取所有持仓 async fn get_positions(&mut self) -> Result, Error>; // 获取市场行情 async fn get_ticker(&mut self) -> Result; // 获取市场行情自定义交易对 async fn get_ticker_symbol(&mut self, symbol: String) -> Result; // 查询所有的市场信息 async fn get_market(&mut self) -> Result; // 查询所有的市场信息自定义交易对 async fn get_market_symbol(&mut self, symbol: String) -> Result; // 查询订单详情 async fn get_order_detail(&mut self, order_id: &str, custom_id: &str) -> Result; // 获取订单列表 async fn get_orders_list(&mut self, status: &str) -> Result, Error>; // 下单接口 async fn take_order(&mut self, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result; // 下单接口自定义交易对 async fn take_order_symbol(&mut self, symbol: String, ct_val: Decimal, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result; // 撤销订单 async fn cancel_order(&mut self, order_id: &str, custom_id: &str) -> Result; // 批量撤销订单 async fn cancel_orders(&mut self) -> Result, Error>; // 撤销所有订单 async fn cancel_orders_all(&mut self) -> Result, Error>; /// 下一个止损单 /// - stop_price: 触发价 /// - price: 委托价,0就市价委托 /// - side: 止损哪个方向[long多单,short空单] async fn take_stop_loss_order(&mut self, stop_price: Decimal, price: Decimal, side: &str) -> Result; /// 撤销止损订单 /// - order_id: 需要撤销的id async fn cancel_stop_loss_order(&mut self, order_id: &str) -> Result; // 设置持仓模式 async fn set_dual_mode(&mut self, coin: &str, is_dual_mode: bool) -> Result; // 更新双持仓模式下杠杆 async fn set_dual_leverage(&mut self, leverage: &str) -> Result; // 设置自动追加保证金 async fn set_auto_deposit_status(&mut self, status: bool) -> Result; // 交易账户互转 async fn wallet_transfers(&mut self, coin: &str, from: &str, to: &str, amount: Decimal) -> Result; // 指令下单 async fn command_order(&mut self, order_command: &mut OrderCommand, trace_stack: &TraceStack); }