A TypeScript SDK for MEXC Futures trading with REST API and WebSocket support, plus a built-in Telegram signal bot that auto-executes trades from channel messages.
- Quick Start (Local Bot)
- Authentication
- Telegram Signal Bot
- Creating the Telegram Bot & Adding Channels
- Remote Server Deployment
- Desktop App & Auto-Updates
- SDK Usage (Programmatic)
- API Reference
- Safety Features
# 1. Install dependencies
npm install
# 2. Copy and configure environment
cp .env.example .env
# Edit .env with your MEXC keys and Telegram bot token
# 3. Build the project
npm run build
# 4. Run in dry-run mode first (no real trades)
DRY_RUN=true npm run bot
# 5. When ready, enable live trading
DRY_RUN=false npm run botThe SDK supports two authentication methods. API keys are preferred for bot usage.
Set these in your .env:
MEXC_KEY=mx0your_api_key_here # Your MEXC API key
MEXC_SECRET_KEY=your_secret_here # Your MEXC API secretThe bot uses HMAC-SHA256 signing with these credentials.
- Login to MEXC Futures in your browser
- Open Developer Tools (F12) β Network tab
- Make any request to
futures.mexc.com - Find the
authorizationheader (starts withWEB...) - Set
MEXC_AUTH_TOKEN=WEB...in your.env
The bot listens for trading signals posted in Telegram channels, parses them, validates against MEXC contracts, sizes positions based on your risk parameters, and executes trades automatically.
flowchart LR
A[Telegram Channel] -->|New Message| B[Bot Listens]
B -->|Matches Signal Format| C[Parse Signal]
C --> D[Normalize Symbol]
D --> E[Resolve MEXC Contract]
E --> F[Fetch Account Equity]
F --> G[Calculate Position Size]
G --> H{Dry Run?}
H -->|Yes| I[Log Only]
H -->|No| J[Submit Order to MEXC]
J --> K[Track in State File]
The bot recognizes these signal patterns:
BUY TAOUSDT@187.54 SL 185.13 TP 188.81
SELL BTCUSDT@65000 SL 66000 TP 63000
BUY ETHUSDT@3500 SL 3400 TP1 3600 TP2 3700 TP3 3800
BUY SOLUSDT@150 SL 145
BUY TAOUSDT@187.54 SL 185.13 TP 188.81 R2 L50 V7
| Element | Meaning |
|---|---|
BUY / SELL |
Direction: BUY = long, SELL = short |
SYMBOL@PRICE |
Trading pair and entry price |
SL <price> |
Stop-loss price (mandatory) |
TP <price> |
Take-profit (optional β defaults to 1.5Γ risk) |
TP1/TP2/TP3 |
Multiple TP targets β volume is split equally |
R<number> |
Risk per trade override in % (e.g. R2 = 2%, valid 0β6) |
L<number> |
Leverage override (e.g. L200 = 200x, valid 1β200, clamped to the contract max) |
V<number> |
Plan-order validity: V1/absent = 24h, V7 = 7 days |
Symbol normalization: TAOUSDT β TAO_USDT, BTCUSDT β BTC_USDT
All settings are environment variables. Copy .env.example and fill in:
| Variable | Default | Description |
|---|---|---|
| Required | ||
MEXC_KEY |
β | MEXC API key (starts with mx0...) |
MEXC_SECRET_KEY |
β | MEXC API secret key |
TELEGRAM_BOT_TOKEN |
β | Telegram Bot token from @BotFather |
ALLOWED_CHANNELS |
β | Comma-separated channel IDs or usernames |
CONFIRM_CHANNELS |
β | Subset of ALLOWED_CHANNELS where signals are queued (awaiting CONFIRM ORDERS). Channels not listed here auto-place immediately. Leave empty to disable the confirmation flow entirely. |
| Trading | ||
DEFAULT_LEVERAGE |
10 |
Leverage (1β200) |
OPEN_TYPE |
1 |
1 = isolated margin, 2 = cross margin |
RISK_PERCENT |
0.01 |
Risk per trade (0.01 = 1% of equity) |
DEFAULT_TP_RATIO |
1.5 |
Default TP:SL ratio when no TP in signal |
MAX_CONCURRENT_TRADES |
5 |
Max simultaneous open positions |
MAX_NOTIONAL_PER_TRADE |
10000 |
Max USDT notional value per trade |
USE_LIMIT_TP_SL |
false |
Place TP/SL as Limit (Maker) Stop-Limit orders (0% maker fee) instead of market (taker) TP/SL. Applies to market entries; plan/stop entries keep market TP/SL (a warning is logged) |
USE_MAKER_CLOSE |
false |
Close positions with Limit (Maker) orders at the best bid/ask instead of market (taker) orders β maker fills pay the maker fee (often 0%) instead of taker (0.05%). Falls back to a market close after ~2.5s if the maker order hasn't filled |
| Safety | ||
DRY_RUN |
true |
Parse & size, but don't submit orders |
TRADING_ENABLED |
true |
Master trading on/off switch |
| Other | ||
LOG_LEVEL |
INFO |
SILENT, ERROR, WARN, INFO, DEBUG |
BASE_CURRENCY |
USDT |
Base currency for equity checks |
STATE_FILE_PATH |
./bot-state.json |
Idempotency state file location |
MEXC_AUTH_TOKEN |
β | Legacy: browser WEB token (not needed with API keys) |
| Position-Close Notifications | ||
PNL_NOTIFICATION_CHANNEL |
(empty) | Channel/chat ID that receives realized PNL + balance updates when a position closes. Empty disables the feature |
POSITION_MONITOR_INTERVAL_SECONDS |
30 |
How often (s) to poll MEXC for closed positions (min 5) |
| Position Summary | ||
SUMMARY_NOTIFICATION_CHANNEL |
(empty) | Channel/chat ID for the periodic position summary. Empty = reuse PNL_NOTIFICATION_CHANNEL |
SUMMARY_INTERVAL_HOURS |
8 |
How often (h) the position summary is sent |
SUMMARY_WINDOW_HOURS |
4 |
Trailing window (h) for the PNL max/min stats shown in the summary |
| API Rate Limiting | ||
ORDER_RATE_CAPACITY |
3 |
Token-bucket burst capacity β max MEXC API requests fired immediately before throttling |
ORDER_RATE_INTERVAL_MS |
200 |
Spacing (ms) between requests after the burst is spent (sustained β 5 req/s) |
Signals with multiple orders + TPs (e.g. 2 orders Γ 3 TPs = 6 order submissions, plus the
pre-order ticker/equity/position calls) can fire a burst that exceeds MEXC's request limit,
causing 513 rejections. The bot applies a token-bucket rate limiter to every MEXC API call
that:
- Bursts first β up to
ORDER_RATE_CAPACITYrequests are sent back-to-back with zero delay, so normal signals are placed as fast as possible (no artificial sleep). - Then spaces out β once the burst is spent, excess requests are queued FIFO and released
one every
ORDER_RATE_INTERVAL_MS, keeping the sustained rate safe.
For the default ORDER_RATE_CAPACITY=3 / ORDER_RATE_INTERVAL_MS=200, a 6-order signal
places 3 orders immediately and the rest at ~200ms intervals β all done in under a second,
without exhausting the API. If you still see 513 errors, lower ORDER_RATE_CAPACITY
to 1β2; if you want more burst headroom, raise it. Throttling events are logged as
β³ MEXC rate-limit: throttled ... (waited Xms).
By default the bot attaches market take-profit and stop-loss orders to every entry.
Market (taker) exits incur the taker fee on both the TP and the SL. Setting
USE_LIMIT_TP_SL=true switches TP/SL to Stop-Limit orders placed via
/private/stoporder/place:
- The market entry is submitted without attached TP/SL.
- Once the position opens, a limit TP and a limit SL are attached to the
position at the signal's TP/SL prices (
takeProfitType=1/stopLossType=1). - If the limit order rests in the book and adds liquidity when it fills, it's executed as a maker order β potentially 0% fee on the exit.
- If placing a limit TP/SL fails, the bot automatically falls back to a market TP/SL via the same endpoint so your position is never left unprotected.
β οΈ Stop-entry (plan/trigger) orders can't attach limit TP/SL until the position actually opens, so they keep market TP/SL (a warning is logged). Limit TP/SL applies to market entries (@/EP-free signals), which is the default signal type.
The bot runs as a single Node.js process β no daemon or container is required.
All file paths in .env are resolved against the working directory.
# Build once (or after any source change)
npm run build
# Run (foreground β Ctrl+C to stop)
node dist/bot/index.js
# Run in background
nohup node dist/bot/index.js > bot.log 2>&1 &
# Check logs: tail -f bot.logFirst run checklist:
- Start with
DRY_RUN=trueβ verify signals are parsed correctly - Check logs for symbol normalization and contract resolution
- Once confident, set
DRY_RUN=falseandTRADING_ENABLED=true - Monitor your first few trades closely
When a position closes (TP, SL, or manual close), the bot can send a summary to a separate channel of your choice, showing:
- Realized PNL β the amount in USDT plus the return as a % of the position's initial margin
- Entry β Exit prices, direction (LONG/SHORT), leverage and margin mode
- Available balance and equity after the close
Example message:
π POSITION CLOSED
πͺ BTC_USDT Β· LONG Β· 10x Β· Isolated
Entry: 67,000.00 β Exit: 69,000.00
π Realized PNL: +176.70 USDT (+5.12%)
πΌ Available: 1,234.56 USDT
π Equity: 5,678.90 USDT
Setup:
- Set
PNL_NOTIFICATION_CHANNELin.envto the channel/chat ID you want the notifications sent to (numeric or@username). Leave it empty to disable the feature. - Add your bot as an admin in the notification channel (otherwise sending will be forbidden).
- Optionally tune
POSITION_MONITOR_INTERVAL_SECONDS(default30, min5) β how often the bot polls MEXC to detect a closed position.
π‘ The monitor detects any position on your account that closes β whether opened by the bot or manually. On startup it seeds its known-position list, so positions that already closed while the bot was offline won't trigger notifications.
Every SUMMARY_INTERVAL_HOURS (default 8), the bot sends a summary of the current account state to the summary channel, showing:
- Open positions β symbol, direction, leverage, entry price, current PNL, and the max / min PNL reached over the trailing
SUMMARY_WINDOW_HOURS(default4hours), plus each position's position ID, its estimated TP / SL P&L and the % of the TP target already reached - Pending orders β one line per pending STOP (entry) order: symbol, direction, trigger price, volume and a shortened order ID
- Available balance and equity
Example message:
π POSITION SUMMARY
β±οΈ Last 4h Β· report every 8h
π Open Positions (2)
ββββββββββββββ
π’ BTC_USDT LONG Β· 10x
Entry: 67,000.00
PNL: +176.70 USDT
max +210.10 / min -5.30 USDT
π― Est TP +500.00 / SL -250.00 USDT Β· 35% of TP
π 5839201
ββββββββββββββ
π΄ ETH_USDT SHORT Β· 5x
Entry: 3,500.00
PNL: -12.00 USDT
max +40.50 / min -15.20 USDT
π― Est TP +180.00 / SL -90.00 USDT Β· -7% of TP
π 2948573
π Pending Orders (2)
π‘ TAO_USDT LONG Β· STOP β₯187.54 Β· 0.50 Β· <code>β¦397504</code>
π‘ ETH_USDT SHORT Β· TP β€1,856.00 / SL β₯1,884.95 Β· 0.17 Β· <code>β¦2904</code>
πΌ Available: 1,234.56 USDT
π Equity: 5,678.90 USDT
The estimated TP/SL P&L is what the position would make/lose if the price reached its take-profit or stop-loss level (derived from the current PNL, entry, volume and the contract's size). The % of TP shows how much of that target is already banked as unrealized PNL (negative = currently losing). The SL/TP levels come from the bot's own orders (stored at execution) and, as a fallback, from the pending TP/SL stop orders on the exchange β so the estimate and the >50% alerts keep working across restarts and for manually opened positions.
Pending orders are the orders currently open on the exchange, fetched from the futures API in two calls and shown one line each:
- STOP entries β from
GET /private/planorder/list/orders(untriggered): direction,STOPwith its trigger condition (β₯/β€) and price. - TP/SL pairs β from
GET /private/stoporder/list/orders(uncompleted): direction plusTP β¦ / SL β¦with the correct trigger direction (a long's TP fires on a rise, SL on a fall; a short's the reverse).
Order IDs are shown shortened for a compact layout β the full IDs appear in the order-placed alerts.
Setup:
- Set
SUMMARY_NOTIFICATION_CHANNELin.env(numeric ID or@username). Leave it empty to reusePNL_NOTIFICATION_CHANNEL. - The bot samples unrealized PNL on the same
POSITION_MONITOR_INTERVAL_SECONDScadence to build the max/min stats. - Tune the cadence with
SUMMARY_INTERVAL_HOURSand the reporting window withSUMMARY_WINDOW_HOURS.
π‘ Max/min PNL is tracked only while the bot is running (it polls unrealized PNL continuously). If the bot restarts, the stats begin accumulating again from scratch.
Verifying polling & persistence:
- The bot logs
π Polling active: N open position(s)at INFO on the first successful poll. - Poll stats are written to
<STATE_FILE_PATH>-summary-stats.json(e.g../bot-summary-stats.json) β check itsstatsarray andupdatedAttimestamp. - Set
LOG_LEVEL=DEBUGto see per-poll lines (π Polled N open position(s) β¦) and per-source pending-order status (π¦ Pending order sources β β¦). - All HTTP requests and responses (including pending-order endpoint attempts) are logged to
{LOG_DIR}/http-YYYY-MM-DD.logβ check this file for raw MEXC API responses if pending orders show 0.
On-demand summary:
Send CHECK POSITIONS (or the shorthand @) to the summary channel and the bot will emit the position summary immediately, without waiting for the next SUMMARY_INTERVAL_HOURS tick. Both forms are case-insensitive (for the word form), work regardless of whether the summary channel is listed in ALLOWED_CHANNELS, and each message is only honored once (idempotent across restarts).
CHECK POSITIONS
@
π‘ The on-demand summary reflects the same data as the periodic one, including the current / max / min PNL tracked over the trailing window. If the summary feature is disabled (no
SUMMARY_NOTIFICATION_CHANNEL), the command is ignored.
50%-of-way alerts:
While the summary monitor polls open positions, it also checks whether the current price has travelled more than halfway from entry toward the stop-loss or the take-profit. When the >50% threshold is crossed, an alert is sent to the summary channel β once per position per target. Example:
π¨ POSITION ALERT β 65% toward SL
πͺ BTC_USDT Β· LONG Β· 10x
Entry: 67,000.00 β Now: 66,350.00
π― Stop-loss @ 66,000.00 β 65% of the way
The SL/TP levels come from the bot's own order execution (and, as a fallback, from the pending TP/SL stop orders on the exchange, so alerts survive restarts and cover manually opened positions with attached TP/SL). Progress is computed from the position's unrealized PNL, volume and the contract's size, so it stays correct for contracts with a non-1 contract size (e.g. ATOM 0.1, BTC 0.0001). Alert flags are reset when the position closes, so a new position on the same symbol can alert again. Stale entries older than LOG_RETENTION_DAYS are pruned automatically.
Closing a position manually:
Send Close {id} to an allowed channel and the bot will resolve the position and close it immediately with a market order. A confirmation is sent to the summary channel.
The summary shows the recommended identifier for each open position β its position ID β as the ready-to-use close command π CLOSE {positionId}:
Close 1462152523
A partial close is supported by appending a percentage:
Close 1462152523 30%
The position ID is preferred because it always exists on the open-positions API and carries the authoritative position direction, so closing by it never hits MEXC's "wrong direction" error (important in hedge mode, where a symbol can hold both a LONG and a SHORT simultaneously). For backward compatibility the command still accepts a MEXC fill order ID or plan/trigger order ID, which are resolved via the API. The command is idempotent and requires the channel to be in ALLOWED_CHANNELS.
By default, signals from all ALLOWED_CHANNELS are placed automatically (no queue, no confirmation step). You can enable the queue+confirmation flow on specific channels by listing them in CONFIRM_CHANNELS:
Channel in CONFIRM_CHANNELS? |
Behaviour |
|---|---|
| Yes | Signal is queued β a trade confirmation is posted, and the order is not placed until the operator sends CONFIRM ORDERS |
| No | Signal is auto-placed immediately (no confirmation message) |
When the confirmation flow is active for a channel, a valid signal is parsed and sized, then the bot queues the order and sends a trade confirmation to the channel β showing the expected TP and expected SL, plus the estimated realized PNL net of fees when the contract fee rates are known:
π§Ύ TRADE CONFIRMATION
πͺ TAO_USDT Β· LONG Β· 50x Β· Isolated
πΉ Market entry @ 123.00
π Expected TP: 124.00
Est. net profit: +34.92 USDT (34.6%) Β· incl. fees
π Expected SL: 122.00
Est. net loss: -47.03 USDT (-46.6%) Β· incl. fees
π΅ Risk: 100.00 USDT (1.0%) Β· Notional: ~5,043.00 USDT
π§Ύ Est. fees: 6.08 USDT (3.03 entry + 3.05 exit)
π Queue: 1 order(s) pending β send CONFIRM ORDERS to place
β³ Queued β awaiting CONFIRM ORDERS
The operator then decides what happens to the pending queue:
CONFIRM ORDERSβ places every queued order (market orders fill immediately, trigger entries are submitted as pending plan orders). Confirmation is idempotent per message.CANCEL ORDERSβ discards the pending queue without placing anything.
Both commands only work from a channel listed in CONFIRM_CHANNELS.
Once CONFIRM ORDERS is sent, the bot also posts a short alert to the summary channel for each order that is successfully placed/executed (market fills immediately, trigger entries are placed as pending). It shows the symbol, direction, leverage, entry, SL/TP, volume, notional, risk and the order ID:
π ORDER PLACED
πͺ TAO_USDT LONG Β· 50x Β· Isolated
πΉ Market entry @ 123.00
SL: 122.00 Β· TP: 124.00, 125.00
Vol: 41 Β· Notional: ~5,043.00 USDT
Risk: 100.00 USDT (1.0%)
Order ID: 817027833053397504
π‘ These alerts are sent only in live trading mode (
DRY_RUN=false) β dry-run does not submit real orders.
This step-by-step guide walks you through creating a Telegram bot and configuring it to monitor trading signal channels.
-
Open Telegram and search for @BotFather (the official bot creation tool)
-
Start a chat and send:
/newbot -
Choose a name (display name, e.g. "MEXC Signal Trader")
-
Choose a username (must end in
bot, e.g.mexc_signal_bot) -
BotFather will respond with your bot token β save it:
Done! Congratulations on your new bot. Use this token to access the HTTP API: 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz Keep your token secure and store it safely. -
Copy this token into your
.envfile:TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
By default, bots cannot read messages in group chats. You MUST disable privacy mode:
- In @BotFather, send:
/mybots - Select your bot
- Tap Bot Settings β Group Privacy
- Select Turn off (Disable)
- Confirm the change
β οΈ Without this step, the bot will NOT see messages in channels/groups.
For each channel you want to monitor:
-
Open the Telegram channel
-
Tap the channel name β Administrators (or Subscribers for public channels)
-
Tap Add Admin β search for your bot's username
-
Grant the bot admin rights β at minimum, it needs:
- β Read Messages (usually auto-granted)
Note: The bot needs to be an admin of the channel (not just a subscriber) to read messages via the Bot API.
-
Repeat for every channel you want to monitor.
You need to tell the bot WHICH channels to listen to. Each channel has an identifier β either a numeric ID or a @username.
For public channels with a username (e.g. @crypto_signals):
ALLOWED_CHANNELS=@crypto_signals,@btc_alertsFor private channels (numeric IDs only):
-
Method A β Forward a message to @RawDataBot:
- Forward any message from the channel to @RawDataBot
- It replies with JSON containing
"chat":{"id":-1001234567890,...} - The ID will be negative (e.g.
-1001234567890) β use the full number
-
Method B β Use the bot itself:
- Temporarily add this to
bot.ts:this.telegram.on(message("text"), (ctx) => { console.log("Chat ID:", ctx.chat.id); });
- Send a test message in the channel β the bot logs the ID
- Temporarily add this to
-
Set the channel IDs in
.env:ALLOWED_CHANNELS=-1001234567890,-1009876543210
- Start the bot with
DRY_RUN=true:npm run bot
- Post a test signal in one of your channels:
BUY BTCUSDT@65000 SL 64000 TP 66000 - Check the bot logs β you should see:
π¨ Message from -1001234567890#42: BUY BTCUSDT@65000... π Signal detected: BUY BTCUSDT@65000 SL 64000 TP 66000 π Normalized: BTCUSDT β BTC_USDT π§ͺ [DRY RUN] Would submit order: ...
If you see π Not a trade signal β ignoring, the message format isn't matching the parser. Check the signal format carefully.
| Problem | Solution |
|---|---|
| Bot doesn't see messages | Ensure Group Privacy is disabled in @BotFather |
| "Forbidden: bot is not a member" | Add the bot as an admin to the channel |
| Wrong channel ID | Private channels always have negative IDs starting with -100 |
| Rate limited | Telegram limits bots to ~30 msg/sec β not an issue for signal monitoring |
The bot runs as a single Node.js process. Deploy the project directory anywhere,
cd into it, and run node dist/bot/index.js.
# 1. Clone & set up the project
cd /opt/mexc-signal-bot
git clone https://github.com/oboshto/mexc-futures-sdk.git .
npm install && npm run build
# 2. Create and edit .env (see Configuration Reference above)
# Keep paths relative β they resolve against the working directory:
# STATE_FILE_PATH=./bot-state.json
# LOG_DIR=./logs
# 3. Run
node dist/bot/index.js
# To keep running after logout:
nohup node dist/bot/index.js > bot.log 2>&1 &
tail -f bot.logsystemd (optional): A ready-to-use service file lives at deploy/mexc-signal-bot.service.
Create a Dockerfile in the project root:
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
RUN addgroup -S mexcbot && adduser -S mexcbot -G mexcbot
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
USER mexcbot
CMD ["node", "dist/bot/index.js"]# Build and run
docker build -t mexc-signal-bot .
docker run -d \
--name mexc-signal-bot \
--restart unless-stopped \
--env-file .env \
-v $(pwd)/bot-state.json:/app/bot-state.json \
mexc-signal-bot
# View logs
docker logs -f mexc-signal-botBefore switching from dry-run to live trading on the server:
- Bot connects to Telegram and sees channel messages
- Signals are parsed correctly (check logs)
- Symbols resolve to valid MEXC contracts
- Position sizing looks correct in dry-run logs
- MEXC connection test passes
-
.envhasDRY_RUN=falseandTRADING_ENABLED=true - You have sufficient balance in your MEXC Futures account
- You've set a reasonable
MAX_NOTIONAL_PER_TRADEandRISK_PERCENT - Bot auto-restarts on crash (systemd or Docker restart policy)
The Electron desktop app wraps the bot with a GUI (configuration, logs, position
summary) and ships the compiled bot code (dist/) inside the app bundle.
It supports two update mechanisms, both reachable from the π Updates tab:
- Downloads a newer app build from GitHub Releases and installs it.
- New builds bundle the latest script code, so this is the "big" update path.
- On macOS the app must be code-signed for auto-install to work; otherwise users update manually.
- Pulls just the latest compiled bot code from the
dist.ziprelease asset and swaps it into a writable runtime folder (<userData>/code/dist), then restarts the bot β no reinstall needed. - The bot is loaded from this runtime folder when present; otherwise it falls
back to the bundled code. Third-party deps resolve from the app's own
node_modules.
# 1. Bump the version in package.json, then build everything
npm run build
# 2. Package the compiled bot code for the "Refresh Code" feature
npm run dist:zip # creates dist.zip at the repo root
# 3. Build desktop installers and publish to GitHub Releases
# (uploads app bundles AND latest*.yml metadata that electron-updater uses)
npm run desktop:publish # needs a GH_TOKEN with repo scope
β οΈ Attach the generateddist.zipto the same GitHub release so the desktop app's "Refresh Code" button has something to pull. The asset name must be exactlydist.zip.
Update feed: github.com/dupipcom/iris releases. dev-app-update.yml enables
update checks during development; the packaged app uses the app-update.yml
electron-builder generates from the publish section in electron-builder.yml.
import { MexcFuturesClient } from "mexc-futures-sdk";
// With API key + secret (recommended)
const client = new MexcFuturesClient({
apiKey: "mx0vglS6XtxqHJsEse",
secretKey: "60cbe8535ba6419da3449b6e58c458be",
});
// Get ticker data
const ticker = await client.getTicker("BTC_USDT");
console.log("BTC Price:", ticker.data.lastPrice);
// Place a market order
const order = await client.submitOrder({
symbol: "BTC_USDT",
price: 50000,
vol: 0.001,
side: 1, // 1=open long, 3=open short
type: 5, // 5=market order
openType: 1, // 1=isolated margin
leverage: 10,
});import { MexcFuturesWebSocket } from "mexc-futures-sdk";
const ws = new MexcFuturesWebSocket({
apiKey: "YOUR_API_KEY",
secretKey: "YOUR_SECRET_KEY",
autoReconnect: true,
});
ws.on("connected", () => {
ws.login(false).then(() => {
console.log("Login successful");
ws.subscribeToAll();
});
});
ws.on("orderUpdate", (data) => {
console.log("Order:", data.orderId, data.symbol, data.state);
});
ws.on("positionUpdate", (data) => {
console.log("Position:", data.symbol, data.holdVol, data.pnl);
});
ws.on("assetUpdate", (data) => {
console.log("Balance:", data.currency, data.availableBalance);
});
await ws.connect();getTicker(symbol)β Get ticker datagetContractDetail(symbol?)β Get contract info (all or specific)getContractDepth(symbol, limit?)β Get order booksubmitOrder(params)β Place an ordercancelOrder(orderIds)β Cancel orders (up to 50)cancelOrderByExternalId(params)β Cancel by external IDcancelAllOrders(params?)β Cancel all ordersgetOrderHistory(params)β Get order historygetOrderDeals(params)β Get order trade detailsgetOrder(orderId)β Get single order by IDgetOrderByExternalId(symbol, externalOid)β Get order by external IDgetRiskLimit()β Get account risk limitsgetFeeRate()β Get fee ratesgetAccountAsset(currency)β Get balance for a currencygetOpenPositions(symbol?)β Get current positionsgetPositionHistory(params)β Get historical positionstestConnection()β Test API connectivity
| Param | Values | Description |
|---|---|---|
side |
1=long, 2=close short, 3=short, 4=close long |
Order direction |
type |
1=limit, 3=IOC, 4=FOK, 5=market |
Order type |
openType |
1=isolated, 2=cross |
Margin mode |
| Event | Description |
|---|---|
orderUpdate |
Order status changes |
orderDeal |
Trade executions |
positionUpdate |
Position changes (PnL, margin, liquidation) |
assetUpdate |
Balance updates |
stopOrder |
Stop-loss / take-profit triggers |
tickers |
All symbol prices |
depth |
Order book updates |
kline |
Candlestick data |
- Dry-run mode β Verify parsing and sizing without submitting orders
- Idempotency β
bot-state.jsontracks processed message IDs; duplicate signals are never executed twice - Position limits β
MAX_CONCURRENT_TRADEScaps open positions - Notional cap β
MAX_NOTIONAL_PER_TRADElimits USDT value per trade - Symbol validation β Only trades active, API-allowed MEXC contracts
- Risk-based sizing β Volume calculated from equity, stop distance, and
RISK_PERCENT - Trading switch β
TRADING_ENABLED=falsedisables all order submission - Contract refresh β Caches MEXC contract list (5 min TTL)
This is an unofficial SDK. Use at your own risk. For issues and feature requests, please open a GitHub issue.
Join the Discord | Telegram Contact
MIT