Algorithmic Trading Basics
22 min read | Last reviewed: 11/10/2025 by GCP
Loading...
22 min read | Last reviewed: 11/10/2025 by GCP
You've learned to read charts, manage risk, and understand market microstructure. But what if you could trade 24/7, execute instantly, and never let emotions affect your decisions? That's the promise of algorithmic trading—using code to automate your strategies.
Algorithmic trading (or "algo trading") isn't just for hedge funds and high-frequency traders. With exchange APIs and modern tools, retail traders can automate strategies like DCA (dollar-cost averaging), grid trading, rebalancing, and even complex momentum strategies—all without writing a single line of code.
But automation isn't a magic bullet. Bots can amplify both profits and losses. A poorly designed bot can lose your entire account in minutes. This lesson teaches you the fundamentals: how algos work, when to use them, how to build simple bots, and—most importantly—how to avoid the traps that blow up 90% of beginner algo traders.
Let's demystify the robots.
Algorithmic trading is using computer programs (algorithms) to execute trades automatically based on predefined rules. Instead of manually clicking "buy" and "sell," you write rules like:
The algorithm monitors the market 24/7 and executes trades instantly when conditions are met—no human intervention required.
Advantages:
Disadvantages:
Bottom line: Algos are powerful tools, but they're not autopilot money printers. Treat them like power tools—useful, but dangerous if misused.
To automate trading, you need to talk to the exchange programmatically using its API (Application Programming Interface). APIs let your code:
Exchanges provide two types of APIs:
You send a request, the exchange sends back a response. Like visiting a website.
Example: "What's the current BTC price?"
GET https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT
Response: {"symbol":"BTCUSDT","price":"42150.50"}
Best for:
Limitations:
You open a persistent connection, and the exchange pushes updates to you instantly (no need to keep asking).
Example: "Send me every BTC trade as it happens"
// Open WebSocket connection
const ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");
// Receive real-time trades
ws.onmessage = (event) => {
const trade = JSON.parse(event.data);
console.log(`Price: ${trade.p}, Size: ${trade.q}`);
};
Best for:
Limitations:
To place trades (not just read data), you need API keys:
Security Best Practices:
Example disaster: A trader posts his code on GitHub with API keys hardcoded. Bots scrape GitHub, steal keys, and drain his account in 10 minutes. $50,000 gone.
Before building bots, understand how professional traders execute large orders. These algorithms minimize slippage and hide order size (see Lesson 19).
Goal: Execute a large order evenly over time.
How it works:
Advantages:
Disadvantages:
When to use: Low-volatility markets, when time is more important than price.
Goal: Execute orders in proportion to market volume.
How it works:
Advantages:
Disadvantages:
When to use: When you want to "blend in" with natural market activity.
Goal: Hide order size from other traders.
How it works:
Advantages:
Disadvantages:
When to use: Large orders in illiquid markets.
Example: Binance lets you set "Iceberg Qty" when placing limit orders. If you want to buy 100 BTC but only show 5 BTC at a time, set:
Before coding your own bot, try no-code bot platforms. These are beginner-friendly and let you test strategies without programming.
Strategy: Profit from volatility by placing buy and sell orders at fixed intervals.
How it works:
Best for: Ranging markets (price oscillates between $40K–44K for weeks).
Platforms:
Example Setup (Pionex):
Risks:
Strategy: Buy a fixed amount at regular intervals, regardless of price.
How it works:
Best for: Long-term investors who want to accumulate without timing the market.
Platforms:
Example: Invest $500/month in BTC via Swan. Over 12 months, you accumulate ~0.15 BTC (assuming $40K average price). No stress about timing the market.
Risks:
Strategy: Maintain a fixed portfolio allocation (e.g., 50% BTC, 50% USDT).
How it works:
Best for: Maintaining diversification, taking profits automatically.
Platforms:
Example: You want 40% BTC, 30% ETH, 30% USDT. Shrimpy rebalances daily, selling winners and buying losers. Over a year, this captures volatility without manual trades.
Risks:
If you want full control, build your own bot. Here's a simple grid trading bot in Python using CCXT (a library that connects to 100+ exchanges).
pip install ccxt
import ccxt
# Initialize Binance exchange
exchange = ccxt.binance({
'apiKey': 'YOUR_API_KEY',
'secret': 'YOUR_API_SECRET',
'enableRateLimit': True, # Respect rate limits
})
# Test connection
balance = exchange.fetch_balance()
print(f"USDT Balance: {balance['USDT']['free']}")
ticker = exchange.fetch_ticker('BTC/USDT')
current_price = ticker['last']
print(f"BTC Price: ${current_price}")
# Buy 0.01 BTC at $41,000
order = exchange.create_limit_buy_order(
symbol='BTC/USDT',
amount=0.01,
price=41000
)
print(f"Order placed: {order['id']}")
# Grid bot parameters
symbol = 'BTC/USDT'
grid_levels = 10
price_range = 2000 # $2000 range above/below current price
investment = 5000 # $5000 USDT
# Calculate grid
current_price = exchange.fetch_ticker(symbol)['last']
lower_bound = current_price - price_range / 2
upper_bound = current_price + price_range / 2
grid_step = price_range / grid_levels
# Place buy orders below current price
for i in range(grid_levels // 2):
price = current_price - (i + 1) * grid_step
amount = (investment / grid_levels) / price
exchange.create_limit_buy_order(symbol, amount, price)
print(f"Buy order at ${price}")
# Place sell orders above current price
for i in range(grid_levels // 2):
price = current_price + (i + 1) * grid_step
amount = (investment / grid_levels) / price
exchange.create_limit_sell_order(symbol, amount, price)
print(f"Sell order at ${price}")
Warning: This is a simplified example. A production bot needs:
Don't run bots on your laptop (you'll close it, lose connection). Use a cloud server:
Deploy your bot, run it in the background using screen or tmux, and monitor logs remotely.
Once you master grid/DCA bots, explore advanced strategies:
Strategy: Buy on Exchange A (lower price), sell on Exchange B (higher price).
Example: BTC is $42,000 on Binance, $42,200 on Kraken. Buy on Binance, sell on Kraken, profit $200 (minus fees).
Challenges:
Tools: Hummingbot (open-source arbitrage bot), Coinigy (cross-exchange tracking)
Strategy: Place buy and sell orders around current price, profit from the spread.
Example: BTC is $42,000. Place buy at $41,990, sell at $42,010. When both fill, profit $20 (0.05%).
Challenges:
Tools: Hummingbot (market making strategies), Maker DAO Keeper (Ethereum-based)
Strategy: When price deviates far from average, bet on reversion.
Example: BTC's 50-day moving average is $42,000. Price drops to $38,000 (10% below). Bot buys, expecting reversion to $42,000.
Challenges:
Tools: Freqtrade (open-source bot with mean reversion strategies)
Never run an untested bot with real money. Backtest first (see Lesson 18).
Freqtrade (Open-Source, Python)
TradingView (Pine Script)
Backtrader (Python Library)
Backtesting Checklist:
Example Backtest Result (Grid Bot):
Conclusion: Strategy is profitable, but only 14% annual return after fees. Is it worth the complexity vs. just holding BTC (which returned +60% in 2023)? Maybe not.
Bots can fail spectacularly. Protect yourself:
Configure your bot to stop trading if it loses more than X%:
if total_loss > 0.10 * starting_balance:
# Stop bot, send alert
send_telegram_alert("Bot stopped: 10% loss limit hit")
exit()
Start with 1–5% of your portfolio in the bot. If it works, scale up.
Example: $50K portfolio → start with $2,500 in bot. If bot loses 100%, you lose $2,500 (5%), not $50,000.
Check bot performance every day:
If bot underperforms backtest by 50%+ for 2 weeks → turn it off, investigate.
# .env file (never commit to GitHub)
BINANCE_API_KEY=abc123
BINANCE_API_SECRET=xyz789
import os
api_key = os.getenv('BINANCE_API_KEY')
api_secret = os.getenv('BINANCE_API_SECRET')
Always have a way to instantly stop the bot:
/stop sends a signal to stop tradingpkill -f bot.py)Mistake: Optimize bot to perfection on 2023 data (95% win rate!), then it fails in 2024.
Why: You overfitted to past data. Strategy has 20 parameters tuned to 2023's specific conditions.
Solution: Use walk-forward testing (train on 2021–2022, test on 2023, validate on 2024).
Mistake: Backtest shows 30% annual return, but live bot loses money.
Why: Backtest didn't include fees. Bot makes 500 trades/month × 0.1% fees = 50% of capital in fees.
Solution: Always include fees in backtests. Use maker orders (0.01–0.05%) instead of taker (0.1–0.5%).
Mistake: Exchange goes down for 2 hours. Bot can't cancel orders. Price crashes. Orders fill at terrible prices.
Why: No contingency plan for exchange outages.
Solution: Set max order lifetime (cancel orders if not filled within 1 hour) and use stop-loss orders.
Mistake: Bot runs on your laptop. You close lid, connection drops, bot stops. You miss 12 hours of trading.
Why: Bots need 24/7 uptime.
Solution: Use a cloud server ($5/month) or Raspberry Pi (one-time $50, runs 24/7 at home).
Mistake: Bot loses $2,000. You have no idea why (no trade history, no error logs).
Why: You didn't log trades, errors, or decisions.
Solution: Log everything:
import logging
logging.basicConfig(filename='bot.log', level=logging.INFO)
logging.info(f"Buy order placed: {symbol} at ${price}, amount {amount}")
logging.error(f"API error: {error}")
Algorithmic trading is powerful, but it's not a substitute for skill. A bad strategy automated is just a faster way to lose money. Master manual trading first, then automate.
Question 1: What is the main advantage of using a WebSocket API over a REST API?
A) WebSocket APIs have no rate limits B) WebSocket APIs provide real-time data streams without repeated requests C) WebSocket APIs are easier to implement D) WebSocket APIs are more secure
Question 2: What is a TWAP algorithm designed to do?
A) Maximize profit by buying at the lowest price B) Execute a large order evenly over time to minimize market impact C) Place fake orders to manipulate the market D) Only execute during high-volume periods
Question 3: You backtest a grid bot on 2023 data and get 30% returns. In live trading in 2024, it loses 5%. What's the most likely cause?
A) Exchange fees weren't included in the backtest B) The strategy was overfitted to 2023 market conditions C) 2024 market has different volatility/trends than 2023 D) All of the above
Question 4: What is the biggest risk of running a trading bot on your personal laptop?
A) The bot will use too much CPU B) Connection drops when you close the lid, causing missed trades C) Laptops are too slow for algorithmic trading D) API keys are less secure on laptops
Question 5: You set up a grid bot with 20 levels in a $40K–$44K range. BTC suddenly pumps to $60K. What happens?
A) The bot automatically adjusts the grid to $56K–$60K B) The bot keeps running and profits from the pump C) The bot sold all BTC around $44K and missed the 50% gain D) The bot stops trading when price exits the grid
Answers: 1-B, 2-B, 3-D, 4-B, 5-C