Skip to main content

v_exchanges_adapters/exchanges/
binance.rs

1// A module for communicating with the [Binance API](https://binance-docs.github.io/apidocs/spot/en/).
2
3use std::{marker::PhantomData, str::FromStr, time::SystemTime};
4
5use ahash::AHashSet;
6use eyre::eyre;
7use generics::{
8	ConstructAuthError, UrlError,
9	http::{ApiError, BuildError, HandleError, *},
10	tokio_tungstenite::tungstenite,
11	ws::{ContentEvent, ResponseOrContent, Topic, WsConfig, WsError, WsHandler},
12};
13use hmac::{Hmac, KeyInit as _, Mac};
14use jiff::{SignedDuration, Timestamp};
15use secrecy::{ExposeSecret as _, SecretString};
16use serde::{Deserialize, Serialize, de::DeserializeOwned};
17use sha2::Sha256;
18use url::Url;
19use v_utils::utils::truncate_msg;
20
21use crate::traits::*;
22
23// https://binance-docs.github.io/apidocs/spot/en/#general-api-information
24impl<B, R> RequestHandler<B> for BinanceRequestHandler<'_, R>
25where
26	B: Serialize,
27	R: DeserializeOwned,
28{
29	type Successful = R;
30
31	fn base_url(&self, is_test: bool) -> Result<Url, UrlError> {
32		match is_test {
33			true => self.options.http_url.url_testnet().ok_or_else(|| UrlError::MissingTestnet(self.options.http_url.url_mainnet())),
34			false => Ok(self.options.http_url.url_mainnet()),
35		}
36	}
37
38	#[tracing::instrument(skip_all, fields(?builder))]
39	fn build_request(&self, mut builder: RequestBuilder, request_body: &Option<B>, _: u8) -> Result<Request, BuildError> {
40		if let Some(body) = request_body {
41			let encoded = serde_urlencoded::to_string(body)?;
42			builder = builder.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(encoded);
43		}
44
45		if self.options.http_auth != BinanceAuth::None {
46			// https://binance-docs.github.io/apidocs/spot/en/#signed-trade-user_data-and-margin-endpoint-security
47			let pubkey = self.options.pubkey.as_deref().ok_or(ConstructAuthError::new_missing_pubkey())?;
48			builder = builder.header("X-MBX-APIKEY", pubkey);
49
50			if self.options.http_auth == BinanceAuth::Sign {
51				let time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap(); // always after the epoch
52				let timestamp = time.as_millis();
53
54				builder = builder.query(&[("timestamp", timestamp)]);
55				if let Some(recv_window) = self.options.recv_window {
56					builder = builder.query(&[("recvWindow", recv_window.as_millis() as u64)]);
57				}
58
59				let secret = self.options.secret.as_ref().map(|s| s.expose_secret()).ok_or(ConstructAuthError::new_missing_secret())?;
60				let mut hmac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap(); // hmac accepts key of any length
61
62				let mut request = builder.build().expect("From what I understand, can't trigger this from client-side");
63				let query = request.url().query().unwrap();
64				let body = request.body().and_then(|body| body.as_bytes()).unwrap_or_default();
65
66				hmac.update(&[query.as_bytes(), body].concat());
67				let signature = hex::encode(hmac.finalize().into_bytes());
68
69				request.url_mut().query_pairs_mut().append_pair("signature", &signature);
70
71				return Ok(request);
72			}
73		}
74		Ok(builder.build().expect("don't expect this to be reached by client, so fail fast for dev"))
75	}
76
77	fn rate_limit_key_name(&self) -> Option<String> {
78		use sha2::{Digest as _, Sha256};
79		self.options.pubkey.as_deref().map(|k| hex::encode(&Sha256::digest(k.as_bytes())[..4]))
80	}
81
82	fn handle_response(&self, status: StatusCode, headers: HeaderMap, response_body: Bytes) -> Result<Self::Successful, HandleError> {
83		if status.is_success() {
84			serde_json::from_slice(&response_body).map_err(|error| {
85				let response_str = truncate_msg(String::from_utf8_lossy(&response_body));
86				HandleError::Parse(eyre!("Failed to parse response: {error}\nResponse body: {response_str}"))
87			})
88		} else {
89			// https://binance-docs.github.io/apidocs/spot/en/#limits
90
91			// 403: WAF block (CloudFront) - HTML body, not JSON
92			if status == 403 {
93				let msg = std::str::from_utf8(&response_body).unwrap_or("<non-utf8 body>").to_string();
94				return Err(ApiError::from(IpError::Waf { msg }).into());
95			}
96			// 451: Geo-restriction - JSON body with code:0 and eligibility message
97			if status == 451 {
98				let msg = serde_json::from_slice::<serde_json::Value>(&response_body)
99					.ok()
100					.and_then(|v| v.get("msg").and_then(|m| m.as_str()).map(String::from))
101					.unwrap_or_else(|| String::from_utf8_lossy(&response_body).into_owned());
102				return Err(ApiError::from(IpError::GeoBlocked { msg }).into());
103			}
104
105			if status == 429 || status == 418 {
106				let retry_after_sec = if let Some(value) = headers.get("Retry-After") {
107					if let Ok(string) = value.to_str() {
108						if let Ok(retry_after) = u32::from_str(string) {
109							Some(retry_after)
110						} else {
111							tracing::debug!("Invalid number in Retry-After header");
112							None
113						}
114					} else {
115						tracing::debug!("Non-ASCII character in Retry-After header");
116						None
117					}
118				} else {
119					None
120				};
121				let e = match retry_after_sec {
122					Some(s) => {
123						let until = Some(Timestamp::now() + SignedDuration::from_secs(s as i64));
124						ApiError::from(IpError::Timeout { until }).into()
125					}
126					_ => eyre!("Could't interpret Retry-After header").into(),
127				};
128				return Err(e);
129			}
130
131			let e: BinanceError = match serde_json::from_slice::<BinanceError>(&response_body) {
132				Ok(binance_error) => binance_error,
133				Err(parse_error) => {
134					let response_str = truncate_msg(String::from_utf8_lossy(&response_body));
135					return Err(HandleError::Parse(eyre!("Failed to parse error response: {parse_error}\nResponse body: {response_str}")));
136				}
137			};
138			Err(ApiError::from(e).into())
139		}
140	}
141}
142
143// Ws stuff {{{
144#[derive(Clone, Debug)]
145pub struct BinanceWsHandler {
146	options: BinanceOptions,
147	/// Binance has a retarded `listen-key` system. This is needed only for that.
148	_last_keep_alive: SystemTime = SystemTime::UNIX_EPOCH,
149}
150impl BinanceWsHandler {
151	pub fn new(options: BinanceOptions) -> Self {
152		Self {
153			options,
154			_last_keep_alive: SystemTime::UNIX_EPOCH, // semantically creation itself does nothing for refreshing the token. But refreshment timer on it will be set to 0 on creation, so that's when we'll set it to [now](SystemTime::now)
155		}
156	}
157}
158impl WsHandler for BinanceWsHandler {
159	fn config(&self) -> Result<WsConfig, UrlError> {
160		let mut config = self.options.ws_config.clone();
161		match self.options.ws_url {
162			BinanceWsUrl::None => tracing::warn!(
163				"BinanceWsUrl was not set. Due to Binance shenanigans, any provided topics will now be ignored, and must be manually hardcoded into the provided url on creation of the websocket. However, recommended approach is to simply provide a BinanceOption::WsUrl."
164			),
165			_ => {
166				let mut streams = String::new();
167				config.topics = config.topics.union(&self.options.ws_topics).cloned().collect();
168				for (i, topic) in config.topics.iter().enumerate() {
169					if i > 0 {
170						streams.push('/');
171					}
172					streams.push_str(topic);
173				}
174				let base_url = match self.options.test {
175					true => self.options.ws_url.url_testnet().ok_or_else(|| UrlError::MissingTestnet(self.options.ws_url.url_mainnet()))?,
176					false => self.options.ws_url.url_mainnet(),
177				};
178				config.base_url = Some(base_url.join(&format!("stream?streams={streams}")).unwrap());
179			}
180		}
181		Ok(config)
182	}
183
184	fn handle_auth(&mut self) -> Result<Vec<tungstenite::Message>, WsError> {
185		if self.options.ws_config.auth {
186			//TODO: implement ws auth once I can acquire ed25519 keys: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info#log-in-with-api-key-signed
187
188			let _pubkey = self.options.pubkey.as_ref().ok_or(ConstructAuthError::new_missing_pubkey())?;
189			let _secret = self.options.secret.as_ref().ok_or(ConstructAuthError::new_missing_secret())?;
190
191			//TODO!!!: auth for binance
192			/*
193			match
194				user_data_stream => POST /api/v3/userDataStream
195				trade => need to sign each request (can't sign connection itself without ed25519), so do nothing here
196			*/
197		}
198
199		Ok(vec![])
200	}
201
202	fn handle_subscribe(&mut self, topics: AHashSet<Topic>) -> Result<Vec<tungstenite::Message>, WsError> {
203		let string_topics = topics
204			.iter()
205			.filter_map(|topic| if let Topic::String(s) = topic { Some(s) } else { None })
206			.cloned()
207			.collect::<Vec<_>>();
208		let messages = {
209			let msg = serde_json::json!({
210				"method": "SUBSCRIBE",
211				"params": string_topics,
212				"id": rand::random::<u64>(),
213			});
214			vec![tungstenite::Message::Text(msg.to_string().into())]
215		};
216
217		let order_topics = topics
218			.into_iter()
219			.filter_map(|topic| if let Topic::Order(v) = topic { Some(v) } else { None })
220			.collect::<Vec<_>>();
221		for _o in order_topics {
222			todo!();
223		}
224
225		Ok(messages)
226	}
227
228	fn handle_jrpc(&mut self, jrpc: serde_json::Value) -> Result<ResponseOrContent, WsError> {
229		#[derive(serde::Deserialize)]
230		struct NamedStreamData {
231			pub stream: String,
232			pub data: serde_json::Value,
233		}
234		let (event_topic, data) = {
235			match serde_json::from_value::<NamedStreamData>(jrpc.clone()) {
236				Ok(NamedStreamData { stream, data }) => (stream, data),
237				Err(_) => ("".to_string(), jrpc),
238			}
239		};
240		assert!(data.is_object(), "data should be an object");
241
242		let (event_type, event_time, event_data) = {
243			//dbg: dirty impl
244			let mut event_data = data.as_object().unwrap().to_owned();
245			let event_type = data["e"].as_str().unwrap().to_owned();
246			event_data.remove("e");
247			let event_ts: i64 = data["E"].as_i64().unwrap();
248			let event_time = Timestamp::from_millisecond(event_ts).unwrap();
249			event_data.remove("E");
250			(event_type, event_time, event_data.into())
251		};
252
253		//TEST: handle listen-key expiration //NB: Claude wrote this, no clue if logic is correct
254		if event_type == "listenKeyExpired" {
255			tracing::error!("Listen key expired. This requires re-authentication and reconnection.");
256			return Err(WsError::Auth(ConstructAuthError::Other(eyre!("Listen key expired"))));
257		}
258
259		let content = ContentEvent {
260			data: event_data,
261			topic: event_topic,
262			time: event_time,
263			event_type,
264		};
265		Ok(ResponseOrContent::Content(content))
266	}
267
268	// stream listen-key keepalive works for:
269	// - [x] binance spot
270	// - [?] binance perp
271
272	//DEPRECATE
273	//	fn handle_post(&mut self) -> Result<Option<Vec<tungstenite::Message>>, WsError> {
274	//	if SystemTime::now().duration_since(self.last_keep_alive).unwrap() > Duration::from_mins(30) {
275	//		//XXX: will fail if it's not a USER_DATA_STREAM //TODO: generalize to all binance streams
276	//		let msg_json = serde_json::json!({
277	//			"id": "815d5fce-0880-4287-a567-80badf004c74",
278	//			"method": "userDataStream.ping",
279	//			"params": {
280	//				"apiKey": self.options.pubkey.as_ref().unwrap()
281	//			}
282	//		});
283	//		return Ok(Some(vec![tungstenite::Message::Text(msg_json.to_string().into())]));
284	//	}
285	//	Ok(None)
286	//}
287	//DEPRECATE
288	//if SystemTime::now().duration_since(self.last_keep_alive).unwrap() > Duration::from_mins(30) {
289	//	//XXX: will fail if it's not a USER_DATA_STREAM
290	//	//TODO send `PUT /api/v3/userDataStream`
291	//	let client = crate::Client::default();
292	//	.request(
293	//		&self.options,
294	//		"PUT",
295	//		"/api/v3/userDataStream",
296	//		None::<()>,
297	//	)
298	//}
299}
300impl WsOption for BinanceOption {
301	type WsHandler = BinanceWsHandler;
302
303	fn ws_handler(options: Self::Options) -> Self::WsHandler {
304		BinanceWsHandler::new(options)
305	}
306}
307//,}}}
308
309/// Options that can be set when creating handlers
310#[derive(Debug, Default)]
311pub enum BinanceOption {
312	#[default]
313	None,
314	/// API key
315	Pubkey(String),
316	/// Api secret
317	Secret(SecretString),
318	/// Use testnet
319	Test(bool),
320
321	/// Duration the request is valid for. Only applicable for signed requests.
322	RecvWindow(std::time::Duration),
323	/// Frequency at which REST book snapshots are interleaved into the WS book stream.
324	/// `None` = disabled (default). For multi-pair connections this is the full-cycle period;
325	/// each individual pair is re-snapshotted once per `freq`, with fires spaced `freq / pairs.len()` apart.
326	BookSnapshotFreq(Option<std::time::Duration>),
327	/// Base url for HTTP requests
328	HttpUrl(BinanceHttpUrl),
329	/// Authentication type for HTTP requests
330	HttpAuth(BinanceAuth),
331
332	/// Base url for WebSocket connections
333	WsUrl(BinanceWsUrl),
334	/// [WebSocketConfig] used for creating [WebSocketConnection]s
335	/// `url_prefix` will be overridden by [WebSocketUrl](Self::WebSocketUrl) unless `WebSocketUrl` is [BinanceWebSocketUrl::None].
336	WsConfig(WsConfig),
337	/// See [WsConfig::topics]. Will be merged with those manually defined in [Self::WsConfig::topics], if any.
338	WsTopics(Vec<String>),
339}
340
341/// A `enum` that represents the base url of the Binance REST API.
342#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
343#[non_exhaustive]
344pub enum BinanceHttpUrl {
345	/// `https://api.binance.com`
346	Spot,
347	/// `https://api1.binance.com`
348	Spot1,
349	/// `https://api2.binance.com`
350	Spot2,
351	/// `https://api3.binance.com`
352	Spot3,
353	/// `https://api4.binance.com`
354	Spot4,
355	/// `https://data.binance.com`
356	SpotData,
357	/// `https://fapi.binance.com`
358	FuturesUsdM,
359	/// `https://dapi.binance.com`
360	FuturesCoinM,
361	/// `https://eapi.binance.com`
362	EuropeanOptions,
363	/// The url will not be modified by [BinanceRequestHandler]
364	#[default]
365	None,
366}
367impl EndpointUrl for BinanceHttpUrl {
368	fn url_mainnet(&self) -> Url {
369		match self {
370			Self::Spot => Url::parse("https://api.binance.com").unwrap(),
371			Self::Spot1 => Url::parse("https://api1.binance.com").unwrap(),
372			Self::Spot2 => Url::parse("https://api2.binance.com").unwrap(),
373			Self::Spot3 => Url::parse("https://api3.binance.com").unwrap(),
374			Self::Spot4 => Url::parse("https://api4.binance.com").unwrap(),
375			Self::SpotData => Url::parse("https://data.binance.com").unwrap(),
376			Self::FuturesUsdM => Url::parse("https://fapi.binance.com").unwrap(),
377			Self::FuturesCoinM => Url::parse("https://dapi.binance.com").unwrap(),
378			Self::EuropeanOptions => Url::parse("https://eapi.binance.com").unwrap(),
379			Self::None => Url::parse("").unwrap(),
380		}
381	}
382
383	fn url_testnet(&self) -> Option<Url> {
384		match self {
385			Self::Spot => Some(Url::parse("https://testnet.binance.vision").unwrap()),
386			Self::Spot1 => Some(Url::parse("https://testnet.binance.vision").unwrap()),
387			Self::Spot2 => Some(Url::parse("https://testnet.binance.vision").unwrap()),
388			Self::Spot3 => Some(Url::parse("https://testnet.binance.vision").unwrap()),
389			Self::Spot4 => Some(Url::parse("https://testnet.binance.vision").unwrap()),
390			Self::SpotData => Some(Url::parse("https://testnet.binance.vision").unwrap()),
391			Self::FuturesUsdM => Some(Url::parse("https://testnet.binancefuture.com").unwrap()),
392			Self::FuturesCoinM => Some(Url::parse("https://testnet.binancefuture.com").unwrap()),
393			Self::EuropeanOptions => None,
394			Self::None => Some(Url::parse("").unwrap()),
395		}
396	}
397}
398
399/// A `enum` that represents the base url of the Binance WebSocket API
400#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
401pub enum BinanceWsUrl {
402	/// Evaluated to whatever spot url is estimated to be currently preferrable.
403	Spot,
404	/// `wss://stream.binance.com:9443`
405	Spot9443,
406	/// `wss://stream.binance.com:443`
407	Spot443,
408	/// `wss://data-stream.binance.com`
409	SpotData,
410	/// `wss://ws-api.binance.com:443`
411	WebSocket443,
412	/// `wss://ws-api.binance.com:9443`
413	WebSocket9443,
414	/// `wss://fstream.binance.com`
415	FuturesUsdM,
416	/// `wss://fstream-auth.binance.com`
417	FuturesUsdMAuth,
418	/// `wss://dstream.binance.com`
419	FuturesCoinM,
420	/// `wss://nbstream.binance.com`
421	EuropeanOptions,
422	/// The url will not be modified by [BinanceRequestHandler]
423	#[default]
424	None,
425}
426impl EndpointUrl for BinanceWsUrl {
427	// Can't impl [ToOwned], as there is a blanket impl of it on everything with [Clone]
428	fn url_mainnet(&self) -> url::Url {
429		match self {
430			Self::Spot => Url::parse("wss://stream.binance.com:9443").unwrap(), //TODO: actually have some metric to select the best url here
431			Self::Spot9443 => Url::parse("wss://stream.binance.com:9443").unwrap(),
432			Self::Spot443 => Url::parse("wss://stream.binance.com:443").unwrap(),
433			Self::SpotData => Url::parse("wss://data-stream.binance.com").unwrap(),
434			Self::WebSocket443 => Url::parse("wss://ws-api.binance.com:443").unwrap(),
435			Self::WebSocket9443 => Url::parse("wss://ws-api.binance.com:9443").unwrap(),
436			Self::FuturesUsdM => Url::parse("wss://fstream.binance.com").unwrap(),
437			Self::FuturesUsdMAuth => Url::parse("wss://fstream-auth.binance.com").unwrap(),
438			Self::FuturesCoinM => Url::parse("wss://dstream.binance.com").unwrap(),
439			Self::EuropeanOptions => Url::parse("wss://nbstream.binance.com").unwrap(),
440			Self::None => Url::parse("").unwrap(),
441		}
442	}
443
444	fn url_testnet(&self) -> Option<url::Url> {
445		match self {
446			Self::Spot => Some(Url::parse("wss://testnet.binance.vision").unwrap()),
447			Self::Spot9443 => Some(Url::parse("wss://testnet.binance.vision:9443").unwrap()),
448			Self::Spot443 => Some(Url::parse("wss://testnet.binance.vision:443").unwrap()),
449			Self::FuturesUsdM => Some(Url::parse("wss://stream.binancefuture.com").unwrap()),
450			Self::FuturesCoinM => Some(Url::parse("wss://dstream.binancefuture.com").unwrap()),
451			Self::SpotData | Self::WebSocket443 | Self::WebSocket9443 | Self::FuturesUsdMAuth | Self::EuropeanOptions | Self::None => None,
452		}
453	}
454}
455
456#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
457pub enum BinanceAuth {
458	Sign,
459	Key, //Q: Not sure if anything uses it.
460	#[default]
461	None,
462}
463
464#[non_exhaustive]
465#[derive(Debug)]
466pub enum BinanceHandlerError {
467	ApiError(BinanceError),
468	RateLimitError { retry_after: Option<u32> },
469	ParseError,
470}
471
472/// A `struct` that implements [RequestHandler]
473pub struct BinanceRequestHandler<'a, R: DeserializeOwned> {
474	options: BinanceOptions,
475	_phantom: PhantomData<&'a R>,
476}
477
478/// A `struct` that represents a set of [BinanceOption] s.
479#[derive(Clone, derive_more::Debug, Default)]
480pub struct BinanceOptions {
481	/// see [BinanceOption::Pubkey]
482	pub pubkey: Option<String>,
483	/// see [BinanceOption::Secret]
484	#[debug("[REDACTED]")]
485	pub secret: Option<SecretString>,
486	// see [BinanceOption::RecvWindow]
487	pub recv_window: Option<std::time::Duration>,
488	/// see [BinanceOption::HttpUrl]
489	pub http_url: BinanceHttpUrl,
490	/// see [BinanceOption::HttpAuth]
491	pub http_auth: BinanceAuth,
492	/// see [BinanceOption::WsUrl]
493	pub ws_url: BinanceWsUrl,
494	/// see [BinanceOption::WsConfig]
495	pub ws_config: WsConfig,
496	/// see [BinanceOption::WsTopics]
497	pub ws_topics: AHashSet<String>,
498	/// see [BinanceOption::Test]
499	pub test: bool,
500	/// see [BinanceOption::BookSnapshotFreq]
501	pub book_snapshot_freq: Option<std::time::Duration>,
502}
503impl HandlerOptions for BinanceOptions {
504	type OptionItem = BinanceOption;
505
506	fn update(&mut self, option: Self::OptionItem) {
507		match option {
508			Self::OptionItem::None => (),
509			Self::OptionItem::Pubkey(v) => self.pubkey = Some(v),
510			Self::OptionItem::RecvWindow(v) => self.recv_window = Some(v),
511			Self::OptionItem::Test(v) => self.test = v,
512			Self::OptionItem::Secret(v) => self.secret = Some(v),
513			Self::OptionItem::HttpUrl(v) => self.http_url = v,
514			Self::OptionItem::HttpAuth(v) => self.http_auth = v,
515			Self::OptionItem::WsUrl(v) => self.ws_url = v,
516			Self::OptionItem::WsConfig(v) => self.ws_config = v,
517			Self::OptionItem::WsTopics(v) => self.ws_topics = v.into_iter().collect(),
518			Self::OptionItem::BookSnapshotFreq(v) => self.book_snapshot_freq = v,
519		}
520	}
521
522	fn is_authenticated(&self) -> bool {
523		self.pubkey.is_some() // some end points are satisfied with just the key, and it's really difficult to provide only a key without a secret from the clientside, so assume intent if it's missing.
524	}
525}
526
527impl<'a, R, B> HttpOption<'a, R, B> for BinanceOption
528where
529	R: DeserializeOwned + 'a,
530	B: Serialize,
531{
532	type RequestHandler = BinanceRequestHandler<'a, R>;
533
534	fn request_handler(options: Self::Options) -> Self::RequestHandler {
535		BinanceRequestHandler::<'a, R> { options, _phantom: PhantomData }
536	}
537}
538
539impl HandlerOption for BinanceOption {
540	type Options = BinanceOptions;
541}
542
543// Error Codes {{{
544#[derive(Clone, Debug, Deserialize)]
545pub struct BinanceError {
546	pub code: BinanceErrorCode,
547	pub msg: String,
548}
549impl From<BinanceError> for ApiError {
550	fn from(e: BinanceError) -> Self {
551		use generics::http::AuthError;
552		match e.code {
553			BinanceErrorCode::RejectedMbxKey(_) | BinanceErrorCode::InvalidListenKey(_) => AuthError::KeyExpired { msg: e.msg }.into(),
554			BinanceErrorCode::Unauthorized(_) | BinanceErrorCode::InvalidSignature(_) | BinanceErrorCode::BadApiKeyFmt(_) => AuthError::Unauthorized { msg: e.msg }.into(),
555			_ => ApiError::Other(eyre!("Binance API error: {}", e.msg)),
556		}
557	}
558}
559
560#[non_exhaustive]
561#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
562#[serde(from = "i32")]
563pub enum BinanceErrorCode {
564	// 10xx - General Server/Network
565	Unknown(i32),
566	Disconnected(i32),
567	Unauthorized(i32),
568	TooManyRequests(i32),
569	UnexpectedResponse(i32),
570	Timeout(i32),
571	ServerBusy(i32),
572	InvalidMessage(i32),
573	UnknownOrderComposition(i32),
574	TooManyOrders(i32),
575	ServiceShuttingDown(i32),
576	UnsupportedOperation(i32),
577	InvalidTimestamp(i32),
578	InvalidSignature(i32),
579
580	// 11xx - Request issues
581	IllegalChars(i32),
582	TooManyParameters(i32),
583	MandatoryParamEmptyOrMalformed(i32),
584	UnknownParam(i32),
585	UnreadParameters(i32),
586	ParamEmpty(i32),
587	ParamNotRequired(i32),
588	ParamOverflow(i32),
589	BadPrecision(i32),
590	NoDepth(i32),
591	TifNotRequired(i32),
592	InvalidTif(i32),
593	InvalidOrderType(i32),
594	InvalidSide(i32),
595	EmptyNewClOrdId(i32),
596	EmptyOrgClOrdId(i32),
597	BadInterval(i32),
598	BadSymbol(i32),
599	InvalidSymbolStatus(i32),
600	InvalidListenKey(i32),
601	MoreThanXXHours(i32),
602	OptionalParamsBadCombo(i32),
603	InvalidParameter(i32),
604	BadStrategyType(i32),
605	InvalidJson(i32),
606	InvalidTickerType(i32),
607	InvalidCancelRestrictions(i32),
608	DuplicateSymbols(i32),
609	InvalidSbeHeader(i32),
610	UnsupportedSchemaId(i32),
611	SbeDisabled(i32),
612	OcoOrderTypeRejected(i32),
613	OcoIcebergqtyTimeinforce(i32),
614	DeprecatedSchema(i32),
615	BuyOcoLimitMustBeBelow(i32),
616	SellOcoLimitMustBeAbove(i32),
617	BothOcoOrdersCannotBeLimit(i32),
618	InvalidTagNumber(i32),
619	TagNotDefinedInMessage(i32),
620	TagAppearsMoreThanOnce(i32),
621	TagOutOfOrder(i32),
622	GroupFieldsOutOfOrder(i32),
623	InvalidComponent(i32),
624	ResetSeqNumSupport(i32),
625	AlreadyLoggedIn(i32),
626	GarbledMessage(i32),
627	BadSenderCompid(i32),
628	BadSeqNum(i32),
629	ExpectedLogon(i32),
630	TooManyMessages(i32),
631	ParamsBadCombo(i32),
632	NotAllowedInDropCopySessions(i32),
633	DropCopySessionNotAllowed(i32),
634	DropCopySessionRequired(i32),
635	NotAllowedInOrderEntrySessions(i32),
636	NotAllowedInMarketDataSessions(i32),
637	IncorrectNumInGroupCount(i32),
638	DuplicateEntriesInAGroup(i32),
639	InvalidRequestId(i32),
640	TooManySubscriptions(i32),
641	BuyOcoStopLossMustBeAbove(i32),
642	SellOcoStopLossMustBeBelow(i32),
643	BuyOcoTakeProfitMustBeBelow(i32),
644	SellOcoTakeProfitMustBeAbove(i32),
645
646	// 20xx - Business logic errors
647	NewOrderRejected(i32),
648	CancelRejected(i32),
649	NoSuchOrder(i32),
650	BadApiKeyFmt(i32),
651	RejectedMbxKey(i32),
652	NoTradingWindow(i32),
653	OrderArchived(i32),
654	OrderCancelReplacePartiallyFailed(i32),
655	OrderCancelReplaceFailed(i32),
656
657	// Unknown error code
658	Other(i32),
659}
660
661impl From<i32> for BinanceErrorCode {
662	fn from(code: i32) -> Self {
663		match code {
664			-1000 => Self::Unknown(code),
665			-1001 => Self::Disconnected(code),
666			-1002 => Self::Unauthorized(code),
667			-1003 => Self::TooManyRequests(code),
668			-1006 => Self::UnexpectedResponse(code),
669			-1007 => Self::Timeout(code),
670			-1008 => Self::ServerBusy(code),
671			-1013 => Self::InvalidMessage(code),
672			-1014 => Self::UnknownOrderComposition(code),
673			-1015 => Self::TooManyOrders(code),
674			-1016 => Self::ServiceShuttingDown(code),
675			-1020 => Self::UnsupportedOperation(code),
676			-1021 => Self::InvalidTimestamp(code),
677			-1022 => Self::InvalidSignature(code),
678
679			-1100 => Self::IllegalChars(code),
680			-1101 => Self::TooManyParameters(code),
681			-1102 => Self::MandatoryParamEmptyOrMalformed(code),
682			-1103 => Self::UnknownParam(code),
683			-1104 => Self::UnreadParameters(code),
684			-1105 => Self::ParamEmpty(code),
685			-1106 => Self::ParamNotRequired(code),
686			-1108 => Self::ParamOverflow(code),
687			-1111 => Self::BadPrecision(code),
688			-1112 => Self::NoDepth(code),
689			-1114 => Self::TifNotRequired(code),
690			-1115 => Self::InvalidTif(code),
691			-1116 => Self::InvalidOrderType(code),
692			-1117 => Self::InvalidSide(code),
693			-1118 => Self::EmptyNewClOrdId(code),
694			-1119 => Self::EmptyOrgClOrdId(code),
695			-1120 => Self::BadInterval(code),
696			-1121 => Self::BadSymbol(code),
697			-1122 => Self::InvalidSymbolStatus(code),
698			-1125 => Self::InvalidListenKey(code),
699			-1127 => Self::MoreThanXXHours(code),
700			-1128 => Self::OptionalParamsBadCombo(code),
701			-1130 => Self::InvalidParameter(code),
702			-1134 => Self::BadStrategyType(code),
703			-1135 => Self::InvalidJson(code),
704			-1139 => Self::InvalidTickerType(code),
705			-1145 => Self::InvalidCancelRestrictions(code),
706			-1151 => Self::DuplicateSymbols(code),
707			-1152 => Self::InvalidSbeHeader(code),
708			-1153 => Self::UnsupportedSchemaId(code),
709			-1155 => Self::SbeDisabled(code),
710			-1158 => Self::OcoOrderTypeRejected(code),
711			-1160 => Self::OcoIcebergqtyTimeinforce(code),
712			-1161 => Self::DeprecatedSchema(code),
713			-1165 => Self::BuyOcoLimitMustBeBelow(code),
714			-1166 => Self::SellOcoLimitMustBeAbove(code),
715			-1168 => Self::BothOcoOrdersCannotBeLimit(code),
716			-1169 => Self::InvalidTagNumber(code),
717			-1170 => Self::TagNotDefinedInMessage(code),
718			-1171 => Self::TagAppearsMoreThanOnce(code),
719			-1172 => Self::TagOutOfOrder(code),
720			-1173 => Self::GroupFieldsOutOfOrder(code),
721			-1174 => Self::InvalidComponent(code),
722			-1175 => Self::ResetSeqNumSupport(code),
723			-1176 => Self::AlreadyLoggedIn(code),
724			-1177 => Self::GarbledMessage(code),
725			-1178 => Self::BadSenderCompid(code),
726			-1179 => Self::BadSeqNum(code),
727			-1180 => Self::ExpectedLogon(code),
728			-1181 => Self::TooManyMessages(code),
729			-1182 => Self::ParamsBadCombo(code),
730			-1183 => Self::NotAllowedInDropCopySessions(code),
731			-1184 => Self::DropCopySessionNotAllowed(code),
732			-1185 => Self::DropCopySessionRequired(code),
733			-1186 => Self::NotAllowedInOrderEntrySessions(code),
734			-1187 => Self::NotAllowedInMarketDataSessions(code),
735			-1188 => Self::IncorrectNumInGroupCount(code),
736			-1189 => Self::DuplicateEntriesInAGroup(code),
737			-1190 => Self::InvalidRequestId(code),
738			-1191 => Self::TooManySubscriptions(code),
739			-1196 => Self::BuyOcoStopLossMustBeAbove(code),
740			-1197 => Self::SellOcoStopLossMustBeBelow(code),
741			-1198 => Self::BuyOcoTakeProfitMustBeBelow(code),
742			-1199 => Self::SellOcoTakeProfitMustBeAbove(code),
743
744			-2010 => Self::NewOrderRejected(code),
745			-2011 => Self::CancelRejected(code),
746			-2013 => Self::NoSuchOrder(code),
747			-2014 => Self::BadApiKeyFmt(code),
748			-2015 => Self::RejectedMbxKey(code),
749			-2016 => Self::NoTradingWindow(code),
750			-2021 => Self::OrderCancelReplacePartiallyFailed(code),
751			-2022 => Self::OrderCancelReplaceFailed(code),
752			-2026 => Self::OrderArchived(code),
753
754			code => {
755				tracing::warn!("Encountered unknown Binance error code: {code}");
756				Self::Other(code)
757			}
758		}
759	}
760}
761//,}}}