Grid Trading System

An adaptive grid trading engine that places layered buy and sell orders at calculated price intervals, profiting from natural market oscillation. Rather than predicting direction, slorz harvests volatility by systematically buying dips and selling rips within a defined range.

Contents

I. Core Grid Mechanics

The foundation of slorz. How grid levels are calculated, spaced, and maintained as price moves. These mechanics determine whether the grid captures oscillation efficiently or gets stuck in trending markets.

1
Adaptive Grid Spacing (ATR-Based)

Fixed-width grids ($1 apart, $2 apart) break in different volatility regimes. A $1 grid on a $10 stock is 10% spacing; on a $500 stock it's 0.2%. The solution: use ATR (Average True Range) to set spacing dynamically.

grid_spacing = ATR(14) × multiplier
multiplier range: 0.3x (tight scalp) — 2.0x (wide swing)

In a calm market (ATR = $0.50), a 1.0x multiplier gives $0.50 spacing. When volatility spikes (ATR = $3.00), spacing widens to $3.00 automatically. This prevents rapid-fire fills during chaos while keeping grids tight enough to capture small moves in quiet markets.

ADAPTIVE The multiplier can itself be dynamic — tighten during low-VIX environments, widen when VIX > 25. This creates a self-regulating grid that matches market conditions.

2
Asymmetric Grid Bias

Standard grids place equal levels above and below price. But markets trend. A bullish bias deploys more buy levels below and fewer sell levels above, creating a natural DCA engine that loads up on dips:

S4
S3
S2
S1
PRICE
B1
B2
B3
B4
B5
B6
B7

This example: 4 sell levels, 7 buy levels. The asymmetry reflects bullish conviction — you're willing to accumulate more on dips than you are eager to sell on rallies. Reverse the ratio for bearish bias. Use 1:1 for neutral/ranging markets.

TIP Auto-detect bias from the 50-day EMA slope. Positive slope = bullish bias. Negative = bearish. Flat = neutral.

3
Geometric vs Arithmetic Spacing

Arithmetic: Fixed dollar increments. $100, $99, $98, $97... Simple, predictable, but breaks on assets with large price ranges. A $1 grid on a $500 stock = 0.2% per level (too tight). On a $10 stock = 10% (too wide).

Geometric: Fixed percentage increments. $100, $98 (-2%), $96.04 (-2%), $94.12 (-2%)... Scales naturally across price ranges. A 2% grid works the same whether the stock is $10 or $500.

Arithmetic: level_n = center ± (n × spacing)
Geometric: level_n = center × (1 ± pct)^n

Geometric grids also create a natural compounding effect — lower levels are closer together in absolute dollars, which means you buy more shares per dollar spent as price drops. This is mathematically equivalent to DCA with increasing sizes.

RECOMMENDATION Default to geometric for equities. Use arithmetic only for narrow-range instruments like bonds or stable forex pairs.

4
Drift Correction (Auto-Recenter)

The grid's worst enemy: a strong trend. Price moves up 15% and leaves all your buy levels behind. Or drops 20% and blows through every buy level. The grid goes stale.

Drift correction detects when price has moved significantly from the grid center and re-anchors the grid. Two approaches:

EMA Anchor: Recenter the grid on EMA-20 every N minutes. If price has moved > 2 ATR from center, shift the entire grid. Cancel unfilled orders and place new ones.

Rolling Recenter: After every completed buy-sell cycle (a round trip), recenter the grid on current VWAP. This naturally follows trends without explicit detection.

DANGER Don't recenter too aggressively in choppy markets — you'll cancel and replace orders constantly, burning commissions. Use a cooldown timer: minimum 15 minutes between recenters.

II. Position Sizing

How much capital to deploy at each grid level. This is where most grid systems fail — either too aggressive (blown account on a trending day) or too conservative (tiny profits that don't justify the complexity).

5
Pyramid Scaling

Deeper grid levels get progressively larger positions. The logic: if price has fallen through 5 buy levels, it's more likely at a local extreme. Buying more at deeper levels creates a favorable average cost basis.

Level 1: 100 shares (1.0x)
Level 2: 150 shares (1.5x)
Level 3: 200 shares (2.0x)
Level 4: 300 shares (3.0x)
Level 5: 400 shares (4.0x)

Total exposure if all fill: 1,150 shares (vs 500 with flat sizing). This means the grid is heavily weighted toward buying the dip, which is the entire thesis — buy more when it's cheaper.

RISK Pyramiding amplifies losses in continuous downtrends. Must be combined with circuit breakers (see Risk Management). Never pyramid without a max drawdown kill switch.

6
Kelly Criterion Sizing

The Kelly Criterion calculates the mathematically optimal bet size based on your edge:

Kelly% = W - [(1-W) / R]
W = win rate, R = avg win / avg loss

Example: 60% win rate, 1.5:1 win/loss ratio
Kelly% = 0.60 - [(1-0.60) / 1.5] = 0.60 - 0.267 = 0.333 (33.3%)

Most practitioners use "fractional Kelly" (half or quarter Kelly) to reduce variance. For grid trading, apply Kelly to the total grid exposure, not individual levels. If Kelly says 33%, your entire grid (all levels combined) should not exceed 33% of portfolio.

DATA NEEDED Requires historical win rate and win/loss ratio from backtesting or paper trading. Run slorz in paper mode first to generate these statistics, then size accordingly.

7
Portfolio Heat Map

Portfolio Heat = percentage of total capital at risk if everything goes wrong simultaneously. This is the most important number in the system.

Heat = Σ(position_size × distance_to_stop) / total_portfolio

Rule: Heat must never exceed 6% of total portfolio.
Aggressive: 10%. Conservative: 3%.

If you run 3 slorz grids on correlated tech stocks and a broad selloff hits, ALL grids fill their buy levels simultaneously. Your heat calculation must account for this correlation scenario.

Pre-compute the worst case: "If every buy level on every grid fills and price continues to the circuit breaker, how much am I down?" If the answer exceeds your heat limit, reduce sizes before deploying.

III. Entry/Exit Intelligence

Dumb grids fill mechanically at every level. Smart grids use context — momentum, volume, spread, and timing — to decide whether a fill is likely to be profitable or a trap.

8
Momentum Filter (RSI Gate)

RSI (Relative Strength Index) measures how overbought or oversold an asset is on a 0-100 scale. Use it as a gate on grid fills:

BUY grid active when: RSI(14) < 65
BUY grid paused when: RSI(14) > 75 (overbought — likely pullback)
SELL grid active when: RSI(14) > 35
SELL grid paused when: RSI(14) < 25 (oversold — likely bounce)

This prevents the classic grid mistake: buying every $1 drop during a parabolic rally, only to see all those buy-fills become profits that evaporate when the rally reverses. By pausing buys when RSI is elevated, you avoid catching the top.

UPGRADE Use multi-timeframe RSI. If the daily RSI is overbought AND the 5-minute RSI is overbought, the pause signal is stronger.

9
Volume Confirmation

Thin-volume price moves tend to reverse. A grid level hit on 0.3x average volume is likely a fake-out. Require minimum volume before executing:

Fill condition: current_bar_volume > 1.5 × SMA(volume, 20)
Skip fill if volume < threshold (order stays pending)

This is especially important in pre-market or after-hours trading where a single large order can sweep through multiple grid levels on minimal volume. Those fills will likely reverse when regular trading starts.

10
Time-Weighted Fill Confirmation

When price touches a grid level, don't fill instantly. Wait for confirmation that the level holds:

Price touches $142.00 buy level
Start 30-second timer
If price stays ≤ $142.00 for 30 seconds: FILL
If price bounces above $142.00 within 30 seconds: SKIP (wait for next touch)

This filters out spiky wicks that briefly touch a level but immediately reverse. The trade-off: you might miss some legitimate fills where price touches and immediately bounces in your favor. But statistically, the fills you avoid (fakeout wicks) lose more than the fills you miss (instant reversals) gain.

TUNABLE Confirmation time: 15s for scalp grids, 60s for swing grids. Adjust based on timeframe and asset volatility.

11
Spread-Aware Execution

Every market order crosses the bid-ask spread. On a stock with a $0.05 spread, each round-trip costs $0.10. If your grid spacing is $0.50, that's 20% of your profit eaten by spread alone.

Spread cost per round-trip = 2 × (ask - bid) / 2 = spread
Grid profit per round-trip = grid_spacing - spread
Min viable spacing = spread × 5 (rule of thumb)

Solution: Use limit orders exclusively. Place buy limits at the bid price (or slightly above) and sell limits at the ask price (or slightly below). You earn the spread instead of paying it.

For wide-spread assets (small caps, options), increase grid spacing proportionally. Never run a grid where spread exceeds 20% of the spacing.

IV. Risk Management

Grid trading without risk management is a guaranteed account blowup. These are the guardrails that keep slorz alive during black swan events, flash crashes, and gap downs. Every one of these is non-negotiable.

12
Circuit Breaker (Cascade Detection)

If 3+ buy levels fill within 60 seconds, something abnormal is happening. Flash crash, news event, or market structure failure. The grid should halt immediately:

CIRCUIT BREAKER triggers when:
• 3 consecutive fills in < 60 seconds
• OR price moves > 3 ATR in < 5 minutes
• OR VIX spikes > 15% intraday

On trigger: Cancel all pending orders. Hold existing positions. Alert via Qu.

The circuit breaker does NOT close positions — it just stops new fills. The reasoning: during a flash crash, the best action is usually to hold and wait for the bounce. But you don't want to keep buying into a 20% freefall.

MANDATORY This is the single most important safety feature. Without it, a fat-finger event or flash crash fills every grid level in seconds.

13
Max Drawdown Kill Switch

An absolute limit on how much the grid can lose before it self-terminates:

MAX_DRAWDOWN = -5% of total portfolio (configurable)

Check every 10 seconds:
unrealized_pnl = Σ(current_price - fill_price) × shares
If unrealized_pnl / portfolio < -MAX_DRAWDOWN:
  Close all positions at market
  Cancel all pending orders
  Enter cooldown (no new grids for 24 hours)
  Alert via Qu with full report

This is the nuclear option. It means accepting the loss and stepping away. The 24-hour cooldown prevents emotional re-entry ("I'll just run another grid to make it back").

14
Correlation Guard

Running slorz on AAPL, MSFT, and QQQ simultaneously feels diversified. It's not. These assets have 0.85+ correlation. When the market drops, ALL three grids fill their buy levels at the same time.

correlation(AAPL, QQQ) = 0.92
correlation(MSFT, QQQ) = 0.89
correlation(AAPL, MSFT) = 0.87

Combined worst-case = sum of all grid max exposures
Must stay within portfolio heat limit

Implementation: Track a "correlation group" for each grid. Assets within the same group share a combined heat cap. The sum of all positions across the group cannot exceed the group's heat limit, even if individual grids have capacity.

DIVERSIFICATION For genuine diversification, run grids on uncorrelated assets: equities + commodities + forex. SPY + GLD + EUR/USD gives much better risk dispersion.

15
Overnight & Weekend Gap Protection

Markets gap. A stock closes at $150 and opens at $140 because of after-hours earnings. Your grid levels between $150 and $140 never triggered — price jumped over them. But you're still exposed to the positions you already hold.

OVERNIGHT RULES:
• 30 min before close: reduce position sizes by 50%
• Cancel all pending buy orders
• Apply tight stops to existing positions (2% trail)

WEEKEND RULES:
• Option A: Close all positions Friday 3:50 PM
• Option B: Hold positions but no pending orders
• Reopen grid Monday 9:35 AM (skip first 5 min chaos)

The 5-minute delay on Monday open avoids the opening auction volatility where spreads are wide and prices whipsaw.

V. Profit Taking

How to harvest profits from completed grid cycles. The tension: take profits quickly (high win rate, small wins) or let winners run (lower win rate, bigger wins). Slorz can do both.

16
Trailing Grid Profits

Fixed take-profit: buy at $140, sell at $141. Simple but leaves money on the table when price runs to $145.

Trailing approach: After the buy fills at $140, set a trailing stop instead of a fixed sell. The stop follows price upward by 0.5 ATR:

Buy fill: $140.00
Price rises to $141.00 → trailing stop at $140.50
Price rises to $143.00 → trailing stop at $142.50
Price drops to $142.50 → SELL at $142.50 (profit: $2.50)

vs fixed grid profit of $1.00

The trailing stop captures trending moves while still protecting against reversals. Best used with a minimum profit threshold — the trail doesn't activate until price has moved at least 1 grid spacing in your favor.

17
Compound Reinvestment

After each completed round-trip (buy-then-sell), the profit is added to the grid's capital base. This creates geometric growth:

Starting capital: $10,000
Month 1: 15 round-trips × $12 avg profit = $180 (1.8%)
New capital: $10,180
Month 2: sizes increase 1.8%, profits increase 1.8%...

After 12 months at 1.8%/month: $10,000 × 1.018^12 = $12,392

The snowball effect is significant over time. The key constraint: only reinvest realized profits, never unrealized. And maintain the heat cap — as positions get larger, the circuit breaker thresholds should scale proportionally.

18
Partial Exits (Split Takes)

Instead of selling the entire position at the grid sell level, split the exit:

Buy 100 shares at $140.00

Sell 70 shares at $141.00 (grid target) → lock in $70 profit
Hold 30 shares with trailing stop at $140.50

If price continues to $145: sell remaining 30 at ~$144.50 → +$135
If price reverses: stop out 30 at $140.50 → +$15

Total best case: $205 vs $100 with full exit
Total worst case: $85 vs $100 with full exit

The 70/30 split (tunable) gives you the best of both worlds: consistent base profits from the 70% exit, plus occasional home runs from the 30% trailing portion. The slight reduction in worst-case profits is worth the upside optionality.

VI. Data & Signals

External intelligence that makes slorz context-aware. Rather than trading blind, integrate macro regime data, event calendars, and sentiment to modulate grid behavior in real-time.

19
Macro Regime Detection

Your existing FRED infrastructure already tracks the economic regime. Use it to auto-tune slorz:

EXPANSION (GDP > 2%, inflation < 3%):
  Grid multiplier: 1.5x (wider grids)
  Position sizing: 1.2x (larger positions)
  Bias: bullish (7 buy / 4 sell)

STAGFLATION (GDP < 1%, inflation > 3%):
  Grid multiplier: 0.7x (tighter grids)
  Position sizing: 0.6x (smaller positions)
  Bias: neutral (5 buy / 5 sell)

RECESSION (negative GDP, rising unemployment):
  Grid multiplier: 0.5x (very tight)
  Position sizing: 0.3x (minimal capital)
  Bias: bearish (3 buy / 7 sell) or GRID OFF

INTEGRATION Pull regime data from your fred-intel.php endpoint. Update regime classification daily. The grid adjusts automatically without manual intervention.

20
Earnings Calendar Integration

Earnings reports cause 5-15% gaps. A grid running through an earnings event is gambling, not trading.

24 hours before earnings:
• Close all positions on this ticker
• Cancel all pending orders
• Log: "SLORZ paused for AAPL earnings 2026-03-18 AMC"

Day after earnings (next day 9:35 AM):
• Recenter grid on new price
• Recalculate ATR (post-earnings vol is different)
• Resume grid with fresh levels

Free earnings calendars: Yahoo Finance API, Alpha Vantage, or scrape from finviz.com. Cache the calendar weekly and check it before each grid deployment.

21
News Sentiment Guard

Headlines move prices before fundamentals do. A strong negative headline ("SEC investigation", "product recall", "mass layoffs") should temporarily pause buy grids to avoid catching a news-driven waterfall.

Feed: RSS from CNBC, Reuters, Bloomberg
Filter: mentions of grid ticker symbols
Classify: positive / neutral / negative

Strong negative (-0.8 to -1.0 sentiment):
  Pause buy grid for 30 minutes
  Tighten stops on existing positions
  Alert via Qu

The 30-minute window allows the news to be digested and the initial panic selling to subside. After 30 minutes, if price has stabilized, the grid resumes. If price is still falling, the circuit breaker handles it.

AI-POWERED Use your existing Grok API integration for sentiment classification. Feed it the headline and ask for a -1 to +1 score.

VII. Architecture & Implementation

How to build slorz. Event-driven state machines, paper trading, backtesting, and integration with your existing orconectes infrastructure.

22
Event-Driven State Machine

Each grid level is an independent state machine with 5 states:

IDLE
PENDING
FILLED
PROFIT_TARGET
CLOSED

IDLE: Level calculated but no order placed (filters not met).
PENDING: Limit order placed, waiting for fill.
FILLED: Order filled, position open. Sell target calculated.
PROFIT_TARGET: Sell order placed at target price.
CLOSED: Round-trip complete. Log P&L. Return to IDLE.

The entire grid state serializes to a JSON file. On crash/restart, read the file and resume from exactly where you left off. This is the orconectes crash-and-resume philosophy applied to trading.

{
  "grid_id": "slorz-spy-001",
  "ticker": "SPY",
  "center": 560.00,
  "spacing_atr_mult": 1.0,
  "levels": [
    {"price": 558.00, "state": "FILLED", "fill_price": 558.02, "shares": 100},
    {"price": 556.00, "state": "PENDING", "order_id": "ABC123"},
    {"price": 554.00, "state": "IDLE"}
  ]
}
23
Paper Trade Mode

Before risking real capital, run slorz against live market data with simulated fills. Every fill is logged with full detail as if it were real:

PAPER FILL LOG:
2026-03-18 09:32:14 | BUY | SPY | 100 shares @ $558.02 | Level 1
2026-03-18 09:47:33 | SELL | SPY | 100 shares @ $560.00 | Profit: $198
2026-03-18 10:15:01 | BUY | SPY | 100 shares @ $558.50 | Level 1
2026-03-18 10:22:47 | BUY | SPY | 150 shares @ $556.50 | Level 2
...

Run paper mode for at least 2 weeks (10 trading days) to generate meaningful statistics. Track: total trades, win rate, avg win/loss, max drawdown, Sharpe ratio, profit factor. Only deploy real capital when paper results are satisfactory.

ZERO RISK Paper mode uses the exact same code as live mode — the only difference is that "place order" calls are replaced with simulated fills. When you're ready to go live, flip one boolean.

24
Multi-Timeframe Grid Stacking

Run two independent grids on the same asset at different timeframes:

SCALP GRID (5-minute):
  Spacing: 0.3x ATR, tight
  Position size: small (20 shares)
  Target: 1 grid spacing profit
  Many trades per day

SWING GRID (daily):
  Spacing: 2.0x ATR, wide
  Position size: larger (100 shares)
  Target: trailing stop, ride trends
  1-3 trades per week

The scalp grid harvests intraday noise. The swing grid catches multi-day moves. They operate independently but share the same portfolio heat cap. If the swing grid has filled 3 levels, the scalp grid reduces its maximum exposure accordingly.

25
Qu Integration & Notifications

Every significant grid event fires a notification through your Qu message system:

EVENTS that trigger Qu messages:
• Grid fill: "SLORZ BUY SPY 100@558.02 (L1)"
• Profit taken: "SLORZ SELL SPY 100@560.00 +$198"
• Circuit breaker: "SLORZ HALTED SPY — 3 fills in 45s"
• Kill switch: "SLORZ KILLED SPY — drawdown -5.2%"
• Daily report: "SLORZ daily: 8 fills, 6 closed, +$412, heat: 3.1%"

You get real-time alerts on Qu when anything important happens, and a daily summary every evening. No need to watch the dashboard — slorz tells you what it's doing.

26
Historical Backtester

Feed historical candle data through the slorz engine and measure performance before deploying:

INPUT: 1-minute candles for SPY, 6 months (approx 58,000 bars)
CONFIG: ATR multiplier, grid levels, sizing, all parameters

OUTPUT REPORT:
• Total trades: 847
• Win rate: 72.4%
• Average win: $87.50
• Average loss: $142.30
• Max drawdown: -3.8%
• Sharpe ratio: 1.42
• Profit factor: 1.76
• Total P&L: +$18,430
• Monthly equity curve: [chart]

The backtester must account for realistic execution: slippage (add $0.01 to buy fills, subtract from sells), commission costs ($0.005/share minimum), and no fills on the exact high/low of a bar (use next bar's open for stop fills).

WARNING Backtesting is not prediction. Past performance doesn't guarantee future results. But it validates that the grid logic is mechanically sound and would have survived historical market conditions including the 2020 crash, 2022 bear market, and 2024-2025 tariff shocks.

27
Live Dashboard (slorz-dashboard.html)

A real-time monitoring page showing the complete state of all active slorz grids:

DASHBOARD PANELS:
• Active Grids: ticker, center price, filled levels (highlighted), P&L
• Level Map: visual grid showing IDLE/PENDING/FILLED/TARGET states
• P&L Curve: equity curve over time (chart.js or canvas)
• Exposure Meter: current heat as % of portfolio (gauge)
• Regime Badge: current macro regime from FRED
• Recent Fills: last 20 fills with timestamp, price, P&L
• Circuit Breaker Status: armed/triggered/cooldown
• Daily Stats: trades today, win rate, net P&L

Dark theme (matching your existing tools), auto-refresh via polling every 5 seconds, mobile responsive. Built with vanilla JS and canvas — zero dependencies.

28
Implementation Stack

Built on your existing zero-dependency philosophy:

ENGINE: Python stdlib (or shell + Python hybrid)
  - State persistence: JSON files (orconectes crash-resume pattern)
  - Broker API: Alpaca (free, REST API, paper trading built in)
  - Market data: Alpaca WebSocket or polling via stock-quote.sh

DASHBOARD: Vanilla HTML/JS/CSS
  - slorz-dashboard.html (this page, with live data)
  - slorz-api.php (grid state + fill log as JSON)

INTEGRATION:
  - Qu notifications via comms/qu-reply.sh
  - Regime data via fred-intel.php
  - Existing stock-quote.sh for price feeds
  - Cycle logging via core/cycle-log.sh

READY TO BUILD All infrastructure exists. The slorz engine is the new component. Everything else (Qu, FRED, price feeds, deployment) is already operational.