JiahengHe 1 anno fa
parent
commit
9a3598811f

+ 2 - 2
exchanges/src/bybit_swap_ws.rs

@@ -71,10 +71,10 @@ impl BybitSwapWs {
         /*******公共频道-私有频道数据组装*/
         let address_url = match ws_type {
             BybitSwapWsType::Public => {
-                "wss://stream.bybit.com/v5/public/linear?max_alive_time=1m".to_string()
+                "wss://stream.bybit.com/v5/public/linear?max_alive_time=10m".to_string()
             }
             BybitSwapWsType::Private => {
-                "wss://stream.bybit.com/v5/private?max_alive_time=1m".to_string()
+                "wss://stream.bybit.com/v5/private?max_alive_time=10m".to_string()
             }
         };
 

+ 7 - 5
exchanges/src/socket_tool.rs

@@ -64,7 +64,7 @@ impl AbstractWsMode {
         };
         // 如果不需要事先登录,则直接订阅消息
         if !is_first_login {
-            info!("不需要登录,订阅内容:{:?}", subscribe_array.clone());
+            info!("不需要登录,订阅内容:{:?}", subscribe_array.clone());
             for s in &subscribe_array {
                 let mut write_lock = ws_write_arc.lock().await;
                 write_lock.send(Message::Text(s.parse().unwrap())).await.expect("订阅消息失败");
@@ -114,11 +114,13 @@ impl AbstractWsMode {
                             //登录成功
                             info!("ws登录成功:{:?}", data);
                             info!("订阅内容:{:?}", subscribe_array.clone());
-                            for s in &subscribe_array {
-                                let mut write_lock = ws_write_arc.lock().await;
-                                write_lock.send(Message::Text(s.parse().unwrap())).await.expect("订阅消息失败");
+                            if is_first_login {
+                                for s in &subscribe_array {
+                                    let mut write_lock = ws_write_arc.lock().await;
+                                    write_lock.send(Message::Text(s.parse().unwrap())).await.expect("订阅消息失败");
+                                }
+                                info!("订阅完成!");
                             }
-                            info!("订阅完成!");
                         }
                         -201 => {
                             //订阅成功

+ 748 - 748
standard/src/bybit_swap.rs

@@ -1,748 +1,748 @@
-// use std::collections::{BTreeMap};
-// use std::io::{Error, ErrorKind};
-// use std::str::FromStr;
-// use tokio::sync::mpsc::Sender;
-// use async_trait::async_trait;
-// use futures::stream::FuturesUnordered;
-// use futures::TryStreamExt;
-// use rust_decimal::Decimal;
-// use serde_json::{from_value, json, Value};
-// use rust_decimal::prelude::FromPrimitive;
-// use serde::{Deserialize, Serialize};
-// use tokio::time::Instant;
-// use tracing::{error, info, trace};
-// use exchanges::bybit_swap_rest::BybitSwapRest;
-// use crate::{Platform, ExchangeEnum, Account, Position, Ticker, Market, Order, OrderCommand, PositionModeEnum};
-// use global::trace_stack::TraceStack;
-//
-// #[derive(Debug, Clone, Deserialize, Serialize)]
-// #[serde(rename_all = "camelCase")]
-// struct SwapTicker {
-//     symbol: String,
-//     high_price24h: Decimal,
-//     low_price24h: Decimal,
-//     bid1_price: Decimal,
-//     ask1_price: Decimal,
-//     last_price: Decimal,
-//     volume24h: Decimal
-// }
-//
-// #[allow(dead_code)]
-// #[derive(Clone)]
-// pub struct BybitSwap {
-//     exchange: ExchangeEnum,
-//     symbol: String,
-//     symbol_uppercase: String,
-//     is_colo: bool,
-//     params: BTreeMap<String, String>,
-//     request: BybitSwapRest,
-//     market: Market,
-//     order_sender: Sender<Order>,
-//     error_sender: Sender<Error>,
-// }
-//
-// impl BybitSwap {
-//     pub async fn new(symbol: String, is_colo: bool, params: BTreeMap<String, String>, order_sender: Sender<Order>, error_sender: Sender<Error>) -> BybitSwap {
-//         let market = Market::new();
-//         let mut bybit_swap = BybitSwap {
-//             exchange: ExchangeEnum::BybitSwap,
-//             symbol: symbol.to_uppercase(),
-//             symbol_uppercase: symbol.replace("_", "").to_uppercase(),
-//             is_colo,
-//             params: params.clone(),
-//             request: BybitSwapRest::new(is_colo, params.clone()),
-//             market,
-//             order_sender,
-//             error_sender,
-//         };
-//
-//         // 修改持仓模式
-//         let symbol_array: Vec<&str> = symbol.split("_").collect();
-//         let mode_result = bybit_swap.set_dual_mode(symbol_array[1], true).await;
-//         match mode_result {
-//             Ok(_) => {
-//                 trace!("Bybit:设置持仓模式成功!")
-//             }
-//             Err(error) => {
-//                 error!("Bybit:设置持仓模式失败!mode_result={}", error)
-//             }
-//         }
-//         // 获取市场信息
-//         bybit_swap.market = BybitSwap::get_market(&mut bybit_swap).await.unwrap_or(bybit_swap.market);
-//         return bybit_swap;
-//     }
-// }
-//
-// #[async_trait]
-// impl Platform for BybitSwap {
-//     // 克隆方法
-//     fn clone_box(&self) -> Box<dyn Platform + Send + Sync> { Box::new(self.clone()) }
-//     // 获取交易所模式
-//     fn get_self_exchange(&self) -> ExchangeEnum {
-//         ExchangeEnum::GateSwap
-//     }
-//     // 获取交易对
-//     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> {
-//         let res_data = self.request.get_server_time().await;
-//         if res_data.code == 200 {
-//             let result = res_data.data["server_time"].to_string();
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//     // 获取账号信息
-//     async fn get_account(&mut self) -> Result<Account, Error> {
-//         let symbol_array: Vec<&str> = self.symbol.split("_").collect();
-//         let res_data = self.request.get_account_balance(symbol_array[1].parse().unwrap()).await;
-//         if res_data.code == 200 {
-//             let arr_infos: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
-//             if arr_infos.len() < 1usize{
-//                 return Err(Error::new(ErrorKind::NotFound, format!("{} 无账户信息", symbol_array[1])));
-//             }
-//             let coin_infos: Vec<Value> = from_value(arr_infos[0]["coin"].clone()).unwrap();
-//             if coin_infos.len() < 1usize{
-//                return Err(Error::new(ErrorKind::NotFound, format!("{} 无账户信息", symbol_array[1])));
-//             }
-//             let balance = Decimal::from_str(coin_infos[0]["equity"].as_str().unwrap()).unwrap();
-//             let available_balance = Decimal::from_str(coin_infos[0]["walletBalance"].as_str().unwrap()).unwrap();
-//             let frozen_balance = balance - available_balance;
-//             let result = Account {
-//                 coin: symbol_array[1].to_string(),
-//                 balance,
-//                 available_balance,
-//                 frozen_balance,
-//                 stocks: Decimal::ZERO,
-//                 available_stocks: Decimal::ZERO,
-//                 frozen_stocks: Decimal::ZERO,
-//             };
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     async fn get_spot_account(&mut self) -> Result<Vec<Account>, Error> {
-//         Err(Error::new(ErrorKind::NotFound, "bybit_swap:该交易所方法未实现".to_string()))
-//     }
-//
-//     // 获取持仓信息
-//     async fn get_position(&mut self) -> Result<Vec<Position>, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let ct_val = self.market.ct_val;
-//         let res_data = self.request.get_positions(symbol, "".to_string()).await;
-//         if res_data.code == 200 {
-//             let result = res_data.data["list"].as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect();
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//     // 获取所有持仓
-//     async fn get_positions(&mut self) -> Result<Vec<Position>, Error> {
-//         let symbol_array: Vec<&str> = self.symbol.split("_").collect();
-//         let ct_val = self.market.ct_val;
-//         let res_data = self.request.get_positions("".to_string(), symbol_array[1].to_string().to_uppercase()).await;
-//         if res_data.code == 200 {
-//             info!("{}", res_data.data.to_string());
-//             let result = res_data.data["list"].as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect();
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//     // 获取市场行情
-//     async fn get_ticker(&mut self) -> Result<Ticker, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let res_data = self.request.get_tickers(symbol).await;
-//         if res_data.code == 200 {
-//             let list :Vec<SwapTicker> = from_value(res_data.data["list"].clone()).unwrap_or(Vec::new());
-//
-//             if list.len() < 1usize {
-//                 error!("bybit_swap:获取Ticker信息错误!\nget_ticker:res_data={:?}", res_data);
-//                 return Err(Error::new(ErrorKind::Other, res_data.to_string()));
-//             }
-//             let value = list[0].clone();
-//             Ok(Ticker{
-//                 time: chrono::Utc::now().timestamp_millis(),
-//                 high: value.high_price24h,
-//                 low: value.low_price24h,
-//                 sell: value.ask1_price,
-//                 buy: value.bid1_price,
-//                 last: value.last_price,
-//                 volume: value.volume24h
-//             })
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     async fn get_ticker_symbol(&mut self, symbol: String) -> Result<Ticker, Error> {
-//         let symbol_upper = symbol.replace("_", "").to_uppercase();
-//         let res_data = self.request.get_tickers(symbol_upper.clone()).await;
-//         if res_data.code == 200 {
-//             let list: Vec<SwapTicker> = from_value(res_data.data["list"].clone()).unwrap();
-//             let ticker_info = list.iter().find(|&item| item.symbol == symbol_upper);
-//
-//             match ticker_info {
-//                 None => {
-//                     error!("bybit_swap:获取Ticker信息错误!\nget_ticker:res_data={:?}", res_data);
-//                     Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//                 }
-//                 Some(value) => {
-//                     let result = Ticker {
-//                         time: chrono::Utc::now().timestamp_millis(),
-//                         high: value.high_price24h,
-//                         low: value.low_price24h,
-//                         sell: value.ask1_price,
-//                         buy: value.bid1_price,
-//                         last: value.last_price,
-//                         volume: value.volume24h
-//                     };
-//                     Ok(result)
-//                 }
-//             }
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     async fn get_market(&mut self) -> Result<Market, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let res_data = self.request.get_instruments_info(symbol.clone()).await;
-//         if res_data.code == 200 {
-//             let arr_data: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
-//             let market_info = arr_data.iter().find(|&item| item["symbol"].as_str().unwrap() == symbol);
-//             match market_info {
-//                 None => {
-//                     error!("bybit_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
-//                     Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//                 }
-//                 Some(value) => {
-//                     let base_coin = value["baseCoin"].as_str().unwrap();
-//                     let quote_coin = value["quoteCoin"].as_str().unwrap();
-//                     let name = format!("{}_{}",base_coin, quote_coin);
-//                     let tick_size = Decimal::from_str(value["priceFilter"]["minPrice"].as_str().unwrap().trim()).unwrap();
-//                     let min_qty = Decimal::from_str(value["lotSizeFilter"]["minOrderQty"].as_str().unwrap().trim()).unwrap();
-//                     let max_qty = Decimal::from_str(value["lotSizeFilter"]["maxOrderQty"].as_str().unwrap().trim()).unwrap();
-//                     let ct_val = Decimal::ONE;
-//
-//                     let amount_size = min_qty * ct_val;
-//                     let price_precision = Decimal::from_u32(tick_size.scale()).unwrap();
-//                     let amount_precision = Decimal::from_u32(amount_size.scale()).unwrap();
-//                     let min_notional = min_qty * ct_val;
-//                     let max_notional = max_qty * ct_val;
-//
-//                     let result = Market {
-//                         symbol: name,
-//                         base_asset: base_coin.to_string(),
-//                         quote_asset: quote_coin.to_string(),
-//                         tick_size,
-//                         amount_size,
-//                         price_precision,
-//                         amount_precision,
-//                         min_qty,
-//                         max_qty,
-//                         min_notional,
-//                         max_notional,
-//                         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 = symbol.replace("_", "").to_uppercase();
-//         let res_data = self.request.get_instruments_info(symbol.clone()).await;
-//         if res_data.code == 200 {
-//             let arr_data: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
-//             let market_info = arr_data.iter().find(|item| item["symbol"].as_str().unwrap() == symbol);
-//             match market_info {
-//                 None => {
-//                     error!("bybit_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
-//                     Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//                 }
-//                 Some(value) => {
-//                     let base_coin = value["baseCoin"].as_str().unwrap();
-//                     let quote_coin = value["quoteCoin"].as_str().unwrap();
-//                     let name = format!("{}_{}",base_coin, quote_coin);
-//                     let tick_size = Decimal::from_str(value["priceFilter"]["minPrice"].as_str().unwrap().trim()).unwrap();
-//                     let min_qty = Decimal::from_str(value["lotSizeFilter"]["minOrderQty"].as_str().unwrap().trim()).unwrap();
-//                     let max_qty = Decimal::from_str(value["lotSizeFilter"]["maxOrderQty"].as_str().unwrap().trim()).unwrap();
-//                     let ct_val = Decimal::ONE;
-//
-//                     let amount_size = min_qty * ct_val;
-//                     let price_precision = Decimal::from_u32(tick_size.scale()).unwrap();
-//                     let amount_precision = Decimal::from_u32(amount_size.scale()).unwrap();
-//                     let min_notional = min_qty * ct_val;
-//                     let max_notional = max_qty * ct_val;
-//
-//                     let result = Market {
-//                         symbol: name,
-//                         base_asset: base_coin.to_string(),
-//                         quote_asset: quote_coin.to_string(),
-//                         tick_size,
-//                         amount_size,
-//                         price_precision,
-//                         amount_precision,
-//                         min_qty,
-//                         max_qty,
-//                         min_notional,
-//                         max_notional,
-//                         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> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let ct_val = self.market.ct_val;
-//         let id = if !custom_id.trim().eq("") { format!("t-{}", custom_id) } else { String::new() };
-//         let res_data = self.request.get_order(symbol, order_id.parse().unwrap(), id).await;
-//         if res_data.code == 200 {
-//             let res_data_json: Value = res_data.data["list"].clone();
-//             if res_data_json.is_array() && res_data_json.as_array().unwrap().len() == 0 {
-//                 return Err(Error::new(ErrorKind::Other, "没有该订单!"));
-//             }
-//             let result = format_order_item(res_data_json.as_array().unwrap()[0].clone(), ct_val);
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//     // 获取订单列表
-//     async fn get_orders_list(&mut self, _status: &str) -> Result<Vec<Order>, Error> {
-//        Err(Error::new(ErrorKind::Other, "bybit获取订单列表暂未实现".to_string()))
-//     }
-//     // 下单接口
-//     async fn take_order(&mut self, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let ct_val = self.market.ct_val;
-//         let size = amount / ct_val;
-//         let mut params = json!({
-//             "orderLinkId": format!("t-{}", custom_id),
-//             "symbol": symbol.to_string(),
-//             "price": price.to_string(),
-//             "category": "linear",
-//             "orderType":"Limit",
-//             "qty": json!(size),
-//             // 0.單向持倉 1.買側雙向持倉 2.賣側雙向持倉
-//             "positionIdx": json!(1),
-//             "reduceOnly": json!(false)
-//         });
-//
-//         if price.eq(&Decimal::ZERO) {
-//             params["timeInForce"] = json!("IOC".to_string());
-//         }
-//         match origin_side {
-//             "kd" => {
-//                 params["side"] = json!("Buy");
-//             }
-//             "pd" => {
-//                 params["side"] = json!("Sell");
-//                 // 减仓
-//                 params["reduceOnly"] = json!(true);
-//             }
-//             "kk" => {
-//                 params["side"] = json!("Sell");
-//                 params["positionIdx"] = json!(2);
-//             }
-//             "pk" => {
-//                 params["side"] = json!("Buy");
-//                 // 减仓
-//                 params["reduceOnly"] = json!(true);
-//                 params["positionIdx"] = json!(2);
-//             }
-//             _ => { error!("下单参数错误"); }
-//         };
-//         let res_data = self.request.swap_order(params).await;
-//         if res_data.code == 200 {
-//             let result = format_new_order_item(res_data.data, price, size);
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.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> {
-//         let symbol_upper = symbol.replace("_", "").trim().to_uppercase();
-//         let size = (amount / ct_val).floor();
-//         let order_type = if price == Decimal::ZERO {
-//             "Market"
-//         } else {
-//             "Limit"
-//         };
-//         let mut params = json!({
-//             "orderLinkId": format!("t-{}", custom_id),
-//             "symbol": symbol_upper,
-//             "price": price.to_string(),
-//             "category": "linear",
-//             "orderType": order_type,
-//             "qty": json!(size),
-//             // 0.單向持倉 1.買側雙向持倉 2.賣側雙向持倉
-//             "positionIdx": json!(1),
-//             "reduceOnly": json!(false)
-//         });
-//
-//         if price.eq(&Decimal::ZERO) {
-//             params["timeInForce"] = json!("IOC".to_string());
-//         }
-//         match origin_side {
-//             "kd" => {
-//                 params["side"] = json!("Buy");
-//             }
-//             "pd" => {
-//                 params["side"] = json!("Sell");
-//                 params["positionIdx"] = json!(1);
-//                 // 减仓
-//                 params["reduceOnly"] = json!(true);
-//             }
-//             "kk" => {
-//                 params["side"] = json!("Sell");
-//                 params["positionIdx"] = json!(2);
-//             }
-//             "pk" => {
-//                 params["side"] = json!("Buy");
-//                 params["positionIdx"] = json!(2);
-//                 // 减仓
-//                 params["reduceOnly"] = json!(true);
-//             }
-//             _ => { error!("下单参数错误"); }
-//         };
-//         let res_data = self.request.swap_order(params.clone()).await;
-//         if res_data.code == 200 {
-//             let result = format_new_order_item(res_data.data, price, size);
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     // 撤销订单
-//     async fn cancel_order(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let id = format!("t-{}", custom_id);
-//         let res_data = self.request.cancel_order(symbol, String::from(order_id), id.clone()).await;
-//         if res_data.code == 200 {
-//             let result = format_cancel_order_item(res_data.data);
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//     // 批量撤销订单
-//     async fn cancel_orders(&mut self) -> Result<Vec<Order>, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let res_data = self.request.cancel_orders(symbol).await;
-//         if res_data.code == 200 {
-//             info!("{}", res_data.data.to_string());
-//             let res_arr: Vec<Value> = from_value(res_data.data).unwrap();
-//             let result = res_arr.iter().map(|item| format_cancel_order_item(item.clone())).collect();
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     async fn cancel_orders_all(&mut self) -> Result<Vec<Order>, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let res_data = self.request.cancel_orders(symbol).await;
-//         if res_data.code == 200 {
-//             info!("{}", res_data.data.to_string());
-//             let res_arr: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
-//             let result = res_arr.iter().map(|item| format_cancel_order_item(item.clone())).collect();
-//             Ok(result)
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.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, "bybit_swap:该交易所方法未实现".to_string()))
-//     }
-//
-//     async fn cancel_stop_loss_order(&mut self, _order_id: &str) -> Result<Value, Error> {
-//         Err(Error::new(ErrorKind::NotFound, "bybit_swap:该交易所方法未实现".to_string()))
-//     }
-//
-//     // 设置持仓模式
-//     async fn set_dual_mode(&mut self, _coin: &str, is_dual_mode: bool) -> Result<String, Error> {
-//         let coin_format = self.symbol_uppercase.clone();
-//         let mut mod_num = 0;
-//         if is_dual_mode {
-//             mod_num = 3;
-//         }
-//         let res_data = self.request.set_position_mode(coin_format, mod_num).await;
-//         if res_data.code == 200 {
-//             Ok(res_data.data.to_string())
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     // 更新双持仓模式下杠杆
-//     async fn set_dual_leverage(&mut self, leverage: &str) -> Result<String, Error> {
-//         let symbol = self.symbol_uppercase.clone();
-//         let res_data = self.request.set_leverage(symbol, leverage.to_string()).await;
-//         if res_data.code == 200 {
-//             Ok(res_data.data.to_string())
-//         } else {
-//             Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         }
-//     }
-//
-//     async fn set_auto_deposit_status(&mut self, _status: bool) -> Result<String, Error> { Err(Error::new(ErrorKind::NotFound, "gate:该交易所方法未实现".to_string())) }
-//
-//     // 交易账户互转
-//     async fn wallet_transfers(&mut self, _coin: &str, _from: &str, _to: &str, _amount: Decimal) -> Result<String, Error> {
-//         // let coin_format = coin.to_string().to_lowercase();
-//         // let res_data = self.request.wallet_transfers(coin_format.clone(), from.to_string(), to.to_string(), amount.to_string(), coin_format.clone()).await;
-//         // if res_data.code == 200 {
-//         //     let res_data_str = &res_data.data;
-//         //     let result = res_data_str.clone();
-//         //     Ok(result)
-//         // } else {
-//         //     Err(Error::new(ErrorKind::Other, res_data.to_string()))
-//         // }
-//         Err(Error::new(ErrorKind::Other, "暂未实现!"))
-//     }
-//
-//     // 指令下单
-//     async fn command_order(&mut self, order_command: &mut OrderCommand, trace_stack: &TraceStack) {
-//         // 下单指令
-//         let mut handles = vec![];
-//         for item in order_command.limits_open.keys() {
-//             let mut self_clone = self.clone();
-//
-//             let amount = Decimal::from_str(order_command.limits_open[item].get(0).unwrap_or(&"0".to_string())).unwrap();
-//             let side = order_command.limits_open[item].get(1).unwrap().clone();
-//             let price = Decimal::from_str(order_command.limits_open[item].get(2).unwrap_or(&"0".to_string())).unwrap();
-//             let cid = order_command.limits_open[item].get(3).unwrap().clone();
-//
-//             let mut ts = trace_stack.clone();
-//
-//             let handle = tokio::spawn(async move {
-//                 ts.on_before_send();
-//                 // TraceStack::show_delay(&ts.ins);
-//                 let result = self_clone.take_order(cid.as_str(), side.as_str(), price, amount).await;
-//                 ts.on_after_send();
-//                 match result {
-//                     Ok(mut result) => {
-//                         // 记录此订单完成时间
-//                         result.trace_stack = ts;
-//
-//                         self_clone.order_sender.send(result).await.unwrap();
-//                     }
-//                     Err(error) => {
-//                         error!("bybit:下单失败:{:?}", error);
-//
-//                         let mut err_order = Order::new();
-//                         err_order.custom_id = cid.clone();
-//                         err_order.status = "REMOVE".to_string();
-//
-//                         self_clone.order_sender.send(err_order).await.unwrap();
-//                         self_clone.error_sender.send(error).await.unwrap();
-//                     }
-//                 }
-//             });
-//             handles.push(handle)
-//         }
-//         let futures = FuturesUnordered::from_iter(handles);
-//         let _: Result<Vec<_>, _> = futures.try_collect().await;
-//
-//         // 撤销订单
-//         let mut cancel_handles = vec![];
-//         for item in order_command.cancel.keys() {
-//             let mut self_clone = self.clone();
-//
-//             let order_id = order_command.cancel[item].get(1).unwrap().clone();
-//             let custom_id = order_command.cancel[item].get(0).unwrap().clone();
-//
-//             let handle = tokio::spawn(async move {
-//                 let result = self_clone.cancel_order(&order_id, &custom_id).await;
-//                 match result {
-//                     Ok(_) => {
-//                         // result_sd.send(result).await.unwrap();
-//                     }
-//                     Err(error) => {
-//                         // 取消失败去查订单。
-//                         let query_rst = self_clone.get_order_detail(&order_id, &custom_id).await;
-//                         match query_rst {
-//                             Ok(order) => {
-//                                 self_clone.order_sender.send(order).await.unwrap();
-//                             }
-//                             Err(_err) => {
-//                                 error!("bybit:撤单失败,而且查单也失败了,oid={}, cid={}。", order_id.clone(), custom_id.clone());
-//                             }
-//                         }
-//                         self_clone.error_sender.send(error).await.unwrap();
-//                     }
-//                 }
-//             });
-//             cancel_handles.push(handle)
-//         }
-//         let futures = FuturesUnordered::from_iter(cancel_handles);
-//         let _: Result<Vec<_>, _> = futures.try_collect().await;
-//
-//         // 检查订单指令
-//         let mut check_handles = vec![];
-//         for item in order_command.check.keys() {
-//             let mut self_clone = self.clone();
-//
-//             let order_id = order_command.check[item].get(1).unwrap().clone();
-//             let custom_id = order_command.check[item].get(0).unwrap().clone();
-//
-//             let handle = tokio::spawn(async move {
-//                 let result = self_clone.get_order_detail(&order_id, &custom_id).await;
-//                 match result {
-//                     Ok(result) => {
-//                         self_clone.order_sender.send(result).await.unwrap();
-//                     }
-//                     Err(error) => {
-//                         self_clone.error_sender.send(error).await.unwrap();
-//                     }
-//                 }
-//             });
-//             check_handles.push(handle)
-//         }
-//         let futures = FuturesUnordered::from_iter(check_handles);
-//         let _: Result<Vec<_>, _> = futures.try_collect().await;
-//     }
-// }
-//
-// pub fn format_position_item(position: &Value, ct_val: Decimal) -> Position {
-//     let position_idx = position["positionIdx"].to_string();
-//     let mut position_mode = match position_idx.as_str() {
-//         "0" => PositionModeEnum::Both,
-//         "1" => PositionModeEnum::Long,
-//         "2" => PositionModeEnum::Short,
-//         _ => {
-//             error!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position);
-//             panic!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position)
-//         }
-//     };
-//     let size_str: String = from_value(position["size"].clone()).unwrap();
-//     let size = Decimal::from_str(size_str.as_str()).unwrap();
-//     let amount = size * ct_val;
-//     let mut profit = Decimal::ZERO;
-//     let profit_str = position["unrealisedPnl"].as_str().unwrap_or("0");
-//     if profit_str != "" {
-//         profit = Decimal::from_str(profit_str).unwrap();
-//     }
-//
-//     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["symbol"].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["avgPrice"].as_str().unwrap()).unwrap(),
-//         profit,
-//         position_mode,
-//         margin: Decimal::from_str(position["positionBalance"].as_str().unwrap()).unwrap(),
-//     }
-// }
-//
-// fn format_cancel_order_item(order: Value) -> Order {
-//      Order {
-//         id: format!("{}", order["orderId"].as_str().unwrap()),
-//         custom_id: order["orderLinkId"].as_str().unwrap().replace("t-my-custom-id_", "").replace("t-", ""),
-//         price: Decimal::ZERO,
-//         amount: Decimal::ZERO,
-//         deal_amount: Decimal::ZERO,
-//         avg_price: Decimal::ZERO,
-//         status: "REMOVE".to_string(),
-//         order_type: "limit".to_string(),
-//         trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string())
-//     }
-// }
-//
-// fn format_new_order_item(order: Value, price: Decimal, amount: Decimal) -> Order {
-//     Order {
-//         id: format!("{}", order["orderId"].as_str().unwrap()),
-//         custom_id: order["orderLinkId"].as_str().unwrap().replace("t-my-custom-id_", "").replace("t-", ""),
-//         price,
-//         amount,
-//         deal_amount: Decimal::ZERO,
-//         avg_price: price,
-//         status: "NEW".to_string(),
-//         order_type: "limit".to_string(),
-//         trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string())
-//     }
-// }
-//
-// pub fn format_order_item(order: Value, ct_val: Decimal) -> Order {
-//     let status = order["orderStatus"].as_str().unwrap_or("");
-//     let text = order["orderLinkId"].as_str().unwrap_or("");
-//     let mut size = Decimal::ZERO;
-//     let mut deal_amount = Decimal::ZERO;
-//     let mut avg_price = Decimal::ZERO;
-//
-//     let right_str = order["cumExecQty"].to_string();
-//     let size_str = order["qty"].to_string();
-//
-//     if !order.get("qty").is_some() {
-//         size = Decimal::from_str(size_str.as_str()).unwrap();
-//         let right_val = Decimal::from_str(order["cumExecValue"].as_str().unwrap()).unwrap();
-//         let right = Decimal::from_str(right_str.as_str()).unwrap();
-//         if right != Decimal::ZERO {
-//             avg_price = right_val / right;
-//         }
-//         deal_amount = right * ct_val;
-//     }
-//
-//     let amount = size * ct_val;
-//     let custom_status = if status == "Filled" || status == "Cancelled" { "REMOVE".to_string() } else if status == "New" { "NEW".to_string() } else {
-//         "NULL".to_string()
-//     };
-//     let rst_order = Order {
-//         id: format!("{}", order["orderId"].as_str().unwrap()),
-//         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,
-//         status: custom_status,
-//         order_type: "limit".to_string(),
-//         trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string()),
-//     };
-//     return rst_order;
-// }
+use std::collections::{BTreeMap};
+use std::io::{Error, ErrorKind};
+use std::str::FromStr;
+use tokio::sync::mpsc::Sender;
+use async_trait::async_trait;
+use futures::stream::FuturesUnordered;
+use futures::TryStreamExt;
+use rust_decimal::Decimal;
+use serde_json::{from_value, json, Value};
+use rust_decimal::prelude::FromPrimitive;
+use serde::{Deserialize, Serialize};
+use tokio::time::Instant;
+use tracing::{error, info, trace};
+use exchanges::bybit_swap_rest::BybitSwapRest;
+use crate::{Platform, ExchangeEnum, Account, Position, Ticker, Market, Order, OrderCommand, PositionModeEnum};
+use global::trace_stack::TraceStack;
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SwapTicker {
+    symbol: String,
+    high_price24h: Decimal,
+    low_price24h: Decimal,
+    bid1_price: Decimal,
+    ask1_price: Decimal,
+    last_price: Decimal,
+    volume24h: Decimal
+}
+
+#[allow(dead_code)]
+#[derive(Clone)]
+pub struct BybitSwap {
+    exchange: ExchangeEnum,
+    symbol: String,
+    symbol_uppercase: String,
+    is_colo: bool,
+    params: BTreeMap<String, String>,
+    request: BybitSwapRest,
+    market: Market,
+    order_sender: Sender<Order>,
+    error_sender: Sender<Error>,
+}
+
+impl BybitSwap {
+    pub async fn new(symbol: String, is_colo: bool, params: BTreeMap<String, String>, order_sender: Sender<Order>, error_sender: Sender<Error>) -> BybitSwap {
+        let market = Market::new();
+        let mut bybit_swap = BybitSwap {
+            exchange: ExchangeEnum::BybitSwap,
+            symbol: symbol.to_uppercase(),
+            symbol_uppercase: symbol.replace("_", "").to_uppercase(),
+            is_colo,
+            params: params.clone(),
+            request: BybitSwapRest::new(is_colo, params.clone()),
+            market,
+            order_sender,
+            error_sender,
+        };
+
+        // 修改持仓模式
+        let symbol_array: Vec<&str> = symbol.split("_").collect();
+        let mode_result = bybit_swap.set_dual_mode(symbol_array[1], true).await;
+        match mode_result {
+            Ok(_) => {
+                trace!("Bybit:设置持仓模式成功!")
+            }
+            Err(error) => {
+                error!("Bybit:设置持仓模式失败!mode_result={}", error)
+            }
+        }
+        // 获取市场信息
+        bybit_swap.market = BybitSwap::get_market(&mut bybit_swap).await.unwrap_or(bybit_swap.market);
+        bybit_swap
+    }
+}
+
+#[async_trait]
+impl Platform for BybitSwap {
+    // 克隆方法
+    fn clone_box(&self) -> Box<dyn Platform + Send + Sync> { Box::new(self.clone()) }
+    // 获取交易所模式
+    fn get_self_exchange(&self) -> ExchangeEnum {
+        ExchangeEnum::GateSwap
+    }
+    // 获取交易对
+    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> {
+        let res_data = self.request.get_server_time().await;
+        if res_data.code == 200 {
+            let result = res_data.data["server_time"].to_string();
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+    // 获取账号信息
+    async fn get_account(&mut self) -> Result<Account, Error> {
+        let symbol_array: Vec<&str> = self.symbol.split("_").collect();
+        let res_data = self.request.get_account_balance(symbol_array[1].parse().unwrap()).await;
+        if res_data.code == 200 {
+            let arr_infos: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
+            if arr_infos.len() < 1usize{
+                return Err(Error::new(ErrorKind::NotFound, format!("{} 无账户信息", symbol_array[1])));
+            }
+            let coin_infos: Vec<Value> = from_value(arr_infos[0]["coin"].clone()).unwrap();
+            if coin_infos.len() < 1usize{
+               return Err(Error::new(ErrorKind::NotFound, format!("{} 无账户信息", symbol_array[1])));
+            }
+            let balance = Decimal::from_str(coin_infos[0]["equity"].as_str().unwrap()).unwrap();
+            let available_balance = Decimal::from_str(coin_infos[0]["walletBalance"].as_str().unwrap()).unwrap();
+            let frozen_balance = balance - available_balance;
+            let result = Account {
+                coin: symbol_array[1].to_string(),
+                balance,
+                available_balance,
+                frozen_balance,
+                stocks: Decimal::ZERO,
+                available_stocks: Decimal::ZERO,
+                frozen_stocks: Decimal::ZERO,
+            };
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    async fn get_spot_account(&mut self) -> Result<Vec<Account>, Error> {
+        Err(Error::new(ErrorKind::NotFound, "bybit_swap:该交易所方法未实现".to_string()))
+    }
+
+    // 获取持仓信息
+    async fn get_position(&mut self) -> Result<Vec<Position>, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let ct_val = self.market.multiplier;
+        let res_data = self.request.get_positions(symbol, "".to_string()).await;
+        if res_data.code == 200 {
+            let result = res_data.data["list"].as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect();
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+    // 获取所有持仓
+    async fn get_positions(&mut self) -> Result<Vec<Position>, Error> {
+        let symbol_array: Vec<&str> = self.symbol.split("_").collect();
+        let ct_val = self.market.multiplier;
+        let res_data = self.request.get_positions("".to_string(), symbol_array[1].to_string().to_uppercase()).await;
+        if res_data.code == 200 {
+            info!("{}", res_data.data.to_string());
+            let result = res_data.data["list"].as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect();
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+    // 获取市场行情
+    async fn get_ticker(&mut self) -> Result<Ticker, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let res_data = self.request.get_tickers(symbol).await;
+        if res_data.code == 200 {
+            let list :Vec<SwapTicker> = from_value(res_data.data["list"].clone()).unwrap_or(Vec::new());
+
+            if list.len() < 1usize {
+                error!("bybit_swap:获取Ticker信息错误!\nget_ticker:res_data={:?}", res_data);
+                return Err(Error::new(ErrorKind::Other, res_data.to_string()));
+            }
+            let value = list[0].clone();
+            Ok(Ticker{
+                time: chrono::Utc::now().timestamp_millis(),
+                high: value.high_price24h,
+                low: value.low_price24h,
+                sell: value.ask1_price,
+                buy: value.bid1_price,
+                last: value.last_price,
+                volume: value.volume24h
+            })
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    async fn get_ticker_symbol(&mut self, symbol: String) -> Result<Ticker, Error> {
+        let symbol_upper = symbol.replace("_", "").to_uppercase();
+        let res_data = self.request.get_tickers(symbol_upper.clone()).await;
+        if res_data.code == 200 {
+            let list: Vec<SwapTicker> = from_value(res_data.data["list"].clone()).unwrap();
+            let ticker_info = list.iter().find(|&item| item.symbol == symbol_upper);
+
+            match ticker_info {
+                None => {
+                    error!("bybit_swap:获取Ticker信息错误!\nget_ticker:res_data={:?}", res_data);
+                    Err(Error::new(ErrorKind::Other, res_data.to_string()))
+                }
+                Some(value) => {
+                    let result = Ticker {
+                        time: chrono::Utc::now().timestamp_millis(),
+                        high: value.high_price24h,
+                        low: value.low_price24h,
+                        sell: value.ask1_price,
+                        buy: value.bid1_price,
+                        last: value.last_price,
+                        volume: value.volume24h
+                    };
+                    Ok(result)
+                }
+            }
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    async fn get_market(&mut self) -> Result<Market, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let res_data = self.request.get_instruments_info(symbol.clone()).await;
+        if res_data.code == 200 {
+            let arr_data: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
+            let market_info = arr_data.iter().find(|&item| item["symbol"].as_str().unwrap() == symbol);
+            match market_info {
+                None => {
+                    error!("bybit_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
+                    Err(Error::new(ErrorKind::Other, res_data.to_string()))
+                }
+                Some(value) => {
+                    let base_coin = value["baseCoin"].as_str().unwrap();
+                    let quote_coin = value["quoteCoin"].as_str().unwrap();
+                    let name = format!("{}_{}",base_coin, quote_coin);
+                    let tick_size = Decimal::from_str(value["priceFilter"]["minPrice"].as_str().unwrap().trim()).unwrap();
+                    let min_qty = Decimal::from_str(value["lotSizeFilter"]["minOrderQty"].as_str().unwrap().trim()).unwrap();
+                    let max_qty = Decimal::from_str(value["lotSizeFilter"]["maxOrderQty"].as_str().unwrap().trim()).unwrap();
+                    let ct_val = Decimal::ONE;
+
+                    let amount_size = min_qty * ct_val;
+                    let price_precision = Decimal::from_u32(tick_size.scale()).unwrap();
+                    let amount_precision = Decimal::from_u32(amount_size.scale()).unwrap();
+                    let min_notional = Decimal::from_str(value["lotSizeFilter"]["minNotionalValue"].as_str().unwrap().trim()).unwrap();
+                    let max_notional = max_qty * ct_val;
+
+                    let result = Market {
+                        symbol: name,
+                        base_asset: base_coin.to_string(),
+                        quote_asset: quote_coin.to_string(),
+                        tick_size,
+                        amount_size,
+                        price_precision,
+                        amount_precision,
+                        min_qty,
+                        max_qty,
+                        min_notional,
+                        max_notional,
+                        multiplier: 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 = symbol.replace("_", "").to_uppercase();
+        let res_data = self.request.get_instruments_info(symbol.clone()).await;
+        if res_data.code == 200 {
+            let arr_data: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
+            let market_info = arr_data.iter().find(|item| item["symbol"].as_str().unwrap() == symbol);
+            match market_info {
+                None => {
+                    error!("bybit_swap:获取Market信息错误!\nget_market:res_data={:?}", res_data);
+                    Err(Error::new(ErrorKind::Other, res_data.to_string()))
+                }
+                Some(value) => {
+                    let base_coin = value["baseCoin"].as_str().unwrap();
+                    let quote_coin = value["quoteCoin"].as_str().unwrap();
+                    let name = format!("{}_{}",base_coin, quote_coin);
+                    let tick_size = Decimal::from_str(value["priceFilter"]["minPrice"].as_str().unwrap().trim()).unwrap();
+                    let min_qty = Decimal::from_str(value["lotSizeFilter"]["minOrderQty"].as_str().unwrap().trim()).unwrap();
+                    let max_qty = Decimal::from_str(value["lotSizeFilter"]["maxOrderQty"].as_str().unwrap().trim()).unwrap();
+                    let ct_val = Decimal::ONE;
+
+                    let amount_size = min_qty * ct_val;
+                    let price_precision = Decimal::from_u32(tick_size.scale()).unwrap();
+                    let amount_precision = Decimal::from_u32(amount_size.scale()).unwrap();
+                    let min_notional = Decimal::from_str(value["lotSizeFilter"]["minNotionalValue"].as_str().unwrap().trim()).unwrap();
+                    let max_notional = max_qty * ct_val;
+
+                    let result = Market {
+                        symbol: name,
+                        base_asset: base_coin.to_string(),
+                        quote_asset: quote_coin.to_string(),
+                        tick_size,
+                        amount_size,
+                        price_precision,
+                        amount_precision,
+                        min_qty,
+                        max_qty,
+                        min_notional,
+                        max_notional,
+                        multiplier: 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> {
+        let symbol = self.symbol_uppercase.clone();
+        let ct_val = self.market.multiplier;
+        let id = if !custom_id.trim().eq("") { format!("t-{}", custom_id) } else { String::new() };
+        let res_data = self.request.get_order(symbol, order_id.parse().unwrap(), id).await;
+        if res_data.code == 200 {
+            let res_data_json: Value = res_data.data["list"].clone();
+            if res_data_json.is_array() && res_data_json.as_array().unwrap().len() == 0 {
+                return Err(Error::new(ErrorKind::Other, "没有该订单!"));
+            }
+            let result = format_order_item(res_data_json.as_array().unwrap()[0].clone(), ct_val);
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+    // 获取订单列表
+    async fn get_orders_list(&mut self, _status: &str) -> Result<Vec<Order>, Error> {
+       Err(Error::new(ErrorKind::Other, "bybit获取订单列表暂未实现".to_string()))
+    }
+    // 下单接口
+    async fn take_order(&mut self, custom_id: &str, origin_side: &str, price: Decimal, amount: Decimal) -> Result<Order, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let ct_val = self.market.multiplier;
+        let size = amount / ct_val;
+        let mut params = json!({
+            "orderLinkId": format!("t-{}", custom_id),
+            "symbol": symbol.to_string(),
+            "price": price.to_string(),
+            "category": "linear",
+            "orderType":"Limit",
+            "qty": json!(size),
+            // 0.單向持倉 1.買側雙向持倉 2.賣側雙向持倉
+            "positionIdx": json!(1),
+            "reduceOnly": json!(false)
+        });
+
+        if price.eq(&Decimal::ZERO) {
+            params["timeInForce"] = json!("IOC".to_string());
+        }
+        match origin_side {
+            "kd" => {
+                params["side"] = json!("Buy");
+            }
+            "pd" => {
+                params["side"] = json!("Sell");
+                // 减仓
+                params["reduceOnly"] = json!(true);
+            }
+            "kk" => {
+                params["side"] = json!("Sell");
+                params["positionIdx"] = json!(2);
+            }
+            "pk" => {
+                params["side"] = json!("Buy");
+                // 减仓
+                params["reduceOnly"] = json!(true);
+                params["positionIdx"] = json!(2);
+            }
+            _ => { error!("下单参数错误"); }
+        };
+        let res_data = self.request.swap_order(params).await;
+        if res_data.code == 200 {
+            let result = format_new_order_item(res_data.data, price, size);
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.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> {
+        let symbol_upper = symbol.replace("_", "").trim().to_uppercase();
+        let size = (amount / ct_val).floor();
+        let order_type = if price == Decimal::ZERO {
+            "Market"
+        } else {
+            "Limit"
+        };
+        let mut params = json!({
+            "orderLinkId": format!("t-{}", custom_id),
+            "symbol": symbol_upper,
+            "price": price.to_string(),
+            "category": "linear",
+            "orderType": order_type,
+            "qty": json!(size),
+            // 0.單向持倉 1.買側雙向持倉 2.賣側雙向持倉
+            "positionIdx": json!(1),
+            "reduceOnly": json!(false)
+        });
+
+        if price.eq(&Decimal::ZERO) {
+            params["timeInForce"] = json!("IOC".to_string());
+        }
+        match origin_side {
+            "kd" => {
+                params["side"] = json!("Buy");
+            }
+            "pd" => {
+                params["side"] = json!("Sell");
+                params["positionIdx"] = json!(1);
+                // 减仓
+                params["reduceOnly"] = json!(true);
+            }
+            "kk" => {
+                params["side"] = json!("Sell");
+                params["positionIdx"] = json!(2);
+            }
+            "pk" => {
+                params["side"] = json!("Buy");
+                params["positionIdx"] = json!(2);
+                // 减仓
+                params["reduceOnly"] = json!(true);
+            }
+            _ => { error!("下单参数错误"); }
+        };
+        let res_data = self.request.swap_order(params.clone()).await;
+        if res_data.code == 200 {
+            let result = format_new_order_item(res_data.data, price, size);
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    // 撤销订单
+    async fn cancel_order(&mut self, order_id: &str, custom_id: &str) -> Result<Order, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let id = format!("t-{}", custom_id);
+        let res_data = self.request.cancel_order(symbol, String::from(order_id), id.clone()).await;
+        if res_data.code == 200 {
+            let result = format_cancel_order_item(res_data.data);
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+    // 批量撤销订单
+    async fn cancel_orders(&mut self) -> Result<Vec<Order>, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let res_data = self.request.cancel_orders(symbol).await;
+        if res_data.code == 200 {
+            info!("{}", res_data.data.to_string());
+            let res_arr: Vec<Value> = from_value(res_data.data).unwrap();
+            let result = res_arr.iter().map(|item| format_cancel_order_item(item.clone())).collect();
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    async fn cancel_orders_all(&mut self) -> Result<Vec<Order>, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let res_data = self.request.cancel_orders(symbol).await;
+        if res_data.code == 200 {
+            info!("{}", res_data.data.to_string());
+            let res_arr: Vec<Value> = from_value(res_data.data["list"].clone()).unwrap();
+            let result = res_arr.iter().map(|item| format_cancel_order_item(item.clone())).collect();
+            Ok(result)
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.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, "bybit_swap:该交易所方法未实现".to_string()))
+    }
+
+    async fn cancel_stop_loss_order(&mut self, _order_id: &str) -> Result<Value, Error> {
+        Err(Error::new(ErrorKind::NotFound, "bybit_swap:该交易所方法未实现".to_string()))
+    }
+
+    // 设置持仓模式
+    async fn set_dual_mode(&mut self, _coin: &str, is_dual_mode: bool) -> Result<String, Error> {
+        let coin_format = self.symbol_uppercase.clone();
+        let mut mod_num = 0;
+        if is_dual_mode {
+            mod_num = 3;
+        }
+        let res_data = self.request.set_position_mode(coin_format, mod_num).await;
+        if res_data.code == 200 {
+            Ok(res_data.data.to_string())
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    // 更新双持仓模式下杠杆
+    async fn set_dual_leverage(&mut self, leverage: &str) -> Result<String, Error> {
+        let symbol = self.symbol_uppercase.clone();
+        let res_data = self.request.set_leverage(symbol, leverage.to_string()).await;
+        if res_data.code == 200 {
+            Ok(res_data.data.to_string())
+        } else {
+            Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        }
+    }
+
+    async fn set_auto_deposit_status(&mut self, _status: bool) -> Result<String, Error> { Err(Error::new(ErrorKind::NotFound, "gate:该交易所方法未实现".to_string())) }
+
+    // 交易账户互转
+    async fn wallet_transfers(&mut self, _coin: &str, _from: &str, _to: &str, _amount: Decimal) -> Result<String, Error> {
+        // let coin_format = coin.to_string().to_lowercase();
+        // let res_data = self.request.wallet_transfers(coin_format.clone(), from.to_string(), to.to_string(), amount.to_string(), coin_format.clone()).await;
+        // if res_data.code == 200 {
+        //     let res_data_str = &res_data.data;
+        //     let result = res_data_str.clone();
+        //     Ok(result)
+        // } else {
+        //     Err(Error::new(ErrorKind::Other, res_data.to_string()))
+        // }
+        Err(Error::new(ErrorKind::Other, "暂未实现!"))
+    }
+
+    // 指令下单
+    async fn command_order(&mut self, order_command: &mut OrderCommand, trace_stack: &TraceStack) {
+        // 下单指令
+        let mut handles = vec![];
+        for item in order_command.limits_open.keys() {
+            let mut self_clone = self.clone();
+
+            let amount = Decimal::from_str(order_command.limits_open[item].get(0).unwrap_or(&"0".to_string())).unwrap();
+            let side = order_command.limits_open[item].get(1).unwrap().clone();
+            let price = Decimal::from_str(order_command.limits_open[item].get(2).unwrap_or(&"0".to_string())).unwrap();
+            let cid = order_command.limits_open[item].get(3).unwrap().clone();
+
+            let mut ts = trace_stack.clone();
+
+            let handle = tokio::spawn(async move {
+                ts.on_before_send();
+                // TraceStack::show_delay(&ts.ins);
+                let result = self_clone.take_order(cid.as_str(), side.as_str(), price, amount).await;
+                ts.on_after_send();
+                match result {
+                    Ok(mut result) => {
+                        // 记录此订单完成时间
+                        result.trace_stack = ts;
+
+                        self_clone.order_sender.send(result).await.unwrap();
+                    }
+                    Err(error) => {
+                        error!("bybit:下单失败:{:?}", error);
+
+                        let mut err_order = Order::new();
+                        err_order.custom_id = cid.clone();
+                        err_order.status = "REMOVE".to_string();
+
+                        self_clone.order_sender.send(err_order).await.unwrap();
+                        self_clone.error_sender.send(error).await.unwrap();
+                    }
+                }
+            });
+            handles.push(handle)
+        }
+        let futures = FuturesUnordered::from_iter(handles);
+        let _: Result<Vec<_>, _> = futures.try_collect().await;
+
+        // 撤销订单
+        let mut cancel_handles = vec![];
+        for item in order_command.cancel.keys() {
+            let mut self_clone = self.clone();
+
+            let order_id = order_command.cancel[item].get(1).unwrap().clone();
+            let custom_id = order_command.cancel[item].get(0).unwrap().clone();
+
+            let handle = tokio::spawn(async move {
+                let result = self_clone.cancel_order(&order_id, &custom_id).await;
+                match result {
+                    Ok(_) => {
+                        // result_sd.send(result).await.unwrap();
+                    }
+                    Err(error) => {
+                        // 取消失败去查订单。
+                        let query_rst = self_clone.get_order_detail(&order_id, &custom_id).await;
+                        match query_rst {
+                            Ok(order) => {
+                                self_clone.order_sender.send(order).await.unwrap();
+                            }
+                            Err(_err) => {
+                                error!("bybit:撤单失败,而且查单也失败了,oid={}, cid={}。", order_id.clone(), custom_id.clone());
+                            }
+                        }
+                        self_clone.error_sender.send(error).await.unwrap();
+                    }
+                }
+            });
+            cancel_handles.push(handle)
+        }
+        let futures = FuturesUnordered::from_iter(cancel_handles);
+        let _: Result<Vec<_>, _> = futures.try_collect().await;
+
+        // 检查订单指令
+        let mut check_handles = vec![];
+        for item in order_command.check.keys() {
+            let mut self_clone = self.clone();
+
+            let order_id = order_command.check[item].get(1).unwrap().clone();
+            let custom_id = order_command.check[item].get(0).unwrap().clone();
+
+            let handle = tokio::spawn(async move {
+                let result = self_clone.get_order_detail(&order_id, &custom_id).await;
+                match result {
+                    Ok(result) => {
+                        self_clone.order_sender.send(result).await.unwrap();
+                    }
+                    Err(error) => {
+                        self_clone.error_sender.send(error).await.unwrap();
+                    }
+                }
+            });
+            check_handles.push(handle)
+        }
+        let futures = FuturesUnordered::from_iter(check_handles);
+        let _: Result<Vec<_>, _> = futures.try_collect().await;
+    }
+}
+
+pub fn format_position_item(position: &Value, ct_val: Decimal) -> Position {
+    let position_idx = position["positionIdx"].to_string();
+    let mut position_mode = match position_idx.as_str() {
+        "0" => PositionModeEnum::Both,
+        "1" => PositionModeEnum::Long,
+        "2" => PositionModeEnum::Short,
+        _ => {
+            error!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position);
+            panic!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position)
+        }
+    };
+    let size_str: String = from_value(position["size"].clone()).unwrap();
+    let size = Decimal::from_str(size_str.as_str()).unwrap();
+    let amount = size * ct_val;
+    let mut profit = Decimal::ZERO;
+    let profit_str = position["unrealisedPnl"].as_str().unwrap_or("0");
+    if profit_str != "" {
+        profit = Decimal::from_str(profit_str).unwrap();
+    }
+
+    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["symbol"].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["avgPrice"].as_str().unwrap()).unwrap(),
+        profit,
+        position_mode,
+        margin: Decimal::from_str(position["positionBalance"].as_str().unwrap()).unwrap(),
+    }
+}
+
+fn format_cancel_order_item(order: Value) -> Order {
+     Order {
+        id: format!("{}", order["orderId"].as_str().unwrap()),
+        custom_id: order["orderLinkId"].as_str().unwrap().replace("t-my-custom-id_", "").replace("t-", ""),
+        price: Decimal::ZERO,
+        amount: Decimal::ZERO,
+        deal_amount: Decimal::ZERO,
+        avg_price: Decimal::ZERO,
+        status: "REMOVE".to_string(),
+        order_type: "limit".to_string(),
+        trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string())
+    }
+}
+
+fn format_new_order_item(order: Value, price: Decimal, amount: Decimal) -> Order {
+    Order {
+        id: format!("{}", order["orderId"].as_str().unwrap()),
+        custom_id: order["orderLinkId"].as_str().unwrap().replace("t-my-custom-id_", "").replace("t-", ""),
+        price,
+        amount,
+        deal_amount: Decimal::ZERO,
+        avg_price: price,
+        status: "NEW".to_string(),
+        order_type: "limit".to_string(),
+        trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string())
+    }
+}
+
+pub fn format_order_item(order: Value, ct_val: Decimal) -> Order {
+    let status = order["orderStatus"].as_str().unwrap_or("");
+    let text = order["orderLinkId"].as_str().unwrap_or("");
+    let mut size = Decimal::ZERO;
+    let mut deal_amount = Decimal::ZERO;
+    let mut avg_price = Decimal::ZERO;
+
+    let right_str = order["cumExecQty"].to_string();
+    let size_str = order["qty"].to_string();
+
+    if !order.get("qty").is_some() {
+        size = Decimal::from_str(size_str.as_str()).unwrap();
+        let right_val = Decimal::from_str(order["cumExecValue"].as_str().unwrap()).unwrap();
+        let right = Decimal::from_str(right_str.as_str()).unwrap();
+        if right != Decimal::ZERO {
+            avg_price = right_val / right;
+        }
+        deal_amount = right * ct_val;
+    }
+
+    let amount = size * ct_val;
+    let custom_status = if status == "Filled" || status == "Cancelled" { "REMOVE".to_string() } else if status == "New" { "NEW".to_string() } else {
+        "NULL".to_string()
+    };
+    let rst_order = Order {
+        id: format!("{}", order["orderId"].as_str().unwrap()),
+        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,
+        status: custom_status,
+        order_type: "limit".to_string(),
+        trace_stack: TraceStack::new(0, Instant::now()).on_special("688 trace_stack".to_string()),
+    };
+    return rst_order;
+}

+ 169 - 163
standard/src/bybit_swap_handle.rs

@@ -1,167 +1,173 @@
-// use std::str::FromStr;
-// use rust_decimal::Decimal;
-// use serde_json::{from_value, Value};
-// use tracing::{error};
-// use exchanges::response_base::ResponseData;
-// use crate::{Account, OrderBook, Order, Position, PositionModeEnum, SpecialOrder};
+use std::str::FromStr;
+use rust_decimal::Decimal;
+use serde_json::{from_value, Value};
+use tokio::time::Instant;
+use tracing::{error};
+use exchanges::response_base::ResponseData;
+use global::trace_stack::TraceStack;
+use crate::{Account, OrderBook, Order, Position, PositionModeEnum, SpecialOrder};
+
+// 处理账号信息
+pub fn handle_account_info(res_data: &ResponseData, symbol: &String) -> Account {
+    format_account_info(res_data.data.as_array().unwrap().clone(), symbol)
+}
+
+pub fn format_account_info(data: Vec<Value>, symbol: &String) -> Account {
+    let account = data.iter().find(| &item | item["accountType"] == "UNIFIED");
+    match account {
+        None => {
+            error!("Bybit:格式化统一账户信息错误!\nformat_account_info: data={:?}", data);
+            panic!("Bybit:格式化统一账户信息错误!\nformat_account_info: data={:?}", data)
+        }
+        Some(val) =>{
+            let arr: Vec<Value> = from_value(val["coin"].clone()).unwrap();
+            let upper_str = symbol.to_uppercase();
+            let symbol_array: Vec<&str> = upper_str.split("_").collect();
+            let balance_info = arr.iter().find(|&item| item["coin"].as_str().unwrap() == symbol_array[1]);
+            match balance_info {
+                None => {
+                    error!("Bybit:格式化usdt余额信息错误!\nformat_account_info: data={:?}", balance_info);
+                    panic!("Bybit:格式化usdt余额信息错误!\nformat_account_info: data={:?}", balance_info)
+                }
+                Some(value) => {
+                    let balance = Decimal::from_str(&value["walletBalance"].as_str().unwrap().to_string()).unwrap();
+                    Account {
+                        coin: symbol_array[1].to_string(),
+                        balance,
+                        available_balance: Decimal::ZERO,
+                        frozen_balance: Decimal::ZERO,
+                        stocks: Decimal::ZERO,
+                        available_stocks: Decimal::ZERO,
+                        frozen_stocks: Decimal::ZERO,
+                    }
+                }
+            }
+        }
+    }
+}
+
+// 处理position信息
+pub fn handle_position(res_data: &ResponseData, ct_val: &Decimal) -> Vec<Position> {
+    res_data.data.as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect()
+}
+
+pub fn format_position_item(position: &Value, ct_val: &Decimal) -> Position {
+    let position_idx: String = position["positionIdx"].to_string();
+    let mut position_mode = match position_idx.as_str() {
+        "0" => PositionModeEnum::Both,
+        "1" => PositionModeEnum::Long,
+        "2" => PositionModeEnum::Short,
+        _ => {
+            error!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position);
+            panic!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position)
+        }
+    };
+    let symbol_mapper =  position["symbol"].as_str().unwrap().to_string();
+    let currency = "USDT";
+    let coin = &symbol_mapper[..symbol_mapper.find(currency).unwrap_or(0)];
+    let size_str: String = from_value(position["size"].clone()).unwrap();
+    let size = Decimal::from_str(size_str.as_str()).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: format!{"{}_{}", coin, currency},
+        margin_level: Decimal::from_str(position["leverage"].as_str().unwrap()).unwrap(),
+        amount,
+        frozen_amount: Decimal::ZERO,
+        price: Decimal::from_str(position["entryPrice"].as_str().unwrap()).unwrap(),
+        profit: Decimal::from_str(position["unrealisedPnl"].as_str().unwrap()).unwrap(),
+        position_mode,
+        margin: Decimal::from_str(position["positionBalance"].as_str().unwrap()).unwrap(),
+    }
+}
+
+// 处理order信息
+pub fn handle_order(res_data: &ResponseData, ct_val: &Decimal) -> SpecialOrder {
+    let res_data_json: Vec<Value> = res_data.data.as_array().unwrap().clone();
+    let mut order_info = Vec::new();
+    for item in res_data_json.iter() {
+        order_info.push(format_order_item(item.clone(), ct_val));
+    };
+
+    SpecialOrder {
+        name: res_data.label.clone(),
+        order: order_info,
+    }
+}
+
+pub fn format_order_item(order: Value, ct_val: &Decimal) -> Order {
+    let status = order["orderStatus"].as_str().unwrap_or("");
+    let text = order["orderLinkId"].as_str().unwrap_or("");
+    let size = Decimal::from_str(order["qty"].as_str().unwrap()).unwrap();
+    let right = Decimal::from_str(order["cumExecQty"].as_str().unwrap()).unwrap();
+    let right_val = Decimal::from_str(order["cumExecValue"].as_str().unwrap()).unwrap();
+    let price = Decimal::from_str(order["price"].as_str().unwrap()).unwrap();
+    let amount = size * ct_val;
+    let mut avg_price = Decimal::ZERO;
+    if right != Decimal::ZERO {
+        avg_price = right_val / right;
+    }
+    let deal_amount = right * ct_val;
+    let custom_status = if status == "Filled" || status == "Cancelled" { "REMOVE".to_string() } else if status == "New" { "NEW".to_string() } else {
+        "NULL".to_string()
+    };
+    let rst_order = Order {
+        id: format!("{}", order["orderId"].as_str().unwrap()),
+        custom_id: text.replace("t-my-custom-id_", "").replace("t-", ""),
+        price,
+        amount,
+        deal_amount,
+        avg_price,
+        status: custom_status,
+        order_type: "limit".to_string(),
+        trace_stack: TraceStack::new(0, Instant::now()).on_special("132 bybit_swap_handle".to_string()),
+    };
+
+    rst_order
+}
+
+// 处理特殊Ticket信息
+// pub fn handle_ticker(res_data: &ResponseData) -> SpecialDepth {
+//     let ap = Decimal::from_str(res_data.data["ask1Price"].as_str().unwrap()).unwrap();
+//     let bp = Decimal::from_str(res_data.data["bid1Price"].as_str().unwrap()).unwrap();
+//     let aq = Decimal::from_str(res_data.data["ask1Size"].as_str().unwrap()).unwrap();
+//     let bq = Decimal::from_str(res_data.data["bid1Size"].as_str().unwrap()).unwrap();
+//     let mp = (bp + ap) * dec!(0.5);
 //
-// // 处理账号信息
-// pub fn handle_account_info(res_data: &ResponseData, symbol: &String) -> Account {
-//     format_account_info(res_data.data.as_array().unwrap().clone(), symbol)
-// }
-//
-// pub fn format_account_info(data: Vec<Value>, symbol: &String) -> Account {
-//     let account = data.iter().find(| &item | item["accountType"] == "UNIFIED");
-//     match account {
-//         None => {
-//             error!("Bybit:格式化统一账户信息错误!\nformat_account_info: data={:?}", data);
-//             panic!("Bybit:格式化统一账户信息错误!\nformat_account_info: data={:?}", data)
-//         }
-//         Some(val) =>{
-//             let arr: Vec<Value> = from_value(val["coin"].clone()).unwrap();
-//             let upper_str = symbol.to_uppercase();
-//             let symbol_array: Vec<&str> = upper_str.split("_").collect();
-//             let balance_info = arr.iter().find(|&item| item["coin"].as_str().unwrap() == symbol_array[1]);
-//             match balance_info {
-//                 None => {
-//                     error!("Bybit:格式化usdt余额信息错误!\nformat_account_info: data={:?}", balance_info);
-//                     panic!("Bybit:格式化usdt余额信息错误!\nformat_account_info: data={:?}", balance_info)
-//                 }
-//                 Some(value) => {
-//                     let balance = Decimal::from_str(&value["walletBalance"].as_str().unwrap().to_string()).unwrap();
-//                     Account {
-//                         coin: symbol_array[1].to_string(),
-//                         balance,
-//                         available_balance: Decimal::ZERO,
-//                         frozen_balance: Decimal::ZERO,
-//                         stocks: Decimal::ZERO,
-//                         available_stocks: Decimal::ZERO,
-//                         frozen_stocks: Decimal::ZERO,
-//                     }
-//                 }
-//             }
-//         }
-//     }
-// }
-//
-// // 处理position信息
-// pub fn handle_position(res_data: &ResponseData, ct_val: &Decimal) -> Vec<Position> {
-//     res_data.data.as_array().unwrap().iter().map(|item| { format_position_item(item, ct_val) }).collect()
-// }
-//
-// pub fn format_position_item(position: &Value, ct_val: &Decimal) -> Position {
-//     let position_idx: String = position["positionIdx"].to_string();
-//     let mut position_mode = match position_idx.as_str() {
-//         "0" => PositionModeEnum::Both,
-//         "1" => PositionModeEnum::Long,
-//         "2" => PositionModeEnum::Short,
-//         _ => {
-//             error!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position);
-//             panic!("bybit_swap:格式化持仓模式错误!\nformat_position_item:position={:?}", position)
-//         }
-//     };
-//     let symbol_mapper =  position["symbol"].as_str().unwrap().to_string();
-//     let currency = "USDT";
-//     let coin = &symbol_mapper[..symbol_mapper.find(currency).unwrap_or(0)];
-//     let size_str: String = from_value(position["size"].clone()).unwrap();
-//     let size = Decimal::from_str(size_str.as_str()).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: format!{"{}_{}", coin, currency},
-//         margin_level: Decimal::from_str(position["leverage"].as_str().unwrap()).unwrap(),
-//         amount,
-//         frozen_amount: Decimal::ZERO,
-//         price: Decimal::from_str(position["entryPrice"].as_str().unwrap()).unwrap(),
-//         profit: Decimal::from_str(position["unrealisedPnl"].as_str().unwrap()).unwrap(),
-//         position_mode,
-//         margin: Decimal::from_str(position["positionBalance"].as_str().unwrap()).unwrap(),
-//     }
-// }
-//
-// // 处理order信息
-// pub fn handle_order(res_data: &ResponseData, ct_val: Decimal) -> SpecialOrder {
-//     let res_data_json: Vec<Value> = res_data.data.as_array().unwrap().clone();
-//     let mut order_info = Vec::new();
-//     for item in res_data_json.iter() {
-//         order_info.push(format_order_item(item.clone(), ct_val));
-//     };
+//     let t = Decimal::from_i64(res_data.data["ts"].as_i64().unwrap()).unwrap();
+//     let create_at = t.to_i64().unwrap();
 //
-//     SpecialOrder {
-//         name: res_data.label.clone(),
-//         order: order_info,
+//     let ticker_info = SpecialTicker { sell: ap, buy: bp, mid_price: mp, t, create_at: 0 };
+//     let depth_info = vec![bp, bq, ap, aq];
+//     SpecialDepth {
+//         name: res_data.tag.clone(),
+//         depth: depth_info,
+//         ticker: ticker_info,
+//         t,
+//         create_at,
 //     }
 // }
-//
-// pub fn format_order_item(order: Value, ct_val: Decimal) -> Order {
-//     let status = order["orderStatus"].as_str().unwrap_or("");
-//     let text = order["orderLinkId"].as_str().unwrap_or("");
-//     let size = Decimal::from_str(order["qty"].as_str().unwrap()).unwrap();
-//     let right = Decimal::from_str(order["cumExecQty"].as_str().unwrap()).unwrap();
-//     let right_val = Decimal::from_str(order["cumExecValue"].as_str().unwrap()).unwrap();
-//     let price = Decimal::from_str(order["price"].as_str().unwrap()).unwrap();
-//     let amount = size * ct_val;
-//     let mut avg_price = Decimal::ZERO;
-//     if right != Decimal::ZERO {
-//         avg_price = right_val / right;
-//     }
-//     let deal_amount = right * ct_val;
-//     let custom_status = if status == "Filled" || status == "Cancelled" { "REMOVE".to_string() } else if status == "New" { "NEW".to_string() } else {
-//         "NULL".to_string()
-//     };
-//     let rst_order = Order {
-//         id: format!("{}", order["orderId"].as_str().unwrap()),
-//         custom_id: text.replace("t-my-custom-id_", "").replace("t-", ""),
-//         price,
-//         amount,
-//         deal_amount,
-//         avg_price,
-//         status: custom_status,
-//         order_type: "limit".to_string()
-//     };
-//
-//     return rst_order;
-// }
-//
-// // 处理特殊Ticket信息
-// // pub fn handle_ticker(res_data: &ResponseData) -> SpecialDepth {
-// //     let ap = Decimal::from_str(res_data.data["ask1Price"].as_str().unwrap()).unwrap();
-// //     let bp = Decimal::from_str(res_data.data["bid1Price"].as_str().unwrap()).unwrap();
-// //     let aq = Decimal::from_str(res_data.data["ask1Size"].as_str().unwrap()).unwrap();
-// //     let bq = Decimal::from_str(res_data.data["bid1Size"].as_str().unwrap()).unwrap();
-// //     let mp = (bp + ap) * dec!(0.5);
-// //
-// //     let t = Decimal::from_i64(res_data.data["ts"].as_i64().unwrap()).unwrap();
-// //     let create_at = t.to_i64().unwrap();
-// //
-// //     let ticker_info = SpecialTicker { sell: ap, buy: bp, mid_price: mp, t, create_at: 0 };
-// //     let depth_info = vec![bp, bq, ap, aq];
-// //     SpecialDepth {
-// //         name: res_data.tag.clone(),
-// //         depth: depth_info,
-// //         ticker: ticker_info,
-// //         t,
-// //         create_at,
-// //     }
-// // }
-//
-// pub fn format_depth_items(value: serde_json::Value) -> Vec<OrderBook> {
-//     let mut depth_items: Vec<OrderBook> = vec![];
-//     for val in value.as_array().unwrap() {
-//         let arr = val.as_array().unwrap();
-//         depth_items.push(OrderBook {
-//             price: Decimal::from_str(arr[0].as_str().unwrap()).unwrap(),
-//             amount: Decimal::from_str(arr[1].as_str().unwrap()).unwrap(),
-//         })
-//     }
-//     return depth_items;
-// }
+
+pub fn format_depth_items(value: Value) -> Vec<OrderBook> {
+    let mut depth_items: Vec<OrderBook> = vec![];
+    for val in value.as_array().unwrap() {
+        let arr = val.as_array().unwrap();
+        let price = Decimal::from_str(arr[0].as_str().unwrap()).unwrap();
+        let size = Decimal::from_str(arr[1].as_str().unwrap()).unwrap();
+        depth_items.push(OrderBook {
+            price,
+            size,
+            value: price * size,
+        })
+    }
+    depth_items
+}

+ 5 - 4
standard/src/exchange.rs

@@ -3,6 +3,7 @@ use std::io::Error;
 use tokio::sync::mpsc::Sender;
 use crate::{Order, Platform};
 use crate::binance_swap::BinanceSwap;
+use crate::bybit_swap::BybitSwap;
 use crate::coinex_swap::CoinexSwap;
 use crate::gate_swap::GateSwap;
 
@@ -24,7 +25,7 @@ pub enum ExchangeEnum {
     // OkxSwap,
     // BitgetSpot,
     // BitgetSwap,
-    // BybitSwap,
+    BybitSwap,
     // HtxSwap,
     // BingxSwap,
     // MexcSwap,
@@ -101,9 +102,9 @@ impl Exchange {
             // ExchangeEnum::BitgetSwap => {
             //     Box::new(BitgetSwap::new(symbol, is_colo, params, order_sender, error_sender).await)
             // }
-            // ExchangeEnum::BybitSwap => {
-            //     Box::new(BybitSwap::new(symbol, is_colo, params, order_sender, error_sender).await)
-            // }
+            ExchangeEnum::BybitSwap => {
+                Box::new(BybitSwap::new(symbol, is_colo, params, order_sender, error_sender).await)
+            }
             ExchangeEnum::CoinexSwap => {
                 Box::new(CoinexSwap::new(symbol, is_colo, params, order_sender, error_sender).await)
             }

+ 32 - 15
standard/src/exchange_struct_handler.rs

@@ -1,9 +1,10 @@
 use std::str::FromStr;
 use rust_decimal::{Decimal};
+use rust_decimal::prelude::FromPrimitive;
 use tracing::error;
 use exchanges::response_base::ResponseData;
 use crate::exchange::ExchangeEnum;
-use crate::{binance_swap_handle, coinex_swap_handle, gate_swap_handle};
+use crate::{binance_swap_handle, bybit_swap_handle, coinex_swap_handle, gate_swap_handle};
 use crate::{Record, Trade, Depth};
 use crate::{Account, OrderBook, Position, SpecialOrder};
 
@@ -50,11 +51,13 @@ impl ExchangeStructHandler {
             //     depth_bids = bitget_swap_handle::format_depth_items(res_data.data[0]["bids"].clone());
             //     t = Decimal::from_str(res_data.data[0]["ts"].as_str().unwrap()).unwrap();
             // }
-            // ExchangeEnum::BybitSwap => {
-            //     depth_asks = bybit_swap_handle::format_depth_items(res_data.data["a"].clone());
-            //     depth_bids = bybit_swap_handle::format_depth_items(res_data.data["b"].clone());
-            //     t = Decimal::from_i64(res_data.reach_time).unwrap();
-            // }
+            ExchangeEnum::BybitSwap => {
+                depth_asks = bybit_swap_handle::format_depth_items(res_data.data["a"].clone());
+                depth_bids = bybit_swap_handle::format_depth_items(res_data.data["b"].clone());
+                t = Decimal::from_i64(res_data.reach_time).unwrap();
+
+                res_data.data["s"].as_str().unwrap().to_string().replace("USDT", "_USDT")
+            }
             // ExchangeEnum::BingxSwap => {
             //     depth_asks = bingx_swap_handle::format_depth_items(&res_data.data["data"]["asks"].clone());
             //     depth_bids = bingx_swap_handle::format_depth_items(&res_data.data["data"]["bids"].clone());
@@ -113,6 +116,9 @@ impl ExchangeStructHandler {
             ExchangeEnum::BinanceSwap => {
                 binance_swap_handle::format_trade_items(&res_data)
             }
+            ExchangeEnum::BybitSwap => { // 未使用暂不实现
+                vec![]
+            }
             ExchangeEnum::CoinexSwap => {
                 coinex_swap_handle::format_trade_items(&res_data)
             }
@@ -162,6 +168,14 @@ impl ExchangeStructHandler {
             ExchangeEnum::BinanceSwap => {
                 binance_swap_handle::handle_book_ticker(&res_data, mul)
             }
+            ExchangeEnum::BybitSwap => {  // 未使用暂不实现
+                Depth {
+                    time: Decimal::ZERO,
+                    symbol: "".to_string(),
+                    asks: vec![],
+                    bids: vec![],
+                }
+            }
             _ => {
                 error!("未找到该交易所!book_ticker_handle: {:?}", exchange);
                 panic!("未找到该交易所!book_ticker_handle: {:?}", exchange);
@@ -183,6 +197,9 @@ impl ExchangeStructHandler {
             ExchangeEnum::BinanceSwap => {
                 binance_swap_handle::handle_records(&res_data.data)
             }
+            ExchangeEnum::BybitSwap => { // 未使用暂不实现
+                vec![]
+            }
             // ExchangeEnum::HtxSwap => {
             //     htx_swap_handle::handle_records(&res_data.data)
             // }
@@ -231,9 +248,9 @@ impl ExchangeStructHandler {
             // ExchangeEnum::BitgetSwap => {
             //     bitget_swap_handle::handle_account_info(res_data, symbol)
             // }
-            // ExchangeEnum::BybitSwap => {
-            //     bybit_swap_handle::handle_account_info(res_data, symbol)
-            // }
+            ExchangeEnum::BybitSwap => {
+                bybit_swap_handle::handle_account_info(res_data, symbol)
+            }
             _ => {
                 error!("未找到该交易所!handle_account_info: {:?}", exchange);
                 panic!("未找到该交易所!handle_account_info: {:?}", exchange);
@@ -255,9 +272,9 @@ impl ExchangeStructHandler {
             // ExchangeEnum::BitgetSwap => {
             //     bitget_swap_handle::handle_position(res_data, ct_val)
             // }
-            // ExchangeEnum::BybitSwap => {
-            //     bybit_swap_handle::handle_position(res_data, ct_val)
-            // }
+            ExchangeEnum::BybitSwap => {
+                bybit_swap_handle::handle_position(res_data, mul)
+            }
             _ => {
                 error!("暂未提供此交易所方法!handle_position:{:?}", exchange);
                 panic!("暂未提供此交易所方法!handle_position:{:?}", exchange);
@@ -279,9 +296,9 @@ impl ExchangeStructHandler {
             // ExchangeEnum::BitgetSwap => {
             //     bitget_swap_handle::handle_order(res_data, ct_val)
             // }
-            // ExchangeEnum::BybitSwap => {
-            //     bybit_swap_handle::handle_order(res_data, ct_val)
-            // }
+            ExchangeEnum::BybitSwap => {
+                bybit_swap_handle::handle_order(res_data, ct_val)
+            }
             _ => {
                 error!("暂未提供此交易所方法!order_handle:{:?}", exchange);
                 panic!("暂未提供此交易所方法!order_handle:{:?}", exchange);

+ 202 - 246
strategy/src/bybit_usdt_swap.rs

@@ -1,253 +1,209 @@
-// use std::collections::BTreeMap;
-// use std::sync::Arc;
-// use std::sync::atomic::{AtomicBool};
-// use rust_decimal::Decimal;
-// use tokio::{spawn};
-// use tokio::sync::Mutex;
-// use tracing::{error, info};
-// use tokio_tungstenite::tungstenite::Message;
-// use exchanges::bybit_swap_ws::{BybitSwapLogin, BybitSwapSubscribeType, BybitSwapWs, BybitSwapWsType};
-// use exchanges::response_base::ResponseData;
-// use global::trace_stack::TraceStack;
-// use standard::exchange::ExchangeEnum::BybitSwap;
-// use crate::core::Core;
-// use crate::exchange_disguise::on_special_depth;
-// use crate::model::OrderInfo;
-//
-// // 1交易、0参考 bybit 合约 启动
-// pub async fn bybit_swap_run(is_shutdown_arc: Arc<AtomicBool>,
-//                             is_trade: bool,
-//                             core_arc: Arc<Mutex<Core>>,
-//                             name: String,
-//                             symbols: Vec<String>,
-//                             is_colo: bool,
-//                             exchange_params: BTreeMap<String, String>) {
-//     // 启动公共频道
-//     let (write_tx_public, write_rx_public) = futures_channel::mpsc::unbounded::<Message>();
-//
-//     let mut ws_public = BybitSwapWs::new_label(name.clone(), is_colo, None, BybitSwapWsType::Public);
-//     ws_public.set_symbols(symbols.clone());
-//     ws_public.set_subscribe(vec![
-//         BybitSwapSubscribeType::PuTickers
-//     ]);
-//     // if is_trade {
-//     //     ws_public.set_subscribe(vec![
-//     //         BybitSwapSubscribeType::PuBlicTrade
-//     //     ]);
-//     // }
-//     // 挂起公共ws
-//     let write_tx_am_public = Arc::new(Mutex::new(write_tx_public));
-//     let is_shutdown_clone_public = Arc::clone(&is_shutdown_arc);
-//     let core_arc_clone_public = core_arc.clone();
-//     spawn(async move {
-//         // 消费数据
-//         let mut update_flag_u = Decimal::ZERO;
-//
-//         let fun = move |data: ResponseData| {
-//             let core_arc = core_arc_clone_public.clone();
-//
-//             async move {
-//                 on_public_data(core_arc,
-//                                &mut update_flag_u,
-//                                data).await;
-//             }
-//         };
-//
-//         // ws_public.ws_connect_async(is_shutdown_clone_public,
-//         //                            fun,
-//         //                            &write_tx_am_public,
-//         //                            write_rx_public).await.expect("链接失败(内部一个心跳线程应该已经关闭了)");
-//     });
-//     let trade_symbols = symbols.clone();
-//     // 交易交易所需要启动私有ws
-//     if is_trade {
-//         let (write_tx_private, write_rx_private) = futures_channel::mpsc::unbounded();
-//         let auth = Some(parse_btree_map_to_bybit_swap_login(exchange_params));
-//
-//         let mut ws_private = BybitSwapWs::new_label(name.clone(), is_colo, auth, BybitSwapWsType::Private);
-//         ws_private.set_symbols(trade_symbols);
-//         ws_private.set_subscribe(vec![
-//             BybitSwapSubscribeType::PrPosition,
-//             BybitSwapSubscribeType::PrOrder,
-//             BybitSwapSubscribeType::PrWallet
-//         ]);
-//
-//         // 挂起私有ws
-//         let write_tx_am_private = Arc::new(Mutex::new(write_tx_private));
-//         let is_shutdown_clone_private = Arc::clone(&is_shutdown_arc);
-//         let core_arc_clone_private = core_arc.clone();
-//         spawn(async move {
-//             let ct_val = core_arc_clone_private.lock().await.platform_rest.get_self_market().ct_val;
-//             let run_symbol = symbols.clone()[0].clone();
-//
-//             let fun = move |data: ResponseData| {
-//                 let core_arc_clone = core_arc_clone_private.clone();
-//                 let run_symbol_clone = run_symbol.clone();
-//
-//                 async move {
-//                     on_private_data(core_arc_clone.clone(), &ct_val, &run_symbol_clone, data).await;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool};
+use rust_decimal::Decimal;
+use tokio::{spawn};
+use tokio::sync::Mutex;
+use tracing::{error, info};
+use tokio_tungstenite::tungstenite::Message;
+use exchanges::bybit_swap_ws::{BybitSwapLogin, BybitSwapSubscribeType, BybitSwapWs, BybitSwapWsType};
+use exchanges::response_base::ResponseData;
+use global::trace_stack::TraceStack;
+use standard::exchange::ExchangeEnum::BybitSwap;
+use standard::exchange_struct_handler::ExchangeStructHandler;
+use crate::core::Core;
+use crate::model::OrderInfo;
+
+// 参考 币安 合约 启动
+pub(crate) async fn reference_bybit_swap_run(is_shutdown_arc: Arc<AtomicBool>,
+                                             core_arc: Arc<Mutex<Core>>,
+                                             name: String,
+                                             symbols: Vec<String>,
+                                             is_colo: bool) {
+    spawn(async move {
+        //创建读写通道
+        let (write_tx, write_rx) = futures_channel::mpsc::unbounded::<Message>();
+        let mut ws = BybitSwapWs::new_label(name, is_colo, None, BybitSwapWsType::Public);
+        ws.set_subscribe(vec![
+            BybitSwapSubscribeType::PuOrderBook1
+        ]);
+
+        // 读取数据
+        let core_arc_clone = Arc::clone(&core_arc);
+        let multiplier = core_arc_clone.lock().await.platform_rest.get_self_market().multiplier;
+        let run_symbol = symbols.clone()[0].clone();
+
+        let fun = move |data: ResponseData| {
+            // 在 async 块之前克隆 Arc
+            let core_arc_cc = core_arc_clone.clone();
+            let mul = multiplier.clone();
+            let rs = run_symbol.clone();
+
+            async move {
+                // 使用克隆后的 Arc,避免 move 语义
+                on_data(core_arc_cc, &mul, &rs, &data).await
+            }
+        };
+
+        // 链接
+        let write_tx_am = Arc::new(Mutex::new(write_tx));
+        ws.set_symbols(symbols);
+        ws.ws_connect_async(is_shutdown_arc, fun, &write_tx_am, write_rx).await.expect("链接失败");
+    });
+}
+
+// 交易 bybit 合约 启动
+pub(crate) async fn bybit_swap_run(is_shutdown_arc: Arc<AtomicBool>,
+                                   core_arc: Arc<Mutex<Core>>,
+                                   name: String,
+                                   symbols: Vec<String>,
+                                   is_colo: bool,
+                                   exchange_params: BTreeMap<String, String>) {
+    spawn(async move {
+        // 交易交易所需要启动私有ws
+        let (write_tx, write_rx) = futures_channel::mpsc::unbounded();
+        let auth = Some(parse_btree_map_to_bybit_swap_login(exchange_params));
+        let mut ws = BybitSwapWs::new_label(name.clone(), is_colo, auth, BybitSwapWsType::Private);
+        ws.set_subscribe(vec![
+            BybitSwapSubscribeType::PrPosition,
+            BybitSwapSubscribeType::PrOrder,
+            BybitSwapSubscribeType::PrWallet
+        ]);
+
+        let core_arc_clone_private = core_arc.clone();
+        let multiplier = core_arc_clone_private.lock().await.platform_rest.get_self_market().multiplier;
+        let run_symbol = symbols.clone()[0].clone();
+
+        // 挂起私有ws
+        let fun = move |data: ResponseData| {
+            // 在 async 块之前克隆 Arc
+            let core_arc_cc = core_arc_clone_private.clone();
+            let mul = multiplier.clone();
+            let rs = run_symbol.clone();
+
+            async move {
+                // 使用克隆后的 Arc,避免 move 语义
+                on_data(core_arc_cc, &mul, &rs, &data).await;
+            }
+        };
+
+        // 链接
+        let write_tx_am = Arc::new(Mutex::new(write_tx));
+        ws.set_symbols(symbols);
+        ws.ws_connect_async(is_shutdown_arc, fun, &write_tx_am, write_rx).await.expect("链接失败");
+    });
+}
+
+async fn on_data(core_arc_clone: Arc<Mutex<Core>>, ct_val: &Decimal, run_symbol: &String, response: &ResponseData) {
+    let mut trace_stack = TraceStack::new(response.time, response.ins);
+    trace_stack.on_after_span_line();
+
+    match response.channel.as_str() {
+        "orderbook" => {
+            // let mut is_update = false;
+            // let data_type = data.data_type.clone();
+            // let label = data.label.clone();
+            // if data_type == "delta"  {
+            //     is_update = true;
+            // }
+            // let mut depth_format: DepthParam = format_depth(BybitSwap, &data);
+            // // 是增量更新
+            // if is_update {
+            //     update_order_book(depth_asks, depth_bids, depth_format.depth_asks, depth_format.depth_bids);
+            // } else { // 全量
+            //     depth_asks.clear();
+            //     depth_asks.append(&mut depth_format.depth_asks);
+            //     depth_bids.clear();
+            //     depth_bids.append(&mut depth_format.depth_bids);
+            // }
+            // let depth = make_special_depth(label.clone(), depth_asks, depth_bids, depth_format.t, depth_format.create_at);
+            // trace_stack.on_before_network(depth_format.create_at.clone());
+            // trace_stack.on_after_format();
+            //
+            // on_special_depth(core_arc_clone, update_flag_u, &label, &mut trace_stack, &depth).await;
+        }
+        "wallet" => {
+            let account = ExchangeStructHandler::account_info_handle(BybitSwap, response, run_symbol);
+            let mut core = core_arc_clone.lock().await;
+            core.update_equity(account).await;
+        }
+        "order" => {
+            let orders = ExchangeStructHandler::order_handle(BybitSwap, response, ct_val);
+            trace_stack.on_after_format();
+
+            let mut order_infos:Vec<OrderInfo> = Vec::new();
+            for mut order in orders.order {
+                if order.status == "NULL" {
+                    error!("bybit_usdt_swap 未识别的订单状态:{:?}", response);
+
+                    continue;
+                }
+
+                if order.deal_amount != Decimal::ZERO {
+                    info!("bybit order 消息原文:{:?}", response);
+                }
+
+                let order_info = OrderInfo::parse_order_to_order_info(&mut order);
+                order_infos.push(order_info);
+            }
+
+            let mut core = core_arc_clone.lock().await;
+            core.update_order(order_infos, trace_stack).await;
+        }
+        "position" => {
+            let positions = ExchangeStructHandler::position_handle(BybitSwap, response, ct_val);
+            let mut core = core_arc_clone.lock().await;
+            core.update_position(positions).await;
+        }
+        _ => {
+            error!("未知推送类型");
+            error!(?response);
+        }
+    }
+}
+
+fn parse_btree_map_to_bybit_swap_login(exchange_params: BTreeMap<String, String>) -> BybitSwapLogin {
+    BybitSwapLogin {
+        api_key: exchange_params.get("access_key").unwrap().clone(),
+        secret_key: exchange_params.get("secret_key").unwrap().clone(),
+    }
+}
+
+// fn update_order_book(depth_asks: &mut Vec<MarketOrder>, depth_bids: &mut Vec<MarketOrder>, asks : Vec<MarketOrder>, bids: Vec<MarketOrder>) {
+//     for i in asks {
+//         let index_of_value = depth_asks.iter().position(|x| x.price == i.price);
+//         match index_of_value {
+//             Some(index) => {
+//                 if i.amount == Decimal::ZERO {
+//                     depth_asks.remove(index);
+//                 } else {
+//                     depth_asks[index].amount = i.amount.clone();
 //                 }
-//             };
-//
-//             ws_private.ws_connect_async(is_shutdown_clone_private,
-//                                         fun,
-//                                         &write_tx_am_private,
-//                                         write_rx_private).await.expect("链接失败(内部一个心跳线程应该已经关闭了)");
-//         });
-//     }
-// }
-//
-// async fn on_private_data(core_arc_clone: Arc<Mutex<Core>>, ct_val: &Decimal, run_symbol: &String, response: ResponseData) {
-//     let mut trace_stack = TraceStack::new(response.time, response.ins);
-//     trace_stack.on_after_span_line();
-//
-//     match response.channel.as_str() {
-//         // "wallet" => {
-//         //     let account = standard::handle_info::HandleSwapInfo::handle_account_info(BybitSwap, &response, run_symbol);
-//         //     let mut core = core_arc_clone.lock().await;
-//         //     core.update_equity(account).await;
-//         // }
-//         // "order" => {
-//         //     let orders = standard::handle_info::HandleSwapInfo::handle_order(BybitSwap, response.clone(), ct_val.clone());
-//         //     trace_stack.on_after_format();
-//         //
-//         //     let mut order_infos:Vec<OrderInfo> = Vec::new();
-//         //     for mut order in orders.order {
-//         //         if order.status == "NULL" {
-//         //             error!("bybit_usdt_swap 未识别的订单状态:{:?}", response);
-//         //
-//         //             continue;
-//         //         }
-//         //
-//         //         if order.deal_amount != Decimal::ZERO {
-//         //             info!("bybit order 消息原文:{:?}", response);
-//         //         }
-//         //
-//         //         let order_info = OrderInfo::parse_order_to_order_info(&mut order);
-//         //         order_infos.push(order_info);
-//         //     }
-//         //
-//         //     let mut core = core_arc_clone.lock().await;
-//         //     core.update_order(order_infos, trace_stack).await;
-//         // }
-//         // "position" => {
-//         //     let positions = standard::handle_info::HandleSwapInfo::handle_position(BybitSwap, &response, ct_val);
-//         //     let mut core = core_arc_clone.lock().await;
-//         //     core.update_position(positions).await;
-//         // }
-//         _ => {
-//             error!("未知推送类型");
-//             error!(?response);
+//             },
+//             None => {
+//                 depth_asks.push(i.clone());
+//             },
 //         }
 //     }
-// }
-//
-// async fn on_public_data(core_arc_clone: Arc<Mutex<Core>>, update_flag_u: &mut Decimal, response: ResponseData) {
-//     if response.code != 200 {
-//         return;
-//     }
-//
-//     let mut trace_stack = TraceStack::new(response.time, response.ins);
-//     trace_stack.on_after_span_line();
-//
-//     match response.channel.as_str() {
-//         "tickers" => {
-//             // trace_stack.set_source("bybit_usdt_swap.tickers".to_string());
-//             //
-//             // // 处理ticker信息
-//             // let special_depth = standard::handle_info::HandleSwapInfo::handle_book_ticker(BybitSwap, &response);
-//             // trace_stack.on_after_format();
-//             //
-//             // on_special_depth(core_arc_clone, update_flag_u, &response.label, &mut trace_stack, &special_depth).await;
-//         }
-//         "orderbook" => {
-//             // let mut is_update = false;
-//             // let data_type = data.data_type.clone();
-//             // let label = data.label.clone();
-//             // if data_type == "delta"  {
-//             //     is_update = true;
-//             // }
-//             // let mut depth_format: DepthParam = format_depth(BybitSwap, &data);
-//             // // 是增量更新
-//             // if is_update {
-//             //     update_order_book(depth_asks, depth_bids, depth_format.depth_asks, depth_format.depth_bids);
-//             // } else { // 全量
-//             //     depth_asks.clear();
-//             //     depth_asks.append(&mut depth_format.depth_asks);
-//             //     depth_bids.clear();
-//             //     depth_bids.append(&mut depth_format.depth_bids);
-//             // }
-//             // let depth = make_special_depth(label.clone(), depth_asks, depth_bids, depth_format.t, depth_format.create_at);
-//             // trace_stack.on_before_network(depth_format.create_at.clone());
-//             // trace_stack.on_after_format();
-//             //
-//             // on_special_depth(core_arc_clone, update_flag_u, &label, &mut trace_stack, &depth).await;
-//         }
-//         "trade" => {
-//             // let mut core = core_arc_clone.lock().await;
-//             // let str = data.label.clone();
-//             // if core.is_update.contains_key(&data.label) && *core.is_update.get(str.as_str()).unwrap(){
-//             //     *max_buy = Decimal::ZERO;
-//             //     *min_sell = Decimal::ZERO;
-//             //     core.is_update.remove(str.as_str());
-//             // }
-//             // let trades: Vec<OriginalTradeBy> = serde_json::from_str(data.data.as_str()).unwrap();
-//             // for trade in trades {
-//             //     if trade.p > *max_buy || *max_buy == Decimal::ZERO{
-//             //         *max_buy = trade.p
-//             //     }
-//             //     if trade.p < *min_sell || *min_sell == Decimal::ZERO{
-//             //         *min_sell = trade.p
-//             //     }
-//             // }
-//             // core.max_buy_min_sell_cache.insert(data.label, vec![*max_buy, *min_sell]);
+//     for i in bids {
+//         let index_of_value = depth_bids.iter().position(|x| x.price == i.price);
+//         match index_of_value {
+//             Some(index) => {
+//                 if i.amount == Decimal::ZERO {
+//                     depth_bids.remove(index);
+//                 } else {
+//                     depth_bids[index].amount = i.amount.clone();
+//                 }
+//             },
+//             None => {
+//                 depth_bids.push(i.clone());
+//             },
 //         }
-//         _ => {}
 //     }
-// }
+//     depth_asks.sort_by(|a, b| a.price.partial_cmp(&b.price).unwrap_or(Ordering::Equal));
+//     depth_bids.sort_by(|a, b| b.price.partial_cmp(&a.price).unwrap_or(Ordering::Equal));
 //
-// fn parse_btree_map_to_bybit_swap_login(exchange_params: BTreeMap<String, String>) -> BybitSwapLogin {
-//     BybitSwapLogin {
-//         api_key: exchange_params.get("access_key").unwrap().clone(),
-//         secret_key: exchange_params.get("secret_key").unwrap().clone(),
-//     }
+//     // 限制总长度100
+//     depth_asks.truncate(100);
+//     depth_bids.truncate(100);
 // }
-//
-// // fn update_order_book(depth_asks: &mut Vec<MarketOrder>, depth_bids: &mut Vec<MarketOrder>, asks : Vec<MarketOrder>, bids: Vec<MarketOrder>) {
-// //     for i in asks {
-// //         let index_of_value = depth_asks.iter().position(|x| x.price == i.price);
-// //         match index_of_value {
-// //             Some(index) => {
-// //                 if i.amount == Decimal::ZERO {
-// //                     depth_asks.remove(index);
-// //                 } else {
-// //                     depth_asks[index].amount = i.amount.clone();
-// //                 }
-// //             },
-// //             None => {
-// //                 depth_asks.push(i.clone());
-// //             },
-// //         }
-// //     }
-// //     for i in bids {
-// //         let index_of_value = depth_bids.iter().position(|x| x.price == i.price);
-// //         match index_of_value {
-// //             Some(index) => {
-// //                 if i.amount == Decimal::ZERO {
-// //                     depth_bids.remove(index);
-// //                 } else {
-// //                     depth_bids[index].amount = i.amount.clone();
-// //                 }
-// //             },
-// //             None => {
-// //                 depth_bids.push(i.clone());
-// //             },
-// //         }
-// //     }
-// //     depth_asks.sort_by(|a, b| a.price.partial_cmp(&b.price).unwrap_or(Ordering::Equal));
-// //     depth_bids.sort_by(|a, b| b.price.partial_cmp(&a.price).unwrap_or(Ordering::Equal));
-// //
-// //     // 限制总长度100
-// //     depth_asks.truncate(100);
-// //     depth_bids.truncate(100);
-// // }

+ 4 - 4
strategy/src/core.rs

@@ -20,7 +20,7 @@ use global::params::Params;
 use global::trace_stack::TraceStack;
 use standard::{Account, Depth, Market, Order, OrderCommand, Platform, Position, PositionModeEnum, SpecialTicker, Ticker, Trade};
 use standard::exchange::{Exchange};
-use standard::exchange::ExchangeEnum::{BinanceSwap, GateSwap};
+use standard::exchange::ExchangeEnum::{BinanceSwap, BybitSwap, GateSwap};
 
 use crate::model::{LocalPosition, OrderInfo, TokenParam};
 use crate::avellaneda_stoikov::AvellanedaStoikov;
@@ -215,9 +215,9 @@ impl Core {
                 // "okex_usdt_swap" => {
                 //     Exchange::new(OkxSwap, symbol, params.colo != 0i8, exchange_params, order_sender, error_sender).await
                 // }
-                // "bybit_usdt_swap" => {
-                //     Exchange::new(BybitSwap, symbol, params.colo != 0i8, exchange_params, order_sender, error_sender).await
-                // }
+                "bybit_usdt_swap" => {
+                    Exchange::new(BybitSwap, symbol, params.colo != 0i8, exchange_params, order_sender, error_sender).await
+                }
                 // "coinex_usdt_swap" => {
                 //     Exchange::new(CoinexSwap, symbol, params.colo != 0i8, exchange_params, order_sender, error_sender).await
                 // }

+ 7 - 6
strategy/src/exchange_disguise.rs

@@ -5,6 +5,7 @@ use tokio::sync::Mutex;
 use global::trace_stack::TraceStack;
 use standard::{Depth, Trade};
 use crate::binance_usdt_swap::{binance_swap_run, reference_binance_swap_run};
+use crate::bybit_usdt_swap::{bybit_swap_run, reference_bybit_swap_run};
 use crate::coinex_usdt_swap::coinex_swap_run;
 use crate::gate_usdt_swap::gate_swap_run;
 use crate::core::Core;
@@ -36,9 +37,9 @@ pub async fn run_transactional_exchange(is_shutdown_arc :Arc<AtomicBool>,
         // "bitget_usdt_swap" => {
         //     bitget_usdt_swap_run(is_shutdown_arc, true, core_arc, name, symbols, is_colo, exchange_params).await;
         // }
-        // "bybit_usdt_swap" => {
-        //     bybit_swap_run(is_shutdown_arc,true, core_arc, name, symbols, is_colo, exchange_params).await;
-        // }
+        "bybit_usdt_swap" => {
+            bybit_swap_run(is_shutdown_arc, core_arc, name, symbols, is_colo, exchange_params).await;
+        }
         "coinex_usdt_swap" => {
             coinex_swap_run(is_shutdown_arc,true, core_arc, name, symbols, is_colo, exchange_params).await;
         }
@@ -85,9 +86,9 @@ pub async fn run_reference_exchange(is_shutdown_arc: Arc<AtomicBool>,
         // "bitget_usdt_swap" => {
         //     bitget_usdt_swap_run(is_shutdown_arc, false, core_arc, name, symbols, is_colo, exchange_params).await;
         // }
-        // "bybit_usdt_swap" => {
-        //     bybit_swap_run(is_shutdown_arc, false, core_arc, name, symbols, is_colo, exchange_params).await;
-        // },
+        "bybit_usdt_swap" => {
+            reference_bybit_swap_run(is_shutdown_arc,  core_arc, name, symbols, is_colo).await;
+        },
         "coinex_usdt_swap" => {
             coinex_swap_run(is_shutdown_arc,false, core_arc, name, symbols, is_colo, exchange_params).await;
         }