bybit_swap_ws.rs 13 KB

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