SkillAgentSearch skills...

Pymexc

[Futures bypass] Unofficial python library for interacting with the MEXC crypto exchange

Install / Use

npx skills add makarworld/pymexc

Installs into whichever agent you are using.

About this skill

Quality Score

0/100

Supported Platforms

Universal

README

PyPI version License image Github last commit date

pymexc

pymexc is an unofficial Python library for interacting with the MEXC crypto exchange. It provides a simple and intuitive API for making requests to the MEXC API endpoints.

Base of code was taken from pybit library.

New: Futures Trading via Web API (bypass)

Futures trading via web API is now available in this repository.

  • How to get u_id - https://telegra.ph/pymexc-bypass--Get-U-ID-02-19

Create order example

from pymexc.web import futures

client = futures.HTTP(u_id="")

contract = "ETH_USDT"
price = client.index_price(symbol=contract)["data"]["indexPrice"]

order = client.order(
    symbol=contract,  # symbol
    side=1,  # side 1 - OPEN LONG | 3 - OPEN SHORT
    type=5,  # market
    open_type=1,  # isolated
    vol=200,  # 200 USDT volume
    price=price,  # index price
    leverage=4,  # 4x leverage
)

Total margin formula:

margin = (vol / price) / contractSize * leverage

Installation

You can install pymexc using pip:

pip install pymexc

Getting Started

To start working with pymexc, you must import spot or futures from the library. Each of them contains 2 classes: HTTP and WebSocket. To work with simple requests, you need to initialize the HTTP class. To work with web sockets you need to initialize the WebSocket class

Example

from pymexc import spot, futures

api_key = "YOUR API KEY"
api_secret = "YOUR API SECRET KEY"

def handle_message(message): 
    # handle websocket message
    print(message)


# SPOT V3

# initialize HTTP client
spot_client = spot.HTTP(api_key = api_key, api_secret = api_secret)
# initialize WebSocket client
ws_spot_client = spot.WebSocket(api_key = api_key, api_secret = api_secret)

# make http request to api
print(spot_client.exchange_info())

# create websocket connection to public channel (spot@public.deals.v3.api@BTCUSDT)
# all messages will be handled by function `handle_message`
ws_spot_client.deals_stream(handle_message, "BTCUSDT")


# FUTURES V1

# initialize HTTP client
futures_client = futures.HTTP(api_key = api_key, api_secret = api_secret)
# initialize WebSocket client
ws_futures_client = futures.WebSocket(api_key = api_key, api_secret = api_secret, 
                                      # subscribe on personal information about about account
                                      # if not provided, will not be subscribed
                                      # you can subsctibe later by calling ws_futures_client.personal_stream(callback) for all info
                                      # or ws_futures_client.filter_stream(callback, params={"filters":[{"filter":"..."}]}) for specific info (https://mexcdevelop.github.io/apidocs/contract_v1_en/#filter-subscription)
                                      personal_callback = handle_message)

# make http request to api
print(futures_client.index_price("MX_USDT"))

# create websocket connection to public channel (sub.tickers)
# all messages will be handled by function `handle_message`
ws_futures_client.tickers_stream(handle_message)

# loop forever for save websocket connection 
while True: 
    ...

Common Usage Examples

Getting Current Price and Market Data

from pymexc import spot

spot_client = spot.HTTP()

# Get current price
ticker = spot_client.ticker_price("BTCUSDT")
print(f"BTC Price: {ticker['price']}")

# Get 24h ticker statistics
stats = spot_client.ticker_24h("BTCUSDT")
print(f"24h Change: {stats['priceChangePercent']}%")
print(f"24h Volume: {stats['volume']}")

# Get order book
orderbook = spot_client.order_book("BTCUSDT", limit=10)
print(f"Best Bid: {orderbook['bids'][0]}")
print(f"Best Ask: {orderbook['asks'][0]}")

# Get recent trades
trades = spot_client.trades("BTCUSDT", limit=10)
for trade in trades:
    print(f"Price: {trade['price']}, Qty: {trade['qty']}")

Placing and Managing Orders

from pymexc import spot

spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET")

# Get current price first
ticker = spot_client.ticker_price("BTCUSDT")
current_price = float(ticker['price'])

# Place a limit buy order 1% below current price
buy_price = current_price * 0.99
result = spot_client.order(
    symbol="BTCUSDT",
    side="BUY",
    order_type="LIMIT",
    quantity=0.001,
    price=buy_price,
    time_in_force="GTC"
)
print(f"Order placed: {result}")

# Check order status
order_status = spot_client.query_order("BTCUSDT", order_id=result['orderId'])
print(f"Order status: {order_status['status']}")

# Get all open orders
open_orders = spot_client.current_open_orders("BTCUSDT")
print(f"Open orders: {len(open_orders)}")

# Cancel an order
if open_orders:
    cancel_result = spot_client.cancel_order("BTCUSDT", order_id=open_orders[0]['orderId'])
    print(f"Order cancelled: {cancel_result}")

Market Order Example

from pymexc import spot

spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET")

# Place a market buy order for $100 worth of BTC
result = spot_client.order(
    symbol="BTCUSDT",
    side="BUY",
    order_type="MARKET",
    quote_order_qty=100  # Buy $100 worth
)
print(f"Market order executed: {result}")

Getting Account Balance

from pymexc import spot

spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET")

# Get account information
account = spot_client.account_information()

# Print balances for assets with non-zero amounts
for balance in account['balances']:
    free = float(balance['free'])
    locked = float(balance['locked'])
    total = free + locked
    if total > 0:
        print(f"{balance['asset']}: Free={free}, Locked={locked}, Total={total}")

Getting Trading History

from pymexc import spot
import time

spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET")

# Get recent trades for a symbol
trades = spot_client.account_trade_list("BTCUSDT", limit=100)

# Calculate total volume and PnL
total_volume = 0
total_cost = 0
for trade in trades:
    qty = float(trade['qty'])
    price = float(trade['price'])
    total_volume += qty
    if trade['isBuyer']:
        total_cost += qty * price
    else:
        total_cost -= qty * price

print(f"Total Volume: {total_volume} BTC")
print(f"Net Cost: {total_cost} USDT")

Real-time Price Monitoring with WebSocket

from pymexc import spot
from pymexc.proto import PublicMiniTickerV3Api
import time

def handle_price_update(message):
    """Handle real-time price updates"""
    # WebSocket uses protobuf by default, so message is a protobuf object
    if isinstance(message, PublicMiniTickerV3Api):
        symbol = message.symbol if hasattr(message, "symbol") else "N/A"
        price = message.price if hasattr(message, "price") else "N/A"
        volume = message.volume if hasattr(message, "volume") else "N/A"
        print(f"{symbol}: Price={price}, Volume={volume}")
    elif isinstance(message, dict) and "d" in message:
        # Fallback for JSON format (if proto=False)
        data = message["d"]
        symbol = data.get("symbol", "N/A")
        price = data.get("p", "N/A")
        volume = data.get("v", "N/A")
        print(f"{symbol}: Price={price}, Volume={volume}")

# Initialize WebSocket client
ws_client = spot.WebSocket()

# Subscribe to ticker updates
ws_client.mini_ticker_stream(handle_price_update, "BTCUSDT")

# Keep connection alive
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Stopping...")
    ws_client.exit()

Monitoring Order Book Depth

from pymexc import spot
from pymexc.proto import PublicAggreDepthsV3Api
import time

def handle_depth_update(message):
    """Handle order book depth updates"""
    # WebSocket uses protobuf by default, so message is a protobuf object
    if isinstance(message, PublicAggreDepthsV3Api):
        bids = list(message.bids) if hasattr(message, "bids") else []
        asks = list(message.asks) if hasattr(message, "asks") else []
        
        if bids and asks:
            best_bid_price = float(bids[0].price) if bids and hasattr(bids[0], "price") else None
            best_ask_price = float(asks[0].price) if asks and hasattr(asks[0], "price") else None
            if best_bid_price and best_ask_price:
                spread = best_ask_price - best_bid_price
                print(f"Bid={best_bid_price}, Ask={best_ask_price}, Spread={spread:.2f}")
    elif isinstance(message, dict) and "d" in message:
        # Fallback for JSON format (if proto=False)
        data = message["d"]
        symbol = data.get("symbol", "N/A")
        bids = data.get("bids", [])
        asks = data.get("asks", [])
        
        if bids and asks:
            best_bid = bids[0][0] if bids else "N/A"
            best_ask = asks[0][0] if asks else "N/A"
            spread = float(best_ask) - float(best_bid) if best_ask != "N/A" and best_bid != "N/A" else 0
            print(f"{symbol}: Bid={best_bid}, Ask={best_ask}, Spread={spread:.2f}")

# Initialize WebSocket client
ws_client = spot.WebSocket()

# Subscribe to depth updates
ws_client.depth_stream(handle_depth_update, "BTCUSDT", interval="100ms")

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    ws_client.exit()

Getting Kline/Candlestick Data for Analysis

from pymexc impor

Related Skills

View on GitHub
GitHub Stars65
CategoryDevelopment
Updated5d ago
Forks30

Languages

Python

Security Score

100/100

Audited on Aug 2, 2026

No findings