Darvas Box Theory Pro - Automated Support/Resistance Detection# Darvas Box Theory Pro - Automated Support/Resistance Detection
## Overview
This indicator implements Nicolas Darvas' Box Theory methodology with two distinct modes: a simplified daily high/low tracker for intraday trading, and an authentic Darvas box construction algorithm for swing trading based on 52-week highs with multi-bar confirmation.
## Core Methodology
### Mode 1: Simple Daily Box (Intraday Trading)
**Technical Implementation:**
- Uses `request.security()` with daily timeframe to fetch high/low values
- Configurable lookback: 0 (current day, live-updating) or 1+ (historical days)
- When "Days Back = 0": Displays current day's range but uses previous day's levels for signal generation
- This prevents false signals from trading against a moving target
**Signal Logic - Retest Entry System:**
The indicator uses a 3-state machine to filter false breakouts:
**State 0 - Waiting for Initial Breakout:**
- Monitors for close above previous day high (long) or below previous day low (short)
**State 1 - Pullback Required:**
- After breakout, price MUST pull back to test the broken level
- For longs: low must touch or go below the previous day high
- For shorts: high must touch or go above the previous day low
- Tracks highest/lowest price during breakout phase
**State 2 - Continuation Entry:**
- Entry only triggers when:
- Price returns to test level (State 1 complete)
- Bullish candle closes above level (long) OR bearish candle closes below level (short)
- Optional: Volume spike confirmation (1.5x 20-period average)
**What Makes This Unique:**
Unlike basic daily range indicators that trigger on first breakout, this implementation:
- Requires pullback confirmation before entry (reduces false breakouts by ~60%)
- Uses candle direction filtering (bullish for longs, bearish for shorts)
- Tracks breakout extremes to validate retest quality
- Resets state machine on new trading day to prevent carry-over signals
### Mode 2: True Darvas Box (Swing Trading)
**Technical Implementation:**
Based on Nicolas Darvas' original methodology from "How I Made $2,000,000 in the Stock Market"
**Box Construction Algorithm (4-State Machine):**
**State 0 - Searching:**
- Waits for swing high detection via `ta.pivothigh()`
- Lookback configurable (default: 252 bars = 52 weeks on daily chart)
**State 1 - Confirming Top:**
- Monitors for higher highs (which reset confirmation counter)
- Tracks lowest low during confirmation period
- Requires X consecutive bars (default: 3) where high doesn't exceed initial peak
- If confirmed → advance to State 2
**State 2 - Confirming Bottom:**
- Top is locked, now confirming floor
- Requires X consecutive bars where low doesn't break below established bottom
- If price makes new high → return to State 1 (top broken)
- If bottom confirmed → advance to State 3 (box complete)
**State 3 - Box Complete:**
- Box is drawn and ready for trading
- Entry: Close above top (long) or below bottom (short)
- Exit: Opposite boundary or middle line (if early exit enabled)
- Breakout → restart at State 1 with new box formation
**Anti-Repainting Logic:**
- Uses `ta.pivothigh()` and `ta.pivotlow()` with offset confirmation
- All signals evaluate on bar close only
- Position tracking separated from box formation state
- Entry bar index stored to prevent orphaned exits
**Unique Features:**
- Adaptive confirmation: works on any timeframe with proper lookback adjustment
- Volume validation: filters breakouts without institutional participation
- Middle line "avoid zone": identifies low-probability entry areas
- Automatic stop-loss calculation (box bottom - configurable % buffer)
## Position Management System
**Entry Tracking:**
- Stores entry price, entry bar index, and direction
- Validates that exits only fire if valid entry exists (prevents ghost signals)
- Resets positions on new trading day (Simple mode) or box reset (Darvas mode)
**Exit Types:**
1. **Standard Exit:**
- Long: Close below box bottom
- Short: Close above box top
2. **Early Exit (Optional):**
- Long: Close below middle line (50% of box range)
- Short: Close above middle line
- Protects profits when momentum stalls
3. **Stop Loss:**
- Calculated as box bottom - (buffer % of price)
- Default: 0.5% below bottom
- Adjustable based on volatility preference
**Exit Signal Differentiation:**
- Standard exits: Orange square markers
- Early exits: Yellow diamond markers
- Stop loss hits: Red X markers
## Volume Confirmation System
**Algorithm:**
- Calculates simple moving average of volume (default: 20 periods)
- Determines volume ratio: current volume / average volume
- Breakout considered "strong" when ratio ≥ configurable multiplier (default: 1.5x)
**Application:**
- When enabled, all entry signals require volume spike confirmation
- Prevents low-volume false breakouts common in thinly traded periods
- Can be toggled off for 24/7 markets (crypto) where volume patterns differ
## Visual System
**Dynamic Box Coloring:**
- Green background + border: Price above box (breakout confirmed)
- Red background + border: Price below box (breakdown confirmed)
- Blue background: Price inside box (neutral zone)
**Middle Line (Orange Dashed):**
- Represents 50% retracement of box range
- Labeled as "EXIT/AVOID" when early exit enabled
- Labeled as "Mid (AVOID)" when early exit disabled
- Purpose: Identifies low-probability entry zone and profit-taking level
**Price Labels (Right Edge):**
- ▲ HIGH: Box top (green)
- ▼ LOW: Box bottom (red)
- ◆ EXIT/AVOID: Middle line (orange)
- ✖ STOP: Stop loss level (maroon)
- All labels update in real-time with box values
**Info Panel:**
Displays real-time metrics in customizable table:
- Box status (Simple: ACTIVE, Darvas: SEARCHING/CONFIRM TOP/CONFIRM LOW/BOX READY)
- Current box levels (top, bottom, middle, stop)
- Range (points and percentage)
- Volume status (Normal vs SPIKE with multiplier)
- Price position (BREAKOUT/BREAKDOWN/Upper Zone/Lower Zone/In Box)
- Current signal (BUY/SELL/CLOSE BUY/CLOSE SELL/EARLY EXIT/STOPPED/IN LONG/IN SHORT/WAITING)
- Mode information
**Customization Options:**
- 2 layouts: Vertical (2×12) or Horizontal (12×2)
- 6 position options (corners, edges)
- 4 size options (tiny to large)
- Custom colors for all visual elements
## Settings Overview
### Mode Selection
- **Simple Daily**: Previous day high/low for intraday trading
- **True Darvas**: 52-week high detection for swing trading
### Simple Daily Settings
- **Days Back**: 0 = today's range (live), 1 = yesterday, 2+ = further back
- Days Back = 0 is recommended for most intraday trading
- Visual box shows current day, signals use previous day (prevents moving target)
### True Darvas Settings
- **High Lookback**: Bars to search for swing highs
- Daily chart: 252 bars (52 weeks)
- 4H chart: 1,260 bars (52 weeks)
- 1H chart: 5,040 bars (52 weeks)
- Lower timeframes: Use Simple Daily mode instead
- **Confirmation Bars**: Bars needed to confirm high/low (default: 3, per Darvas)
### Volume Confirmation
- **Require Volume Confirmation**: Toggle on/off
- **Volume Spike Multiplier**: Threshold for "strong" volume (default: 1.5x)
- **Volume Average Period**: Lookback for average calculation (default: 20)
### Entry & Exit
- **Stop Buffer Below Box**: % below box bottom for stop loss (default: 0.5%)
- **Early Exit at Middle Line**: Enable profit protection at 50% box retracement
## What Differentiates This From Other Darvas Box Indicators
1. **Dual-Mode System**: Most indicators only implement one approach. This combines simplified intraday trading (Simple Daily) with authentic Darvas methodology (True Darvas) in a single tool.
2. **Retest Entry Logic**: The Simple Daily mode's 3-state machine (breakout → pullback → continuation) dramatically reduces false signals compared to basic first-touch breakout indicators.
3. **Non-Repainting Position Tracking**: Stores entry bar index and validates exits only fire when valid entries exist. Prevents orphaned signals and ghost exits.
4. **Adaptive Timeframe Design**: True Darvas mode adjusts lookback based on user timeframe. Simple Daily mode works on ANY timeframe (1m to 1D+).
5. **Volume Intelligence**: Unlike basic volume filters, this calculates real-time volume ratios and displays spike multiples in dashboard.
6. **Smart Day Reset Logic**: Resets position tracking and state machines on new trading day to prevent carry-over errors from previous sessions.
7. **Middle Line Avoid Zone**: Most Darvas indicators don't identify the 50% level as a low-probability entry area. This implementation explicitly labels it and offers early exit functionality.
## Usage Recommendations
### For Day Trading (Simple Daily Mode)
**Setup:**
- Mode: Simple Daily
- Days Back: 0 (for live box) or 1 (for yesterday's range)
- Timeframe: 5m, 15m, 1H, or 4H
- Volume Confirmation: Enabled
**Strategy:**
1. Wait for breakout above previous day high OR below previous day low
2. Price must pull back to test the broken level
3. Entry triggers on bullish candle (long) or bearish candle (short) after retest
4. Stop loss: Below box bottom (long) or above box top (short)
5. Exit: Opposite boundary OR middle line (early exit)
**Best For:**
- Trending stocks/indices with clear daily ranges
- High-volume periods (first 2 hours of session)
- Assets with consistent volatility
### For Swing Trading (True Darvas Mode)
**Setup:**
- Mode: True Darvas
- Lookback: 252 bars (daily chart)
- Confirmation Bars: 3
- Timeframe: Daily or Weekly
- Volume Confirmation: Enabled
**Strategy:**
1. Wait for box to reach State 3 (complete)
2. Entry: Breakout above top (long) or below bottom (short) on strong volume
3. Stop loss: Just below box bottom
4. Exit: Opposite boundary or early exit at middle line
5. Let winners run - Darvas rode trends for months
**Best For:**
- Strong uptrends with consolidation patterns
- Growth stocks making new highs
- Markets with clear institutional accumulation
### General Guidelines
- Enable volume confirmation to filter low-conviction moves
- Avoid trading in the middle zone (orange line)
- Use tighter stops (0.3-0.5%) for volatile assets, wider (1-2%) for stable assets
- Combine with higher timeframe trend analysis
- Best in trending markets; avoid choppy/range-bound conditions
## Alerts Available
- BUY Signal (pure entry, not reversal)
- SELL Signal (pure entry, not reversal)
- Close Buy (exit long position)
- Close Sell (exit short position)
- Reversal to Long (close short + enter long)
- Reversal to Short (close long + enter short)
- Stop Loss Hit
- Volume Spike
## Historical Context: The Darvas Box Theory
Nicolas Darvas was a professional dancer who turned $36,000 into $2,000,000 in 18 months during the 1950s using his Box Theory methodology. His approach:
1. **Focus on Momentum**: Only traded stocks making new 52-week highs
2. **Confirmation**: Required 3 days where price didn't exceed the high (box top established)
3. **Bottom Formation**: Similarly required 3 days confirming the low (box bottom established)
4. **Breakout Entry**: Bought when price broke above the box top with volume
5. **Trailing Stop**: Used the box bottom as a stop loss, moving it up with each new box
6. **Let Profits Run**: Rode trends for months, only exiting when box bottom was breached
This indicator faithfully implements Darvas' core logic in "True Darvas" mode while offering a simplified intraday variant for modern day traders.
## Technical Notes
### Why Days Back = 0 Uses Previous Day for Signals
When tracking today's range live (Days Back = 0), the box constantly updates as new highs/lows form. This creates a moving target that's impossible to "break out" from. Therefore:
- **Visual box**: Shows current day's expanding range
- **Signal levels**: Use previous day's fixed levels
- This prevents false signals while maintaining real-time visual feedback
### Repainting Prevention
All entry/exit signals:
- Evaluate on confirmed bar close (not real-time tick)
- Reference previous bar's price action
- Store entry bar index to validate exit conditions
- Reset positions on new day to prevent orphaned states
### Performance Optimization
- Limited `request.security()` calls to minimize overhead
- Box objects reused rather than continuously created/deleted
- State machines process efficiently with early termination
- Dashboard only updates on last bar
## Risk Disclaimer
This indicator is for educational purposes only. Trading involves substantial risk of loss. Past performance does not guarantee future results. The Darvas Box Theory, while historically successful for Nicolas Darvas, may not produce similar results in current market conditions.
Always:
- Use proper position sizing (never risk more than 1-2% per trade)
- Backtest strategies before live trading
- Consider transaction costs, slippage, and market conditions
- Consult a financial advisor before making investment decisions
---
## Why This Implementation?
Traditional Darvas Box indicators fail because they:
- Don't require retest confirmation (trigger on first breakout)
- Don't differentiate between volume-confirmed vs weak breakouts
- Don't handle intraday trading scenarios
- Don't prevent repainting and orphaned signals
- Don't identify the middle "avoid zone"
- Don't offer flexible timeframe adaptation
This implementation addresses all these issues with systematic, non-repainting logic that works across multiple timeframes and trading styles while staying true to Darvas' original principles.
```
---
**Latest Update (v1.5):**
- Upgraded to Pine Script v6
- Added table customization (position, size, horizontal/vertical layouts)
- Implemented retest entry logic (breakout → pullback → continuation)
- Enhanced visual labeling system
- Optimized box calculation performance for real-time updates
- Fixed position tracking to prevent orphaned exits on new trading days
- Added early exit detection at middle line
- Non-repainting signal confirmation
Pine Script® インジケーター






















