TWAP (Time-Weighted Average Price) Execution Algorithm Development
TWAP (Time-Weighted Average Price) is an execution algorithm for large orders by distributing volume evenly over time. Goal is not profit from price movement, but minimizing market impact on execution: large order placed at once would push price against you. TWAP divides it into equal parts at equal intervals.
Operating Principle
Need to buy 100 BTC over 4 hours without strong market impact:
Every 10 minutes: buy 100/24 ≈ 4.17 BTC
Total 24 intervals × 4.17 BTC = 100 BTC
Simple TWAP: equal portions at equal time intervals.
Adaptive TWAP accounts for market conditions:
- Skip interval if current price significantly higher than TWAP (don't buy expensive)
- Increase order size if price lower than current TWAP
- Pause on anomalously high volatility
Implementation
import asyncio
from datetime import datetime, timedelta
class TWAPExecutor:
def __init__(self, symbol, total_qty, duration_minutes, exchange):
self.symbol = symbol
self.total_qty = total_qty
self.n_slices = duration_minutes // 5 # every 5 minutes
self.slice_qty = total_qty / self.n_slices
self.exchange = exchange
self.executed_qty = 0
async def execute(self):
interval = (5 * 60) # seconds
for i in range(self.n_slices):
await self.execute_slice()
if i < self.n_slices - 1:
await asyncio.sleep(interval)
async def execute_slice(self):
remaining = self.total_qty - self.executed_qty
qty = min(self.slice_qty, remaining)
# Use limit order close to mid-price to save on fees
ticker = await self.exchange.fetch_ticker(self.symbol)
mid_price = (ticker['bid'] + ticker['ask']) / 2
limit_price = mid_price * 1.0005 # 0.05% above mid
order = await self.exchange.create_limit_buy_order(
self.symbol, qty, limit_price
)
self.executed_qty += qty
return order
Limit vs Market Orders in TWAP
Market orders: guaranteed execution, but worst price. Slippage on BTC can be 0.02–0.1% on volume > $100K.
Limit orders: best price, but risk of non-execution. If order not filled during interval — convert to market near interval end.
Hybrid approach: place limit more aggressively than mid. If 80% through interval unfilled — snipe with market order.
TWAP Benchmark and Quality Assessment
Execution quality = average execution vs market TWAP over period:
TWAP_benchmark = Σ(price_i × volume_i) / Σ(volume_i) for execution period
If algorithm bought at average price below market TWAP — good execution. Above — poor.
Slippage report: per slice record: quote price, fill price, bid/ask spread at execution time.
Applications
- Execution of large fund orders without market movement
- Regular DCA (Dollar Cost Averaging) purchases
- Large position liquidation
- Portfolio rebalancing
Stack: Python (asyncio + CCXT), PostgreSQL for order storage and execution report, REST API for management (start, stop, status). Progress notifications via Telegram.







