use crate::{Channel, Depth, Level, OhlcInterval, Side, SystemStatus, TickerTrigger};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
pub struct SubscribeRequest {
pub method: &'static str,
pub params: SubscribeParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
impl SubscribeRequest {
pub fn new(params: SubscribeParams) -> Self {
Self {
method: "subscribe",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SubscribeParams {
pub channel: Channel,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub symbol: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub depth: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub snapshot: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub interval: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub event_trigger: Option<TickerTrigger>,
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl SubscribeParams {
pub fn book(symbols: Vec<String>, depth: Depth) -> Self {
Self {
channel: Channel::Book,
symbol: symbols,
depth: Some(depth.as_u32()),
snapshot: Some(true),
interval: None,
event_trigger: None,
token: None,
}
}
pub fn ticker(symbols: Vec<String>) -> Self {
Self {
channel: Channel::Ticker,
symbol: symbols,
depth: None,
snapshot: None,
interval: None,
event_trigger: Some(TickerTrigger::Trades),
token: None,
}
}
pub fn trade(symbols: Vec<String>) -> Self {
Self {
channel: Channel::Trade,
symbol: symbols,
depth: None,
snapshot: Some(true),
interval: None,
event_trigger: None,
token: None,
}
}
pub fn ohlc(symbols: Vec<String>, interval: OhlcInterval) -> Self {
Self {
channel: Channel::Ohlc,
symbol: symbols,
depth: None,
snapshot: None,
interval: Some(interval as u32),
event_trigger: None,
token: None,
}
}
pub fn executions(token: String) -> Self {
Self {
channel: Channel::Executions,
symbol: vec![],
depth: None,
snapshot: Some(true),
interval: None,
event_trigger: None,
token: Some(token),
}
}
pub fn balances(token: String) -> Self {
Self {
channel: Channel::Balances,
symbol: vec![],
depth: None,
snapshot: Some(true),
interval: None,
event_trigger: None,
token: Some(token),
}
}
pub fn with_token(mut self, token: String) -> Self {
self.token = Some(token);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UnsubscribeRequest {
pub method: &'static str,
pub params: SubscribeParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
impl UnsubscribeRequest {
pub fn new(params: SubscribeParams) -> Self {
Self {
method: "unsubscribe",
params,
req_id: None,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PingRequest {
pub method: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
impl PingRequest {
pub fn new() -> Self {
Self {
method: "ping",
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
impl Default for PingRequest {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct MethodResponse {
pub method: String,
pub result: Option<SubscribeResult>,
pub success: bool,
pub time_in: String,
pub time_out: String,
#[serde(default)]
pub req_id: Option<u64>,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SubscribeResult {
pub channel: String,
#[serde(default)]
pub symbol: Option<String>,
#[serde(default)]
pub depth: Option<u32>,
#[serde(default)]
pub snapshot: Option<bool>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ChannelMessage<T> {
pub channel: String,
#[serde(rename = "type")]
pub msg_type: String,
pub data: Vec<T>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct StatusData {
pub api_version: String,
pub connection_id: u64,
pub system: SystemStatus,
pub version: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BookData {
pub symbol: String,
pub bids: Vec<Level>,
pub asks: Vec<Level>,
pub checksum: u32,
#[serde(default)]
pub timestamp: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct TickerData {
pub symbol: String,
pub bid: Decimal,
pub bid_qty: Decimal,
pub ask: Decimal,
pub ask_qty: Decimal,
pub last: Decimal,
pub volume: Decimal,
pub vwap: Decimal,
pub low: Decimal,
pub high: Decimal,
pub change: Decimal,
pub change_pct: Decimal,
}
#[derive(Debug, Clone, Deserialize)]
pub struct TradeData {
pub symbol: String,
pub side: Side,
pub price: Decimal,
pub qty: Decimal,
pub ord_type: String,
pub trade_id: u64,
pub timestamp: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct OhlcData {
pub symbol: String,
pub open: Decimal,
pub high: Decimal,
pub low: Decimal,
pub close: Decimal,
pub vwap: Decimal,
pub volume: Decimal,
pub trades: u64,
pub interval_begin: String,
pub interval: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InstrumentAsset {
pub id: String,
#[serde(default)]
pub status: Option<String>,
#[serde(default)]
pub precision: Option<u8>,
#[serde(default)]
pub precision_display: Option<u8>,
#[serde(default)]
pub borrowable: Option<bool>,
#[serde(default)]
pub collateral_value: Option<Decimal>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InstrumentPair {
pub symbol: String,
pub price_precision: u8,
pub qty_precision: u8,
#[serde(default)]
pub price_increment: Option<Decimal>,
#[serde(default)]
pub qty_increment: Option<Decimal>,
#[serde(default)]
pub qty_min: Option<Decimal>,
#[serde(default)]
pub base: Option<String>,
#[serde(default)]
pub quote: Option<String>,
#[serde(default)]
pub status: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InstrumentChannelData {
#[serde(default)]
pub assets: Vec<InstrumentAsset>,
#[serde(default)]
pub pairs: Vec<InstrumentPair>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InstrumentMessage {
pub channel: String,
#[serde(rename = "type")]
pub msg_type: String,
pub data: InstrumentChannelData,
}
pub type InstrumentData = InstrumentPair;
#[derive(Debug, Clone, Deserialize)]
pub struct ExecutionData {
#[serde(rename = "exec_type")]
pub exec_type: String,
pub order_id: String,
#[serde(default)]
pub exec_id: Option<String>,
#[serde(default)]
pub trade_id: Option<u64>,
pub symbol: String,
pub side: Side,
pub order_type: String,
#[serde(default)]
pub order_qty: Option<Decimal>,
#[serde(default)]
pub limit_price: Option<Decimal>,
#[serde(default)]
pub last_qty: Option<Decimal>,
#[serde(default)]
pub last_price: Option<Decimal>,
#[serde(default)]
pub cum_qty: Option<Decimal>,
#[serde(default)]
pub avg_price: Option<Decimal>,
#[serde(default)]
pub fee_paid: Option<Decimal>,
#[serde(default)]
pub fee_currency: Option<String>,
#[serde(default)]
pub order_status: Option<String>,
pub timestamp: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BalanceData {
pub asset: String,
pub balance: Decimal,
#[serde(default)]
pub hold_trade: Option<Decimal>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct WalletData {
pub balances: Vec<BalanceData>,
#[serde(default)]
pub wallet_type: Option<String>,
#[serde(default)]
pub wallet_id: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum L3EventType {
Add,
Modify,
Delete,
}
#[derive(Debug, Clone, Deserialize)]
pub struct L3Order {
pub order_id: String,
pub limit_price: Decimal,
pub order_qty: Decimal,
pub timestamp: String,
#[serde(default)]
pub event: Option<L3EventType>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct L3Data {
pub symbol: String,
#[serde(default)]
pub bids: Vec<L3Order>,
#[serde(default)]
pub asks: Vec<L3Order>,
#[serde(default)]
pub checksum: Option<u32>,
}
pub type L3Message = ChannelMessage<L3Data>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum TimeInForce {
#[serde(rename = "gtc")]
GTC,
#[serde(rename = "ioc")]
IOC,
#[serde(rename = "gtd")]
GTD,
}
#[derive(Debug, Clone, Serialize)]
pub struct AddOrderRequest {
pub method: &'static str,
pub params: AddOrderParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct AddOrderParams {
pub order_type: String,
pub side: Side,
pub symbol: String,
#[serde(serialize_with = "serialize_decimal")]
pub order_qty: Decimal,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub limit_price: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub time_in_force: Option<TimeInForce>,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub trigger_price: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cl_ord_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub post_only: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reduce_only: Option<bool>,
pub token: String,
}
impl AddOrderRequest {
pub fn new(params: AddOrderParams) -> Self {
Self {
method: "add_order",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AmendOrderRequest {
pub method: &'static str,
pub params: AmendOrderParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct AmendOrderParams {
pub order_id: String,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub limit_price: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub trigger_price: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub order_qty: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub post_only: Option<bool>,
pub token: String,
}
impl AmendOrderRequest {
pub fn new(params: AmendOrderParams) -> Self {
Self {
method: "amend_order",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelOrderRequest {
pub method: &'static str,
pub params: CancelOrderParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelOrderParams {
pub order_id: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cl_ord_id: Option<Vec<String>>,
pub token: String,
}
impl CancelOrderRequest {
pub fn new(params: CancelOrderParams) -> Self {
Self {
method: "cancel_order",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelAllRequest {
pub method: &'static str,
pub params: CancelAllParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelAllParams {
pub token: String,
}
impl CancelAllRequest {
pub fn new(token: String) -> Self {
Self {
method: "cancel_all",
params: CancelAllParams { token },
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelOnDisconnectRequest {
pub method: &'static str,
pub params: CancelOnDisconnectParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CancelOnDisconnectParams {
pub timeout: u32,
pub token: String,
}
impl CancelOnDisconnectRequest {
pub fn new(timeout: u32, token: String) -> Self {
Self {
method: "cancel_all_orders_after",
params: CancelOnDisconnectParams { timeout, token },
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct BatchAddRequest {
pub method: &'static str,
pub params: BatchAddParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct BatchAddParams {
pub orders: Vec<BatchOrder>,
pub token: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub deadline: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub validate: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
pub struct BatchOrder {
pub order_type: String,
pub side: Side,
pub symbol: String,
#[serde(serialize_with = "serialize_decimal")]
pub order_qty: Decimal,
#[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_option_decimal")]
pub limit_price: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cl_ord_id: Option<String>,
}
impl BatchAddRequest {
pub fn new(params: BatchAddParams) -> Self {
Self {
method: "batch_add",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Serialize)]
pub struct BatchCancelRequest {
pub method: &'static str,
pub params: BatchCancelParams,
#[serde(skip_serializing_if = "Option::is_none")]
pub req_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct BatchCancelParams {
pub orders: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cl_ord_id: Option<Vec<String>>,
pub token: String,
}
impl BatchCancelRequest {
pub fn new(params: BatchCancelParams) -> Self {
Self {
method: "batch_cancel",
params,
req_id: None,
}
}
pub fn with_req_id(mut self, id: u64) -> Self {
self.req_id = Some(id);
self
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct AddOrderResult {
pub order_id: String,
#[serde(default)]
pub cl_ord_id: Option<String>,
#[serde(default)]
pub order_status: Option<String>,
#[serde(default)]
pub timestamp: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CancelOrderResult {
pub order_id: String,
#[serde(default)]
pub cl_ord_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CancelAllResult {
pub count: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CancelOnDisconnectResult {
#[serde(default)]
pub current_time: Option<String>,
#[serde(default)]
pub trigger_time: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BatchOrderResult {
#[serde(default)]
pub orders: Vec<BatchOrderResultItem>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BatchOrderResultItem {
#[serde(default)]
pub order_id: Option<String>,
#[serde(default)]
pub cl_ord_id: Option<String>,
#[serde(default)]
pub error: Option<String>,
}
fn serialize_decimal<S>(value: &Decimal, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&value.to_string())
}
fn serialize_option_decimal<S>(value: &Option<Decimal>, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match value {
Some(d) => serializer.serialize_str(&d.to_string()),
None => serializer.serialize_none(),
}
}
pub type StatusMessage = ChannelMessage<StatusData>;
pub type BookMessage = ChannelMessage<BookData>;
pub type TickerMessage = ChannelMessage<TickerData>;
pub type TradeMessage = ChannelMessage<TradeData>;
pub type OhlcMessage = ChannelMessage<OhlcData>;
pub type ExecutionsMessage = ChannelMessage<ExecutionData>;
pub type BalancesMessage = ChannelMessage<WalletData>;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WsMessage {
Method(MethodResponse),
Status(StatusMessage),
Book(BookMessage),
Ticker(TickerMessage),
Trade(TradeMessage),
Ohlc(OhlcMessage),
Instrument(InstrumentMessage),
Executions(ExecutionsMessage),
Balances(BalancesMessage),
Level3(L3Message),
Heartbeat,
Unknown(serde_json::Value),
}
pub type SubscribeResponse = MethodResponse;
impl WsMessage {
pub fn parse(json: &str) -> Result<Self, serde_json::Error> {
let value: serde_json::Value = serde_json::from_str(json)?;
if value.get("method").is_some() {
let response: MethodResponse = serde_json::from_value(value)?;
return Ok(Self::Method(response));
}
let channel = value.get("channel").and_then(|v| v.as_str());
match channel {
Some("status") => {
let msg: StatusMessage = serde_json::from_value(value)?;
Ok(Self::Status(msg))
}
Some("book") => {
let msg: BookMessage = serde_json::from_value(value)?;
Ok(Self::Book(msg))
}
Some("ticker") => {
let msg: TickerMessage = serde_json::from_value(value)?;
Ok(Self::Ticker(msg))
}
Some("trade") => {
let msg: TradeMessage = serde_json::from_value(value)?;
Ok(Self::Trade(msg))
}
Some("ohlc") => {
let msg: OhlcMessage = serde_json::from_value(value)?;
Ok(Self::Ohlc(msg))
}
Some("instrument") => {
let msg: InstrumentMessage = serde_json::from_value(value)?;
Ok(Self::Instrument(msg))
}
Some("executions") => {
let msg: ExecutionsMessage = serde_json::from_value(value)?;
Ok(Self::Executions(msg))
}
Some("balances") => {
let msg: BalancesMessage = serde_json::from_value(value)?;
Ok(Self::Balances(msg))
}
Some("level3") => {
let msg: L3Message = serde_json::from_value(value)?;
Ok(Self::Level3(msg))
}
Some("heartbeat") => Ok(Self::Heartbeat),
_ => Ok(Self::Unknown(value)),
}
}
pub fn is_book_snapshot(&self) -> bool {
matches!(self, Self::Book(msg) if msg.msg_type == "snapshot")
}
pub fn is_book_update(&self) -> bool {
matches!(self, Self::Book(msg) if msg.msg_type == "update")
}
pub fn is_l3_snapshot(&self) -> bool {
matches!(self, Self::Level3(msg) if msg.msg_type == "snapshot")
}
pub fn is_l3_update(&self) -> bool {
matches!(self, Self::Level3(msg) if msg.msg_type == "update")
}
pub fn is_trading_response(&self) -> bool {
matches!(self, Self::Method(resp) if matches!(
resp.method.as_str(),
"add_order" | "amend_order" | "edit_order" | "cancel_order" |
"cancel_all" | "cancel_all_orders_after" | "batch_add" | "batch_cancel"
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_status_message() {
let json = r#"{
"channel": "status",
"type": "update",
"data": [{
"api_version": "v2",
"connection_id": 5688663770896937000,
"system": "online",
"version": "2.0.10"
}]
}"#;
let msg = WsMessage::parse(json).unwrap();
match msg {
WsMessage::Status(status) => {
assert_eq!(status.data[0].api_version, "v2");
assert_eq!(status.data[0].system, SystemStatus::Online);
}
_ => panic!("Expected Status message"),
}
}
#[test]
fn test_parse_book_snapshot() {
let json = r#"{
"channel": "book",
"type": "snapshot",
"data": [{
"symbol": "BTC/USD",
"bids": [{"price": 88813.5, "qty": 0.00460208}],
"asks": [{"price": 88813.6, "qty": 2.85806499}],
"checksum": 2919786898,
"timestamp": "2025-12-21T12:28:24.113018Z"
}]
}"#;
let msg = WsMessage::parse(json).unwrap();
assert!(msg.is_book_snapshot());
match msg {
WsMessage::Book(book) => {
assert_eq!(book.data[0].symbol, "BTC/USD");
assert_eq!(book.data[0].checksum, 2919786898);
assert!(!book.data[0].bids.is_empty());
assert!(!book.data[0].asks.is_empty());
}
_ => panic!("Expected Book message"),
}
}
#[test]
fn test_parse_subscribe_response() {
let json = r#"{
"method": "subscribe",
"result": {
"channel": "book",
"depth": 10,
"snapshot": true,
"symbol": "BTC/USD"
},
"success": true,
"time_in": "2025-12-21T12:28:05.362191Z",
"time_out": "2025-12-21T12:28:05.362232Z"
}"#;
let msg = WsMessage::parse(json).unwrap();
match msg {
WsMessage::Method(resp) => {
assert!(resp.success);
assert_eq!(resp.method, "subscribe");
assert!(resp.result.is_some());
}
_ => panic!("Expected Method response"),
}
}
#[test]
fn test_subscribe_request_serialization() {
let params = SubscribeParams::book(vec!["BTC/USD".to_string()], Depth::D10);
let req = SubscribeRequest::new(params).with_req_id(1);
let json = serde_json::to_string(&req).unwrap();
assert!(json.contains("\"method\":\"subscribe\""));
assert!(json.contains("\"channel\":\"book\""));
assert!(json.contains("\"depth\":10"));
}
}