bybit_swap_ws.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. use std::sync::Arc;
  2. use std::sync::atomic::AtomicBool;
  3. use chrono::Utc;
  4. use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
  5. use serde_json::{json, Value};
  6. use tokio::sync::Mutex;
  7. use tokio_tungstenite::tungstenite::{Error, Message};
  8. use tracing::{info, trace};
  9. use ring::hmac;
  10. use crate::response_base::ResponseData;
  11. use crate::socket_tool::{AbstractWsMode, HeartbeatType};
  12. //类型
  13. pub enum BybitSwapWsType {
  14. Public,
  15. Private,
  16. }
  17. //订阅频道
  18. #[derive(Clone)]
  19. pub enum BybitSwapSubscribeType {
  20. PuOrderBook1,
  21. PuOrderBook50,
  22. PuBlicTrade,
  23. PuTickers,
  24. PuKline(String),
  25. PrPosition,
  26. PrExecution,
  27. PrOrder,
  28. PrWallet,
  29. }
  30. //账号信息
  31. #[derive(Clone)]
  32. #[allow(dead_code)]
  33. pub struct BybitSwapLogin {
  34. pub api_key: String,
  35. pub secret_key: String,
  36. }
  37. #[derive(Clone)]
  38. #[allow(dead_code)]
  39. pub struct BybitSwapWs {
  40. //类型
  41. label: String,
  42. //地址
  43. address_url: String,
  44. //账号
  45. login_param: Option<BybitSwapLogin>,
  46. //币对
  47. symbol_s: Vec<String>,
  48. //订阅
  49. subscribe_types: Vec<BybitSwapSubscribeType>,
  50. //心跳间隔
  51. heartbeat_time: u64,
  52. }
  53. impl BybitSwapWs {
  54. /*******************************************************************************************************/
  55. /*****************************************获取一个对象****************************************************/
  56. /*******************************************************************************************************/
  57. pub fn new(is_colo: bool, login_param: Option<BybitSwapLogin>, ws_type: BybitSwapWsType) -> BybitSwapWs {
  58. return BybitSwapWs::new_label("default-BybitSwapWs".to_string(), is_colo, login_param, ws_type);
  59. }
  60. pub fn new_label(label: String, is_colo: bool, login_param: Option<BybitSwapLogin>, ws_type: BybitSwapWsType) -> BybitSwapWs {
  61. /*******公共频道-私有频道数据组装*/
  62. let address_url = match ws_type {
  63. BybitSwapWsType::Public => {
  64. "wss://stream.bybit.com/v5/public/linear?max_alive_time=1m".to_string()
  65. }
  66. BybitSwapWsType::Private => {
  67. "wss://stream.bybit.com/v5/private?max_alive_time=1m".to_string()
  68. }
  69. };
  70. if is_colo {
  71. info!("开启高速(未配置,走普通:{})通道",address_url);
  72. } else {
  73. info!("走普通通道:{}",address_url);
  74. }
  75. BybitSwapWs {
  76. label,
  77. address_url,
  78. login_param,
  79. symbol_s: vec![],
  80. subscribe_types: vec![],
  81. heartbeat_time: 1000 * 10,
  82. }
  83. }
  84. /*******************************************************************************************************/
  85. /*****************************************订阅函数********************************************************/
  86. /*******************************************************************************************************/
  87. //手动添加订阅信息
  88. pub fn set_subscribe(&mut self, subscribe_types: Vec<BybitSwapSubscribeType>) {
  89. self.subscribe_types.extend(subscribe_types);
  90. }
  91. //手动添加币对
  92. pub fn set_symbols(&mut self, mut b_array: Vec<String>) {
  93. for symbol in b_array.iter_mut() {
  94. // 大写
  95. *symbol = symbol.to_uppercase();
  96. // 字符串替换
  97. *symbol = symbol.replace("_", "");
  98. *symbol = symbol.replace("-", "");
  99. }
  100. self.symbol_s = b_array;
  101. }
  102. //频道是否需要登录
  103. fn contains_pr(&self) -> bool {
  104. for t in self.subscribe_types.clone() {
  105. if match t {
  106. BybitSwapSubscribeType::PuOrderBook1 => false,
  107. BybitSwapSubscribeType::PuOrderBook50 => false,
  108. BybitSwapSubscribeType::PuBlicTrade => false,
  109. BybitSwapSubscribeType::PuTickers => false,
  110. BybitSwapSubscribeType::PuKline(_) => false,
  111. BybitSwapSubscribeType::PrPosition => true,
  112. BybitSwapSubscribeType::PrExecution => true,
  113. BybitSwapSubscribeType::PrOrder => true,
  114. BybitSwapSubscribeType::PrWallet => true,
  115. } {
  116. return true;
  117. }
  118. }
  119. false
  120. }
  121. /*******************************************************************************************************/
  122. /*****************************************工具函数********************************************************/
  123. /*******************************************************************************************************/
  124. //订阅枚举解析
  125. pub fn enum_to_string(symbol: String, subscribe_type: BybitSwapSubscribeType) -> String {
  126. match subscribe_type {
  127. BybitSwapSubscribeType::PuOrderBook1 => {
  128. format!("orderbook.1.{}", symbol)
  129. }
  130. BybitSwapSubscribeType::PuOrderBook50 => {
  131. format!("orderbook.50.{}", symbol)
  132. }
  133. BybitSwapSubscribeType::PuBlicTrade => {
  134. format!("publicTrade.{}", symbol)
  135. }
  136. BybitSwapSubscribeType::PuTickers => {
  137. format!("tickers.{}", symbol)
  138. }
  139. BybitSwapSubscribeType::PuKline(t) => {
  140. format!("kline.{}.{}", t, symbol)
  141. }
  142. BybitSwapSubscribeType::PrPosition => {
  143. format!("position")
  144. }
  145. BybitSwapSubscribeType::PrExecution => {
  146. format!("execution")
  147. }
  148. BybitSwapSubscribeType::PrOrder => {
  149. format!("order")
  150. }
  151. BybitSwapSubscribeType::PrWallet => {
  152. format!("wallet")
  153. }
  154. }
  155. }
  156. //订阅信息生成
  157. pub fn get_subscription(&self) -> String {
  158. let mut params = vec![];
  159. for symbol in &self.symbol_s {
  160. for subscribe_type in &self.subscribe_types {
  161. let ty_str = Self::enum_to_string(symbol.clone(), subscribe_type.clone());
  162. params.push(ty_str);
  163. }
  164. }
  165. let str = json!({
  166. "op": "subscribe",
  167. "args": params
  168. });
  169. str.to_string()
  170. }
  171. /*******************************************************************************************************/
  172. /*****************************************socket基本*****************************************************/
  173. /*******************************************************************************************************/
  174. //链接
  175. pub async fn ws_connect_async<F, Future>(&mut self,
  176. is_shutdown_arc: Arc<AtomicBool>,
  177. handle_function: F,
  178. write_tx_am: &Arc<Mutex<UnboundedSender<Message>>>,
  179. write_rx: UnboundedReceiver<Message>) -> Result<(), Error>
  180. where
  181. F: Fn(ResponseData) -> Future + Clone + Send + 'static + Sync,
  182. Future: std::future::Future<Output=()> + Send + 'static, // 确保 Fut 是一个 Future,且输出类型为 ()
  183. {
  184. let login_is = self.contains_pr();
  185. let subscription = self.get_subscription();
  186. let address_url = self.address_url.clone();
  187. let label = self.label.clone();
  188. let timestamp = Utc::now().timestamp_millis();
  189. let login_param = self.login_param.clone();
  190. let (api_key, secret_key) = match login_param {
  191. None => { ("".to_string(), "".to_string()) }
  192. Some(p) => {
  193. (p.api_key.clone().to_string(), p.secret_key.clone().to_string())
  194. }
  195. };
  196. let heartbeat_time = self.heartbeat_time.clone();
  197. trace!("{:?}",format!("{}",subscription));
  198. //心跳-- 方法内部线程启动
  199. let write_tx_clone1 = Arc::clone(write_tx_am);
  200. tokio::spawn(async move {
  201. trace!("线程-异步心跳-开始");
  202. AbstractWsMode::ping_or_pong(write_tx_clone1, HeartbeatType::Ping, heartbeat_time).await;
  203. trace!("线程-异步心跳-结束");
  204. });
  205. //设置订阅
  206. let mut subscribe_array = vec![];
  207. if login_is {
  208. let expires = timestamp + 1000;
  209. let message = format!("GET/realtime{}", expires);
  210. let hmac_key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
  211. let result = hmac::sign(&hmac_key, &message.as_bytes());
  212. let signature = hex::encode(result.as_ref());
  213. //登录相关
  214. let str = json!({
  215. "op": "auth",
  216. "args": [api_key, expires, signature]
  217. });
  218. subscribe_array.push(str.to_string());
  219. }
  220. subscribe_array.push(subscription.to_string());
  221. //链接
  222. let t2 = tokio::spawn(async move {
  223. trace!("线程-异步链接-开始");
  224. match AbstractWsMode::ws_connect_async(is_shutdown_arc,
  225. handle_function,
  226. address_url.clone(),
  227. label.clone(),
  228. subscribe_array,
  229. write_rx,
  230. Self::message_text,
  231. Self::message_ping,
  232. Self::message_pong,
  233. ).await {
  234. Ok(_) => { trace!("线程-异步链接-结束"); }
  235. Err(e) => { trace!("发生异常:bitget-期货链接关闭-{:?}",e); }
  236. }
  237. });
  238. tokio::try_join!(t2).unwrap();
  239. trace!("线程-心跳与链接-结束");
  240. Ok(())
  241. }
  242. /*******************************************************************************************************/
  243. /*****************************************数据解析*****************************************************/
  244. /*******************************************************************************************************/
  245. //数据解析-Text
  246. pub fn message_text(text: String) -> Option<ResponseData> {
  247. let response_data = Self::ok_text(text);
  248. Option::from(response_data)
  249. }
  250. //数据解析-ping
  251. pub fn message_ping(_pi: Vec<u8>) -> Option<ResponseData> {
  252. return Option::from(ResponseData::new("".to_string(), "-300".to_string(), "success".to_string(), Value::Null));
  253. }
  254. //数据解析-pong
  255. pub fn message_pong(_po: Vec<u8>) -> Option<ResponseData> {
  256. return Option::from(ResponseData::new("".to_string(), "-301".to_string(), "success".to_string(), Value::Null));
  257. }
  258. //数据解析
  259. pub fn ok_text(text: String) -> ResponseData {
  260. // trace!("原始数据");
  261. // trace!(?text);
  262. let mut res_data = ResponseData::new("".to_string(), "200".to_string(), "success".to_string(), Value::Null);
  263. let json_value: Value = serde_json::from_str(&text).unwrap();
  264. if json_value.get("success").is_some() {
  265. //订阅内容
  266. let success = json_value["success"].as_bool().unwrap();
  267. // let ret_msg = json_value["ret_msg"].as_str().unwrap();
  268. let op = json_value["op"].as_str().unwrap();
  269. let success_error = if success {
  270. "成功"
  271. } else {
  272. "失败"
  273. };
  274. if op == "auth" {
  275. res_data.code = "-200".to_string();
  276. res_data.message = format!("登录{}", success_error);
  277. } else if op == "subscribe" {
  278. res_data.message = format!("订阅{}", success_error);
  279. res_data.code = "-201".to_string();
  280. } else {
  281. res_data.code = "".to_string();
  282. res_data.channel = "未知订阅".to_string();
  283. }
  284. } else if json_value.get("topic").is_some() && json_value.get("data").is_some() {
  285. let channel = json_value["topic"].to_string();
  286. res_data.data = json_value["data"].clone();
  287. res_data.code = "200".to_string();
  288. if channel.contains("orderbook") {
  289. res_data.channel = "orderbook".to_string();
  290. res_data.data_type = json_value["type"].as_str().unwrap().to_string();
  291. // bybit 时间在data块外
  292. res_data.reach_time = json_value.get("ts").unwrap().as_i64().unwrap_or(0i64);
  293. } else if channel.contains("publicTrade") {
  294. res_data.channel = "trade".to_string();
  295. res_data.data_type = json_value["type"].as_str().unwrap().to_string();
  296. } else if channel.contains("tickers") {
  297. res_data.channel = "tickers".to_string();
  298. res_data.data["ts"] = json_value["ts"].clone();
  299. } else if channel.contains("kline") {
  300. res_data.channel = "kline".to_string();
  301. } else if channel.contains("position") {
  302. res_data.channel = "position".to_string();
  303. } else if channel.contains("execution") {
  304. res_data.channel = "execution".to_string();
  305. } else if channel.contains("order") {
  306. res_data.channel = "order".to_string();
  307. } else if channel.contains("wallet") {
  308. res_data.channel = "wallet".to_string();
  309. } else {
  310. res_data.code = "".to_string();
  311. res_data.channel = "未知的频道".to_string();
  312. }
  313. } else {
  314. //推送数据
  315. res_data.code = "".to_string();
  316. res_data.channel = "未知的频道".to_string();
  317. }
  318. res_data
  319. }
  320. }