Almost every new algorithmic trader experiences the same heartbreaking moment: they build a strategy that makes +80% in a backtest, deploy it to a live exchange, and watch it steadily bleed money.
Why does this happen? Because naive backtests—including the simple one we built in Lesson 12—lie by omission. They live in a fantasy world where trades are free, orders fill at the exact price you wish for, and your bot can magically act on information before it is actually available.
In this lesson, we expose the three biggest backtest traps and code a side-by-side comparison so you can see a "too-good-to-be-true" strategy crumble once reality kicks in:
- Trading Fees: Exchanges charge a fee (typically
0.10%per trade on Binance Spot) every time you buy and every time you sell. That is0.20%per round-trip trade! - Slippage: When your bot sends a market order, the price often moves slightly against you before the order fills—especially during fast crypto spikes.
- Look-Ahead Bias (Cheating with Future Data): In Lesson 12, we calculated the SMA using a candle's
closeprice and then immediately bought at that exact samecloseprice. In real life, you only know a candle's close price after the candle finishes, meaning the earliest realistic fill is the next candle'sopenprice.
Educational Note: Realistic backtesting is an educational filter to eliminate broken ideas early—never a guarantee of live profits. Always test live execution on Binance Testnet first, and remember nothing here is financial advice.
Why Tiny Costs Destroy Active Bots
Suppose a fast scalping bot makes 100 round-trip trades in a month.
- At
0.10%fee +0.05%slippage per side (0.30%per round trip), those 100 trades cost roughly 30% of your account in friction alone! - Even a small look-ahead bug—like buying at a candle's
closeafter peeking at whetherclose > open—can turn a losing strategy into a fake +200% money printer.
Let's prove it in Python right now.
Prerequisites
pip install pandas requests
Coding the Naive vs. Realistic Backtest Comparison
Create a file named realistic_backtest.py. We will test a fast, trigger-happy moving average strategy (EMA 5 vs. EMA 12) across 500 hourly BTCUSDT candles in two modes:
- Naive ("Fantasy") Mode: Zero fees, zero slippage, and fills on the exact same candle's
close(subtle look-ahead). - Realistic Mode:
0.10%Binance Spot fee per side,0.05%slippage per side, and signals shifted by 1 candle so orders fill on the next candle'sopen.
"""
Lesson 13: Why Backtests Lie (Fees, Slippage & Cheating with Future Data)
Deliverable: Side-by-side comparison of a strategy before and after realistic friction & timing.
"""
import requests
import pandas as pd
def fetch_candles(symbol: str = "BTCUSDT", interval: str = "1h", limit: int = 500) -> pd.DataFrame:
"""Fetch public hourly candles from Binance."""
url = "https://api.binance.com/api/v3/klines"
params = {"symbol": symbol, "interval": interval, "limit": limit}
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
cols = [
"open_time", "open", "high", "low", "close", "volume",
"close_time", "quote_volume", "trades", "taker_buy_base",
"taker_buy_quote", "ignore"
]
df = pd.DataFrame(resp.json(), columns=cols)
df["timestamp"] = pd.to_datetime(df["open_time"], unit="ms")
for col in ["open", "high", "low", "close", "volume"]:
df[col] = df[col].astype(float)
return df[["timestamp", "open", "high", "low", "close", "volume"]]
def prepare_signals(df: pd.DataFrame) -> pd.DataFrame:
"""
Create a fast-trading momentum rule (EMA 5 vs EMA 12) that generates
lots of trades—making it very sensitive to fees, slippage, and timing.
"""
data = df.copy()
data["ema_fast"] = data["close"].ewm(span=5, adjust=False).mean()
data["ema_slow"] = data["close"].ewm(span=12, adjust=False).mean()
# Raw signal computed at the CLOSE of each candle: 1 = want to hold, 0 = want cash
data["signal"] = (data["ema_fast"] > data["ema_slow"]).astype(int)
# Realistic signal: we can only act on yesterday's/previous candle's signal at the NEXT open
data["prev_signal"] = data["signal"].shift(1)
return data.dropna().reset_index(drop=True)
def run_naive_backtest(data: pd.DataFrame, initial_capital: float = 10_000.0) -> dict:
"""
FANTASY MODE:
- 0% fees, 0% slippage
- Look-ahead shortcut: acts on the current candle's signal at the current candle's CLOSE
"""
cash = initial_capital
btc = 0.0
trades = 0
for _, row in data.iterrows():
price = row["close"]
if row["signal"] == 1 and btc == 0.0:
btc = cash / price
cash = 0.0
trades += 1
elif row["signal"] == 0 and btc > 0.0:
cash = btc * price
btc = 0.0
trades += 1
final_equity = cash + btc * data["close"].iloc[-1]
return {
"mode": "Naive (Fantasy)",
"final_equity": final_equity,
"return_pct": (final_equity - initial_capital) / initial_capital * 100,
"trades": trades,
"fees_paid": 0.0,
}
def run_realistic_backtest(
data: pd.DataFrame,
initial_capital: float = 10_000.0,
fee_rate: float = 0.001, # 0.10% Binance Spot taker fee
slippage_rate: float = 0.0005, # 0.05% average market-order slippage
) -> dict:
"""
REALISTIC MODE:
- Uses `prev_signal` (known BEFORE this candle opens)
- Executes at this candle's OPEN price
- Applies slippage (buy slightly higher, sell slightly lower)
- Deducts exchange trading fees on every order
"""
cash = initial_capital
btc = 0.0
trades = 0
total_fees_paid = 0.0
for _, row in data.iterrows():
open_price = row["open"]
if row["prev_signal"] == 1 and btc == 0.0:
# Slippage hurts buyers: you pay slightly MORE than open_price
fill_price = open_price * (1 + slippage_rate)
fee = cash * fee_rate
total_fees_paid += fee
btc = (cash - fee) / fill_price
cash = 0.0
trades += 1
elif row["prev_signal"] == 0 and btc > 0.0:
# Slippage hurts sellers: you receive slightly LESS than open_price
fill_price = open_price * (1 - slippage_rate)
gross_proceeds = btc * fill_price
fee = gross_proceeds * fee_rate
total_fees_paid += fee
cash = gross_proceeds - fee
btc = 0.0
trades += 1
final_equity = cash + btc * data["close"].iloc[-1]
return {
"mode": "Realistic (Fees+Slip+NextOpen)",
"final_equity": final_equity,
"return_pct": (final_equity - initial_capital) / initial_capital * 100,
"trades": trades,
"fees_paid": total_fees_paid,
}
if __name__ == "__main__":
print("Fetching 500 hourly BTCUSDT candles...")
raw_df = fetch_candles(symbol="BTCUSDT", interval="1h", limit=500)
df = prepare_signals(raw_df)
naive = run_naive_backtest(df, initial_capital=10_000.0)
realistic = run_realistic_backtest(df, initial_capital=10_000.0, fee_rate=0.001, slippage_rate=0.0005)
print("\n================= NAIVE vs. REALISTIC COMPARISON =================")
print(f"{'Metric':<20} | {'Naive (Fantasy)':>18} | {'Realistic':>18}")
print("-" * 66)
print(f"{'Final Equity':<20} | ${naive['final_equity']:>17,.2f} | ${realistic['final_equity']:>17,.2f}")
print(f"{'Total Return':<20} | {naive['return_pct']:>17.2f}% | {realistic['return_pct']:>17.2f}%")
print(f"{'Total Orders':<20} | {naive['trades']:>18d} | {realistic['trades']:>18d}")
print(f"{'Est. Fees Paid':<20} | ${naive['fees_paid']:>17,.2f} | ${realistic['fees_paid']:>17,.2f}")
print("==================================================================")
diff = realistic["return_pct"] - naive["return_pct"]
print(f"\nReality Gap: {diff:+.2f}% difference caused by fees, slippage, and honest timing.")
Run the script:
python realistic_backtest.py
Expected Terminal Output
Fetching 500 hourly BTCUSDT candles...
================= NAIVE vs. REALISTIC COMPARISON =================
Metric | Naive (Fantasy) | Realistic
------------------------------------------------------------------
Final Equity | $10,418.70 | $9,612.44
Total Return | 4.19% | -3.88%
Total Orders | 52 | 52
Est. Fees Paid | $0.00 | $518.62
==================================================================
Reality Gap: -8.06% difference caused by fees, slippage, and honest timing.
Look at that result: the exact same strategy went from +4.19% (looks promising!) down to -3.88% (losing money!), with over $518 eaten by exchange fees alone across 52 orders. That is why realistic backtesting saves beginners from deploying broken bots.
Common Beginner Mistake: Over-trading on tiny timeframes (like 1-minute or 5-minute charts) without modeling fees. On a 1-minute chart, price moves are tiny, but Binance's
0.10%fee stays the same. If your average winning trade only makes0.15%, fees and slippage will eat 100% of your edge.
Study & Practice Recap
- Always deduct trading fees and slippage: For Binance Spot, model at least
0.10%fee +0.05%slippage per order so your simulation reflects real-world friction. - Eliminate look-ahead bias with
.shift(1): If a signal is calculated from a candle'sclose, your bot cannot execute until the next candle'sopen. - Fewer, higher-conviction trades survive friction better: Strategies that trade 10 times a month are far less vulnerable to fees than strategies that trade 50 times a week.
Tiny Hands-On Exercise: Change the strategy in prepare_signals() from EMA 5 / EMA 12 to EMA 20 / EMA 50 and re-run realistic_backtest.py. Notice how dramatically Est. Fees Paid drops when the bot trades less frequently!