onise 1.0.0

An async client for Kraken's APIs in Rust.
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
use futures_util::{SinkExt, StreamExt};
use std::sync::Arc;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message, MaybeTlsStream};

use crate::error::{KrakenError, KrakenResult};
use crate::ws_models::{
    WsAddOrderRequest,
    WsAdminResponse,
    WsAmendOrderRequest,
    WsAuthorizeRequest,
    WsBatchAddRequest,
    WsBatchCancelRequest,

    WsCancelAllRequest,
    WsCancelOnDisconnectRequest,
    WsCancelOrderRequest,
    WsEditOrderRequest,
    WsHeartbeatRequest,
    // Responses (server → client)
    WsIncomingMessage,
    // Requests (client → server)
    WsPingRequest,
    WsSubscribeRequest,
    WsSubscriptionPayload,
    WsUnsubscribeRequest,
    WsUserTradingResponse,
};

/// `KrakenWsClient` manages a connection to the Spot WebSocket API v2.
/// - It splits the WebSocket into read (stream) and write (sink) halves.
/// - It spawns a task to continuously read messages in `read_loop`.
/// - It offers methods to send typed requests: `ping`, `authorize`, `subscribe`,
///   user trading requests like `add_order`, etc.
/// - It handles all tungstenite `Message` variants, including `Frame(_)`.
/// - It maps inbound JSON into typed `WsIncomingMessage` from `models_ws.rs`.
pub struct KrakenWsClient {
    /// The write half (sink) wrapped in a Mutex for concurrency,
    /// and in an Arc for shared ownership.
    write_half: Arc<
        Mutex<
            futures_util::stream::SplitSink<
                tokio_tungstenite::WebSocketStream<MaybeTlsStream<TcpStream>>,
                Message,
            >,
        >,
    >,

    /// If you need an auth token for user data / trading, store it here.
    pub token: Option<String>,
}

impl KrakenWsClient {
    /// Connect to the specified WebSocket `url` (e.g. "wss://ws.kraken.com/v2").
    /// Splits into read & write halves, spawns a read loop task, and returns `KrakenWsClient`.
    pub async fn connect(url: &str) -> KrakenResult<Self> {
        let (ws_stream, _response) = connect_async(url)
            .await
            .map_err(|err| KrakenError::InvalidUsage(format!("WebSocket connect error: {err}")))?;

        // Split into a write sink and read stream
        let (write_half, read_half) = ws_stream.split();

        // Arc<Mutex<...>> so multiple calls can lock and send messages
        let write_half = Arc::new(Mutex::new(write_half));

        // Spawn the read loop in the background
        tokio::spawn(async move {
            if let Err(e) = Self::read_loop(read_half).await {
                eprintln!("Read loop ended with error: {e}");
            }
        });

        Ok(Self {
            write_half,
            token: None,
        })
    }

    /// The continuous read loop. Reads messages, matches their type, and parses
    /// them into `WsIncomingMessage` if they are textual JSON.
    async fn read_loop(
        mut read_half: futures_util::stream::SplitStream<
            tokio_tungstenite::WebSocketStream<MaybeTlsStream<TcpStream>>,
        >,
    ) -> KrakenResult<()> {
        while let Some(msg_result) = read_half.next().await {
            let msg = msg_result
                .map_err(|err| KrakenError::InvalidUsage(format!("WebSocket read error: {err}")))?;

            match msg {
                Message::Text(text) => {
                    // Attempt to parse the text as WsIncomingMessage
                    match serde_json::from_str::<WsIncomingMessage>(&text) {
                        Ok(incoming) => {
                            Self::handle_incoming(incoming).await;
                        }
                        Err(e) => {
                            eprintln!("Failed to parse text: {e}\nRaw text: {text}");
                        }
                    }
                }
                Message::Binary(bin) => {
                    eprintln!("Received binary message: {bin:?}");
                }
                Message::Ping(payload) => {
                    eprintln!("Received ping: {payload:?}");
                }
                Message::Pong(payload) => {
                    eprintln!("Received pong: {payload:?}");
                }
                Message::Close(close_frame) => {
                    eprintln!("WebSocket closed: {close_frame:?}");
                    break;
                }
                Message::Frame(frame) => {
                    eprintln!("Received raw frame: {frame:?}");
                }
            }
        }
        Ok(())
    }

    /// Handle a typed incoming message variant.
    async fn handle_incoming(msg: WsIncomingMessage) {
        match msg {
            WsIncomingMessage::Admin(admin_resp) => match admin_resp {
                WsAdminResponse::SystemStatus { status, version } => {
                    eprintln!("SystemStatus => status={status}, version={version}");
                }
                WsAdminResponse::SubscriptionStatus {
                    channel,
                    status,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "SubscriptionStatus => channel={channel}, status={status}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsAdminResponse::PingStatus { req_id } => {
                    eprintln!("PingStatus => req_id={req_id:?}");
                }
                WsAdminResponse::Heartbeat {} => {
                    eprintln!("Heartbeat => received");
                }
                WsAdminResponse::Unknown => {
                    eprintln!("Unknown Admin event => unrecognized fields");
                }
            },

            // Market Data
            WsIncomingMessage::TickerMsg(ticker) => {
                eprintln!(
                    "Ticker => symbol={}, bestBid={}, bestAsk={}",
                    ticker.symbol, ticker.best_bid_price, ticker.best_ask_price
                );
            }
            WsIncomingMessage::BookMsg(book) => {
                eprintln!(
                    "Book => symbol={}, #bids={}, #asks={}",
                    book.symbol,
                    book.bids.len(),
                    book.asks.len()
                );
            }
            WsIncomingMessage::CandlesMsg(candles) => {
                eprintln!(
                    "Candles => symbol={}, interval={}, #data={}",
                    candles.symbol,
                    candles.interval,
                    candles.data.len()
                );
            }
            WsIncomingMessage::TradesMsg(trades) => {
                eprintln!(
                    "Trades => symbol={}, #trades={}",
                    trades.symbol,
                    trades.trades.len()
                );
            }
            WsIncomingMessage::InstrumentsMsg(instr) => {
                eprintln!("Instruments => #instruments={}", instr.data.len());
            }

            // User Data
            WsIncomingMessage::BalancesMsg(balances_msg) => {
                eprintln!(
                    "Balances => channel={}, #assets={}",
                    balances_msg.channel,
                    balances_msg.balances.len()
                );
            }
            WsIncomingMessage::ExecutionsMsg(exec_msg) => {
                eprintln!(
                    "Executions => channel={}, #executions={}",
                    exec_msg.channel,
                    exec_msg.executions.len()
                );
            }

            // User Trading
            WsIncomingMessage::Trading(trade_resp) => match trade_resp {
                WsUserTradingResponse::AddOrderStatus {
                    status,
                    txid,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "AddOrderStatus => status={status}, txid={txid:?}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::AmendOrderStatus {
                    status,
                    txid,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "AmendOrderStatus => status={status}, txid={txid:?}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::EditOrderStatus {
                    status,
                    txid,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "EditOrderStatus => status={status}, txid={txid:?}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::CancelOrderStatus {
                    status,
                    txid,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "CancelOrderStatus => status={status}, txid={txid:?}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::CancelAllStatus {
                    status,
                    count,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "CancelAllStatus => status={status}, count={count:?}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::CancelOnDisconnectStatus {
                    status,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "CancelOnDisconnectStatus => status={status}, req_id={req_id:?}, error={error_message:?}"
                        );
                }
                WsUserTradingResponse::BatchAddStatus {
                    status,
                    results,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "BatchAddStatus => status={status}, req_id={req_id:?}, err={error_message:?}, results={:?}",
                            results
                        );
                }
                WsUserTradingResponse::BatchCancelStatus {
                    status,
                    results,
                    req_id,
                    error_message,
                } => {
                    eprintln!(
                            "BatchCancelStatus => status={status}, req_id={req_id:?}, err={error_message:?}, results={:?}",
                            results
                        );
                }
                WsUserTradingResponse::Unknown => {
                    eprintln!("Unknown user trading response => unrecognized fields");
                }
            },

            // CatchAll for untagged or unknown messages
            WsIncomingMessage::CatchAll(unparsed) => {
                eprintln!("CatchAll => unparsed: {unparsed}");
            }
        }
    }

    /// Helper to send a request object T as JSON text over the WebSocket.
    async fn send_message<T: serde::Serialize>(&self, request: &T) -> KrakenResult<()> {
        let json_text = serde_json::to_string(request)
            .map_err(|err| KrakenError::InvalidUsage(format!("Serialize error: {err}")))?;
        let mut sink = self.write_half.lock().await;
        // Use .into() so it matches the expected tungstenite text type
        sink.send(Message::Text(json_text.into()))
            .await
            .map_err(|err| KrakenError::InvalidUsage(format!("WebSocket send error: {err}")))?;
        Ok(())
    }

    // ─────────────────────────────────────────────────────────────────────
    // EXAMPLE HELPER METHODS FOR EACH REQUEST
    // ─────────────────────────────────────────────────────────────────────

    /// Send a ping request (WsPingRequest)
    pub async fn send_ping(&self, req_id: Option<u64>) -> KrakenResult<()> {
        let ping_req = WsPingRequest {
            event: "ping".to_string(),
            req_id,
        };
        self.send_message(&ping_req).await
    }

    /// Send a heartbeat request (WsHeartbeatRequest)
    pub async fn send_heartbeat(&self, req_id: Option<u64>) -> KrakenResult<()> {
        let hb_req = WsHeartbeatRequest {
            event: "heartbeat".to_string(),
            req_id,
        };
        self.send_message(&hb_req).await
    }

    /// Authorize with a token (WsAuthorizeRequest)
    pub async fn authorize(&self, token: &str, req_id: Option<u64>) -> KrakenResult<()> {
        let auth_req = WsAuthorizeRequest {
            event: "authorize".to_string(),
            token: token.to_string(),
            req_id,
        };
        self.send_message(&auth_req).await
    }

    /// Subscribe to a channel (WsSubscribeRequest)
    pub async fn subscribe(
        &self,
        subscription: WsSubscriptionPayload,
        req_id: Option<u64>,
    ) -> KrakenResult<()> {
        let req = WsSubscribeRequest {
            event: "subscribe".to_string(),
            req_id,
            subscription,
        };
        self.send_message(&req).await
    }

    /// Unsubscribe from a channel (WsUnsubscribeRequest)
    pub async fn unsubscribe(
        &self,
        subscription: WsSubscriptionPayload,
        req_id: Option<u64>,
    ) -> KrakenResult<()> {
        let req = WsUnsubscribeRequest {
            event: "unsubscribe".to_string(),
            req_id,
            subscription,
        };
        self.send_message(&req).await
    }

    /// Add order (WsAddOrderRequest)
    pub async fn add_order(&self, add_req: WsAddOrderRequest) -> KrakenResult<()> {
        self.send_message(&add_req).await
    }

    /// Amend order (WsAmendOrderRequest)
    pub async fn amend_order(&self, amend_req: WsAmendOrderRequest) -> KrakenResult<()> {
        self.send_message(&amend_req).await
    }

    /// Edit order (WsEditOrderRequest)
    pub async fn edit_order(&self, edit_req: WsEditOrderRequest) -> KrakenResult<()> {
        self.send_message(&edit_req).await
    }

    /// Cancel order (WsCancelOrderRequest)
    pub async fn cancel_order(&self, cancel_req: WsCancelOrderRequest) -> KrakenResult<()> {
        self.send_message(&cancel_req).await
    }

    /// Cancel all (WsCancelAllRequest)
    pub async fn cancel_all(&self, req: WsCancelAllRequest) -> KrakenResult<()> {
        self.send_message(&req).await
    }

    /// Cancel on disconnect (WsCancelOnDisconnectRequest)
    pub async fn cancel_on_disconnect(&self, req: WsCancelOnDisconnectRequest) -> KrakenResult<()> {
        self.send_message(&req).await
    }

    /// Batch add orders (WsBatchAddRequest)
    pub async fn batch_add(&self, req: WsBatchAddRequest) -> KrakenResult<()> {
        self.send_message(&req).await
    }

    /// Batch cancel orders (WsBatchCancelRequest)
    pub async fn batch_cancel(&self, req: WsBatchCancelRequest) -> KrakenResult<()> {
        self.send_message(&req).await
    }
}