Dynamic Grid Trading Algorithm Development
Grid trading is strategy of placing order grid above and below current price. On price move down — buy, on move up — sell. Profit accumulates on each grid "step". Dynamic grid differs from static by adapting to changing volatility and trend.
Basic Grid Trading Mechanics
Static grid (for understanding): set range $40,000–$50,000, 10 levels. Step: $1,000. Place:
- Buy orders: 40k, 41k, 42k, 43k, 44k
- Sell orders: 46k, 47k, 48k, 49k, 50k
- Current price: ~$45k (middle)
On fall to $44k → buy order fills → automatically place sell $45k. On rise to $45k → sell fills → profit $1,000 per step.
Profit per grid = step / price. 1% step → ~1% profit per complete cycle (fees excluded).
Dynamic Grid: Adapting to Volatility
Static grid works in range. If price exits range — grid "freezes" and doesn't trade. Dynamic grid solves this:
ATR-based grid spacing: step between levels = multiple of ATR. High volatility → wider steps (fewer false signals, higher profit per step). Low → tighter (more trades).
def calculate_grid_levels(current_price, atr, n_levels=10, atr_multiplier=0.5):
step = atr * atr_multiplier
levels = []
for i in range(-n_levels//2, n_levels//2 + 1):
level_price = current_price + i * step
levels.append(level_price)
return sorted(levels)
Recentering: if price exited grid by N steps — recalculate grid around current price. Cancel unfilled orders, place new ones.
Trend-aware grid: in uptrend (positive EMA), grid shifts up. More sell levels above, fewer buy levels below. Opposite in downtrend.
Capital Management in Grid
Even distribution: same capital at each level.
Pyramid allocation: more capital on levels closer to current price (more likely fill), less on extreme levels.
Max inventory: limit on accumulated asset. Continuous buying on fall risks overleveraging.
def check_inventory_limit(current_qty, max_qty_pct, capital, price):
max_qty = (capital * max_qty_pct) / price
if current_qty >= max_qty:
# Stop buy orders, sell only
return False
return True
Profit and Metrics
Grid profit: total profit from executed buy/sell pairs. Unrealized P&L: if inventory accumulated on price fall. Total P&L: grid profit + unrealized P&L. Grid occupancy: % of levels that traded.
When Grid Trading Works
Ideal: sideways market with regular oscillations. BTC in $40k–$50k range for months — excellent grid situation.
Poor: strong trend. Downtrend accumulates losing position without sales.
Trend protection: Stop-loss on entire grid on fall below lower bound by X%. Or spot only (no leverage) — loss stays unrealized, no margin call.
Stack: Python (asyncio + CCXT), PostgreSQL for levels and orders, simple web UI for configuration and monitoring, Telegram alerts on recentering and stop-loss.







