Skip to main content

A fully typed, validated async client for the MEXC API.

Project description

Typed MEXC

A fully typed, validated async client for the MEXC API

Use autocomplete instead of documentation.

from mexc import MEXC

async with MEXC.new() as client:
    account = await client.spot.account()
    for balance in account['balances']:
        if float(balance['free']) > 0:
            print(f"{balance['asset']}: {balance['free']}")

Why Typed MEXC?

  • 🎯 Precise Types: Literal types, not strings. Your IDE knows exactly what's valid.
  • ✅ Automatic Validation: Pydantic-powered response validation catches API changes instantly.
  • ⚡ Async First: Built on httpx for high-performance async operations.
  • 🔒 Type Safety: Full type hints throughout. Catch errors before runtime.
  • 🎨 Beautiful DX: No unnecessary imports, sensible defaults, optional complexity.
  • 📦 Batteries Included: Pagination helpers, WebSocket streams for real-time data.

Installation

pip install typed-mexc

Quick Start

1. Set up API credentials

export MEXC_ACCESS_KEY="your_access_key"
export MEXC_SECRET_KEY="your_secret_key"

2. Start trading

from mexc import MEXC

async with MEXC.new() as client:
    # Get spot account info
    account = await client.spot.account()
    
    # Get futures positions
    positions = await client.futures.positions()
    
    # Get funding rate
    rate = await client.futures.funding_rate(symbol='BTC_USDT')

Features

No Unnecessary Imports

Notice something? You never imported Literal types. Just use strings:

# ❌ Other libraries
from some_sdk import Interval
candles = await client.get_candles(symbol='BTCUSDT', interval=Interval.M1)

# ✅ Typed MEXC
candles = await client.spot.candles(
    'BTCUSDT', interval='1m'  # Your IDE autocompletes this!
)

Precise Type Annotations

Every field is precisely typed. Prices are strings (for precision), timestamps are datetime where applicable:

from datetime import datetime

account = await client.spot.account()
for balance in account['balances']:
    asset: str = balance['asset']
    free: str = balance['free']  # String for decimal precision

Automatic Validation

Response validation is on by default but can be disabled:

# Validated (default) - throws ValidationError if API response changes
account = await client.spot.account()

# Skip validation for maximum performance
account = await client.spot.account(validate=False)

Built-in Pagination

# Manual pagination
candles = await client.spot.candles(
    'BTCUSDT', interval='1m', limit=500
)

# Automatic pagination - yields chunks as they arrive
async for chunk in client.spot.candles_paged(
    'BTCUSDT', interval='1m', start=start, end=end
):
    for candle in chunk:
        print(f"Candle: {candle['open']} -> {candle['close']}")

WebSocket Streams

Real-time market and user data via WebSockets:

async with MEXC.new() as client:
    # Spot: subscribe to candles (public stream)
    async for candle in client.spot.streams.candles('BTCUSDT', interval='Min1'):
        print(candle)
    
    # Futures: subscribe to tickers
    async for tickers in client.futures.streams.tickers():
        print(tickers)

API Coverage

This library covers Spot and Futures with market data, trading, user data, and WebSocket streams.

  • Spot: Account, candles, depth, trades, orders (place/cancel), wallet (deposits, withdrawals)
  • Futures: Positions, assets, funding rates, contracts, candles, depth, user streams

📋 See API Overview for complete coverage details.

Documentation

Design Philosophy

Typed MEXC follows the principles outlined in this blog post:

  1. Inputs shouldn't require custom imports - Use string literals, not enums
  2. Annotate types precisely - TypedDict, strings for prices, Literal for enums
  3. Avoid unnecessary complication - Sensible defaults, optional complexity
  4. Provide extra behavior optionally - Pagination and validation are opt-in

Details matter. Developer experience matters.

Examples

Portfolio Tracking

async with MEXC.new() as client:
    account = await client.spot.account()
    
    total_held = sum(
        float(b['free']) + float(b['locked'])
        for b in account['balances']
        if float(b['free']) > 0 or float(b['locked']) > 0
    )
    print(f"Spot Balance: {total_held}")

Trading Bot

async with MEXC.new() as client:
    # Get open orders
    orders = await client.spot.open_orders(symbol='BTCUSDT')
    
    # Place limit order
    result = await client.spot.place_order(
        'BTCUSDT',
        {'side': 'BUY', 'type': 'LIMIT', 'price': '50000', 'quantity': '0.001'}
    )

Funding Rate Monitor

async with MEXC.new() as client:
    rate = await client.futures.funding_rate(symbol='BTC_USDT')
    print(f"Funding rate: {rate['fundingRate']}")

Error Handling

from mexc import MEXC
from mexc.core import ApiError, ValidationError, NetworkError

async with MEXC.new() as client:
    try:
        account = await client.spot.account()
    except ValidationError:
        # API response doesn't match expected schema
        pass
    except ApiError as e:
        # MEXC API returned an error
        print(f"API Error: {e}")
    except NetworkError:
        # Network/connection issue
        pass

Contributing

This is a work in progress! Contributions are welcome. The codebase is designed to be:

  • Consistent: All endpoints follow the same patterns
  • Type-safe: Everything is fully typed
  • Validated: Pydantic models for all responses

Inspired by this blog post on building better API clients.

Built with ❤️ by Tribulnation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typed_mexc-0.2.0.tar.gz (37.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typed_mexc-0.2.0-py3-none-any.whl (71.6 kB view details)

Uploaded Python 3

File details

Details for the file typed_mexc-0.2.0.tar.gz.

File metadata

  • Download URL: typed_mexc-0.2.0.tar.gz
  • Upload date:
  • Size: 37.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.10

File hashes

Hashes for typed_mexc-0.2.0.tar.gz
Algorithm Hash digest
SHA256 17cce701a2df11cd77980c817b78bee9eeca7274af764b1b5e0f61ebf227480b
MD5 d25ec710147564f6c05ce0ad5bf5a059
BLAKE2b-256 b53cef9f32a9e4e6e14ace3caf0cce3f1c7eeba56e475d8f507c28acb63d61a8

See more details on using hashes here.

File details

Details for the file typed_mexc-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: typed_mexc-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 71.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.10

File hashes

Hashes for typed_mexc-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 84206e61beab915730af76bb22c27d109e91883db9e0f236044f15317a13e66b
MD5 cdb8cfb9eb2c000e5fa05edacbe5ac0d
BLAKE2b-256 3bdf02e28f89d505c9ebc6c8ced15740ba8ca25cd7f940dde861fafbb8fa9bba

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page