|
@@ -0,0 +1,319 @@
|
|
|
|
|
+use std::collections::{BTreeMap};
|
|
|
|
|
+use std::io::{Error, ErrorKind};
|
|
|
|
|
+use std::str::FromStr;
|
|
|
|
|
+use tokio::sync::mpsc::Sender;
|
|
|
|
|
+use async_trait::async_trait;
|
|
|
|
|
+use rust_decimal::{Decimal, MathematicalOps};
|
|
|
|
|
+use rust_decimal::prelude::{FromPrimitive, ToPrimitive};
|
|
|
|
|
+use serde_json::{json, Value};
|
|
|
|
|
+use tracing::{error, info};
|
|
|
|
|
+use crate::{Platform, ExchangeEnum, Account, Position, Ticker, Market, Order, PositionModeEnum, utils};
|
|
|
|
|
+use exchanges::bingx_swap_rest::BingxSwapRest;
|
|
|
|
|
+
|
|
|
|
|
+#[allow(dead_code)]
|
|
|
|
|
+#[derive(Clone)]
|
|
|
|
|
+pub struct BingxSwap {
|
|
|
|
|
+ exchange: ExchangeEnum,
|
|
|
|
|
+ symbol: String,
|
|
|
|
|
+ is_colo: bool,
|
|
|
|
|
+ params: BTreeMap<String, String>,
|
|
|
|
|
+ request: BingxSwapRest,
|
|
|
|
|
+ market: Market,
|
|
|
|
|
+ order_sender: Sender<Order>,
|
|
|
|
|
+ error_sender: Sender<Error>,
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+impl BingxSwap {
|
|
|
|
|
+ pub async fn new(symbol: String, is_colo: bool, params: BTreeMap<String, String>, order_sender: Sender<Order>, error_sender: Sender<Error>) -> BingxSwap {
|
|
|
|
|
+ let market = Market::new();
|
|
|
|
|
+ let mut bingx_swap = BingxSwap {
|
|
|
|
|
+ exchange: ExchangeEnum::BingxSwap,
|
|
|
|
|
+ symbol: symbol.to_uppercase(),
|
|
|
|
|
+ is_colo,
|
|
|
|
|
+ params: params.clone(),
|
|
|
|
|
+ request: BingxSwapRest::new(is_colo, params.clone()),
|
|
|
|
|
+ market,
|
|
|
|
|
+ order_sender,
|
|
|
|
|
+ error_sender,
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ // 修改持仓模式
|
|
|
|
|
+ let symbol_array: Vec<&str> = symbol.split("_").collect();
|
|
|
|
|
+ let mode_result = bingx_swap.set_dual_mode(symbol_array[1], true).await;
|
|
|
|
|
+ match mode_result {
|
|
|
|
|
+ Ok(ok) => {
|
|
|
|
|
+ info!("Bingx:设置持仓模式成功!{:?}", ok);
|
|
|
|
|
+ }
|
|
|
|
|
+ Err(error) => {
|
|
|
|
|
+ error!("Bingx:设置持仓模式失败!mode_result={}", error)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取市场信息
|
|
|
|
|
+ bingx_swap.market = BingxSwap::get_market(&mut bingx_swap).await.unwrap_or(bingx_swap.market);
|
|
|
|
|
+ return bingx_swap;
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+#[async_trait]
|
|
|
|
|
+impl Platform for BingxSwap {
|
|
|
|
|
+ // 克隆方法
|
|
|
|
|
+ fn clone_box(&self) -> Box<dyn Platform + Send + Sync> { Box::new(self.clone()) }
|
|
|
|
|
+ // 获取交易所模式
|
|
|
|
|
+ fn get_self_exchange(&self) -> ExchangeEnum {
|
|
|
|
|
+ ExchangeEnum::BingxSwap
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取交易对
|
|
|
|
|
+ fn get_self_symbol(&self) -> String { self.symbol.clone() }
|
|
|
|
|
+ // 获取是否使用高速通道
|
|
|
|
|
+ fn get_self_is_colo(&self) -> bool {
|
|
|
|
|
+ self.is_colo
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取params信息
|
|
|
|
|
+ fn get_self_params(&self) -> BTreeMap<String, String> {
|
|
|
|
|
+ self.params.clone()
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取market信息
|
|
|
|
|
+ fn get_self_market(&self) -> Market { self.market.clone() }
|
|
|
|
|
+ // 获取请求时间
|
|
|
|
|
+ fn get_request_delays(&self) -> Vec<i64> { self.request.get_delays() }
|
|
|
|
|
+ // 获取请求平均时间
|
|
|
|
|
+ fn get_request_avg_delay(&self) -> Decimal { self.request.get_avg_delay() }
|
|
|
|
|
+ // 获取请求最大时间
|
|
|
|
|
+ fn get_request_max_delay(&self) -> i64 { self.request.get_max_delay() }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取服务器时间
|
|
|
|
|
+ async fn get_server_time(&mut self) -> Result<String, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取账号信息
|
|
|
|
|
+ async fn get_account(&mut self) -> Result<Account, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn get_spot_account(&mut self) -> Result<Vec<Account>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取持仓信息
|
|
|
|
|
+ async fn get_position(&mut self) -> Result<Vec<Position>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取所有持仓
|
|
|
|
|
+ async fn get_positions(&mut self) -> Result<Vec<Position>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取市场行情
|
|
|
|
|
+ async fn get_ticker(&mut self) -> Result<Ticker, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn get_ticker_symbol(&mut self, _symbol: String) -> Result<Ticker, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn get_market(&mut self) -> Result<Market, Error> {
|
|
|
|
|
+ let symbol_format = utils::format_symbol(self.symbol.clone(), "-");
|
|
|
|
|
+ let params = json!({});
|
|
|
|
|
+ let res_data = self.request.get_market(params).await;
|
|
|
|
|
+ if res_data.code == 200 {
|
|
|
|
|
+ let res_data_json = res_data.data.as_array().unwrap();
|
|
|
|
|
+ let market_info = res_data_json.iter().find(|item| item["symbol"].as_str().unwrap() == symbol_format);
|
|
|
|
|
+ match market_info {
|
|
|
|
|
+ None => {
|
|
|
|
|
+ error!("bingx_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
|
|
|
|
|
+ Err(Error::new(ErrorKind::Other, res_data.to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ Some(value) => {
|
|
|
|
|
+ let name = value["symbol"].as_str().unwrap();
|
|
|
|
|
+ let name_array: Vec<&str> = name.split("-").collect();
|
|
|
|
|
+ let price_precision = Decimal::from_str(&value["pricePrecision"].to_string()).unwrap();
|
|
|
|
|
+ let tick_size = Decimal::TEN.powd(Decimal::NEGATIVE_ONE * price_precision);
|
|
|
|
|
+ let amount_precision = Decimal::from_str(&value["quantityPrecision"].to_string()).unwrap();
|
|
|
|
|
+ let amount_size = Decimal::TEN.powd(Decimal::NEGATIVE_ONE * amount_precision);
|
|
|
|
|
+ let min_qty = Decimal::from_str(&value["tradeMinUSDT"].to_string()).unwrap();
|
|
|
|
|
+ let max_qty = Decimal::NEGATIVE_ONE;
|
|
|
|
|
+ let ct_val = Decimal::ONE;
|
|
|
|
|
+
|
|
|
|
|
+ let result = Market {
|
|
|
|
|
+ symbol: name_array.join("_"),
|
|
|
|
|
+ base_asset: name_array[0].to_string(),
|
|
|
|
|
+ quote_asset: name_array[1].to_string(),
|
|
|
|
|
+ tick_size,
|
|
|
|
|
+ amount_size,
|
|
|
|
|
+ price_precision,
|
|
|
|
|
+ amount_precision,
|
|
|
|
|
+ min_qty,
|
|
|
|
|
+ max_qty,
|
|
|
|
|
+ min_notional: min_qty,
|
|
|
|
|
+ max_notional: max_qty,
|
|
|
|
|
+ ct_val,
|
|
|
|
|
+ };
|
|
|
|
|
+ Ok(result)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ Err(Error::new(ErrorKind::Other, res_data.to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn get_market_symbol(&mut self, symbol: String) -> Result<Market, Error> {
|
|
|
|
|
+ let symbol_format = utils::format_symbol(symbol.clone(), "-");
|
|
|
|
|
+ let params = json!({
|
|
|
|
|
+ "symbol": symbol_format.clone()
|
|
|
|
|
+ });
|
|
|
|
|
+ let res_data = self.request.get_market(params).await;
|
|
|
|
|
+ if res_data.code == 200 {
|
|
|
|
|
+ let res_data_json = res_data.data.as_array().unwrap();
|
|
|
|
|
+ let market_info = res_data_json.iter().find(|item| item["symbol"].as_str().unwrap() == symbol_format);
|
|
|
|
|
+ match market_info {
|
|
|
|
|
+ None => {
|
|
|
|
|
+ error!("bingx_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
|
|
|
|
|
+ Err(Error::new(ErrorKind::Other, res_data.to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ Some(value) => {
|
|
|
|
|
+ let name = value["symbol"].as_str().unwrap();
|
|
|
|
|
+ let name_array: Vec<&str> = name.split("-").collect();
|
|
|
|
|
+ let price_precision = Decimal::from_str(&value["pricePrecision"].to_string()).unwrap();
|
|
|
|
|
+ let tick_size = Decimal::TEN.powd(Decimal::NEGATIVE_ONE * price_precision);
|
|
|
|
|
+ let amount_precision = Decimal::from_str(&value["quantityPrecision"].to_string()).unwrap();
|
|
|
|
|
+ let amount_size = Decimal::TEN.powd(Decimal::NEGATIVE_ONE * amount_precision);
|
|
|
|
|
+ let min_qty = Decimal::from_str(&value["tradeMinUSDT"].to_string()).unwrap();
|
|
|
|
|
+ let max_qty = Decimal::NEGATIVE_ONE;
|
|
|
|
|
+ let ct_val = Decimal::ONE;
|
|
|
|
|
+
|
|
|
|
|
+ let result = Market {
|
|
|
|
|
+ symbol: name_array.join("_"),
|
|
|
|
|
+ base_asset: name_array[0].to_string(),
|
|
|
|
|
+ quote_asset: name_array[1].to_string(),
|
|
|
|
|
+ tick_size,
|
|
|
|
|
+ amount_size,
|
|
|
|
|
+ price_precision,
|
|
|
|
|
+ amount_precision,
|
|
|
|
|
+ min_qty,
|
|
|
|
|
+ max_qty,
|
|
|
|
|
+ min_notional: min_qty,
|
|
|
|
|
+ max_notional: max_qty,
|
|
|
|
|
+ ct_val,
|
|
|
|
|
+ };
|
|
|
|
|
+ Ok(result)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ Err(Error::new(ErrorKind::Other, res_data.to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 获取订单详情
|
|
|
|
|
+ async fn get_order_detail(&mut self, _order_id: &str, _custom_id: &str) -> Result<Order, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 获取订单列表
|
|
|
|
|
+ async fn get_orders_list(&mut self, _status: &str) -> Result<Vec<Order>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 下单接口
|
|
|
|
|
+ async fn take_order(&mut self, _custom_id: &str, _origin_side: &str, _price: Decimal, _amount: Decimal) -> Result<Order, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ 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> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 撤销订单
|
|
|
|
|
+ async fn cancel_order(&mut self, _order_id: &str, _custom_id: &str) -> Result<Order, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+ // 批量撤销订单
|
|
|
|
|
+ async fn cancel_orders(&mut self) -> Result<Vec<Order>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn cancel_orders_all(&mut self) -> Result<Vec<Order>, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn take_stop_loss_order(&mut self, _stop_price: Decimal, _price: Decimal, _side: &str) -> Result<Value, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn cancel_stop_loss_order(&mut self, _order_id: &str) -> Result<Value, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 设置持仓模式
|
|
|
|
|
+ async fn set_dual_mode(&mut self, _coin: &str, _is_dual_mode: bool) -> Result<String, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 更新双持仓模式下杠杆
|
|
|
|
|
+ async fn set_dual_leverage(&mut self, _leverage: &str) -> Result<String, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ async fn set_auto_deposit_status(&mut self, _status: bool) -> Result<String, Error> { Err(Error::new(ErrorKind::NotFound, "bingx:该交易所方法未实现".to_string())) }
|
|
|
|
|
+
|
|
|
|
|
+ // 交易账户互转
|
|
|
|
|
+ async fn wallet_transfers(&mut self, _coin: &str, _from: &str, _to: &str, _amount: Decimal) -> Result<String, Error> {
|
|
|
|
|
+ Err(Error::new(ErrorKind::NotFound, "bingx_swap:该交易所方法未实现".to_string()))
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub fn format_position_item(position: &Value, ct_val: Decimal) -> Position {
|
|
|
|
|
+ let mut position_mode = match position["mode"].as_str().unwrap_or("") {
|
|
|
|
|
+ "single" => PositionModeEnum::Both,
|
|
|
|
|
+ "dual_long" => PositionModeEnum::Long,
|
|
|
|
|
+ "dual_short" => PositionModeEnum::Short,
|
|
|
|
|
+ _ => {
|
|
|
|
|
+ error!("bingx_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position);
|
|
|
|
|
+ panic!("bingx_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position)
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+ let size = Decimal::from_str(&position["size"].to_string()).unwrap();
|
|
|
|
|
+ let amount = size * ct_val;
|
|
|
|
|
+ match position_mode {
|
|
|
|
|
+ PositionModeEnum::Both => {
|
|
|
|
|
+ position_mode = match amount {
|
|
|
|
|
+ amount if amount > Decimal::ZERO => PositionModeEnum::Long,
|
|
|
|
|
+ amount if amount < Decimal::ZERO => PositionModeEnum::Short,
|
|
|
|
|
+ _ => { PositionModeEnum::Both }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ _ => {}
|
|
|
|
|
+ }
|
|
|
|
|
+ Position {
|
|
|
|
|
+ symbol: position["contract"].as_str().unwrap_or("").parse().unwrap(),
|
|
|
|
|
+ margin_level: Decimal::from_str(position["leverage"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ amount,
|
|
|
|
|
+ frozen_amount: Decimal::ZERO,
|
|
|
|
|
+ price: Decimal::from_str(position["entry_price"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ profit: Decimal::from_str(position["unrealised_pnl"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ position_mode,
|
|
|
|
|
+ margin: Decimal::from_str(position["margin"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ }
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+pub fn format_order_item(order: Value, ct_val: Decimal) -> Order {
|
|
|
|
|
+ let status = order["status"].as_str().unwrap_or("");
|
|
|
|
|
+ let text = order["text"].as_str().unwrap_or("");
|
|
|
|
|
+ let size = Decimal::from_str(&order["size"].to_string()).unwrap();
|
|
|
|
|
+ let left = Decimal::from_str(&order["left"].to_string()).unwrap();
|
|
|
|
|
+
|
|
|
|
|
+ let amount = size * ct_val;
|
|
|
|
|
+ let deal_amount = (size - left) * ct_val;
|
|
|
|
|
+ let custom_status = if status == "finished" { "REMOVE".to_string() } else if status == "open" { "NEW".to_string() } else {
|
|
|
|
|
+ error!("bingx_swap:格式化订单状态错误!\nformat_order_item:order={:?}", order);
|
|
|
|
|
+ panic!("bingx_swap:格式化订单状态错误!\nformat_order_item:order={:?}", order)
|
|
|
|
|
+ };
|
|
|
|
|
+ let rst_order = Order {
|
|
|
|
|
+ id: order["id"].to_string(),
|
|
|
|
|
+ custom_id: text.replace("t-my-custom-id_", "").replace("t-", ""),
|
|
|
|
|
+ price: Decimal::from_str(order["price"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ amount,
|
|
|
|
|
+ deal_amount,
|
|
|
|
|
+ avg_price: Decimal::from_str(&order["fill_price"].as_str().unwrap()).unwrap(),
|
|
|
|
|
+ status: custom_status,
|
|
|
|
|
+ order_type: "limit".to_string(),
|
|
|
|
|
+ };
|
|
|
|
|
+ return rst_order;
|
|
|
|
|
+}
|