WssMarketClient

Struct WssMarketClient 

Source
pub struct WssMarketClient { /* private fields */ }
Expand description

Reconnecting client for the market channel.

Implementations§

Source§

impl WssMarketClient

Source

pub fn new() -> Self

Create a new instance using the default Polymarket WSS base.

Examples found in repository?
examples/wss_market.rs (line 44)
12async fn main() -> Result<()> {
13    let base_url =
14        env::var("POLY_API_URL").unwrap_or_else(|_| "https://clob.polymarket.com".to_string());
15    let clob = ClobClient::new(&base_url);
16
17    let min_liquidity = env::var("POLY_WSS_MIN_LIQUIDITY")
18        .ok()
19        .and_then(|value| Decimal::from_str(&value).ok())
20        .unwrap_or_else(|| Decimal::from(1_000_000));
21
22    let params = GammaListParams {
23        limit: Some(50),
24        liquidity_num_min: Some(min_liquidity),
25        ..Default::default()
26    };
27
28    let response = clob.get_markets(None, Some(&params)).await?;
29    let market = pick_liquid_market(&response.data, min_liquidity)?;
30
31    println!(
32        "Selected market {} (liquidity={:?})",
33        market.condition_id, market.liquidity_num
34    );
35
36    let asset_ids = derive_asset_ids(market).unwrap_or_else(|| Vec::new());
37
38    if asset_ids.is_empty() {
39        return Err(PolyError::validation(
40            "failed to derive asset IDs for the selected market",
41        ));
42    }
43
44    let mut client = WssMarketClient::new();
45    client.subscribe(asset_ids.clone()).await?;
46
47    println!("Subscribed to market channel for assets={:?}", asset_ids);
48
49    for _ in 0..20 {
50        match client.next_event().await {
51            Ok(WssMarketEvent::PriceChange(change)) => {
52                println!(
53                    "price_change for {}: {:?}",
54                    change.market, change.price_changes
55                );
56            }
57            Ok(WssMarketEvent::Book(book)) => {
58                println!(
59                    "book {} bids={} asks={}",
60                    book.market,
61                    book.bids.len(),
62                    book.asks.len()
63                );
64            }
65            Ok(WssMarketEvent::TickSizeChange(change)) => {
66                println!(
67                    "tick size change {} from {} to {}",
68                    change.market, change.old_tick_size, change.new_tick_size
69                );
70            }
71            Ok(WssMarketEvent::LastTrade(trade)) => {
72                println!(
73                    "last_trade {} {:?}@{}",
74                    trade.market, trade.side, trade.price
75                );
76            }
77            Err(err) => {
78                eprintln!("stream error: {}", err);
79                break;
80            }
81        }
82    }
83
84    Ok(())
85}
Source

pub fn with_url(url: &str) -> Self

Create a new client against a custom endpoint (useful for tests).

Source

pub fn stats(&self) -> WssStats

Access connection stats for observability.

Source

pub async fn subscribe(&mut self, asset_ids: Vec<String>) -> Result<()>

Subscribe to the market channel for the provided token/market IDs.

Examples found in repository?
examples/wss_market.rs (line 45)
12async fn main() -> Result<()> {
13    let base_url =
14        env::var("POLY_API_URL").unwrap_or_else(|_| "https://clob.polymarket.com".to_string());
15    let clob = ClobClient::new(&base_url);
16
17    let min_liquidity = env::var("POLY_WSS_MIN_LIQUIDITY")
18        .ok()
19        .and_then(|value| Decimal::from_str(&value).ok())
20        .unwrap_or_else(|| Decimal::from(1_000_000));
21
22    let params = GammaListParams {
23        limit: Some(50),
24        liquidity_num_min: Some(min_liquidity),
25        ..Default::default()
26    };
27
28    let response = clob.get_markets(None, Some(&params)).await?;
29    let market = pick_liquid_market(&response.data, min_liquidity)?;
30
31    println!(
32        "Selected market {} (liquidity={:?})",
33        market.condition_id, market.liquidity_num
34    );
35
36    let asset_ids = derive_asset_ids(market).unwrap_or_else(|| Vec::new());
37
38    if asset_ids.is_empty() {
39        return Err(PolyError::validation(
40            "failed to derive asset IDs for the selected market",
41        ));
42    }
43
44    let mut client = WssMarketClient::new();
45    client.subscribe(asset_ids.clone()).await?;
46
47    println!("Subscribed to market channel for assets={:?}", asset_ids);
48
49    for _ in 0..20 {
50        match client.next_event().await {
51            Ok(WssMarketEvent::PriceChange(change)) => {
52                println!(
53                    "price_change for {}: {:?}",
54                    change.market, change.price_changes
55                );
56            }
57            Ok(WssMarketEvent::Book(book)) => {
58                println!(
59                    "book {} bids={} asks={}",
60                    book.market,
61                    book.bids.len(),
62                    book.asks.len()
63                );
64            }
65            Ok(WssMarketEvent::TickSizeChange(change)) => {
66                println!(
67                    "tick size change {} from {} to {}",
68                    change.market, change.old_tick_size, change.new_tick_size
69                );
70            }
71            Ok(WssMarketEvent::LastTrade(trade)) => {
72                println!(
73                    "last_trade {} {:?}@{}",
74                    trade.market, trade.side, trade.price
75                );
76            }
77            Err(err) => {
78                eprintln!("stream error: {}", err);
79                break;
80            }
81        }
82    }
83
84    Ok(())
85}
Source

pub async fn next_event(&mut self) -> Result<WssMarketEvent>

Read the next market channel event, reconnecting transparently when the socket drops.

Examples found in repository?
examples/wss_market.rs (line 50)
12async fn main() -> Result<()> {
13    let base_url =
14        env::var("POLY_API_URL").unwrap_or_else(|_| "https://clob.polymarket.com".to_string());
15    let clob = ClobClient::new(&base_url);
16
17    let min_liquidity = env::var("POLY_WSS_MIN_LIQUIDITY")
18        .ok()
19        .and_then(|value| Decimal::from_str(&value).ok())
20        .unwrap_or_else(|| Decimal::from(1_000_000));
21
22    let params = GammaListParams {
23        limit: Some(50),
24        liquidity_num_min: Some(min_liquidity),
25        ..Default::default()
26    };
27
28    let response = clob.get_markets(None, Some(&params)).await?;
29    let market = pick_liquid_market(&response.data, min_liquidity)?;
30
31    println!(
32        "Selected market {} (liquidity={:?})",
33        market.condition_id, market.liquidity_num
34    );
35
36    let asset_ids = derive_asset_ids(market).unwrap_or_else(|| Vec::new());
37
38    if asset_ids.is_empty() {
39        return Err(PolyError::validation(
40            "failed to derive asset IDs for the selected market",
41        ));
42    }
43
44    let mut client = WssMarketClient::new();
45    client.subscribe(asset_ids.clone()).await?;
46
47    println!("Subscribed to market channel for assets={:?}", asset_ids);
48
49    for _ in 0..20 {
50        match client.next_event().await {
51            Ok(WssMarketEvent::PriceChange(change)) => {
52                println!(
53                    "price_change for {}: {:?}",
54                    change.market, change.price_changes
55                );
56            }
57            Ok(WssMarketEvent::Book(book)) => {
58                println!(
59                    "book {} bids={} asks={}",
60                    book.market,
61                    book.bids.len(),
62                    book.asks.len()
63                );
64            }
65            Ok(WssMarketEvent::TickSizeChange(change)) => {
66                println!(
67                    "tick size change {} from {} to {}",
68                    change.market, change.old_tick_size, change.new_tick_size
69                );
70            }
71            Ok(WssMarketEvent::LastTrade(trade)) => {
72                println!(
73                    "last_trade {} {:?}@{}",
74                    trade.market, trade.side, trade.price
75                );
76            }
77            Err(err) => {
78                eprintln!("stream error: {}", err);
79                break;
80            }
81        }
82    }
83
84    Ok(())
85}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more