bitmex_ws_exec/ws-exec.rs
1// -------------------------------------------------------------------------------------------------
2// Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3// https://nautechsystems.io
4//
5// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6// You may not use this file except in compliance with the License.
7// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16// Under development
17#![allow(dead_code)]
18#![allow(unused_variables)]
19
20use futures_util::StreamExt;
21use nautilus_bitmex::{http::client::BitmexHttpClient, websocket::client::BitmexWebSocketClient};
22use tokio::time::Duration;
23use tracing::level_filters::LevelFilter;
24
25#[tokio::main]
26async fn main() -> Result<(), Box<dyn std::error::Error>> {
27 tracing_subscriber::fmt()
28 .with_max_level(LevelFilter::TRACE)
29 .init();
30
31 tracing::info!("Fetching instruments from HTTP API...");
32 let http_client = BitmexHttpClient::new(
33 None, // base_url: defaults to production
34 None, // api_key
35 None, // api_secret
36 false, // testnet
37 Some(60), // timeout_secs
38 );
39
40 let instruments = http_client
41 .request_instruments(true) // active_only
42 .await?;
43
44 tracing::info!("Fetched {} instruments", instruments.len());
45
46 let mut ws_client = BitmexWebSocketClient::new(
47 None, // url: defaults to wss://ws.bitmex.com/realtime
48 None,
49 None,
50 None,
51 Some(5), // 5 second heartbeat
52 )
53 .unwrap();
54 ws_client.initialize_instruments_cache(instruments);
55 ws_client.connect().await?;
56
57 // Give the connection a moment to stabilize
58 tokio::time::sleep(Duration::from_millis(500)).await;
59
60 // Subscribe for all execution related topics
61 ws_client
62 .subscribe(vec![
63 "execution".to_string(),
64 "order".to_string(),
65 "margin".to_string(),
66 "position".to_string(),
67 "wallet".to_string(),
68 ])
69 .await?;
70
71 // Create a future that completes on CTRL+C
72 let sigint = tokio::signal::ctrl_c();
73 tokio::pin!(sigint);
74
75 let stream = ws_client.stream();
76 tokio::pin!(stream); // Pin the stream to allow polling in the loop
77
78 loop {
79 tokio::select! {
80 Some(event) = stream.next() => {
81 tracing::debug!("{event:?}");
82 }
83 _ = &mut sigint => {
84 tracing::info!("Received SIGINT, closing connection...");
85 ws_client.close().await?;
86 break;
87 }
88 else => break,
89 }
90 }
91
92 Ok(())
93}