MEXC API Update sgcWebSockets

· Funktionen
MEXC Spot- und Futures-API-Integration in Delphi

MEXC ist eine globale Kryptobörse, die Spot-Trading und Perpetual-Futures-Kontrakte auf Hunderten von Token-Paaren unterstützt. Delphi-Entwickler können MEXC über zwei dedizierte Komponenten anbinden: TsgcWSAPI_MEXC für den Spot-Markt und TsgcWSAPI_MEXC_Futures für den Futures-Markt. Jede Komponente bietet sowohl WebSocket-Abonnements für Echtzeit-Daten als auch eine REST-Schnittstelle für On-Demand-Abfragen und Order-Management. Dieser Artikel beschreibt jede verfügbare Methode für beide Märkte.

Inhaltsverzeichnis

Architektur-Überblick

MEXC bietet getrennte API-Oberflächen für seine Spot- und Futures-Märkte. In der sgcWebSockets-Bibliothek schlägt sich das in zwei eigenständigen Komponenten nieder:

Beide Komponenten folgen demselben Muster: weise einen TsgcWebSocketClient zu, konfiguriere die API-Zugangsdaten, aktiviere den Client für WebSocket-Abonnements und greife über REST_API auf synchrone HTTP-Aufrufe zu.

Spot-WebSocket-API

Die Spot-WebSocket-API liefert Echtzeit-Marktdaten über öffentliche Kanäle und Kontoupdates über private Kanäle. Jedes Abonnement hat eine entsprechende Methode zum Abbestellen.

Öffentliche Kanäle

Abonnieren Abbestellen Beschreibung
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 Kanäle

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

Abonnieren Abbestellen Beschreibung
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

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

Private Endpoints

Methode Beschreibung
NewOrder Platziert a new spot order (market, limit, or other supported types).
TestNewOrder Validates a new order without actually placing it (dry run).
CancelOrder Storniert a specific open order by order ID.
CancelAllOrders Storniert all open orders for a symbol.
GetOrder Gibt the status and details of a specific order.
GetOpenOrders Gibt all currently open (unfilled) orders.
GetAllOrders Gibt all orders (open, filled, cancelled) within a time range.
GetAccountInformation Gibt account balances and permissions.
GetMyTrades Gibt your trade history for a symbol.
GetSubAccounts Gibt a list of sub-accounts under the master account.
GetDepositAddress Gibt the deposit address for a specific coin and network.
GetWithdrawHistory Gibt withdrawal history records.
Withdraw Startet a withdrawal to an external address.
GetCapitalConfig Gibt 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.

Abonnieren Abbestellen Beschreibung
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

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

Private Endpoints

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

Getting Started — Code Examples

Spot Market Example

Das folgende Beispiel 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: Abonniere 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: Abonniere futures ticker for BTC_USDT
  oMEXCFut.SubscribeTicker('BTC_USDT');
  // REST: Get all available futures contracts
  ShowMessage(oMEXCFut.REST_API.GetContracts);
end;
Hinweis: Spot and Futures use separate WebSocket connections and separate API components. You need a distinct TsgcWebSocketClient instance for each.

Configuration Reference

Spot Configuration

Eigenschaft Typ Beschreibung
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

Eigenschaft Typ Beschreibung
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.

Tipp: 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.