### PrivateAccountV3Api: Track Account Balance Updates (Protobuf, Java) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the structure for real-time account balance change notifications using Protocol Buffers and provides a Java example for handling these updates. It tracks available and frozen balances, along with their changes and the type of transaction. ```protobuf message PrivateAccountV3Api { string vcoinName = 1; string coinId = 2; string balanceAmount = 3; string balanceAmountChange = 4; string frozenAmount = 5; string frozenAmountChange = 6; string type = 7; int64 time = 8; } ``` ```java public class AccountManager { private Map balances = new ConcurrentHashMap<>(); public void handleAccountUpdate(PrivateAccountV3Api update) { String asset = update.getVcoinName(); BigDecimal available = new BigDecimal(update.getBalanceAmount()); BigDecimal availableChange = new BigDecimal(update.getBalanceAmountChange()); BigDecimal frozen = new BigDecimal(update.getFrozenAmount()); BigDecimal frozenChange = new BigDecimal(update.getFrozenAmountChange()); String changeType = update.getType(); Balance balance = balances.computeIfAbsent(asset, k -> new Balance(k)); balance.setAvailable(available); balance.setFrozen(frozen); System.out.printf("[%s] Balance Update: Available=%s (%%+s) Frozen=%s (%%+s) Type=%s%n", asset, available, availableChange, frozen, frozenChange, changeType); } } ``` -------------------------------- ### Define PushDataV3ApiWrapper and Parse in Java Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt The central wrapper message encapsulates all push data types, providing channel identification and metadata. The Java example demonstrates how to parse the binary WebSocket payload and route it based on the message body type. ```protobuf syntax = "proto3"; message PushDataV3ApiWrapper { string channel = 1; oneof body { PublicDealsV3Api publicDeals = 301; PublicIncreaseDepthsV3Api publicIncreaseDepths = 302; PublicLimitDepthsV3Api publicLimitDepths = 303; PrivateOrdersV3Api privateOrders = 304; PublicBookTickerV3Api publicBookTicker = 305; PrivateDealsV3Api privateDeals = 306; PrivateAccountV3Api privateAccount = 307; PublicSpotKlineV3Api publicSpotKline = 308; PublicMiniTickerV3Api publicMiniTicker = 309; PublicMiniTickersV3Api publicMiniTickers = 310; PublicBookTickerBatchV3Api publicBookTickerBatch = 311; PublicIncreaseDepthsBatchV3Api publicIncreaseDepthsBatch = 312; PublicAggreDepthsV3Api publicAggreDepths = 313; PublicAggreDealsV3Api publicAggreDeals = 314; PublicAggreBookTickerV3Api publicAggreBookTicker = 315; } optional string symbol = 3; optional string symbolId = 4; optional int64 createTime = 5; optional int64 sendTime = 6; } ``` ```java import com.mxc.push.common.protobuf.PushDataV3ApiWrapper; import com.mxc.push.common.protobuf.PublicDealsV3Api; public class WebSocketHandler { public void onMessage(byte[] data) { PushDataV3ApiWrapper wrapper = PushDataV3ApiWrapper.parseFrom(data); String channel = wrapper.getChannel(); String symbol = wrapper.getSymbol(); long createTime = wrapper.getCreateTime(); switch (wrapper.getBodyCase()) { case PUBLICDEALS: PublicDealsV3Api deals = wrapper.getPublicDeals(); handleDeals(symbol, deals); break; case PUBLICBOOKTICKER: handleBookTicker(symbol, wrapper.getPublicBookTicker()); break; case PRIVATEORDERS: handlePrivateOrder(wrapper.getPrivateOrders()); break; } } } ``` -------------------------------- ### Define and Process PublicDealsV3Api Trade Stream Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the structure for real-time trade execution data. The Java example shows how to iterate through the trade list and convert binary data into human-readable formats. ```protobuf message PublicDealsV3Api { repeated PublicDealsV3ApiItem deals = 1; string eventType = 2; } message PublicDealsV3ApiItem { string price = 1; string quantity = 2; int32 tradeType = 3; int64 time = 4; } ``` ```java public void handleDeals(String symbol, PublicDealsV3Api dealsMsg) { for (PublicDealsV3ApiItem deal : dealsMsg.getDealsList()) { BigDecimal price = new BigDecimal(deal.getPrice()); BigDecimal quantity = new BigDecimal(deal.getQuantity()); String side = deal.getTradeType() == 1 ? "BUY" : "SELL"; long timestamp = deal.getTime(); System.out.printf("[%s] %s: %s %s @ %s at %d%n", symbol, side, quantity, symbol.replace("USDT", ""), price, timestamp); } } ``` -------------------------------- ### Batch Message Types: Process Batch Updates (Protobuf, Java) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines Protocol Buffer structures for batch processing of market data, including mini tickers, book tickers, and depth updates. Provides Java examples for handling these batch updates efficiently. ```protobuf message PublicMiniTickersV3Api { repeated PublicMiniTickerV3Api items = 1; } message PublicBookTickerBatchV3Api { repeated PublicBookTickerV3Api items = 1; } message PublicIncreaseDepthsBatchV3Api { repeated PublicIncreaseDepthsV3Api items = 1; string eventType = 2; } ``` ```java public void handleMiniTickersBatch(PublicMiniTickersV3Api batch) { System.out.println("=== Market Overview ==="); for (PublicMiniTickerV3Api ticker : batch.getItemsList()) { handleMiniTicker(ticker); } System.out.printf("Updated %d symbols%n", batch.getItemsCount()); } public void handleDepthBatch(PublicIncreaseDepthsBatchV3Api batch) { for (PublicIncreaseDepthsV3Api depth : batch.getItemsList()) { String symbol = extractSymbolFromContext(); orderBooks.get(symbol).applyIncremental(depth); } } ``` -------------------------------- ### Java Implementation for Initializing Order Book from Snapshot Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt This Java method initializes or resets the order book using a complete snapshot received via `PublicLimitDepthsV3Api`. It clears the existing order book data and populates it with the provided ask and bid levels from the snapshot. The `currentVersion` is also updated to reflect the snapshot's version. ```java // Initialize order book from snapshot public void initializeFromSnapshot(PublicLimitDepthsV3Api snapshot) { asks.clear(); bids.clear(); for (PublicLimitDepthV3ApiItem ask : snapshot.getAsksList()) { asks.put(new BigDecimal(ask.getPrice()), new BigDecimal(ask.getQuantity())); } for (PublicLimitDepthV3ApiItem bid : snapshot.getBidsList()) { bids.put(new BigDecimal(bid.getPrice()), new BigDecimal(bid.getQuantity())); } currentVersion = Long.parseLong(snapshot.getVersion()); System.out.printf("Order book initialized: %d asks, %d bids, version %d%n", asks.size(), bids.size(), currentVersion); } ``` -------------------------------- ### SUBSCRIBE spot@public.bookTicker.v3.api Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Real-time best bid and ask price/quantity updates for liquidity monitoring. ```APIDOC ## SUBSCRIBE spot@public.bookTicker.v3.api ### Description Real-time best bid and ask price/quantity updates. Provides the top of book for quick spread and liquidity monitoring. ### Method SUBSCRIBE ### Endpoint spot@public.bookTicker.v3.api ### Response - **bidPrice** (string) - Best bid price. - **bidQuantity** (string) - Best bid quantity. - **askPrice** (string) - Best ask price. - **askQuantity** (string) - Best ask quantity. ### Response Example { "bidPrice": "42150.00", "bidQuantity": "1.25", "askPrice": "42151.50", "askQuantity": "0.89" } ``` -------------------------------- ### SUBSCRIBE spot@public.limit.depth.v3.api Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides complete order book snapshots with limited depth levels for initial state synchronization. ```APIDOC ## SUBSCRIBE spot@public.limit.depth.v3.api ### Description Provides complete order book snapshots with limited depth levels. Useful for initial state synchronization or periodic validation. ### Method SUBSCRIBE ### Endpoint spot@public.limit.depth.v3.api ### Response - **asks** (array) - Full list of ask levels. - **bids** (array) - Full list of bid levels. - **eventType** (string) - Type of the event. - **version** (string) - Current version of the snapshot. ### Response Example { "asks": [{"price": "42151.50", "quantity": "0.89"}], "bids": [{"price": "42150.00", "quantity": "1.25"}], "eventType": "snapshot", "version": "123456789" } ``` -------------------------------- ### Java Implementation for Handling Best Bid/Ask Ticker Updates Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt This Java method processes `PublicBookTickerV3Api` messages to display real-time best bid and ask information for a given symbol. It calculates and prints the spread and spread percentage, providing insights into market liquidity and price volatility. ```java // Monitor spread and liquidity public void handleBookTicker(String symbol, PublicBookTickerV3Api ticker) { BigDecimal bidPrice = new BigDecimal(ticker.getBidPrice()); BigDecimal askPrice = new BigDecimal(ticker.getAskPrice()); BigDecimal bidQty = new BigDecimal(ticker.getBidQuantity()); BigDecimal askQty = new BigDecimal(ticker.getAskQuantity()); BigDecimal spread = askPrice.subtract(bidPrice); BigDecimal spreadPercent = spread.divide(askPrice, 6, RoundingMode.HALF_UP) .multiply(new BigDecimal("100")); System.out.printf("[%s] Bid: %s (%s) | Ask: %s (%s) | Spread: %s (%.4f%%)%n", symbol, bidPrice, bidQty, askPrice, askQty, spread, spreadPercent); // Output: [BTCUSDT] Bid: 42150.00 (1.25) | Ask: 42151.50 (0.89) | Spread: 1.50 (0.0036%%)%n } ``` -------------------------------- ### Protobuf Definition for Order Book Snapshots (PublicLimitDepthsV3Api) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the Protocol Buffer message for obtaining a complete snapshot of the order book. It contains lists of ask and bid price-quantity pairs, an event type, and a version number. This is useful for initial synchronization or periodic validation of the order book state. ```protobuf // PublicLimitDepthsV3Api.proto - Channel: spot@public.limit.depth.v3.api message PublicLimitDepthsV3Api { repeated PublicLimitDepthV3ApiItem asks = 1; // Ask levels (sorted ascending) repeated PublicLimitDepthV3ApiItem bids = 2; // Bid levels (sorted descending) string eventType = 3; string version = 4; } message PublicLimitDepthV3ApiItem { string price = 1; string quantity = 2; } ``` -------------------------------- ### Display Mini Ticker Data with Java Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Processes and displays compact ticker information, including the last price, 24-hour price changes, highs, lows, and volume. This is useful for a quick overview of market activity. ```protobuf // PublicMiniTickerV3Api.proto - Channel: spot@public.miniTicker.v3.api message PublicMiniTickerV3Api { string symbol = 1; // Trading pair string price = 2; // Last price string rate = 3; // 24h change % (UTC+8) string zonedRate = 4; // 24h change % (local timezone) string high = 5; // 24h high string low = 6; // 24h low string volume = 7; // 24h quote volume string quantity = 8; // 24h base volume string lastCloseRate = 9; // Previous close change % (UTC+8) string lastCloseZonedRate = 10; string lastCloseHigh = 11; string lastCloseLow = 12; } ``` ```java // Display market overview public void handleMiniTicker(PublicMiniTickerV3Api ticker) { String symbol = ticker.getSymbol(); BigDecimal price = new BigDecimal(ticker.getPrice()); BigDecimal change = new BigDecimal(ticker.getRate()); BigDecimal high = new BigDecimal(ticker.getHigh()); BigDecimal low = new BigDecimal(ticker.getLow()); BigDecimal volume = new BigDecimal(ticker.getVolume()); String changeIndicator = change.compareTo(BigDecimal.ZERO) >= 0 ? "+" : ""; System.out.printf("%-10s $%-12s %s%-8s%% H:%-12s L:%-12s Vol:$%s%n", symbol, price, changeIndicator, change, high, low, volume); // Output: BTCUSDT $42150.50 +2.35% H:42500.00 L:41200.00 Vol:$1234567890 } ``` -------------------------------- ### PublicAggreDepthsV3Api: Apply Aggregated Order Book Updates (Protobuf, Java) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the structure for aggregated order book updates with version tracking using Protocol Buffers and provides a Java method to apply these updates. It handles price grouping and ensures version continuity for efficient synchronization. ```protobuf message PublicAggreDepthsV3Api { repeated PublicAggreDepthV3ApiItem asks = 1; repeated PublicAggreDepthV3ApiItem bids = 2; string eventType = 3; string fromVersion = 4; string toVersion = 5; } message PublicAggreDepthV3ApiItem { string price = 1; string quantity = 2; } ``` ```java public void applyAggreDepth(PublicAggreDepthsV3Api aggre) { long fromVer = Long.parseLong(aggre.getFromVersion()); long toVer = Long.parseLong(aggre.getToVersion()); if (fromVer > currentVersion + 1) { requestSnapshot(); return; } for (PublicAggreDepthV3ApiItem ask : aggre.getAsksList()) { updateOrderBookLevel(asks, ask.getPrice(), ask.getQuantity()); } for (PublicAggreDepthV3ApiItem bid : aggre.getBidsList()) { updateOrderBookLevel(bids, bid.getPrice(), bid.getQuantity()); } currentVersion = toVer; } ``` -------------------------------- ### Protobuf Definition for Best Bid/Ask Ticker (PublicBookTickerV3Api) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the Protocol Buffer message for real-time best bid and ask price/quantity updates. This message provides the top of the order book, allowing for quick monitoring of the spread and liquidity. ```protobuf // PublicBookTickerV3Api.proto - Channel: spot@public.bookTicker.v3.api message PublicBookTickerV3Api { string bidPrice = 1; // Best bid price string bidQuantity = 2; // Best bid quantity string askPrice = 3; // Best ask price string askQuantity = 4; // Best ask quantity } ``` -------------------------------- ### Java Implementation for Maintaining Order Book with Incremental Updates Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt This Java class manages a local order book state by applying incremental updates received from the `PublicIncreaseDepthsV3Api`. It uses `TreeMap` to store asks and bids, ensuring they are sorted correctly. The `applyIncremental` method processes updates, applying changes to the respective sides of the book and updating the version number. It skips updates with versions older than the current one. ```java // Maintaining local order book with incremental updates public class OrderBookManager { private TreeMap asks = new TreeMap<>(); private TreeMap bids = new TreeMap<>(Comparator.reverseOrder()); private long currentVersion = 0; public void applyIncremental(PublicIncreaseDepthsV3Api update) { long newVersion = Long.parseLong(update.getVersion()); if (newVersion <= currentVersion) return; // Skip old updates // Apply ask updates for (PublicIncreaseDepthV3ApiItem ask : update.getAsksList()) { BigDecimal price = new BigDecimal(ask.getPrice()); BigDecimal qty = new BigDecimal(ask.getQuantity()); if (qty.compareTo(BigDecimal.ZERO) == 0) { asks.remove(price); } else { asks.put(price, qty); } } // Apply bid updates for (PublicIncreaseDepthV3ApiItem bid : update.getBidsList()) { BigDecimal price = new BigDecimal(bid.getPrice()); BigDecimal qty = new BigDecimal(bid.getQuantity()); if (qty.compareTo(BigDecimal.ZERO) == 0) { bids.remove(price); } else { bids.put(price, qty); } } currentVersion = newVersion; } } ``` -------------------------------- ### WebSocket PublicMiniTickerV3Api Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides compact 24-hour rolling market statistics including price changes, highs, lows, and volume. ```APIDOC ## WEBSOCKET spot@public.miniTicker.v3.api ### Description Streams a compact ticker update containing 24h rolling statistics for all symbols. ### Method WEBSOCKET ### Endpoint spot@public.miniTicker.v3.api ### Response - **symbol** (string) - Trading pair - **price** (string) - Last price - **rate** (string) - 24h change % (UTC+8) - **high** (string) - 24h high - **low** (string) - 24h low - **volume** (string) - 24h quote volume - **quantity** (string) - 24h base volume ### Response Example { "symbol": "BTCUSDT", "price": "42150.50", "rate": "2.35", "high": "42500.00", "low": "41200.00", "volume": "1234567890", "quantity": "29336.8" } ``` -------------------------------- ### SUBSCRIBE spot@public.increase.depth.v3.api Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides incremental order book depth updates with version tracking for maintaining a local order book state. ```APIDOC ## SUBSCRIBE spot@public.increase.depth.v3.api ### Description Provides incremental order book depth updates with version tracking for maintaining a local order book state. Contains separate ask and bid lists with price-quantity pairs. ### Method SUBSCRIBE ### Endpoint spot@public.increase.depth.v3.api ### Response - **asks** (array) - List of price-quantity pairs for ask side. - **bids** (array) - List of price-quantity pairs for bid side. - **eventType** (string) - Type of the event. - **version** (string) - Version for synchronization. ### Response Example { "asks": [{"price": "42151.50", "quantity": "0.89"}], "bids": [{"price": "42150.00", "quantity": "1.25"}], "eventType": "update", "version": "123456789" } ``` -------------------------------- ### Protobuf Definition for Incremental Order Book Updates (PublicIncreaseDepthsV3Api) Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the Protocol Buffer message structure for receiving incremental updates to the order book. It includes separate lists for asks and bids, along with an event type and a version for state synchronization. The `PublicIncreaseDepthV3ApiItem` specifies price and quantity for each level, where a quantity of zero indicates removal. ```protobuf // PublicIncreaseDepthsV3Api.proto - Channel: spot@public.increase.depth.v3.api message PublicIncreaseDepthsV3Api { repeated PublicIncreaseDepthV3ApiItem asks = 1; // Ask side updates repeated PublicIncreaseDepthV3ApiItem bids = 2; // Bid side updates string eventType = 3; string version = 4; // Version for synchronization } message PublicIncreaseDepthV3ApiItem { string price = 1; // Price level string quantity = 2; // New quantity (0 = remove level) } ``` -------------------------------- ### Process Candlestick Data with Java Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Handles incoming candlestick (Kline) data from the WebSocket API, converting it into a usable format for charting and analysis. It parses interval, timestamps, OHLCV prices, and determines if the candle is bullish or bearish. ```protobuf // PublicSpotKlineV3Api.proto - Channel: spot@public.kline.v3.api@@ message PublicSpotKlineV3Api { // Interval: Min1, Min5, Min15, Min30, Min60, Hour4, Hour8, Day1, Week1, Month1 string interval = 1; int64 windowStart = 2; // Candle open time (seconds) string openingPrice = 3; // Open price string closingPrice = 4; // Close price string highestPrice = 5; // High price string lowestPrice = 6; // Low price string volume = 7; // Quote volume (e.g., USDT) string quantity = 8; // Base volume (e.g., BTC) int64 windowEnd = 9; // Candle close time (seconds) } ``` ```java // Process kline updates for charting public void handleKline(String symbol, PublicSpotKlineV3Api kline) { Candlestick candle = new Candlestick(); candle.setInterval(kline.getInterval()); candle.setOpenTime(kline.getWindowStart() * 1000); candle.setCloseTime(kline.getWindowEnd() * 1000); candle.setOpen(new BigDecimal(kline.getOpeningPrice())); candle.setHigh(new BigDecimal(kline.getHighestPrice())); candle.setLow(new BigDecimal(kline.getLowestPrice())); candle.setClose(new BigDecimal(kline.getClosingPrice())); candle.setVolume(new BigDecimal(kline.getVolume())); candle.setQuantity(new BigDecimal(kline.getQuantity())); boolean isBullish = candle.getClose().compareTo(candle.getOpen()) >= 0; System.out.printf("[%s] %s Kline: O=%s H=%s L=%s C=%s V=%s (%s)%n", symbol, kline.getInterval(), candle.getOpen(), candle.getHigh(), candle.getLow(), candle.getClose(), candle.getVolume(), isBullish ? "BULLISH" : "BEARISH"); } ``` -------------------------------- ### PrivateAccountV3Api - Account Balance Updates Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides real-time notifications for account balance changes, tracking both available and frozen amounts. ```APIDOC ## PrivateAccountV3Api - Account Balance Updates ### Description Real-time account balance change notifications. Tracks available and frozen balances. ### Method SUBSCRIBE ### Endpoint `spot@public.cny.v2` ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to subscribe to, e.g., `spot@public.cny.v2`. ### Request Body ```json { "op": "sub", "args": [ "spot@public.cny.v2" ] } ``` ### Response #### Success Response (200) - **vcoinName** (string) - Asset name - **coinId** (string) - Asset ID - **balanceAmount** (string) - Available balance - **balanceAmountChange** (string) - Balance change amount - **frozenAmount** (string) - Frozen balance - **frozenAmountChange** (string) - Frozen change amount - **type** (string) - Change type - **time** (integer) - Timestamp #### Response Example ```json { "vcoinName": "BTC", "coinId": "BTC", "balanceAmount": "1.5000", "balanceAmountChange": "0.0500", "frozenAmount": "0.2500", "frozenAmountChange": "-0.0500", "type": "TRADE", "time": 1678886400000 } ``` ``` -------------------------------- ### WebSocket PublicSpotKlineV3Api Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides real-time OHLCV candlestick data for technical analysis across multiple time intervals. ```APIDOC ## WEBSOCKET spot@public.kline.v3.api@@ ### Description Streams OHLCV candlestick data for a specific trading pair and interval. Supports intervals: Min1, Min5, Min15, Min30, Min60, Hour4, Hour8, Day1, Week1, Month1. ### Method WEBSOCKET ### Endpoint spot@public.kline.v3.api@@ ### Parameters #### Path Parameters - **symbol** (string) - Required - The trading pair (e.g., BTCUSDT) - **interval** (string) - Required - The candlestick interval (e.g., Min1, Hour4) ### Response - **windowStart** (int64) - Candle open time (seconds) - **openingPrice** (string) - Open price - **closingPrice** (string) - Close price - **highestPrice** (string) - High price - **lowestPrice** (string) - Low price - **volume** (string) - Quote volume - **quantity** (string) - Base volume - **windowEnd** (int64) - Candle close time (seconds) ### Response Example { "interval": "Min1", "windowStart": 1700000000, "openingPrice": "42000.00", "closingPrice": "42050.00", "highestPrice": "42100.00", "lowestPrice": "41950.00", "volume": "100000", "quantity": "2.38", "windowEnd": 1700000060 } ``` -------------------------------- ### PrivateOrdersV3Api - Private Order Updates Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Provides real-time updates on order status for authenticated users. It includes comprehensive order details and supports OCO orders. ```APIDOC ## PrivateOrdersV3Api - Private Order Updates ### Description Real-time order status updates for authenticated users. Includes full order details, execution status, and OCO order support. ### Channel `spot@private.orders.v3.api` ### Message Structure ```protobuf message PrivateOrdersV3Api { string id = 1; // Order ID string clientId = 2; // Client order ID string price = 3; // Order price string quantity = 4; // Order quantity string amount = 5; // Order amount (price * quantity) string avgPrice = 6; // Average fill price int32 orderType = 7; // Order type int32 tradeType = 8; // 1=buy, 2=sell bool isMaker = 9; // Is maker order string remainAmount = 10; // Remaining amount string remainQuantity = 11; // Remaining quantity optional string lastDealQuantity = 12; string cumulativeQuantity = 13; // Total filled quantity string cumulativeAmount = 14; // Total filled amount int32 status = 15; // Order status int64 createTime = 16; // Creation timestamp optional string market = 17; optional int32 triggerType = 18; optional string triggerPrice = 19; optional int32 state = 20; optional string ocoId = 21; // OCO order ID optional string routeFactor = 22; optional string symbolId = 23; optional string marketId = 24; optional string marketCurrencyId = 25; optional string currencyId = 26; } ``` ### Java Example ```java // Handle private order updates public void handlePrivateOrder(PrivateOrdersV3Api order) { String orderId = order.getId(); String clientId = order.getClientId(); String side = order.getTradeType() == 1 ? "BUY" : "SELL"; BigDecimal price = new BigDecimal(order.getPrice()); BigDecimal qty = new BigDecimal(order.getQuantity()); BigDecimal filled = new BigDecimal(order.getCumulativeQuantity()); BigDecimal avgPrice = new BigDecimal(order.getAvgPrice()); int status = order.getStatus(); String statusStr = switch (status) { case 1 -> "NEW"; case 2 -> "PARTIALLY_FILLED"; case 3 -> "FILLED"; case 4 -> "CANCELED"; case 5 -> "PARTIALLY_CANCELED"; default -> "UNKNOWN"; }; System.out.printf("Order %s [%s]: %s %s @ %s | Filled: %s/%s @ avg %s | Status: %s\n", orderId, clientId, side, qty, price, filled, qty, avgPrice, statusStr); // Trigger callbacks if (status == 3) { onOrderFilled(order); } else if (status == 4 || status == 5) { onOrderCanceled(order); } } ``` ``` -------------------------------- ### Private Trade Execution API Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the structure for private trade execution notifications and provides a Java implementation for processing trades. It handles fee calculations and P&L tracking updates. ```protobuf message PrivateDealsV3Api { string price = 1; string quantity = 2; string amount = 3; int32 tradeType = 4; bool isMaker = 5; bool isSelfTrade = 6; string tradeId = 7; string clientOrderId = 8; string orderId = 9; string feeAmount = 10; string feeCurrency = 11; int64 time = 12; } ``` ```java public void handlePrivateDeal(PrivateDealsV3Api deal) { String tradeId = deal.getTradeId(); String orderId = deal.getOrderId(); String side = deal.getTradeType() == 1 ? "BUY" : "SELL"; BigDecimal price = new BigDecimal(deal.getPrice()); BigDecimal qty = new BigDecimal(deal.getQuantity()); BigDecimal amount = new BigDecimal(deal.getAmount()); BigDecimal fee = new BigDecimal(deal.getFeeAmount()); String feeCurrency = deal.getFeeCurrency(); boolean isMaker = deal.getIsMaker(); System.out.printf("Trade %s: %s %s @ %s = %s | Fee: %s %s | Maker: %s%n", tradeId, side, qty, price, amount, fee, feeCurrency, isMaker); BigDecimal feeInQuote = convertFeeToQuote(fee, feeCurrency); updatePnL(side, amount, feeInQuote); } ``` -------------------------------- ### PrivateDealsV3Api - Private Trade Execution Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Delivers real-time notifications for trade executions to authenticated users, including detailed execution information and fees. ```APIDOC ## PrivateDealsV3Api - Private Trade Execution ### Description Real-time trade execution notifications for authenticated users. Contains execution details including fees. ### Channel `spot@private.deals.v3.api` ### Message Structure ```protobuf message PrivateDealsV3Api { string price = 1; // Execution price string quantity = 2; // Execution quantity string amount = 3; // Execution amount int32 tradeType = 4; // 1=buy, 2=sell bool isMaker = 5; // Executed as maker bool isSelfTrade = 6; // Self-trade indicator string tradeId = 7; // Trade ID string clientOrderId = 8; // Client order ID string orderId = 9; // Order ID string feeAmount = 10; // Fee amount string feeCurrency = 11; // Fee currency int64 time = 12; // Execution timestamp } ``` ### Java Example ```java // Track trade executions and fees public void handlePrivateDeal(PrivateDealsV3Api deal) { String tradeId = deal.getTradeId(); String orderId = deal.getOrderId(); String side = deal.getTradeType() == 1 ? "BUY" : "SELL"; BigDecimal price = new BigDecimal(deal.getPrice()); BigDecimal qty = new BigDecimal(deal.getQuantity()); BigDecimal amount = new BigDecimal(deal.getAmount()); BigDecimal fee = new BigDecimal(deal.getFeeAmount()); String feeCurrency = deal.getFeeCurrency(); boolean isMaker = deal.getIsMaker(); System.out.printf("Trade %s: %s %s @ %s = %s | Fee: %s %s | Maker: %s\n", tradeId, side, qty, price, amount, fee, feeCurrency, isMaker); // Update P&L tracking BigDecimal feeInQuote = convertFeeToQuote(fee, feeCurrency); updatePnL(side, amount, feeInQuote); } ``` ``` -------------------------------- ### PublicDealsV3Api - Public Trade Stream Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Streams real-time trade executions for a trading pair. Each message contains a list of trades with price, quantity, trade direction, and timestamp. ```APIDOC ## PublicDealsV3Api - Public Trade Stream ### Description Streams real-time trade executions for a trading pair. Each message contains a list of trades with price, quantity, trade direction, and timestamp. ### Protobuf Definition ```protobuf // PublicDealsV3Api.proto - Channel: spot@public.deals.v3.api message PublicDealsV3Api { repeated PublicDealsV3ApiItem deals = 1; string eventType = 2; } message PublicDealsV3ApiItem { string price = 1; // Trade price string quantity = 2; // Trade quantity int32 tradeType = 3; // 1=buy, 2=sell int64 time = 4; // Trade timestamp (milliseconds) } ``` ### Java Processing Example ```java // Processing public trade stream public void handleDeals(String symbol, PublicDealsV3Api dealsMsg) { for (PublicDealsV3ApiItem deal : dealsMsg.getDealsList()) { BigDecimal price = new BigDecimal(deal.getPrice()); BigDecimal quantity = new BigDecimal(deal.getQuantity()); String side = deal.getTradeType() == 1 ? "BUY" : "SELL"; long timestamp = deal.getTime(); System.out.printf("[%s] %s: %s %s @ %s at %d%n", symbol, side, quantity, symbol.replace("USDT", ""), price, timestamp); // Output: [BTCUSDT] BUY: 0.5 BTC @ 42150.50 at 1704067200000 } } ``` ``` -------------------------------- ### PushDataV3ApiWrapper - Central Message Wrapper Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt The main wrapper message that encapsulates all push data types. It provides channel identification, symbol information, and timestamp metadata while containing one of many possible message types via a oneof field. ```APIDOC ## PushDataV3ApiWrapper - Central Message Wrapper ### Description The main wrapper message that encapsulates all push data types. It provides channel identification, symbol information, and timestamp metadata while containing one of many possible message types via a oneof field. ### Protobuf Definition ```protobuf syntax = "proto3"; message PushDataV3ApiWrapper { // Channel identifier (e.g., "spot@public.deals.v3.api") string channel = 1; // One of the supported message types oneof body { PublicDealsV3Api publicDeals = 301; PublicIncreaseDepthsV3Api publicIncreaseDepths = 302; PublicLimitDepthsV3Api publicLimitDepths = 303; PrivateOrdersV3Api privateOrders = 304; PublicBookTickerV3Api publicBookTicker = 305; PrivateDealsV3Api privateDeals = 306; PrivateAccountV3Api privateAccount = 307; PublicSpotKlineV3Api publicSpotKline = 308; PublicMiniTickerV3Api publicMiniTicker = 309; PublicMiniTickersV3Api publicMiniTickers = 310; PublicBookTickerBatchV3Api publicBookTickerBatch = 311; PublicIncreaseDepthsBatchV3Api publicIncreaseDepthsBatch = 312; PublicAggreDepthsV3Api publicAggreDepths = 313; PublicAggreDealsV3Api publicAggreDeals = 314; PublicAggreBookTickerV3Api publicAggreBookTicker = 315; } // Trading pair symbol (e.g., "BTCUSDT") optional string symbol = 3; // Trading pair ID optional string symbolId = 4; // Message creation timestamp optional int64 createTime = 5; // Message send timestamp optional int64 sendTime = 6; } ``` ### Java Usage Example ```java // Java usage example - Parsing incoming WebSocket message import com.mxc.push.common.protobuf.PushDataV3ApiWrapper; import com.mxc.push.common.protobuf.PublicDealsV3Api; public class WebSocketHandler { public void onMessage(byte[] data) { PushDataV3ApiWrapper wrapper = PushDataV3ApiWrapper.parseFrom(data); String channel = wrapper.getChannel(); String symbol = wrapper.getSymbol(); long createTime = wrapper.getCreateTime(); switch (wrapper.getBodyCase()) { case PUBLICDEALS: PublicDealsV3Api deals = wrapper.getPublicDeals(); handleDeals(symbol, deals); break; case PUBLICBOOKTICKER: handleBookTicker(symbol, wrapper.getPublicBookTicker()); break; case PRIVATEORDERS: handlePrivateOrder(wrapper.getPrivateOrders()); break; // Handle other message types... } } } ``` ``` -------------------------------- ### Batch Message Types Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Utilizes batch containers for efficient multi-symbol updates within a single message, including mini tickers, book tickers, and depth updates. ```APIDOC ## Batch Message Types ### Description Batch containers for efficient multi-symbol updates in a single message. ### Method SUBSCRIBE ### Endpoint Various channels for batch updates (e.g., `spot/ticker/mini/batch`, `spot/trade/batch`, `spot/depth/increase/batch`) ### Parameters #### Query Parameters - **channel** (string) - Required - The batch channel to subscribe to. ### Request Body ```json { "op": "sub", "args": [ "spot/ticker/mini/batch" ] } ``` ### Response #### Success Response (200) - **PublicMiniTickersV3Api**: Contains a list of `PublicMiniTickerV3Api` items. - **items** (array) - List of mini ticker updates. - **PublicBookTickerBatchV3Api**: Contains a list of `PublicBookTickerV3Api` items. - **items** (array) - List of book ticker updates. - **PublicIncreaseDepthsBatchV3Api**: Contains a list of `PublicIncreaseDepthsV3Api` items and an `eventType`. - **items** (array) - List of depth updates. - **eventType** (string) - Type of the event. #### Response Example (Mini Tickers) ```json { "items": [ { "symbol": "BTC-USDT", "open": "29000.00", "high": "31000.00", "low": "28000.00", "close": "30000.00", "amount": "1000.00", "count": 5000, "bid": "30000.00", "ask": "30000.50" } ] } ``` #### Response Example (Depth Batch) ```json { "eventType": "update", "items": [ { "asks": [{"price": "30000.50", "quantity": "0.1"}], "bids": [{"price": "30000.00", "quantity": "0.2"}] } ] } ``` ``` -------------------------------- ### Private Order Updates API Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Defines the structure for private order status updates and provides a Java implementation for processing these updates. The implementation includes status mapping and callback triggers for filled or canceled orders. ```protobuf message PrivateOrdersV3Api { string id = 1; string clientId = 2; string price = 3; string quantity = 4; string amount = 5; string avgPrice = 6; int32 orderType = 7; int32 tradeType = 8; bool isMaker = 9; string remainAmount = 10; string remainQuantity = 11; optional string lastDealQuantity = 12; string cumulativeQuantity = 13; string cumulativeAmount = 14; int32 status = 15; int64 createTime = 16; optional string market = 17; optional int32 triggerType = 18; optional string triggerPrice = 19; optional int32 state = 20; optional string ocoId = 21; optional string routeFactor = 22; optional string symbolId = 23; optional string marketId = 24; optional string marketCurrencyId = 25; optional string currencyId = 26; } ``` ```java public void handlePrivateOrder(PrivateOrdersV3Api order) { String orderId = order.getId(); String clientId = order.getClientId(); String side = order.getTradeType() == 1 ? "BUY" : "SELL"; BigDecimal price = new BigDecimal(order.getPrice()); BigDecimal qty = new BigDecimal(order.getQuantity()); BigDecimal filled = new BigDecimal(order.getCumulativeQuantity()); BigDecimal avgPrice = new BigDecimal(order.getAvgPrice()); int status = order.getStatus(); String statusStr = switch (status) { case 1 -> "NEW"; case 2 -> "PARTIALLY_FILLED"; case 3 -> "FILLED"; case 4 -> "CANCELED"; case 5 -> "PARTIALLY_CANCELED"; default -> "UNKNOWN"; }; System.out.printf("Order %s [%s]: %s %s @ %s | Filled: %s/%s @ avg %s | Status: %s%n", orderId, clientId, side, qty, price, filled, qty, avgPrice, statusStr); if (status == 3) { onOrderFilled(order); } else if (status == 4 || status == 5) { onOrderCanceled(order); } } ``` -------------------------------- ### PublicAggreDepthsV3Api - Aggregated Order Book Source: https://context7.com/mexcdevelop/websocket-proto/llms.txt Delivers aggregated order book updates with price grouping and version tracking for efficient synchronization. ```APIDOC ## PublicAggreDepthsV3Api - Aggregated Order Book ### Description Aggregated order book updates with price grouping and version range tracking for efficient synchronization. ### Method SUBSCRIBE ### Endpoint `spot@public.aggre.depth.v3.api@aggreType` ### Parameters #### Query Parameters - **channel** (string) - Required - The channel to subscribe to, e.g., `spot@public.aggre.depth.v3.api@100ms`. ### Request Body ```json { "op": "sub", "args": [ "spot@public.aggre.depth.v3.api@100ms" ] } ``` ### Response #### Success Response (200) - **asks** (array) - List of ask orders - **price** (string) - Price of the ask - **quantity** (string) - Quantity of the ask - **bids** (array) - List of bid orders - **price** (string) - Price of the bid - **quantity** (string) - Quantity of the bid - **eventType** (string) - Type of the event - **fromVersion** (string) - Starting version of aggregation - **toVersion** (string) - Ending version of aggregation #### Response Example ```json { "asks": [ {"price": "30000.50", "quantity": "0.1"} ], "bids": [ {"price": "30000.00", "quantity": "0.2"} ], "eventType": "update", "fromVersion": "12345", "toVersion": "12346" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.