v_exchanges_methods 0.1.7

Exchange method implementations backing the v_exchanges crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::collections::{BTreeMap, btree_map::Entry};

use adapters::binance::{BinanceHttpUrl, BinanceOption};
use eyre::Result;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::{DisplayFromStr, serde_as};
use v_utils::trades::Pair;

use crate::{
	ExchangeError,
	core::{ExchangeInfo, PairInfo},
};
//TODO: general endpoints, like ping and exchange info

const PERPETUAL_DELIVERY_DATE: i64 = 4133404800000;
pub async fn exchange_info(client: &v_exchanges_adapters::Client) -> Result<ExchangeInfo, ExchangeError> {
	let options = vec![BinanceOption::HttpUrl(BinanceHttpUrl::FuturesUsdM)];
	let r: BinanceExchangeFutures = client.get_no_query("/fapi/v1/exchangeInfo", options).await?;
	Ok(r.into())
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceExchangeFutures {
	pub exchange_filters: Vec<String>,
	pub rate_limits: Vec<RateLimit>,
	pub server_time: i64,
	pub assets: Vec<Value>,
	pub symbols: Vec<FuturesSymbol>,
	pub timezone: String,
}

impl From<BinanceExchangeFutures> for ExchangeInfo {
	fn from(v: BinanceExchangeFutures) -> Self {
		let server_time = Timestamp::from_millisecond(v.server_time).unwrap();
		let mut pairs = BTreeMap::new();
		for s in v.symbols {
			if s.status != "TRADING" {
				continue;
			}
			// symbol strings aren't reliably splittable (eg `BTCU` perp took the service down), so key off the authoritative asset fields
			let pair = Pair::new(s.base_asset.as_str(), s.quote_asset.as_str());
			let info = PairInfo::from(s);
			match pairs.entry(pair) {
				Entry::Vacant(e) => {
					e.insert(info);
				}
				// delivery contracts share base/quote with their perpetual; perpetual wins the key
				Entry::Occupied(mut e) =>
					if e.get().delivery_date.is_some() && info.delivery_date.is_none() {
						e.insert(info);
					},
			}
		}
		Self { server_time, pairs }
	}
}
impl From<FuturesSymbol> for PairInfo {
	fn from(v: FuturesSymbol) -> Self {
		let delivery_date = match v.delivery_date {
			PERPETUAL_DELIVERY_DATE => None,
			ms => Some(Timestamp::from_millisecond(ms).expect("Binance deliveryDate is valid ms timestamp")),
		};
		Self {
			price_precision: v.price_precision,
			qty_precision: v.quantity_precision as u8,
			delivery_date,
		}
	}
}

//DO: transfer these to be embedded into the outputted struct, compiled for each symbol on acquisition.
//impl BinanceExchangeFutures {
//	pub fn min_notional(&self, symbol: Symbol) -> f64 {
//		let symbol_info = self.symbols.iter().find(|s| s.symbol == symbol.ticker()).unwrap();
//		let min_notional = symbol_info.filters.iter().find(|f| f["filterType"] == "MIN_NOTIONAL").unwrap();
//		min_notional["minNotional"].as_str().unwrap().parse().unwrap()
//	}
//
//	pub fn pair(&self, base_asset: &str, quote_asset: &str) -> Option<&FuturesSymbol> {
//		//? Should I cast `to_uppercase()`?
//		self.symbols.iter().find(|s| s.base_asset == base_asset && s.quote_asset == quote_asset)
//	}
//}

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RateLimit {
	pub interval: String,
	pub interval_num: u32,
	pub limit: u32,
	pub rate_limit_type: String,
}

// the thing with multiplying orders due to weird limits should be here.
//#[derive(Debug, Deserialize, Serialize)]
//#[allow(non_snake_case)]
// struct SymbolFilter {
// 	filterType: String,
// 	maxPrice: String,
// 	minPrice: String,
// 	tickSize: String,
// 	maxQty: String,
// 	minQty: String,
// 	stepSize: String,
// 	limit: u32,
// 	notional: String,
// 	multiplierUp: String,
// 	multiplierDown: String,
// 	multiplierDecimal: u32,
//}

#[serde_as]
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FuturesSymbol {
	pub symbol: String,
	pub pair: String,
	pub contract_type: String,
	pub delivery_date: i64,
	pub onboard_date: i64,
	//TODO: filter based on asset being active, don't return those that aren't.
	//REVIEW: `From<BinanceExchangeFutures> for ExchangeInfo` now skips non-TRADING symbols
	pub status: String,
	pub base_asset: String,
	pub quote_asset: String,
	pub margin_asset: String,
	pub price_precision: u8,
	pub quantity_precision: u32,
	pub base_asset_precision: u32,
	pub quote_precision: u32,
	pub underlying_type: String,
	pub underlying_sub_type: Vec<String>,
	pub settle_plan: Option<u32>,
	pub trigger_protect: String,
	pub filters: Vec<Value>,
	pub order_type: Option<Vec<String>>,
	pub time_in_force: Vec<String>,
	#[serde_as(as = "DisplayFromStr")]
	pub liquidation_fee: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub market_take_bound: f64,
}
impl FuturesSymbol {
	fn get_filter<T: for<'de> Deserialize<'de>>(&self, filter_type: &str) -> Option<T> {
		self.filters.iter().find_map(|filter| {
			if filter["filterType"] == filter_type {
				serde_json::from_value(filter.clone()).ok()
			} else {
				None
			}
		})
	}

	pub fn price_filter(&self) -> Option<PriceFilter> {
		self.get_filter("PRICE_FILTER")
	}

	pub fn lot_size_filter(&self) -> Option<LotSizeFilter> {
		self.get_filter("LOT_SIZE")
	}

	pub fn market_lot_size_filter(&self) -> Option<MarketLotSizeFilter> {
		self.get_filter("MARKET_LOT_SIZE")
	}

	pub fn max_num_orders_filter(&self) -> Option<MaxNumOrdersFilter> {
		self.get_filter("MAX_NUM_ORDERS")
	}

	pub fn max_num_algo_orders_filter(&self) -> Option<MaxNumAlgoOrdersFilter> {
		self.get_filter("MAX_NUM_ALGO_ORDERS")
	}

	pub fn min_notional_filter(&self) -> Option<MinNotionalFilter> {
		self.get_filter("MIN_NOTIONAL")
	}

	pub fn percent_price_filter(&self) -> Option<PercentPriceFilter> {
		self.get_filter("PERCENT_PRICE")
	}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "filterType")]
pub enum Filter {
	#[serde(rename = "PRICE_FILTER")]
	Price(PriceFilter),
	#[serde(rename = "LOT_SIZE")]
	LotSize(LotSizeFilter),
	#[serde(rename = "MARKET_LOT_SIZE")]
	MarketLotSize(MarketLotSizeFilter),
	#[serde(rename = "MAX_NUM_ORDERS")]
	MaxNumOrders(MaxNumOrdersFilter),
	#[serde(rename = "MAX_NUM_ALGO_ORDERS")]
	MaxNumAlgoOrders(MaxNumAlgoOrdersFilter),
	#[serde(rename = "MIN_NOTIONAL")]
	MinNotional(MinNotionalFilter),
	#[serde(rename = "PERCENT_PRICE")]
	PercentPrice(PercentPriceFilter),
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PriceFilter {
	#[serde_as(as = "DisplayFromStr")]
	pub min_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub max_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub tick_size: f64,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LotSizeFilter {
	#[serde_as(as = "DisplayFromStr")]
	pub max_qty: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub min_qty: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub step_size: f64,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketLotSizeFilter {
	#[serde_as(as = "DisplayFromStr")]
	pub max_qty: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub min_qty: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub step_size: f64,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MaxNumOrdersFilter {
	pub limit: u32,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MaxNumAlgoOrdersFilter {
	pub limit: u32,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MinNotionalFilter {
	#[serde_as(as = "DisplayFromStr")]
	pub notional: f64,
}

#[serde_as]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PercentPriceFilter {
	#[serde_as(as = "DisplayFromStr")]
	pub multiplier_up: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub multiplier_down: f64,
	pub multiplier_decimal: u8,
}

#[cfg(test)]
mod tests {
	use serde_json::json;

	use super::*;

	#[serde_as]
	#[derive(Debug, Deserialize, Serialize)]
	#[serde(rename_all = "camelCase")]
	struct MiniSymbol {
		price_precision: u8,
		quantity_precision: u8,
		quote_asset: String,
		quote_precision: u8,
		#[serde_as(as = "DisplayFromStr")]
		required_margin_percent: f64,
		#[serde(default)]
		settle_plan: Option<u32>,
		status: String,
		symbol: String,
		time_in_force: Vec<String>,
		#[serde_as(as = "DisplayFromStr")]
		trigger_protect: f64,
		underlying_sub_type: Vec<String>,
		underlying_type: String,
	}

	#[test]
	fn mini_symbol() {
		let json = json!({
			"pricePrecision": 2,
			"quantityPrecision": 3,
			"quoteAsset": "USDT",
			"quotePrecision": 8,
			"requiredMarginPercent": "5.0000",  // Needs to be a string
			"settlePlan": null,
			"status": "TRADING",
			"symbol": "BTCUSDT",
			"timeInForce": [
				"GTC",
				"IOC",
				"FOK",
				"GTX",
				"GTD"
			],
			"triggerProtect": "0.0500",  // Needs to be a string
			"underlyingSubType": [
				"PoW"
			],
			"underlyingType": "COIN"
		});

		let _: MiniSymbol = serde_json::from_value(json).unwrap();
	}

	#[test]
	fn futures_symbol() {
		let json = json!({
			"baseAsset": "BTC",
			"baseAssetPrecision": 8,
			"contractType": "PERPETUAL",
			"deliveryDate": 4133404800000_i64,
			"filters": [
				{
					"filterType": "PRICE_FILTER",
					"maxPrice": "4529764",
					"minPrice": "556.80",
					"tickSize": "0.10"
				},
				{
					"filterType": "LOT_SIZE",
					"maxQty": "1000",
					"minQty": "0.001",
					"stepSize": "0.001"
				},
				{
					"filterType": "MARKET_LOT_SIZE",
					"maxQty": "120",
					"minQty": "0.001",
					"stepSize": "0.001"
				},
				{
					"filterType": "MAX_NUM_ORDERS",
					"limit": 200
				},
				{
					"filterType": "MAX_NUM_ALGO_ORDERS",
					"limit": 10
				},
				{
					"filterType": "MIN_NOTIONAL",
					"notional": "100"
				},
				{
					"filterType": "PERCENT_PRICE",
					"multiplierDecimal": "4",
					"multiplierDown": "0.9500",
					"multiplierUp": "1.0500"
				}
			],
			"liquidationFee": "0.012500",  // Needs to be a string
			"maintMarginPercent": "2.5000", // Needs to be a string
			"marginAsset": "USDT",
			"marketTakeBound": "0.05",      // Needs to be a string
			"maxMoveOrderLimit": 10000,
			"onboardDate": 1569398400000_i64,
			"orderTypes": [
				"LIMIT",
				"MARKET",
				"STOP",
				"STOP_MARKET",
				"TAKE_PROFIT",
				"TAKE_PROFIT_MARKET",
				"TRAILING_STOP_MARKET"
			],
			"pair": "BTCUSDT",
			"pricePrecision": 2,
			"quantityPrecision": 3,
			"quoteAsset": "USDT",
			"quotePrecision": 8,
			"requiredMarginPercent": "5.0000",  // Needs to be a string
			"status": "TRADING",
			"symbol": "BTCUSDT",
			"timeInForce": [
				"GTC",
				"IOC",
				"FOK",
				"GTX",
				"GTD"
			],
			"triggerProtect": "0.0500",  // Needs to be a string
			"underlyingSubType": [
				"PoW"
			],
			"underlyingType": "COIN"
		});

		let _: FuturesSymbol = serde_json::from_value(json).unwrap();
	}
}