coinbase_intx_ws/
websocket.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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
16use futures_util::StreamExt;
17use nautilus_coinbase_intx::{
18    http::client::CoinbaseIntxHttpClient, websocket::client::CoinbaseIntxWebSocketClient,
19};
20use nautilus_model::identifiers::InstrumentId;
21use tracing::level_filters::LevelFilter;
22
23#[tokio::main]
24async fn main() -> Result<(), Box<dyn std::error::Error>> {
25    tracing_subscriber::fmt()
26        .with_max_level(LevelFilter::TRACE)
27        .init();
28
29    let client = CoinbaseIntxHttpClient::from_env().unwrap();
30
31    // Cache instruments first (required for correct websocket message parsing)
32    let instruments = client.request_instruments().await?;
33    let mut client = CoinbaseIntxWebSocketClient::default();
34    client.connect(instruments).await?;
35
36    let instrument_id = InstrumentId::from("BTC-PERP.COINBASE_INTX");
37
38    // client.subscribe_instruments(vec![instrument_id]).await?;
39    // client.subscribe_risk(vec![instrument_id]).await?;
40    // client.subscribe_funding(vec![instrument_id]).await?;
41    // client.subscribe_trades(vec![instrument_id]).await?;
42    // client.subscribe_quotes(vec![instrument_id]).await?;
43    client.subscribe_order_book(vec![instrument_id]).await?;
44
45    // let bar_type = BarType::from("ETH-PERP.COINBASE_INTX-1-MINUTE-LAST-EXTERNAL");
46    // client.subscribe_bars(bar_type).await?;
47
48    // Create a future that completes on CTRL+C
49    let sigint = tokio::signal::ctrl_c();
50    tokio::pin!(sigint);
51
52    let stream = client.stream();
53    tokio::pin!(stream); // Pin the stream to allow polling in the loop
54
55    loop {
56        tokio::select! {
57            Some(data) = stream.next() => {
58                tracing::debug!("Received from stream: {data:?}");
59            }
60            _ = &mut sigint => {
61                tracing::info!("Received SIGINT, closing connection...");
62                client.close().await?;
63                break;
64            }
65            else => break,
66        }
67    }
68
69    Ok(())
70}