Algorithmic Trading Basics

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.


What is Algorithmic Trading?

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:

  • "Buy 0.1 BTC every Monday at 9 AM" (DCA bot)
  • "Place buy orders every $500 below current price, sell orders every $500 above" (grid bot)
  • "If RSI drops below 30, buy; if RSI rises above 70, sell" (indicator bot)

The algorithm monitors the market 24/7 and executes trades instantly when conditions are met—no human intervention required.

Why Algorithmic Trading?

Advantages:

  1. 24/7 execution: Crypto markets never sleep. Bots trade while you sleep.
  2. Discipline: Bots follow rules exactly—no emotional decisions, no FOMO, no panic selling.
  3. Speed: Bots react in milliseconds. Humans take seconds to minutes.
  4. Scalability: One bot can monitor 100 pairs simultaneously. Humans can watch maybe 5.
  5. Backtesting: Test strategies on historical data before risking real money.

Disadvantages:

  1. Technical complexity: Requires coding, API knowledge, server management.
  2. Overfitting risk: Strategies that work in backtests fail in live markets (see Lesson 18).
  3. Black swan events: Bots can't handle unexpected events (exchange outages, flash crashes, regulation changes).
  4. Security risks: API keys can be stolen. Bugs can drain accounts.
  5. Competition: You're competing against professional hedge funds with PhDs and millions in infrastructure.

Sources

  • Algorithmic Trading: Winning Strategies - Ernest P. Chan
  • Inside the Black Box - Rishi K. Narang
  • Binance API Documentation
  • CCXT Library Documentation

This content is for educational purposes only and is not financial advice. License: CC-BY-NC.

Bottom line: Algos are powerful tools, but they're not autopilot money printers. Treat them like power tools—useful, but dangerous if misused.


Exchange APIs: The Gateway to Automation

To automate trading, you need to talk to the exchange programmatically using its API (Application Programming Interface). APIs let your code:

  • Fetch market data (prices, order book, trade history)
  • Place orders (market, limit, stop)
  • Check account balances
  • Monitor open orders

REST APIs vs WebSocket APIs

Exchanges provide two types of APIs:

1. REST API (Request-Response)

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:

  • Fetching data infrequently (once per minute, once per hour)
  • Placing orders (buy/sell)
  • Checking balances

Limitations:

  • Rate limits: Exchanges limit requests (e.g., 1200 requests/minute). Exceed this = banned.
  • Latency: Each request takes 50–200ms. Too slow for high-frequency strategies.

2. WebSocket API (Real-Time Stream)

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:

  • Real-time price monitoring
  • Order book updates
  • Trade execution alerts

Limitations:

  • More complex to implement
  • Connection can drop (requires reconnection logic)

API Keys: Your Access Pass

To place trades (not just read data), you need API keys:

  1. API Key: Your username (public)
  2. API Secret: Your password (private, NEVER share)

Security Best Practices:

  • ✅ Enable IP whitelisting: Only allow API access from your server's IP
  • ✅ Restrict permissions: Enable "Trade" only, disable "Withdraw"
  • ✅ Use separate keys for each bot: If one key is compromised, others are safe
  • ✅ Store secrets in environment variables: Never hardcode in your code
  • ❌ NEVER share API secrets: Not in GitHub, not in Discord, not anywhere

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.


Execution Algorithms: How Big Players Execute

Before building bots, understand how professional traders execute large orders. These algorithms minimize slippage and hide order size (see Lesson 19).

1. TWAP (Time-Weighted Average Price)

Goal: Execute a large order evenly over time.

How it works:

  • Want to buy 1,000 BTC over 10 hours
  • Split into 100 orders of 10 BTC each
  • Place 1 order every 6 minutes

Advantages:

  • Minimizes market impact (no sudden price spike)
  • Simple to implement

Disadvantages:

  • Ignores market conditions (buys even when price is spiking)
  • Predictable (other algos can detect and front-run)

When to use: Low-volatility markets, when time is more important than price.

2. VWAP (Volume-Weighted Average Price)

Goal: Execute orders in proportion to market volume.

How it works:

  • Historical data shows BTC has high volume at 9 AM, 12 PM, 6 PM
  • Place larger orders during high-volume periods
  • Place smaller orders during low-volume periods

Advantages:

  • Matches market liquidity (less slippage)
  • Harder to detect than TWAP

Disadvantages:

  • Requires historical volume data
  • More complex to implement

When to use: When you want to "blend in" with natural market activity.

3. Iceberg Orders (Native Exchange Feature)

Goal: Hide order size from other traders.

How it works:

  • Want to buy 1,000 BTC
  • Show only 10 BTC in the order book
  • When 10 BTC fills, automatically replace with another 10 BTC
  • Repeat until all 1,000 BTC is filled

Advantages:

  • Prevents front-running (others don't see your full size)
  • Built into most exchanges (no coding required)

Disadvantages:

  • Only works for limit orders (not market orders)
  • May take longer to fill

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:

  • Total Quantity: 100 BTC
  • Iceberg Qty: 5 BTC

Simple Trading Bots (No Code Required)

Before coding your own bot, try no-code bot platforms. These are beginner-friendly and let you test strategies without programming.

1. Grid Trading Bots

Strategy: Profit from volatility by placing buy and sell orders at fixed intervals.

How it works:

  • BTC is at $42,000
  • Place buy orders at: $41,500, $41,000, $40,500
  • Place sell orders at: $42,500, $43,000, $43,500
  • When price drops to $41,500, bot buys
  • When price rises back to $42,500, bot sells (profit = $1,000)
  • Repeat indefinitely

Best for: Ranging markets (price oscillates between $40K–44K for weeks).

Platforms:

  • 3Commas: $14.50–$49.50/month, visual grid builder
  • Pionex: Free built-in grid bot (exchange charges 0.05% fees)
  • Bitsgap: $29–$149/month, supports 15+ exchanges

Example Setup (Pionex):

  1. Select BTC/USDT pair
  2. Set price range: $40,000–$44,000
  3. Set grid levels: 20 (bot creates 20 buy/sell orders)
  4. Invest $5,000 USDT
  5. Bot runs 24/7, profits from each oscillation

Risks:

  • Trending markets: If BTC pumps to $60,000, you sold at $43,500 (missed 40% gains)
  • Crashes: If BTC dumps to $20,000, you're holding heavy bags
  • Fees: 40 trades/day × 0.1% fees = 4% daily (eats profits fast)

2. DCA (Dollar-Cost Averaging) Bots

Strategy: Buy a fixed amount at regular intervals, regardless of price.

How it works:

  • Buy $100 of BTC every Monday at 9 AM
  • If price is $40K, you get 0.0025 BTC
  • If price is $50K, you get 0.002 BTC
  • Over time, average cost smooths out volatility

Best for: Long-term investors who want to accumulate without timing the market.

Platforms:

  • Swan Bitcoin: $10 minimum, auto-buys BTC, 0.99–1.49% fees
  • River Financial: $1 minimum, 0.5–1.5% fees
  • Coinbase recurring buys: Free, but high spreads (1–2%)

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:

  • Bear markets: You keep buying as price drops (paper losses pile up)
  • Fees: 1% fee on $500 = $5. Over 12 months = $60 in fees (12% of first month's investment)

3. Rebalancing Bots

Strategy: Maintain a fixed portfolio allocation (e.g., 50% BTC, 50% USDT).

How it works:

  • Start with $10,000: $5,000 BTC, $5,000 USDT
  • BTC pumps 20% → portfolio is now $6,000 BTC, $5,000 USDT (55% BTC, 45% USDT)
  • Bot sells $500 of BTC, buys $500 USDT → back to 50/50
  • BTC dumps 20% → bot buys BTC with USDT → back to 50/50

Best for: Maintaining diversification, taking profits automatically.

Platforms:

  • Shrimpy: $19–$79/month, rebalances hourly/daily/weekly
  • 3Commas: Includes rebalancing in higher-tier plans

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:

  • Trending markets: Rebalancing sells winners early (caps upside)
  • Fees: Daily rebalancing = 730 trades/year. At 0.1% fees = 73% of portfolio in fees (devastating)

Building Your First Bot (Code-Based)

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).

Step 1: Install CCXT

pip install ccxt

Step 2: Connect to Exchange

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']}")

Step 3: Fetch Current Price

ticker = exchange.fetch_ticker('BTC/USDT')
current_price = ticker['last']
print(f"BTC Price: ${current_price}")

Step 4: Place a Limit Order

# 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']}")

Step 5: Build Grid Logic

# 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:

  • Error handling (exchange outages, API errors)
  • Order tracking (know which orders filled)
  • Rebalancing (replace filled orders)
  • Stop-loss (exit if price trends strongly)
  • Logging (track performance)

Step 6: Run 24/7 (Cloud Server)

Don't run bots on your laptop (you'll close it, lose connection). Use a cloud server:

  • DigitalOcean Droplet: $6/month, Ubuntu Linux
  • AWS Lightsail: $3.50–$5/month, simple setup
  • Heroku: Free tier (limited), good for small bots

Deploy your bot, run it in the background using screen or tmux, and monitor logs remotely.


Advanced Bot Strategies

Once you master grid/DCA bots, explore advanced strategies:

1. Arbitrage Bots

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:

  • Transfer time: Moving BTC between exchanges takes 10–60 minutes (price spread disappears)
  • Fees: Withdrawal fees ($5–$25) + trading fees (0.2%) eat profits
  • Capital intensive: Need funds on both exchanges

Tools: Hummingbot (open-source arbitrage bot), Coinigy (cross-exchange tracking)

2. Market Making Bots

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:

  • Inventory risk: If price trends, you're stuck with losing positions
  • Competition: You're competing with professional market makers
  • Capital required: $10,000+ to make meaningful profits

Tools: Hummingbot (market making strategies), Maker DAO Keeper (Ethereum-based)

3. Mean Reversion Bots

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:

  • Trends can persist: Price can stay below average for months (2022 bear market)
  • Requires backtesting: Need to find optimal "deviation threshold"

Tools: Freqtrade (open-source bot with mean reversion strategies)


Backtesting Your Bot (Mandatory)

Never run an untested bot with real money. Backtest first (see Lesson 18).

Backtesting Tools

  1. Freqtrade (Open-Source, Python)

    • Backtest on 5+ years of data
    • Optimize parameters (grid levels, thresholds)
    • Paper trade before going live
    • Cost: Free
    • Learning curve: Medium (requires Python knowledge)
  2. TradingView (Pine Script)

    • Visual backtesting on charts
    • Easy to write strategies (Pine Script language)
    • Cost: Free (basic), $15–$60/month (pro)
    • Learning curve: Low
  3. Backtrader (Python Library)

    • Flexible backtesting framework
    • Supports multiple assets, indicators
    • Cost: Free
    • Learning curve: High (Python coding required)

Backtesting Checklist:

  • ✅ Test on 2+ years of data (multiple market cycles)
  • ✅ Include fees (0.1–0.5% per trade)
  • ✅ Include slippage (assume 0.05–0.2% slippage on market orders)
  • ✅ Test on multiple pairs (BTC, ETH, SOL)
  • ✅ Walk-forward test (train on 2020–2022, test on 2023)
  • ✅ Paper trade for 1–3 months before live money

Example Backtest Result (Grid Bot):

  • Strategy: 20-level grid bot, $10K investment, BTC/USDT, 2023 data
  • Gross Profit: +18% ($1,800)
  • Fees: -4% ($400)
  • Net Profit: +14% ($1,400)
  • Max Drawdown: -12%
  • Win Rate: 62%

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.


Risk Management for Bots

Bots can fail spectacularly. Protect yourself:

1. Set Max Loss Limits

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()

2. Use Small Position Sizes

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.

3. Monitor Daily

Check bot performance every day:

  • Are orders filling as expected?
  • Are fees higher than predicted?
  • Is P&L matching backtest results?

If bot underperforms backtest by 50%+ for 2 weeks → turn it off, investigate.

4. API Key Security

  • Never enable withdrawals on trading API keys
  • Use IP whitelisting (only your server's IP can access)
  • Store keys in environment variables, not in code:
# .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')

5. Have a Kill Switch

Always have a way to instantly stop the bot:

  • Telegram bot command: /stop sends a signal to stop trading
  • Exchange kill switch: Binance/Kraken let you disable API keys instantly
  • Server access: SSH into server and kill the process (pkill -f bot.py)

Common Mistakes That Blow Up Bots

1. Over-Optimization (Curve Fitting)

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).

2. Ignoring Fees

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%).

3. No Emergency Stop

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.

4. Running on a Laptop

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).

5. No Logging

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}")

Key Takeaways

  1. Algorithmic trading automates strategies using exchange APIs—24/7 execution, no emotions.
  2. REST APIs for fetching data and placing orders; WebSocket APIs for real-time streams.
  3. API security is critical: Never enable withdrawals, use IP whitelisting, store secrets in env vars.
  4. Execution algorithms (TWAP, VWAP, Iceberg) minimize slippage and hide order size.
  5. No-code bots (grid, DCA, rebalancing) let beginners automate without coding.
  6. Building custom bots requires Python/JavaScript, CCXT library, cloud server, and extensive testing.
  7. Backtest rigorously: 2+ years of data, include fees/slippage, walk-forward test.
  8. Risk management: Set loss limits, start small (1–5% of portfolio), monitor daily.
  9. Common mistakes: Overfitting, ignoring fees, no kill switch, running on laptop, no logging.
  10. Bots aren't magic: Most underperform simple "buy and hold." Only use if strategy is proven profitable.

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.


Quiz

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