okx_swap_ws.rs 15 KB

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