bybit_swap_ws.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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;
  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(&mut self,
  176. bool_v1: Arc<AtomicBool>,
  177. write_tx_am: &Arc<Mutex<UnboundedSender<Message>>>,
  178. write_rx: UnboundedReceiver<Message>,
  179. read_tx: UnboundedSender<ResponseData>) -> Result<(), Error>
  180. {
  181. let login_is = self.contains_pr();
  182. let subscription = self.get_subscription();
  183. let address_url = self.address_url.clone();
  184. let label = self.label.clone();
  185. let timestamp = Utc::now().timestamp_millis();
  186. let login_param = self.login_param.clone();
  187. let (api_key, secret_key) = match login_param {
  188. None => { ("".to_string(), "".to_string()) }
  189. Some(p) => {
  190. (p.api_key.clone().to_string(), p.secret_key.clone().to_string())
  191. }
  192. };
  193. let heartbeat_time = self.heartbeat_time.clone();
  194. trace!("{:?}",format!("{}",subscription));
  195. //心跳-- 方法内部线程启动
  196. let write_tx_clone1 = Arc::clone(write_tx_am);
  197. tokio::spawn(async move {
  198. trace!("线程-异步心跳-开始");
  199. AbstractWsMode::ping_or_pong(write_tx_clone1, HeartbeatType::Ping, heartbeat_time).await;
  200. trace!("线程-异步心跳-结束");
  201. });
  202. //设置订阅
  203. let mut subscribe_array = vec![];
  204. if login_is {
  205. let expires = timestamp + 1000;
  206. let message = format!("GET/realtime{}", expires);
  207. let hmac_key = ring::hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
  208. let result = ring::hmac::sign(&hmac_key, &message.as_bytes());
  209. let signature = hex::encode(result.as_ref());
  210. //登录相关
  211. let str = json!({
  212. "op": "auth",
  213. "args": [api_key, expires, signature]
  214. });
  215. subscribe_array.push(str.to_string());
  216. }
  217. subscribe_array.push(subscription.to_string());
  218. //链接
  219. let t2 = tokio::spawn(async move {
  220. trace!("线程-异步链接-开始");
  221. AbstractWsMode::ws_connect_async(bool_v1, address_url.clone(),
  222. label.clone(), subscribe_array,
  223. write_rx, read_tx,
  224. Self::message_text,
  225. Self::message_ping,
  226. Self::message_pong,
  227. ).await.expect("币安-期货");
  228. trace!("线程-异步链接-结束");
  229. });
  230. tokio::try_join!(t2).unwrap();
  231. trace!("线程-心跳与链接-结束");
  232. Ok(())
  233. }
  234. /*******************************************************************************************************/
  235. /*****************************************数据解析*****************************************************/
  236. /*******************************************************************************************************/
  237. //数据解析-Text
  238. pub fn message_text(text: String) -> Option<ResponseData> {
  239. let response_data = Self::ok_text(text);
  240. Option::from(response_data)
  241. }
  242. //数据解析-ping
  243. pub fn message_ping(_pi: Vec<u8>) -> Option<ResponseData> {
  244. return Option::from(ResponseData::new("".to_string(), "-300".to_string(), "success".to_string(), "".to_string()));
  245. }
  246. //数据解析-pong
  247. pub fn message_pong(_po: Vec<u8>) -> Option<ResponseData> {
  248. return Option::from(ResponseData::new("".to_string(), "-301".to_string(), "success".to_string(), "".to_string()));
  249. }
  250. //数据解析
  251. pub fn ok_text(text: String) -> ResponseData {
  252. // trace!("原始数据");
  253. // trace!(?text);
  254. let mut res_data = ResponseData::new("".to_string(), "200".to_string(), "success".to_string(), "".to_string());
  255. let json_value: serde_json::Value = serde_json::from_str(&text).unwrap();
  256. if json_value.get("success").is_some() {
  257. //订阅内容
  258. let success = json_value["success"].as_bool().unwrap();
  259. // let ret_msg = json_value["ret_msg"].as_str().unwrap();
  260. let op = json_value["op"].as_str().unwrap();
  261. let success_error = if success {
  262. "成功"
  263. } else {
  264. "失败"
  265. };
  266. if op == "auth" {
  267. res_data.code = "-200".to_string();
  268. res_data.message = format!("登录{}", success_error);
  269. } else if op == "subscribe" {
  270. res_data.message = format!("订阅{}", success_error);
  271. res_data.code = "-201".to_string();
  272. } else {
  273. res_data.code = "".to_string();
  274. res_data.channel = "未知订阅".to_string();
  275. }
  276. } else if json_value.get("topic").is_some() && json_value.get("data").is_some() {
  277. let channel = json_value["topic"].to_string();
  278. res_data.data = format!("{}", json_value.get("data").as_ref().unwrap());
  279. res_data.code = "200".to_string();
  280. if channel.contains("orderbook") {
  281. res_data.channel = "orderbook".to_string();
  282. res_data.data_type = json_value["type"].as_str().unwrap().to_string();
  283. // bybit 时间在data块外
  284. res_data.reach_time = json_value.get("ts").unwrap().as_i64().unwrap_or(0i64);
  285. } else if channel.contains("publicTrade") {
  286. res_data.channel = "trade".to_string();
  287. res_data.data_type = json_value["type"].as_str().unwrap().to_string();
  288. } else if channel.contains("tickers") {
  289. res_data.channel = "tickers".to_string();
  290. } else if channel.contains("kline") {
  291. res_data.channel = "kline".to_string();
  292. } else if channel.contains("position") {
  293. res_data.channel = "position".to_string();
  294. } else if channel.contains("execution") {
  295. res_data.channel = "execution".to_string();
  296. } else if channel.contains("order") {
  297. res_data.channel = "order".to_string();
  298. } else if channel.contains("wallet") {
  299. res_data.channel = "wallet".to_string();
  300. } else {
  301. res_data.code = "".to_string();
  302. res_data.channel = "未知的频道".to_string();
  303. }
  304. } else {
  305. //推送数据
  306. res_data.code = "".to_string();
  307. res_data.channel = "未知的频道".to_string();
  308. }
  309. res_data
  310. }
  311. }