v_exchanges_methods 0.1.5

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
411
412
413
use std::{
	collections::{BTreeMap, VecDeque},
	str::FromStr,
};

use ahash::AHashMap;
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use serde_with::{DisplayFromStr, serde_as};
use v_exchanges_adapters::bybit::BybitOption;
use v_utils::{
	trades::{Kline, Ohlc, Pair},
	utils::filter_nulls,
};

use super::{BybitInterval, BybitIntervalTime};
use crate::{
	ExchangeName, ExchangeResult, Instrument, Symbol,
	core::{ExchangeInfo, Klines, OpenInterest, PairInfo, RequestRange},
};

// klines {{{
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KlineResponse {
	pub result: ResponseResult,
	pub ret_code: i32,
	pub ret_ext_info: AHashMap<String, serde_json::Value>,
	pub ret_msg: String,
	pub time: i64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseResult {
	pub category: String,
	pub list: Vec<KlineData>,
	pub symbol: String,
}
#[serde_as]
#[derive(Debug, Deserialize, Serialize)]
pub struct KlineData(
	#[serde_as(as = "DisplayFromStr")] pub i64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
	#[serde_as(as = "DisplayFromStr")] pub f64,
);
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketTickerResponse {
	pub ret_code: i32,
	pub ret_msg: String,
	pub result: MarketTickerResult,
	pub ret_ext_info: AHashMap<String, Value>,
	pub time: i64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketTickerResult {
	pub category: String,
	pub list: Vec<MarketTickerData>,
}
#[serde_as]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketTickerData {
	pub symbol: String,
	#[serde_as(as = "DisplayFromStr")]
	pub last_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub index_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub mark_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub prev_price24h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub price24h_pcnt: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub high_price24h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub low_price24h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub prev_price1h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub open_interest: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub open_interest_value: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub turnover24h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub volume24h: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub funding_rate: f64,
	pub next_funding_time: String,
	#[serde_as(as = "DisplayFromStr")]
	pub bid1_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub bid1_size: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub ask1_price: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub ask1_size: f64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenInterestResponse {
	pub ret_code: i32,
	pub ret_msg: String,
	pub result: OpenInterestResult,
	pub ret_ext_info: AHashMap<String, Value>,
	pub time: i64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenInterestResult {
	pub symbol: String,
	pub category: String,
	pub list: Vec<OpenInterestData>,
	pub next_page_cursor: String,
}
#[serde_as]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenInterestData {
	#[serde_as(as = "DisplayFromStr")]
	pub open_interest: f64,
	#[serde_as(as = "DisplayFromStr")]
	pub timestamp: i64,
}
pub(super) async fn klines(client: &v_exchanges_adapters::Client, symbol: Symbol, tf: BybitInterval, range: RequestRange) -> ExchangeResult<Klines> {
	range.ensure_allowed(1..=1000, &tf)?;
	let range_json = range.serialize(ExchangeName::Bybit);
	let base_params = filter_nulls(json!({
		"category": "linear", // can be ["linear", "inverse", "spot"] afaiu, could drive some generics with this later, but for now hardcode
		"symbol": symbol.pair.fmt_bybit(),
		"interval": tf.to_string(),
	}));

	let mut base_map = base_params.as_object().unwrap().clone();
	let range_map = range_json.as_object().unwrap();
	base_map.extend(range_map.clone());
	let params = filter_nulls(serde_json::Value::Object(base_map));

	let options = vec![BybitOption::None];
	let kline_response: KlineResponse = client.get("/v5/market/kline", &params, options).await?;

	let mut klines = VecDeque::with_capacity(kline_response.result.list.len());
	for k in kline_response.result.list {
		if kline_response.time > k.0 + tf.duration().as_millis() as i64
		/*take `as_millis`, so ok to downcast in all practical applications*/
		{
			klines.push_back(Kline {
				open_time: Timestamp::from_millisecond(k.0).unwrap(),
				ohlc: Ohlc {
					open: k.1,
					close: k.2,
					high: k.3,
					low: k.4,
				},
				volume_quote: k.5,
				trades: None,
				taker_buy_volume_quote: None,
			});
		}
	}
	Ok(Klines::new(klines, *tf))
}

//,}}}

// prices {{{
#[serde_as]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TickerPriceEntry {
	symbol: String,
	#[serde_as(as = "Option<DisplayFromStr>")]
	last_price: Option<f64>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TickerPriceResult {
	list: Vec<TickerPriceEntry>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TickerPriceResponse {
	result: TickerPriceResult,
}
pub(super) async fn prices(client: &v_exchanges_adapters::Client, pairs: Option<Vec<Pair>>, instrument: Instrument) -> ExchangeResult<BTreeMap<Pair, f64>> {
	let category = match instrument {
		Instrument::Perp => "linear",
		_ => unimplemented!(),
	};
	let params = filter_nulls(json!({ "category": category }));
	let options = vec![BybitOption::None];
	let response: TickerPriceResponse = client.get("/v5/market/tickers", &params, options).await?;
	let mut price_map = BTreeMap::default();
	for entry in response.result.list {
		let Some(price) = entry.last_price else { continue };
		let Ok(pair) = Pair::from_str(&entry.symbol) else { continue };
		if let Some(ref requested) = pairs
			&& !requested.contains(&pair)
		{
			continue;
		}
		price_map.insert(pair, price);
	}
	Ok(price_map)
}
//,}}}

// open_interest {{{
pub(super) async fn open_interest(client: &v_exchanges_adapters::Client, symbol: Symbol, tf: BybitIntervalTime, range: RequestRange) -> ExchangeResult<Vec<OpenInterest>> {
	range.ensure_allowed(1..=200, &tf)?;
	let range_json = range.serialize(ExchangeName::Bybit);

	let base_params = filter_nulls(json!({
		"category": "linear",
		"symbol": symbol.pair.fmt_bybit(),
		"intervalTime": tf.to_string(),
	}));

	let mut base_map = base_params.as_object().unwrap().clone();
	let range_map = range_json.as_object().unwrap();
	base_map.extend(range_map.clone());
	let params = filter_nulls(serde_json::Value::Object(base_map));

	let options = vec![BybitOption::None];
	let response: OpenInterestResponse = client.get("/v5/market/open-interest", &params, options).await?;

	if response.result.list.is_empty() {
		return Err(crate::ExchangeError::Other(eyre::eyre!("No open interest data returned")));
	}

	// For PerpInverse, we need to fetch the price to convert
	let price = if symbol.instrument == Instrument::PerpInverse {
		let params = filter_nulls(json!({
			"category": "linear",
			"symbol": symbol.pair.fmt_bybit(),
		}));
		let options = vec![BybitOption::None];
		let ticker_response: MarketTickerResponse = client.get("/v5/market/tickers", &params, options).await?;
		Some(ticker_response.result.list[0].last_price)
	} else {
		None
	};

	// Convert all data points to OpenInterest
	let mut result = Vec::with_capacity(response.result.list.len());
	for data in response.result.list {
		let (val_asset, val_quote) = match symbol.instrument {
			Instrument::PerpInverse => {
				// as of (2025/10/14), Bybit returns value in `quote` for Inverse and in `asset` for Linear reqs
				let val_quote = data.open_interest;
				let price = price.expect("price should be set for PerpInverse");
				let val_asset = val_quote / price;
				(val_asset, Some(val_quote))
			}
			Instrument::Perp => (data.open_interest, None),
			_ => unreachable!(),
		};

		result.push(OpenInterest {
			val_asset,
			val_quote,
			timestamp: Timestamp::from_millisecond(data.timestamp).unwrap(),
			..Default::default()
		});
	}

	Ok(result)
}

//,}}}

// exchange_info {{{
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct InstrumentsInfoResponse {
	result: InstrumentsInfoResult,
	time: i64,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct InstrumentsInfoResult {
	list: Vec<InstrumentInfo>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct LotSizeFilter {
	qty_step: String,
}

#[serde_as]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct InstrumentInfo {
	symbol: String,
	price_scale: String,
	/// Millisecond timestamp; 0 for perpetuals
	#[serde_as(as = "DisplayFromStr")]
	delivery_time: i64,
	lot_size_filter: LotSizeFilter,
}
pub(super) async fn exchange_info(client: &v_exchanges_adapters::Client, instrument: Instrument) -> ExchangeResult<ExchangeInfo> {
	if instrument == Instrument::Spot {
		#[derive(Deserialize)]
		#[serde(rename_all = "camelCase")]
		struct SpotLotSizeFilter {
			base_precision: String,
		}
		#[derive(Deserialize)]
		#[serde(rename_all = "camelCase")]
		struct SpotPriceFilter {
			tick_size: String,
		}
		#[derive(Deserialize)]
		#[serde(rename_all = "camelCase")]
		struct SpotInfo {
			symbol: String,
			lot_size_filter: SpotLotSizeFilter,
			price_filter: SpotPriceFilter,
		}
		#[derive(Deserialize)]
		#[serde(rename_all = "camelCase")]
		struct SpotResult {
			list: Vec<SpotInfo>,
		}
		#[derive(Deserialize)]
		#[serde(rename_all = "camelCase")]
		struct SpotResponse {
			result: SpotResult,
			time: i64,
		}

		let response: SpotResponse = client
			.get("/v5/market/instruments-info", &[("category", "spot"), ("limit", "1000")], vec![BybitOption::None])
			.await?;
		let server_time = Timestamp::from_millisecond(response.time).expect("Bybit time is valid ms");
		let pairs = response
			.result
			.list
			.into_iter()
			.filter_map(|i| {
				let pair: Pair = i.symbol.try_into().ok()?;
				let price_precision = i
					.price_filter
					.tick_size
					.split_once('.')
					.map(|(_, decimals)| decimals.trim_end_matches('0').len() as u8)
					.unwrap_or(0);
				let qty_precision = i
					.lot_size_filter
					.base_precision
					.split_once('.')
					.map(|(_, decimals)| decimals.trim_end_matches('0').len() as u8)
					.unwrap_or(0);
				Some((
					pair,
					PairInfo {
						price_precision,
						qty_precision,
						delivery_date: None,
					},
				))
			})
			.collect();
		return Ok(ExchangeInfo { server_time, pairs });
	}

	let category = match instrument {
		Instrument::Perp => "linear",
		Instrument::PerpInverse => "inverse",
		_ => unimplemented!(),
	};
	let response: InstrumentsInfoResponse = client
		.get("/v5/market/instruments-info", &[("category", category), ("limit", "1000")], vec![BybitOption::None])
		.await?;
	let server_time = Timestamp::from_millisecond(response.time).expect("Bybit time is valid ms");
	let pairs = response
		.result
		.list
		.into_iter()
		.filter_map(|i| {
			let pair: Pair = i.symbol.try_into().ok()?;
			let price_precision = i.price_scale.parse::<u8>().unwrap_or(0);
			let qty_precision = i
				.lot_size_filter
				.qty_step
				.split_once('.')
				.map(|(_, decimals)| decimals.trim_end_matches('0').len() as u8)
				.unwrap_or(0);
			let delivery_date = match i.delivery_time {
				0 => None,
				ms => Some(Timestamp::from_millisecond(ms).expect("Bybit deliveryTime is valid ms")),
			};
			Some((
				pair,
				PairInfo {
					price_precision,
					qty_precision,
					delivery_date,
				},
			))
		})
		.collect();
	Ok(ExchangeInfo { server_time, pairs })
}
//,}}}