gate_swap_ws.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. use std::sync::Arc;
  2. use std::sync::atomic::AtomicBool;
  3. use std::time::Duration;
  4. use chrono::Utc;
  5. use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
  6. use hex;
  7. use hmac::{Hmac, Mac, NewMac};
  8. use serde_json::{json, Value};
  9. use sha2::Sha512;
  10. use tokio::sync::Mutex;
  11. use tokio_tungstenite::tungstenite::{Error, Message};
  12. use tracing::{error, info, trace};
  13. use crate::response_base::ResponseData;
  14. use crate::socket_tool::{AbstractWsMode, HeartbeatType};
  15. //类型
  16. pub enum GateSwapWsType {
  17. PublicAndPrivate(String),
  18. }
  19. //订阅频道
  20. #[derive(Clone)]
  21. pub enum GateSwapSubscribeType {
  22. PuFuturesOrderBook,
  23. PuFuturesCandlesticks,
  24. PuFuturesTrades,
  25. PuFuturesBookTicker,
  26. PrFuturesOrders(String),
  27. PrFuturesPositions(String),
  28. PrFuturesBalances(String),
  29. }
  30. //账号信息
  31. #[derive(Clone)]
  32. #[allow(dead_code)]
  33. pub struct GateSwapLogin {
  34. pub api_key: String,
  35. pub secret: String,
  36. }
  37. #[derive(Clone)]
  38. pub struct GateSwapWs {
  39. //类型
  40. label: String,
  41. //地址
  42. address_url: String,
  43. //账号信息
  44. login_param: Option<GateSwapLogin>,
  45. //币对
  46. symbol_s: Vec<String>,
  47. //订阅
  48. subscribe_types: Vec<GateSwapSubscribeType>,
  49. //心跳间隔
  50. heartbeat_time: u64,
  51. }
  52. impl GateSwapWs {
  53. /*******************************************************************************************************/
  54. /*****************************************获取一个对象****************************************************/
  55. /*******************************************************************************************************/
  56. pub fn new(is_colo: bool, login_param: Option<GateSwapLogin>, ws_type: GateSwapWsType) -> GateSwapWs {
  57. return GateSwapWs::new_label("default-GateSwapWs".to_string(), is_colo, login_param, ws_type);
  58. }
  59. pub fn new_label(label: String, is_colo: bool, login_param: Option<GateSwapLogin>, ws_type: GateSwapWsType) -> GateSwapWs
  60. {
  61. /*******公共频道-私有频道数据组装*/
  62. let address_url = match ws_type {
  63. GateSwapWsType::PublicAndPrivate(name) => {
  64. if is_colo {
  65. let url = format!("wss://fxws-private.gateapi.io/v4/ws/{}", name.to_string());
  66. info!("开启高速通道:{:?}",url);
  67. url
  68. } else {
  69. let url = format!("wss://fx-ws.gateio.ws/v4/ws/{}", name.to_string());
  70. info!("走普通通道:{}",url);
  71. url
  72. }
  73. }
  74. };
  75. GateSwapWs {
  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<GateSwapSubscribeType>) {
  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. }
  99. self.symbol_s = b_array;
  100. }
  101. //频道是否需要登录
  102. fn contains_pr(&self) -> bool {
  103. for t in self.subscribe_types.clone() {
  104. if match t {
  105. GateSwapSubscribeType::PuFuturesOrderBook => false,
  106. GateSwapSubscribeType::PuFuturesCandlesticks => false,
  107. GateSwapSubscribeType::PuFuturesTrades => false,
  108. GateSwapSubscribeType::PuFuturesBookTicker => false,
  109. GateSwapSubscribeType::PrFuturesOrders(_) => true,
  110. GateSwapSubscribeType::PrFuturesPositions(_) => true,
  111. GateSwapSubscribeType::PrFuturesBalances(_) => true,
  112. } {
  113. return true;
  114. }
  115. }
  116. false
  117. }
  118. /*******************************************************************************************************/
  119. /*****************************************工具函数********************************************************/
  120. /*******************************************************************************************************/
  121. //订阅枚举解析
  122. pub fn enum_to_string(symbol: String, subscribe_type: GateSwapSubscribeType, login_param: Option<GateSwapLogin>) -> Value {
  123. let time = chrono::Utc::now().timestamp();
  124. let mut access_key = "".to_string();
  125. let mut secret_key = "".to_string();
  126. match login_param {
  127. None => {}
  128. Some(param) => {
  129. access_key = param.api_key.clone();
  130. secret_key = param.secret.clone();
  131. }
  132. }
  133. match subscribe_type {
  134. GateSwapSubscribeType::PuFuturesOrderBook => {
  135. json!({
  136. "time": time,
  137. "channel": "futures.order_book",
  138. "event": "subscribe",
  139. "payload": [symbol, "20", "0"]
  140. })
  141. }
  142. GateSwapSubscribeType::PuFuturesBookTicker => {
  143. json!({
  144. "time": time,
  145. "channel": "futures.book_ticker",
  146. "event": "subscribe",
  147. "payload": [symbol]
  148. })
  149. }
  150. GateSwapSubscribeType::PuFuturesCandlesticks => {
  151. json!({
  152. "time": time,
  153. "channel": "futures.candlesticks",
  154. "event": "subscribe",
  155. "payload": ["1m", symbol]
  156. })
  157. }
  158. GateSwapSubscribeType::PrFuturesOrders(user_id) => {
  159. json!({
  160. "time": time,
  161. "channel": "futures.orders",
  162. "event": "subscribe",
  163. "payload": [user_id, symbol],
  164. "auth": {
  165. "method": "api_key",
  166. "KEY": access_key,
  167. "SIGN":Self::sign(secret_key.to_string(),
  168. "futures.orders".to_string(),
  169. "subscribe".to_string(),
  170. time.to_string())
  171. }
  172. })
  173. }
  174. GateSwapSubscribeType::PrFuturesPositions(user_id) => {
  175. json!({
  176. "time": time,
  177. "channel": "futures.positions",
  178. "event": "subscribe",
  179. "payload": [user_id, symbol],
  180. "auth": {
  181. "method": "api_key",
  182. "KEY": access_key,
  183. "SIGN":Self::sign(secret_key.to_string(),
  184. "futures.positions".to_string(),
  185. "subscribe".to_string(),
  186. time.to_string())
  187. }
  188. })
  189. }
  190. GateSwapSubscribeType::PrFuturesBalances(user_id) => {
  191. json!({
  192. "time": time,
  193. "channel": "futures.balances",
  194. "event": "subscribe",
  195. "payload": [user_id],
  196. "auth": {
  197. "method": "api_key",
  198. "KEY": access_key,
  199. "SIGN":Self::sign(secret_key.to_string(),
  200. "futures.balances".to_string(),
  201. "subscribe".to_string(),
  202. time.to_string())
  203. }
  204. })
  205. }
  206. GateSwapSubscribeType::PuFuturesTrades => {
  207. json!({
  208. "time": time,
  209. "channel": "futures.trades",
  210. "event": "subscribe",
  211. "payload": [symbol]
  212. })
  213. }
  214. }
  215. }
  216. //订阅信息生成
  217. pub fn get_subscription(&self) -> Vec<Value> {
  218. let mut args = vec![];
  219. for symbol in &self.symbol_s {
  220. for subscribe_type in &self.subscribe_types {
  221. let ty_str = Self::enum_to_string(symbol.clone(),
  222. subscribe_type.clone(),
  223. self.login_param.clone(),
  224. );
  225. args.push(ty_str);
  226. }
  227. }
  228. args
  229. }
  230. //生成签名
  231. fn sign(secret_key: String, channel: String, event: String, time: String) -> String {
  232. let message = format!("channel={}&event={}&time={}", channel, event, time);
  233. let mut mac = Hmac::<Sha512>::new_varkey(secret_key.as_bytes()).expect("Failed to create HMAC");
  234. mac.update(message.as_bytes());
  235. let result = mac.finalize().into_bytes();
  236. let sign = hex::encode(result);
  237. sign
  238. }
  239. /*******************************************************************************************************/
  240. /*****************************************socket基本*****************************************************/
  241. /*******************************************************************************************************/
  242. //链接
  243. pub async fn ws_connect_async<F, Future>(&mut self,
  244. is_shutdown_arc: Arc<AtomicBool>,
  245. handle_function: F,
  246. write_tx_am: &Arc<Mutex<UnboundedSender<Message>>>,
  247. write_to_socket_rx: UnboundedReceiver<Message>) -> Result<(), Error>
  248. where
  249. F: Fn(ResponseData) -> Future + Clone + Send + 'static + Sync,
  250. Future: std::future::Future<Output=()> + Send + 'static, // 确保 Fut 是一个 Future,且输出类型为 ()
  251. {
  252. let login_is = self.contains_pr();
  253. let subscription = self.get_subscription();
  254. let address_url = self.address_url.clone();
  255. let label = self.label.clone();
  256. let heartbeat_time = self.heartbeat_time.clone();
  257. let timestamp = Utc::now().timestamp();
  258. //心跳-- 方法内部线程启动
  259. let write_tx_clone1 = Arc::clone(write_tx_am);
  260. tokio::spawn(async move {
  261. trace!("线程-异步心跳-开始");
  262. let ping_str = json!({
  263. "time" : timestamp,
  264. "channel" : "futures.ping",
  265. });
  266. AbstractWsMode::ping_or_pong(write_tx_clone1, HeartbeatType::Custom(ping_str.to_string()), heartbeat_time).await;
  267. trace!("线程-异步心跳-结束");
  268. });
  269. //设置订阅
  270. let mut subscribe_array = vec![];
  271. if login_is {
  272. //登录相关
  273. }
  274. for s in subscription {
  275. subscribe_array.push(s.to_string());
  276. }
  277. //链接
  278. let t2 = tokio::spawn(async move {
  279. let write_to_socket_rx_arc = Arc::new(Mutex::new(write_to_socket_rx));
  280. loop {
  281. info!("gate_usdt_swap socket 连接中……");
  282. AbstractWsMode::ws_connect_async(is_shutdown_arc.clone(), handle_function.clone(), address_url.clone(),
  283. false, label.clone(), subscribe_array.clone(), write_to_socket_rx_arc.clone(),
  284. Self::message_text, Self::message_ping, Self::message_pong).await;
  285. error!("gate_usdt_swap socket 断连,1s以后重连……");
  286. tokio::time::sleep(Duration::from_secs(1)).await;
  287. }
  288. });
  289. tokio::try_join!(t2).unwrap();
  290. trace!("线程-心跳与链接-结束");
  291. Ok(())
  292. }
  293. /*******************************************************************************************************/
  294. /*****************************************数据解析*****************************************************/
  295. /*******************************************************************************************************/
  296. //数据解析-Text
  297. pub fn message_text(text: String) -> Option<ResponseData> {
  298. let response_data = Self::ok_text(text);
  299. Option::from(response_data)
  300. }
  301. //数据解析-ping
  302. pub fn message_ping(_pi: Vec<u8>) -> Option<ResponseData> {
  303. return Option::from(ResponseData::new("".to_string(), "-300".to_string(), "success".to_string(), Value::Null));
  304. }
  305. //数据解析-pong
  306. pub fn message_pong(_po: Vec<u8>) -> Option<ResponseData> {
  307. return Option::from(ResponseData::new("".to_string(), "-301".to_string(), "success".to_string(), Value::Null));
  308. }
  309. //数据解析
  310. pub fn ok_text(text: String) -> ResponseData
  311. {
  312. // trace!("原始数据:{}", text);
  313. let mut res_data = ResponseData::new("".to_string(), "200".to_string(), "success".to_string(), Value::Null);
  314. let json_value: Value = serde_json::from_str(&text).unwrap();
  315. if json_value["channel"].as_str() == Option::from("futures.pong") {
  316. res_data.code = "-301".to_string();
  317. res_data.message = "success".to_string();
  318. } else if json_value.get("error").is_some() {
  319. let message = json_value["error"]["message"].as_str().unwrap().to_string();
  320. let mes = message.trim_end_matches('\n');
  321. res_data.code = json_value["error"]["code"].to_string();
  322. res_data.message = mes.to_string();
  323. } else if json_value["result"]["status"].as_str() == Option::from("success") {//订阅返回
  324. res_data.code = "-201".to_string();
  325. res_data.data = json_value;
  326. } else {
  327. res_data.channel = format!("{}", json_value["channel"].as_str().unwrap());
  328. res_data.code = "200".to_string();
  329. res_data.data = json_value["result"].clone();
  330. }
  331. res_data
  332. }
  333. }