gate_swap_ws.rs 13 KB

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