MEXC API Update sgcWebSockets

MEXC Spot and Futures API Integration in Delphi

MEXC is a global cryptocurrency exchange supporting spot trading and perpetual futures contracts across hundreds of token pairs. Delphi developers can integrate with MEXC through two dedicated components: TsgcWSAPI_MEXC for the Spot market and TsgcWSAPI_MEXC_Futures for the Futures market. Each component provides both WebSocket subscriptions for real-time data and a REST interface for on-demand queries and order management. This article details every available method across both markets.

Architecture Overview

MEXC provides separate API surfaces for its Spot and Futures markets. In the sgcWebSockets library, this is reflected by two distinct components:

  • TsgcWSAPI_MEXC — Handles the Spot market. Provides WebSocket subscriptions for real-time trades, klines, depth, and tickers, plus private account event streams. The REST interface is accessible through REST_API (type TsgcHTTP_API_MEXC_Spot).
  • TsgcWSAPI_MEXC_Futures — Handles the Futures market. Provides WebSocket subscriptions for futures-specific data such as deals, funding rates, index prices, and fair prices. The REST interface is accessible through REST_API (type TsgcHTTP_API_MEXC_Futures).

Both components follow the same pattern: assign a TsgcWebSocketClient, configure API credentials, activate the client for WebSocket subscriptions, and access REST_API for synchronous HTTP calls.

Spot WebSocket API

The Spot WebSocket API provides real-time market data through public channels and account updates through private channels. Each subscription has a corresponding unsubscribe method.

Public Channels

Subscribe Unsubscribe Description
SubscribeTrade UnSubscribeTrade Real-time trade executions for a symbol.
SubscribeKline UnSubscribeKline Live candlestick/kline updates for a symbol and interval.
SubscribeDiffDepth UnSubscribeDiffDepth Incremental order book depth updates (diff stream).
SubscribeBookDepth UnSubscribeBookDepth Full order book depth snapshots at a given level.
SubscribeBookTicker UnSubscribeBookTicker Best bid/ask price and quantity for a specific symbol.
SubscribeBookTickerBatch UnSubscribeBookTickerBatch Best bid/ask prices for all symbols in a single stream.
SubscribeMiniTickers UnSubscribeMiniTickers Condensed ticker data (price, volume) for all symbols.
SubscribeMiniTicker UnSubscribeMiniTicker Condensed ticker data for a specific symbol.

Private Channels

Private channels require authentication and deliver real-time updates about your account activity. Enable the user data stream via the MEXCUserDataStreams.UserStream property.

Subscribe Unsubscribe Description
SubscribeAccountUpdate UnSubscribeAccountUpdate Account balance and position updates when changes occur.
SubscribeAccountDeals UnSubscribeAccountDeals Real-time notifications when your orders are filled (trade executions).
SubscribeAccountOrders UnSubscribeAccountOrders Order status changes (placed, partially filled, filled, cancelled).

Spot REST API

The Spot REST API is accessible via oMEXC.REST_API (of type TsgcHTTP_API_MEXC_Spot). Public endpoints do not require authentication; private endpoints require a valid API key and secret.

Public Endpoints

Method Description
Ping Tests connectivity to the MEXC API server.
GetServerTime Returns the current MEXC server time.
GetDefaultSymbols Returns the list of default trading symbols.
GetExchangeInformation Returns exchange trading rules and symbol information (filters, precision, status).
GetOrderBook Returns the order book (bids and asks) for a symbol at a given depth.
GetTrades Returns recent public trades for a symbol.
GetAggregateTrades Returns aggregated/compressed trade records.
GetKlines Returns historical kline/candlestick data for a symbol and interval.
GetAveragePrice Returns the current average price for a symbol.
Get24hrTicker Returns 24-hour rolling window price change statistics.
GetPriceTicker Returns the latest price for one or all symbols.
GetBookTicker Returns the best bid/ask price and quantity from the order book.

Private Endpoints

Method Description
NewOrder Places a new spot order (market, limit, or other supported types).
TestNewOrder Validates a new order without actually placing it (dry run).
CancelOrder Cancels a specific open order by order ID.
CancelAllOrders Cancels all open orders for a symbol.
GetOrder Returns the status and details of a specific order.
GetOpenOrders Returns all currently open (unfilled) orders.
GetAllOrders Returns all orders (open, filled, cancelled) within a time range.
GetAccountInformation Returns account balances and permissions.
GetMyTrades Returns your trade history for a symbol.
GetSubAccounts Returns a list of sub-accounts under the master account.
GetDepositAddress Returns the deposit address for a specific coin and network.
GetWithdrawHistory Returns withdrawal history records.
Withdraw Initiates a withdrawal to an external address.
GetCapitalConfig Returns capital configuration (supported networks, min/max withdrawal amounts, fees).

Futures WebSocket API

The Futures WebSocket API provides real-time data specific to perpetual futures contracts. All channels are public and do not require authentication. Each subscription has a corresponding unsubscribe method.

Subscribe Unsubscribe Description
SubscribeDeal UnSubscribeDeal Real-time futures trade/deal executions.
SubscribeTickers UnSubscribeTickers Ticker data for all futures contracts.
SubscribeTicker UnSubscribeTicker Ticker data for a specific futures contract.
SubscribeDepth UnSubscribeDepth Incremental order book depth updates for futures.
SubscribeDepthFull UnSubscribeDepthFull Full order book depth snapshots for futures.
SubscribeKline UnSubscribeKline Live candlestick/kline updates for futures contracts.
SubscribeFundingRate UnSubscribeFundingRate Real-time funding rate updates for perpetual contracts.
SubscribeIndexPrice UnSubscribeIndexPrice Real-time index price updates.
SubscribeFairPrice UnSubscribeFairPrice Real-time fair/mark price updates used for liquidation calculations.

Futures REST API

The Futures REST API is accessible via oMEXCFut.REST_API (of type TsgcHTTP_API_MEXC_Futures). It covers market data, account management, position control, and order operations.

Public Endpoints

Method Description
GetPing Tests connectivity to the MEXC Futures API server.
GetServerTime Returns the current futures server time.
GetContracts Returns a list of all available futures contracts and their specifications.
GetDepth Returns the order book depth for a futures contract.
GetDeals Returns recent public trade/deal history for a futures contract.
GetKlines Returns historical kline/candlestick data for a futures contract.
GetIndexPrice Returns the current index price for a contract.
GetFairPrice Returns the current fair/mark price for a contract.
GetFundingRate Returns the current and predicted funding rate for a perpetual contract.

Private Endpoints

Method Description
GetAccountAssets Returns futures account asset balances and margin information.
GetPositionList Returns all open futures positions with size, entry price, and PnL.
SetPositionLeverage Sets the leverage multiplier for a specific futures contract.
PlaceOrder Places a new futures order (market, limit, or other supported types).
CancelOrder Cancels a specific open futures order.
CancelAllOrders Cancels all open futures orders for a contract.
GetOpenOrders Returns all currently open futures orders.
GetOrderHistory Returns historical futures orders (filled, cancelled, etc.).
GetFundingHistory Returns your funding fee payment history.

Getting Started — Code Examples

Spot Market Example

The following example connects to the MEXC Spot WebSocket, subscribes to real-time trades, queries exchange information via REST, and places a market buy order.

var
  oClient: TsgcWebSocketClient;
  oMEXC: TsgcWSAPI_MEXC;
begin
  // Create the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  // Create the MEXC Spot API component
  oMEXC := TsgcWSAPI_MEXC.Create(nil);
  oMEXC.Client := oClient;

  // Configure API credentials
  oMEXC.MEXCAPI.ApiKey := 'your_api_key';
  oMEXC.MEXCAPI.ApiSecret := 'your_api_secret';

  // Connect to the WebSocket
  oClient.Active := True;

  // WebSocket: Subscribe to real-time trades for BTCUSDT
  oMEXC.SubscribeTrade('BTCUSDT');

  // REST: Get exchange information
  ShowMessage(oMEXC.REST_API.GetExchangeInformation);

  // REST: Place a market buy order for 0.001 BTC
  ShowMessage(oMEXC.REST_API.NewOrder('BTCUSDT', 'BUY', 'MARKET', '', 0.001));
end;

Futures Market Example

This example connects to the MEXC Futures WebSocket, subscribes to a futures ticker, and queries available contracts via REST.

var
  oClientFut: TsgcWebSocketClient;
  oMEXCFut: TsgcWSAPI_MEXC_Futures;
begin
  // Create the WebSocket client for futures
  oClientFut := TsgcWebSocketClient.Create(nil);
  // Create the MEXC Futures API component
  oMEXCFut := TsgcWSAPI_MEXC_Futures.Create(nil);
  oMEXCFut.Client := oClientFut;

  // Configure API credentials
  oMEXCFut.MEXCFuturesAPI.ApiKey := 'your_api_key';
  oMEXCFut.MEXCFuturesAPI.ApiSecret := 'your_api_secret';

  // Connect to the WebSocket
  oClientFut.Active := True;

  // WebSocket: Subscribe to futures ticker for BTC_USDT
  oMEXCFut.SubscribeTicker('BTC_USDT');

  // REST: Get all available futures contracts
  ShowMessage(oMEXCFut.REST_API.GetContracts);
end;
Note: Spot and Futures use separate WebSocket connections and separate API components. You need a distinct TsgcWebSocketClient instance for each.

Configuration Reference

Spot Configuration

Property Type Description
MEXCAPI.ApiKey String Your MEXC API key for authenticated spot requests.
MEXCAPI.ApiSecret String Your MEXC API secret for request signing.
MEXCUserDataStreams.UserStream Boolean Set to True to enable the private user data stream for account updates, deals, and order events.

Futures Configuration

Property Type Description
MEXCFuturesAPI.ApiKey String Your MEXC API key for authenticated futures requests.
MEXCFuturesAPI.ApiSecret String Your MEXC API secret for futures request signing.

Tips and Notes

Separate Components for Spot and Futures

MEXC treats Spot and Futures as entirely separate markets with different API endpoints, symbol naming conventions (e.g., BTCUSDT for spot vs. BTC_USDT for futures), and authentication scopes. Always use the correct component for your target market.

User Data Streams

To receive private account events on the Spot WebSocket (account updates, deals, order changes), you must set MEXCUserDataStreams.UserStream := True before activating the client. This tells the component to request a listen key and establish the private stream automatically.

Order Testing

Use the TestNewOrder method on the Spot REST API to validate order parameters without actually placing the order. This is useful for verifying that your symbol, side, type, and quantity parameters are correctly formatted before committing real funds.

Symbol Naming Conventions

Pay attention to the different symbol formats across the two markets. Spot uses concatenated pairs like BTCUSDT, while Futures uses underscore-separated pairs like BTC_USDT. Using the wrong format will result in "symbol not found" errors.

Rate Limits

MEXC enforces rate limits on both REST and WebSocket APIs. REST endpoints typically allow a fixed number of requests per minute. If you exceed the limit, you will receive a 429 status code. Implement appropriate backoff logic or use WebSocket subscriptions for data that changes frequently.

Tip: For high-frequency monitoring, prefer WebSocket subscriptions over polling REST endpoints. Subscriptions deliver data in real time with lower latency and do not count against REST rate limits.
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

Kucoin API Update sgcWebSockets

Related Posts