DEV Community

maymay5692
maymay5692

Posted on

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

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, and place orders.

Why bother? Because manual trading means staring at charts 24/7. You miss the 3 AM crash because you're asleep. 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.

Exchange Maker Fee Global Access ccxt Support
MEXC 0% (Spot) Yes Yes
Bitget 0.1% Yes Yes
OKX 0.08% Yes Yes

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 icon → API 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Fetching your balance. This is 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,
})

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

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 is just as easy:

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

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 ($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}')
Enter fullscreen mode Exit fullscreen mode

Simple. 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 here is one I actually made.

Rate limits. During development, I was hitting the API in a loop while testing. Even with enableRateLimit: True, rapid-fire requests in a tight loop can exceed the limit. Keep it to about one request per second to be safe.

Accidentally enabling withdrawal permissions. I turned on withdrawal when creating my first key. Caught it fast and turned it back off, but if my .env had leaked, someone could have drained my entire account. Withdrawal permissions stay OFF. Always.

Committing .env to git. Classic. If you commit and push before adding .env to .gitignore, it's in the git history forever. Force-pushing doesn't fully remove it. Set up .gitignore first. If you mess this up, immediately regenerate your API keys.

Timestamp drift. If your computer's clock is off by a few minutes, the exchange rejects your API calls. You'll see errors like InvalidNonce or Timestamp outside recv_window. Make sure NTP time sync is enabled. (Macs do this automatically; WSL and some Linux setups don't.)

Minimum order amounts. Every exchange has minimum order sizes, and they vary. Bitget requires ~$5 for BTC/USDT spot orders. Try to place a $1 order and it fails silently or throws an error. MEXC lets you go as low as $1, which makes it better for small-scale testing.

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 don't have to learn each exchange's API docs.

The important stuff:

  • Withdrawal permissions → OFF
  • .env → never in git
  • Start with DRY_RUN
  • First live test → $1 USDT

Once you've got this working, the next step is writing the trading logic — compute a technical indicator, generate a signal, execute. I started 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.

Top comments (0)