bitget_spot_ws.rs 14 KB

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