I Connected to a Crypto Exchange API in 3 Lines of Python

Published: (March 28, 2026 at 12:46 AM EDT)
5 min read
Source: Dev.to

Source: Dev.to

I needed to connect to a crypto exchange to build a trading bot

APIs sounded intimidating. Then I installed one Python library and got my balance in three lines. Getting from there to placing actual orders wasn’t much harder.

Here’s the whole path — from creating an account to placing your first order in Python, including every mistake I made along the way.

What’s an API Key, Anyway?

It’s a password that lets your code talk to the exchange directly, without logging into the website. You hand this key to your Python script, and suddenly your code can:

  • Check balances
  • Pull price data
  • Place orders

Why bother? Manual trading means staring at charts 24/7. You miss the 3 AM crash because you’re asleep, or you hold too long because “maybe it’ll go higher.” An API lets you hand that job to a bot.

Picking an Exchange

For automated trading, fees matter more than anything else. When your bot trades ten times a month, a 0.1 % difference in fees compounds over a year.

ExchangeMaker FeeGlobal Accessccxt Support
MEXC0 % (Spot)YesYes
Bitget0.1 %YesYes
OKX0.08 %YesYes

I run my bot on Bitget, but if I were starting today I’d go with MEXC – zero maker fees on spot. For a bot that trades automatically, that’s free money you’re not leaving on the table. Account creation is free and takes about five minutes.

Creating Your API Key

Once you have an account:

  1. Log in → Profile iconAPI Management
  2. Click “Create API Key”
  3. Permissions: enable Read and Trade. Leave Withdraw OFF – seriously, never turn this on.
  4. Copy the API key and secret

Save them in a .env file in your project:

API_KEY=your_api_key_here
API_SECRET=your_secret_here

Add .env to your .gitignore before your first commit. If you push your API key to GitHub, congratulations — you just published your exchange credentials to the entire internet.

Connecting with ccxt

ccxt is a Python library that talks to 100+ exchanges with the same interface. Code you write for MEXC works on Bitget, Binance, OKX — same syntax.

pip install ccxt python-dotenv

Fetching your balance (the three‑liner)

import ccxt
import os
from dotenv import load_dotenv

load_dotenv()

exchange = ccxt.mexc({
    'apiKey': os.getenv('API_KEY'),
    'secret': os.getenv('API_SECRET'),
    'enableRateLimit': True,   # throttle requests automatically
})

# The actual work — three lines
balance = exchange.fetch_balance()
usdt = balance['USDT']['total']
print(f'USDT balance: {usdt}')

That’s it. It works.

enableRateLimit: True tells ccxt to throttle requests automatically. Without it you’ll hammer the API too fast and get 429 errors.

Grabbing candlestick data

ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d', limit=30)
# → [[timestamp, open, high, low, close, volume], ...]

One line gets you 30 days of daily candles. Throw that into a pandas DataFrame, compute your indicators, and you’ve got the bones of a trading bot.

Placing Your First Order

Do not start with real money. Build a DRY_RUN mode first. Your code goes through the entire pipeline — fetching prices, computing signals, deciding whether to buy — but skips the final step of actually sending the order.

Run in DRY_RUN for a week. If nothing weird happens, switch to live with a tiny amount (e.g., $1 USDT).

# Market buy
if not DRY_RUN:
    order = exchange.create_market_buy_order('BTC/USDT', amount)
    print(f'Order placed: {order["id"]}')
else:
    print(f'[DRY_RUN] Skipping order: BTC/USDT {amount}')

Simple. Use create_market_buy_order for market orders, create_limit_buy_order for limit orders. ccxt abstracts away the differences between exchanges, so code written for MEXC runs on Bitget too (in theory – in practice there are occasional quirks, but it mostly just works).

Things That Tripped Me Up

Every mistake below is one I actually made.

IssueWhat HappenedFix / Mitigation
Rate limitsHitting the API in a tight loop during development caused 429 errors even with enableRateLimit.Keep it to ~1 request per second, or add explicit time.sleep(1) in loops.
Withdrawal permission enabledAccidentally turned on withdrawals when creating the first key.Keep withdrawals OFF. If you ever enable them, regenerate the key immediately.
Committing .env to gitPushed API keys to a public repo.Add .env to .gitignore before the first commit. If you already pushed, revoke the key and generate a new one.
Timestamp driftComputer clock off by a few minutes → InvalidNonce / Timestamp outside recv_window.Enable NTP time sync (e.g., ntpdate pool.ntp.org on Linux).
Minimum order amountsTried to place a $1 order on Bitget; it failed silently.Check each exchange’s minimum order size (Bitget ≈ $5 for BTC/USDT spot, MEXC ≈ $1).

If you don’t have an exchange account yet, you can create one here. Zero fees really does make a difference when you’re running a bot.

Wrapping Up

API access turned out to be way easier than I expected. ccxt handles the messy parts — authentication, rate limiting, exchange‑specific quirks — so you can focus on the strategy itself. Happy coding, and trade responsibly!

Quick Setup Checklist

  • Withdrawal permissionsOFF
  • .env → never commit to Git
  • Start with DRY_RUN
  • First live test$1 USDT

Once you have this working, the next step is to write the trading logic: compute a technical indicator, generate a signal, and execute the trade. I began with an EMA Crossover strategy—​that’s a story for another post.

This post is based on personal experience. Not financial advice—trade at your own risk with money you can afford to lose. This post contains affiliate links.

0 views
Back to Blog

Related posts

Read more »