| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- use std::collections::{BTreeMap};
- use std::io::{Error};
- use async_trait::async_trait;
- use rust_decimal::Decimal;
- use serde_json::Value;
- use serde::{Serialize, Deserialize};
- use crate::exchange::ExchangeEnum;
- // 引入工具模块
- pub mod utils;
- // 引入exchange模块
- pub mod exchange;
- pub mod exchange_struct_handler;
- // 引入gate模块
- mod gate_swap;
- pub mod gate_swap_handle;
- pub mod coinex_swap;
- pub mod coinex_swap_handle;
- pub mod binance_swap;
- pub mod binance_swap_handle;
- pub mod phemex_swap;
- pub mod phemex_swap_handle;
- pub mod mexc_swap;
- pub mod mexc_swap_handle;
- pub mod bybit_swap;
- pub mod bybit_swap_handle;
- pub mod bitget_swap;
- pub mod bitget_swap_handle;
- pub mod gate_spot;
- pub mod gate_spot_handle;
- /// 持仓模式枚举
- /// - `Both`:单持仓方向
- /// - `LONG`:多仓
- /// - `SHORT`:空仓
- #[derive(Debug, Clone, PartialEq, Eq)]
- pub enum PositionModeEnum {
- Both,
- Long,
- Short,
- }
- /// 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(),
- }
- }
- }
- /// 交易结构体(订单流)
- /// - `id(String)`: id
- /// - `time(Decimal)`: 交易更新时间戳(ms)
- /// - `size(Decimal)`: 交易量,负数是卖方
- /// - `price(Decimal)`: 成交价格
- /// - `symbol(String)`: 成交符号
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct Trade {
- pub id: String,
- pub time: Decimal,
- pub size: Decimal,
- pub price: Decimal,
- pub symbol: String
- }
- /// 特殊压缩结构体(订单流)
- /// - `0(Decimal)`: id
- /// - `1(Decimal)`: 交易更新时间戳(ms)
- /// - `2(Decimal)`: 交易量,负数是卖方
- /// - `3(Decimal)`: 成交价格
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct SpecialTrade(pub Vec<String>);
- impl SpecialTrade {
- // 获取内部 Vec<Decimal> 的引用
- pub fn inner(&self) -> &Vec<String> {
- &self.0
- }
- // 获取内部 Vec<Decimal> 的可变引用
- pub fn inner_mut(&mut self) -> &mut Vec<String> {
- &mut self.0
- }
- // 索引访问特定元素
- pub fn get(&self, index: usize) -> Option<&String> {
- self.0.get(index)
- }
- pub fn new(trade: &Trade) -> SpecialTrade {
- SpecialTrade(vec![trade.id.clone(), trade.time.to_string(), trade.size.to_string(), trade.price.to_string()])
- }
- }
- /// Depth结构体(市场深度)
- /// - `time(Decimal)`: 深度更新时间戳(ms);
- /// - `symbol(String)`: 币对符号;
- /// - `asks(Vec<MarketOrder>)`: 卖方深度列表;
- /// - `bids(Vec<MarketOrder>)`: 买方深度列表;
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct Depth {
- pub time: Decimal,
- pub symbol: String,
- pub asks: Vec<OrderBook>,
- pub bids: Vec<OrderBook>,
- }
- impl Depth {
- pub fn new() -> Depth {
- Depth {
- time: Decimal::ZERO,
- symbol: String::new(),
- asks: vec![],
- bids: vec![],
- }
- }
- }
- /// 特殊Depth结构体(市场深度),用于存放到本地数据库中
- /// - `a(Vec<Vec<Decimal>>)`: asks;
- /// - `b(Vec<Vec<Decimal>>)`: bids;
- /// - `t(Decimal)`: 数据生成时间
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct SpecialDepth {
- pub b: Vec<Vec<Decimal>>,
- pub a: Vec<Vec<Decimal>>,
- pub t: Decimal,
- }
- impl SpecialDepth {
- pub fn new(depth: &Depth) -> SpecialDepth {
- let bids = depth.bids.iter().map(|ob| vec![ob.price, ob.amount]).collect::<Vec<_>>();
- let asks = depth.asks.iter().map(|ob| vec![ob.price, ob.amount]).collect::<Vec<_>>();
- SpecialDepth {
- b: bids,
- a: asks,
- t: depth.time,
- }
- }
- }
- // 简易深度信息
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct SimpleDepth {
- pub time: Decimal,
- pub size: Decimal,
- pub b1: Decimal,
- pub a1: Decimal,
- pub symbol: String,
- }
- impl SimpleDepth {
- pub fn new(depth: &Depth) -> SimpleDepth {
- let mut total_size = Decimal::ZERO;
- for ask in &depth.asks {
- total_size += ask.price * ask.amount;
- }
- for bid in &depth.bids {
- total_size += bid.price * bid.amount;
- }
- total_size.rescale(2);
- SimpleDepth {
- time: depth.time,
- size: total_size,
- b1: depth.bids[0].price,
- a1: depth.asks[0].price,
- symbol: depth.symbol.clone(),
- }
- }
- }
- /// 特殊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,
- }
- }
- }
- /// OrderBook结构体(市场深度单)
- /// - `price(Decimal)`: 价格
- /// - `amount(Decimal)`: 数量
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct OrderBook {
- pub price: Decimal,
- pub amount: Decimal,
- }
- impl OrderBook {
- pub fn new() -> OrderBook {
- OrderBook {
- price: Default::default(),
- amount: Default::default(),
- }
- }
- }
- /// Record结构体(标准的OHLC结构)
- /// - `time(i64)`: 时间戳;
- /// - `open(Decimal)`: 开盘价;
- /// - `high(Decimal)`: 最高价;
- /// - `low(Decimal):` 最低价;
- /// - `close(Decimal)`: 收盘价;
- /// - `volume(Decimal)`: 交易量;
- /// - `symbol(String)`: 交易对;
- #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
- pub struct Record {
- pub time: Decimal,
- pub open: Decimal,
- pub high: Decimal,
- pub low: Decimal,
- pub close: Decimal,
- pub volume: Decimal,
- pub symbol: String
- }
- impl Record {
- pub fn new() -> Record {
- Record {
- time: Default::default(),
- open: Default::default(),
- high: Default::default(),
- low: Default::default(),
- close: Default::default(),
- volume: Default::default(),
- symbol: "".to_string(),
- }
- }
- }
- /// 特殊Order结构体(订单)
- /// - `name<String>`: 平台信息;
- /// - `order<Vec<Order>>`: 订单信息数组;
- #[derive(Debug, Clone, PartialEq, Eq)]
- pub struct SpecialOrder {
- pub name: String,
- pub order: Vec<Order>,
- }
- 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,
- }
- 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()
- }
- }
- }
- /// 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<String,String> = 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<String,String> = 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<String,String> = 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<String,String> = 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<String, String>;
- /// ```rust
- /// # use std::collections::BTreeMap;
- /// # use standard::exchange::{Exchange, ExchangeEnum};
- /// # let mut params:BTreeMap<String,String> = 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<Account, Error>;
- /// ```rust
- /// # use std::collections::BTreeMap;
- /// # use standard::exchange::{Exchange, ExchangeEnum};
- /// # let mut params:BTreeMap<String,String> = 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<String,String> = 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<dyn Platform + Send + Sync>;
- // 获取当前交易所交易模式
- 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<String, String>;
- // 获取market信息
- fn get_self_market(&self) -> Market;
- // 获取请求时间
- fn get_request_delays(&self) -> Vec<i64>;
- // 获取请求平均时间
- fn get_request_avg_delay(&self) -> Decimal;
- // 获取请求最大时间
- fn get_request_max_delay(&self) -> i64;
- // 获取服务器时间
- async fn get_server_time(&mut self) -> Result<String, Error>;
- // 获取账号信息
- async fn get_account(&mut self) -> Result<Account, Error>;
- // 获取现货账号信息
- async fn get_spot_account(&mut self) -> Result<Vec<Account>, Error>;
- // 获取持仓信息
- async fn get_position(&mut self) -> Result<Vec<Position>, Error>;
- // 获取所有持仓
- async fn get_positions(&mut self) -> Result<Vec<Position>, Error>;
- // 获取市场行情
- async fn get_ticker(&mut self) -> Result<Ticker, Error>;
- // 获取市场行情自定义交易对
- async fn get_ticker_symbol(&mut self, symbol: String) -> Result<Ticker, Error>;
- // 查询所有的市场信息
- async fn get_market(&mut self) -> Result<Market, Error>;
- // 查询所有的市场信息自定义交易对
- async fn get_market_symbol(&mut self, symbol: String) -> Result<Market, Error>;
- // 查询订单详情
- async fn get_order_detail(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error>;
- // 获取订单列表
- async fn get_orders_list(&mut self, status: &str) -> Result<Vec<Order>, Error>;
- // 下单接口
- async fn take_order(&mut self, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error>;
- // 下单接口自定义交易对
- async fn take_order_symbol(&mut self, symbol: String, ct_val: Decimal, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error>;
- // 撤销订单
- async fn cancel_order(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error>;
- // 批量撤销订单
- async fn cancel_orders(&mut self) -> Result<Vec<Order>, Error>;
- // 撤销所有订单
- async fn cancel_orders_all(&mut self) -> Result<Vec<Order>, Error>;
- /// 下一个止损单
- /// - stop_price: 触发价
- /// - price: 委托价,0就市价委托
- /// - side: 止损哪个方向[long多单,short空单]
- async fn take_stop_loss_order(&mut self, stop_price: Decimal, price: Decimal, side: &str) -> Result<Value, Error>;
- /// 撤销止损订单
- /// - order_id: 需要撤销的id
- async fn cancel_stop_loss_order(&mut self, order_id: &str) -> Result<Value, Error>;
- // 设置持仓模式
- async fn set_dual_mode(&mut self, coin: &str, is_dual_mode: bool) -> Result<String, Error>;
- // 更新双持仓模式下杠杆
- async fn set_dual_leverage(&mut self, leverage: &str) -> Result<String, Error>;
- // 设置自动追加保证金
- async fn set_auto_deposit_status(&mut self, status: bool) -> Result<String, Error>;
- // 交易账户互转
- async fn wallet_transfers(&mut self, coin: &str, from: &str, to: &str, amount: Decimal) -> Result<String, Error>;
- }
|