Skip to main content

WsTicker

Struct WsTicker 

Source
pub struct WsTicker {
    pub topic: String,
    pub event_type: String,
    pub data: Ticker,
    pub cs: i64,
    pub ts: u64,
}
Expand description

WebSocket ticker message from Bybit.

This struct represents a ticker update received via WebSocket for either linear perpetual futures or spot markets. Bots use this to process real-time market data for trading decisions, including price tracking, volume analysis, and funding rate monitoring.

§Bybit API Reference

The Bybit WebSocket API (https://bybit-exchange.github.io/docs/v5/ws/connect) streams ticker data for subscribed topics. This struct deserializes the JSON payload into a structured format for bot consumption.

§Perpetual Futures Context

For perpetual futures, ticker data includes funding rates, open interest, and mark/index prices, which are critical for bots managing positions and monitoring funding costs. Spot ticker data provides reference prices for arbitrage strategies.

Fields§

§topic: String

The topic (channel) of the WebSocket message.

Identifies the type of data stream (e.g., “tickers.BTCUSDT”). Bots use this to route messages to appropriate handlers.

§event_type: String

The event type (e.g., “snapshot”, “delta”).

Indicates whether the message is a full snapshot or incremental update. Bots use this to determine how to update their internal state.

§data: Ticker

The ticker data payload.

Contains market-specific metrics for linear perpetuals or spot markets. Bots extract fields like last price, volume, and funding rates from this data.

§cs: i64

The cross sequence identifier.

Used to ensure message ordering and detect gaps in the data stream. Bots can use this to validate data integrity.

§ts: u64

The timestamp in milliseconds.

The server timestamp when the message was generated. Bots use this to calculate latency and age of market data.

Implementations§

Source§

impl WsTicker

Source

pub fn new( topic: String, event_type: String, data: Ticker, cs: i64, ts: u64, ) -> Self

Creates a new WsTicker instance.

Bots use this constructor when synthesizing ticker data for testing or simulation purposes.

Source

pub fn symbol(&self) -> &str

Extracts the symbol from the ticker data.

Returns the trading pair symbol (e.g., “BTCUSDT”). Bots use this to identify the market for the ticker update.

Source

pub fn is_snapshot(&self) -> bool

Checks if the ticker data is a snapshot.

Returns true if the event type is “snapshot”. Bots use this to determine whether to replace or update their market data.

Source

pub fn is_delta(&self) -> bool

Checks if the ticker data is a delta (incremental update).

Returns true if the event type is “delta”. Bots use this to apply incremental updates to their market data.

Source

pub fn timestamp_datetime(&self) -> DateTime<Utc>

Converts the timestamp to a DateTime<Utc>.

Returns a UTC datetime representation of the timestamp. Bots use this for time-based analysis and logging.

Source

pub fn age_ms(&self) -> u64

Calculates the age of the ticker data in milliseconds.

Returns the time elapsed since the ticker was generated. Bots use this to filter stale data and monitor latency.

Source

pub fn is_stale(&self) -> bool

Checks if the ticker data is stale.

Returns true if the data is older than 5000ms (5 seconds). Bots use this to avoid acting on outdated market information.

Source

pub fn last_price(&self) -> Option<f64>

Extracts the last traded price.

Returns the most recent trade price, or None if not available. Bots use this for real-time price tracking and order execution.

Source

pub fn price_change_24h(&self) -> Option<f64>

Extracts the 24-hour price change percentage.

Returns the percentage price change over the last 24 hours, or None if not available. Bots use this to assess market trends and volatility.

Source

pub fn high_24h(&self) -> Option<f64>

Extracts the 24-hour high price.

Returns the highest price in the last 24 hours, or None if not available. Bots use this to identify resistance levels and assess volatility.

Source

pub fn low_24h(&self) -> Option<f64>

Extracts the 24-hour low price.

Returns the lowest price in the last 24 hours, or None if not available. Bots use this to identify support levels and assess volatility.

Source

pub fn volume_24h(&self) -> Option<f64>

Extracts the 24-hour trading volume.

Returns the trading volume in the last 24 hours, or None if not available. Bots use this to analyze market activity and liquidity.

Source

pub fn turnover_24h(&self) -> Option<f64>

Extracts the 24-hour trading turnover.

Returns the trading value in the last 24 hours, or None if not available. Bots use this to assess market activity and liquidity in monetary terms.

Source

pub fn funding_rate(&self) -> Option<f64>

Extracts the funding rate (linear perpetuals only).

Returns the funding rate for linear perpetuals, or None for spot markets. Bots use this to monitor funding costs and arbitrage opportunities.

Source

pub fn next_funding_time(&self) -> Option<u64>

Extracts the next funding time (linear perpetuals only).

Returns the timestamp of the next funding settlement, or None for spot markets. Bots use this to schedule funding-related operations.

Source

pub fn bid_price(&self) -> Option<f64>

Extracts the best bid price.

Returns the highest bid price in the order book, or None if not available. Bots use this for spread calculations and liquidity assessment.

Source

pub fn bid_size(&self) -> Option<f64>

Extracts the best bid size.

Returns the quantity available at the best bid price, or None if not available. Bots use this to evaluate buy-side liquidity.

Source

pub fn ask_price(&self) -> Option<f64>

Extracts the best ask price.

Returns the lowest ask price in the order book, or None if not available. Bots use this for spread calculations and liquidity assessment.

Source

pub fn ask_size(&self) -> Option<f64>

Extracts the best ask size.

Returns the quantity available at the best ask price, or None if not available. Bots use this to evaluate sell-side liquidity.

Source

pub fn spread(&self) -> Option<f64>

Calculates the bid-ask spread.

Returns the difference between ask and bid prices, or None if either is missing. Bots use this to assess market liquidity and trading costs.

Source

pub fn mid_price(&self) -> Option<f64>

Calculates the mid price.

Returns the average of bid and ask prices, or None if either is missing. Bots use this as a reference price for market analysis.

Source

pub fn spread_percentage(&self) -> Option<f64>

Calculates the spread as a percentage of the mid price.

Returns the relative spread (spread / mid price), or None if insufficient data. Bots use this to compare liquidity across different markets.

Source

pub fn open_interest(&self) -> Option<f64>

Extracts the open interest (linear perpetuals only).

Returns the total number of open contracts, or None for spot markets. Bots use this to gauge market sentiment and positioning.

Source

pub fn open_interest_value(&self) -> Option<f64>

Extracts the open interest value (linear perpetuals only).

Returns the monetary value of open interest, or None for spot markets. Bots use this to assess market exposure and leverage levels.

Source

pub fn mark_price(&self) -> Option<f64>

Extracts the mark price.

Returns the mark price used for liquidation calculations, or None if not available. Bots use this to monitor position health and avoid liquidation.

Source

pub fn index_price(&self) -> Option<f64>

Extracts the index price.

Returns the underlying index price, or None if not available. Bots use this to monitor basis (futures-spot spread) for arbitrage opportunities.

Source

pub fn is_valid_for_trading(&self) -> bool

Returns true if the ticker data is valid for trading decisions.

Checks that the data is not stale and has essential fields like symbol and last price. Bots use this to filter out invalid or incomplete market data.

Source

pub fn to_summary_string(&self) -> String

Returns a summary string for this ticker update.

Provides a human-readable summary of key ticker metrics. Bots use this for logging and debugging purposes.

Source

pub fn price_change_amount_24h(&self) -> Option<f64>

Returns the price change amount over 24 hours.

Calculates the absolute price change based on last price and 24-hour percentage change. Bots use this for volatility-based strategies and risk management.

Source

pub fn is_price_up_24h(&self) -> bool

Returns true if the price has increased over 24 hours.

Checks if the 24-hour price change percentage is positive. Bots use this for trend-following strategies and market sentiment analysis.

Source

pub fn is_price_down_24h(&self) -> bool

Returns true if the price has decreased over 24 hours.

Checks if the 24-hour price change percentage is negative. Bots use this for trend-following strategies and market sentiment analysis.

Source

pub fn price_range_24h(&self) -> Option<f64>

Returns the price range over 24 hours.

Calculates the difference between 24-hour high and low prices. Bots use this to assess volatility and set stop-loss/take-profit levels.

Source

pub fn price_position_in_range(&self) -> Option<f64>

Returns the current price position within the 24-hour range.

Returns a value between 0.0 (at 24-hour low) and 1.0 (at 24-hour high). Bots use this for mean-reversion strategies and overbought/oversold indicators.

Source

pub fn vwap_24h(&self) -> Option<f64>

Returns the volume-weighted average price over 24 hours.

Calculates VWAP using 24-hour turnover and volume. Bots use this as a benchmark price for execution quality assessment.

Source

pub fn premium_to_index(&self) -> Option<f64>

Returns the premium/discount to index price.

Calculates the percentage difference between last price and index price. Bots use this for arbitrage strategies between spot and futures markets.

Source

pub fn funding_rate_annualized(&self) -> Option<f64>

Returns the funding rate annualized.

Converts the funding rate to an annualized percentage. Bots use this to compare funding costs across different timeframes and markets.

Source

pub fn validate_checksum(&self) -> bool

Validates the checksum against the ticker data.

Note: This is a placeholder implementation. Actual checksum validation would require the original message bytes. Bots should implement proper checksum validation for production use.

Trait Implementations§

Source§

impl Clone for WsTicker

Source§

fn clone(&self) -> WsTicker

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for WsTicker

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for WsTicker

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for WsTicker

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,