How markets work: orders, the book, and execution
Before you automate trades you must understand what actually happens when you press "buy" — the order book, spread, slippage and fees.
When you send an order, it does not vanish into "the market". It hits an order book: a live list of everyone willing to buy (bids) and sell (asks), stacked by price. Understanding the book is the difference between a backtest that works and a live account that bleeds.
Bids, asks and the spread
The highest bid is the most anyone will pay right now. The lowest ask is the least anyone will sell for. The gap between them is the spread — and it is a cost you pay every time you cross it.
Market orders vs limit orders
- Market order — "fill me now, whatever the price". Fast and certain, but you pay the spread and risk slippage (getting a worse price than you saw).
- Limit order — "fill me only at price X or better". You control the price but might never get filled.
The real cost of a round trip
Every complete trade (in and out) pays: spread + slippage + commission. On a strategy that trades often, these dominate. A quick way to feel it in code:
class="c"># Costs per round-trip trade
spread_cost = class="n">0.0002 class="c"># class="n">2 bps crossing the spread
slippage = class="n">0.0001 class="c"># class="n">1 bp average slippage
commission = class="n">0.0002 class="c"># class="n">2 bps broker fee
cost_per_trade = spread_cost + slippage + commission class="c"># class="n">5 bps
trades_per_year = class="n">500
annual_cost_drag = trades_per_year * cost_per_trade
print(fclass="s">"Cost drag: {annual_cost_drag:.class="n">1%} per year") class="c"># -> class="n">2.5% per yearA strategy that trades 500 times a year starts each year 2.5% in the hole before it makes a cent. That is why "edge per trade must exceed cost per trade" is the first law of automated trading.