← Back to Blog
TUTORIALS

LMEX API Python Tutorial: Connect, Authenticate and Place Your First Order

May 29, 2026 · 12 min read · LMEX.AI

If you're new to programmatic trading on LMEX, this tutorial gets you from "nothing installed" to "placed your first authenticated order" in under 30 minutes. It assumes basic Python familiarity but no prior trading API experience.


Step 1: Generate API keys


Log into your LMEX account, navigate to Account → API Management, and create a new key.


A few decisions to make at this step:


**Permissions:** Start with Read-only. Don't enable Trading until you've verified the read-only access works. Enabling Wallet permission lets the bot check balances; that's needed for almost any strategy.


**IP restrictions:** If you're running from a fixed server, restrict the key to that IP. If you're testing locally, you can skip this initially but should enable it before going live.


**Withdrawal permission:** Never enable this for a trading bot. There's no legitimate reason a trading bot needs to withdraw funds, and enabling it dramatically increases the impact of a compromised key.


Save both the API key and secret somewhere safe. The secret is shown only once.


Step 2: Install dependencies


Use a fresh Python environment to avoid version conflicts:


python3 -m venv lmex-env
source lmex-env/bin/activate  # On Windows: lmex-env\Scripts\activate
pip install ccxt python-dotenv

CCXT is the standard library for connecting to crypto exchanges. As of this year, LMEX is fully supported in CCXT.


Step 3: Set up credentials


Create a `.env` file in your project folder:


LMEX_API_KEY=your_key_here
LMEX_API_SECRET=your_secret_here

Add `.env` to your `.gitignore` immediately. Credentials in source control is the most common way bots get hacked.


Then load them in Python:


import os
from dotenv import load_dotenv

load_dotenv()
api_key = os.getenv('LMEX_API_KEY')
api_secret = os.getenv('LMEX_API_SECRET')

Step 4: Connect and verify


A minimal connection test:


import ccxt

exchange = ccxt.lmex({
    'apiKey': api_key,
    'secret': api_secret,
    'enableRateLimit': True,
})

# Test connection with a public endpoint
ticker = exchange.fetch_ticker('BTC-PERP')
print(f"BTC-PERP last price: {ticker['last']}")

# Test authentication with a private endpoint
balance = exchange.fetch_balance()
print(f"USDT balance: {balance['USDT']['free']}")

If the first line prints a price, you're connected. If the second prints your balance, authentication works.


Common errors at this step:


  • `AuthenticationError`: API key or secret is wrong. Double-check for whitespace.
  • `PermissionDenied`: Your API key doesn't have Wallet permission. Update key permissions.
  • `NetworkError`: Your network can't reach api.lmex.io. Check firewall or VPN.

  • Step 5: Fetch market data


    The most common operations:


    # Current price
    ticker = exchange.fetch_ticker('BTC-PERP')
    print(f"Bid: {ticker['bid']}, Ask: {ticker['ask']}, Last: {ticker['last']}")
    
    # Order book
    orderbook = exchange.fetch_order_book('BTC-PERP', limit=10)
    print(f"Best bid: {orderbook['bids'][0]}")
    print(f"Best ask: {orderbook['asks'][0]}")
    
    # Recent trades
    trades = exchange.fetch_trades('BTC-PERP', limit=10)
    for t in trades:
        print(f"{t['datetime']} {t['side']} {t['amount']} @ {t['price']}")
    
    # Historical candles
    candles = exchange.fetch_ohlcv('BTC-PERP', '1h', limit=24)
    for c in candles:
        print(f"{c[0]}: O={c[1]} H={c[2]} L={c[3]} C={c[4]} V={c[5]}")

    These methods work without API keys (public endpoints) so they're a good place to verify before doing anything authenticated.


    Step 6: Place your first order


    Once read-only access works, enable Trading permission on your API key and try a small order:


    # Get current price to size correctly
    ticker = exchange.fetch_ticker('BTC-PERP')
    current_price = ticker['last']
    
    # Place a limit buy order well below market (won't fill, just for testing)
    test_price = current_price * 0.5  # 50% below market
    test_qty = 0.001  # smallest meaningful size
    
    order = exchange.create_order(
        symbol='BTC-PERP',
        type='limit',
        side='buy',
        amount=test_qty,
        price=test_price,
    )
    
    print(f"Order placed: {order['id']}")
    
    # Check the order
    order_status = exchange.fetch_order(order['id'], 'BTC-PERP')
    print(f"Status: {order_status['status']}")
    
    # Cancel the order
    exchange.cancel_order(order['id'], 'BTC-PERP')
    print("Order cancelled")

    If this works end-to-end, you can place, query, and cancel orders. That's the foundation of every trading strategy.


    Step 7: Common operations


    The complete toolkit:


    # Place a market order (caution: fills immediately)
    market_order = exchange.create_order('BTC-PERP', 'market', 'buy', 0.001)
    
    # Place a stop-loss
    stop_order = exchange.create_order(
        'BTC-PERP', 'stop', 'sell', 0.001, None,
        {'stopPrice': 55000}
    )
    
    # Get open orders
    open_orders = exchange.fetch_open_orders('BTC-PERP')
    for o in open_orders:
        print(f"{o['side']} {o['amount']} @ {o['price']}")
    
    # Get position
    positions = exchange.fetch_positions(['BTC-PERP'])
    for p in positions:
        if p['contracts'] > 0:
            print(f"Position: {p['side']} {p['contracts']} @ {p['markPrice']}")
            print(f"Unrealized PnL: {p['unrealizedPnl']}")
    
    # Cancel all orders for a symbol
    exchange.cancel_all_orders('BTC-PERP')

    These cover 90% of what most strategies need.


    Common gotchas


    **Symbol format.** LMEX uses `BTC-PERP` (with hyphen). Some exchanges use `BTC/USDT:USDT` (CCXT's unified format). For LMEX, both work but `BTC-PERP` is canonical.


    Quantity precision. LMEX has minimum order sizes and precision limits per symbol. Use `exchange.amount_to_precision('BTC-PERP', 0.0123456)` to round correctly.


    **Price precision.** Same — `exchange.price_to_precision('BTC-PERP', 60123.456)`.


    **Rate limits.** LMEX limits API calls per second/minute. Use `enableRateLimit: True` in your config; CCXT will automatically throttle.


    **Testnet vs mainnet.** Add `'options': {'testnet': True}` to test with testnet. Switch to `False` for live trading.


    What to do next


    After this tutorial, you have working connection code. The next steps:


    1. Run your read-only code for a few days to make sure it stays connected

    2. Plan a strategy and write its logic in a separate file

    3. Test the strategy on testnet for at least 2 weeks

    4. Add risk management (see our portfolio risk article)

    5. Go live with the smallest possible size

    6. Scale up only after weeks of stable operation


    The rush to "deploy live with real money" is the #1 cause of bot failures. Take your time at each step.


    Frequently Asked Questions


    Q: Should I use the LMEX native Python SDK or CCXT?

    CCXT is easier to learn and supports more strategies portable across exchanges. The native SDK gives slightly better feature coverage. Start with CCXT.


    Q: How do I get historical data for backtesting?

    `exchange.fetch_ohlcv('BTC-PERP', '1h', limit=1000)` gets the last 1000 hourly candles. For longer histories, paginate using the `since` parameter. For very long histories, consider third-party data providers.


    Q: What rate limit should I worry about?

    LMEX allows several hundred requests per second per IP. Most retail bots stay well under this. If you're hitting limits, you're probably polling too aggressively — use WebSocket for streaming data instead.


    Q: How do I keep my API keys safe?

    Use environment variables or a secrets manager. Never put them in code. Never commit them. Restrict by IP. Use Read-only or Wallet+Trading only — never enable Withdrawal. Rotate keys every few months.


    Related Articles


    → Building a Crypto Perpetuals Trading Bot in Python: Complete Guide
    → We Added LMEX to CCXT — Stop Writing Custom API Wrappers
    → WebSocket vs REST for Trading Bots: When Each One Wins
    ← All ArticlesBuild a Bot →