INVITE-ONLY SCRIPT

QV 2H/4D 2BX & FVB Strategy

34
QuantVault

### Strategy Description for Presentation

The **QV 2H/4D 2BX & FVB Strategy** is a versatile, timeframe-based trading system designed for TradingView using Pine Script v5. It combines momentum oscillators (B-Xtrender) across a 2-hour (120-minute) and 4-day timeframe with Fair Value Bands (FVB) for dynamic support/resistance levels, a trailing ATR-based stop (Red Line), and Break of Structure (BOS) detection. The strategy supports both long and short directions, allowing for main entries, optional pyramiding (adding to positions), and multiple exit mechanisms including full exits and partial scale-outs. It's optimized for trend-following in volatile markets like forex, stocks, or crypto, with built-in risk management via percent-of-equity sizing (default 5% per trade) and commission accounting. Alerts are included for band touches and BOS events to aid real-time monitoring. Key features include customizable toggles for entries/exits, making it adaptable for backtesting or live trading with an initial capital of $50,000.

This strategy emphasizes multi-timeframe confirmation: the higher timeframe (4D) provides directional bias, while the lower (2H) drives precise entries and exits. It aims to capture trends by entering on momentum shifts and exiting via profit-taking at deviation bands or protective stops, reducing drawdowns through pyramiding limits (max 1 add-on) and conditional re-entries only after full exits or band resets.

### Detailed Breakdown of How It Works

The strategy operates as a complete trading system with indicator calculations, entry logic, position management, exit conditions, and alerts. Below, I'll explain each section step by step, including the underlying calculations and logic flows. Note that all plots (e.g., histograms, lines, bands) are overlaid on the chart unless specified otherwise, but the strategy itself plots in a separate pane (overlay=false).

#### 1. Input Parameters
Users can customize the strategy via inputs, which control direction, features, and indicator settings. These are grouped into categories for ease:

| Category | Key Inputs | Description/Default |
|----------|------------|----------------------|
| **Direction** | `direction` | "Long" or "Short" – restricts strategy to one side (default: "Long"). |
| **Entry Settings** | `enable_main_entry`, `enable_pyramiding` | Toggle main entry and adding to positions (both default: true). |
| **Exit Settings** | `enable_atr_exit`, `enable_2bar_exit`, `enable_tf1_below0_exit`, `enable_large_decrease_exit`, `enable_bos_exit`, `enable_1x_scaleout`, `enable_2x_scaleout`, `enable_3x_exit` | Toggles for various full/partial exits (all default: true). |
| **Alert Settings** | `enable_band_alerts`, `enable_bos_touch_alert`, `enable_bos_cross_alert` | Toggles for deviation band and BOS alerts (all default: true). |
| **Indicator Lengths** | `short_l1` (5), `short_l2` (20), `short_l3` (5), `long_l1` (20), `long_l2` (5) | Periods for short/long Xtrender EMAs and RSIs. |
| **Timeframes** | `tf1` ("120" – 2 hours), `tf2` ("4D" – 4 days) | Multi-timeframe data sources. |
| **Exit/Thresholds** | `exit_amount` (40.0), `tf2_threshold` (10.0) | TF1 change for large exit; TF2 momentum threshold. |
| **ATR & Bands** | `len` (10 – ATR length), `mult_red` (2.5 – Red Line multiplier), `fair_value_length` (33), `fair_value_mult1/2/3` (0.6/1.0/1.4) | Settings for Red ATR trailing line and FVB deviation levels. |

A custom T3 moving average function is defined but not used in the core logic (possibly for future extensions).

#### 2. Indicator Calculations
The strategy relies on several computed indicators for signals:

- **B-Xtrender Oscillators (Short-Term)**:
- Calculated on TF1 (2H) and TF2 (4D): `shortTermXtrender_tf1/tf2 = RSI(EMA(close, short_l1) - EMA(close, short_l2), short_l3) - 50`.
- This creates a momentum histogram centered at 0, showing overbought (>0, green) or oversold (<0, red) conditions.
- Combined: `combinedShortTermXtrender = tf1 + tf2` (not directly used in entries/exits).
- TF2 direction is tracked persistently: `tf2_increasing` if change >0, `tf2_decreasing` if <0.
- Plotted as columns (TF1 with color variations for 2-bar trends/crosses) and area (TF2, translucent).

- **Long-Term Xtrender**:
- `longTermXtrender = RSI(EMA(close, long_l1), long_l2)`.
- Not used in the provided logic (potential remnant or for visualization).

- **2-Bar Conditions**:
- For longs: `tf1_green_and_increasing_2bars` – TF1 >0 and increasing for 2 bars.
- For shorts: `tf1_red_and_decreasing_2bars` – TF1 <0 and decreasing for 2 bars.
- Used for exits and histogram coloring.

- **Centerline Crosses**:
- `tf1_cross_above_zero` (crossover >0), `tf1_cross_below_zero` (crossunder <0).
- Influences histogram colors and exits.

- **Red ATR Line**:
- Base ATR: `atr = ta.atr(len)`.
- Trailing levels: `up_red = close - (mult_red * atr)`, `dn_red = close + (mult_red * atr)`.
- Trend detection: Switches between up/dn based on close vs previous trail, with breaks flipping direction.
- Plotted as a red broken line on the price chart – acts as a dynamic trailing stop.

- **Fair Value Bands (FVB)**:
- Fair price: `fairPriceSmooth = SMA(ohlc4, fair_value_length)` (blue midline).
- Deviations calculated from high/low spreads relative to fair price, using medians of historical pivots and boosts.
- Upper bands (for longs): `upper1/2/3 = fairPriceSmooth + mult1/2/3 * pivot-based spread` (colors: yellow, orange, red).
- Lower bands (for shorts): `lower1/2/3 = fairPriceSmooth - mult1/2/3 * pivot-based spread`.
- Only relevant bands plot based on direction.
- Uses arrays (limited to 1000-2000 elements) for median calculations to adapt dynamically.

- **Break of Structure (BOS)**:
- Swing levels: `last_swing_low = pivotlow(low, 5,5)`, `last_swing_high = pivothigh(high, 5,5)`.
- Plotted as white lines (SL for longs, SH for shorts) if enabled.

A centerline at 0 is plotted on the oscillator pane.

#### 3. Entry Logic
Entries are direction-specific and use multi-timeframe momentum for confirmation. Position sizing is 5% of equity, with pyramiding limited to one add-on.

- **Long Entries**:
- Main: If `enable_main_entry` and (TF2 increasing or > threshold) and TF1 increasing, and no position (or after full exit if close <= upper2).
- Command: `strategy.entry('Long', strategy.long)`.
- On new position: Reset flags, set initial qty, store swing low as SL.
- Pyramiding: If enabled and not doubled, add equal qty on crossover above Red Line.

- **Short Entries**:
- Mirror of longs: TF2 decreasing or < -threshold, TF1 decreasing, no position (or after full exit if close >= lower2).
- Command: `strategy.entry('Short', strategy.short)`.
- Pyramiding: Add on crossunder below Red Line.

Re-entries are blocked until full exit unless price resets to a band (e.g., below upper2 for longs).

#### 4. Position Management
Uses variables to track state:
- Initial qty, doubled flag, waiting for scale-out flags, full exit flag (per direction).
- Ensures scale-outs only trigger after crosses, and full exits set flags to allow re-entries.

#### 5. Exit Logic
Exits are checked only when in position and use multiple independent conditions. Full exits set `has_fully_exited` to true. Scale-outs are partial (50% of current size for longs, initial qty *0.5 for shorts – note asymmetry).

- **Long Exits**:
1. ATR: Crossunder below Red Line (full, if enabled).
2. 2-Bar: TF1 red/decreasing for 2 bars and below Red Line (full).
3. TF1 Below 0: Crossunder centerline and below Red Line (full).
4. Large TF1 Decrease: TF1 drop > exit_amount (full).
5. BOS: Crossunder swing low (full, if enabled).
6. 1x Scale-Out: Crossover upper1, then crossunder (50%).
7. 2x Scale-Out: Similar for upper2 (50%).
8. 3x Exit: Similar for upper3 (full).

- **Short Exits**:
- Mirror: ATR crossover above Red Line, TF1 green/increasing 2 bars above Red Line, TF1 above 0 above Red Line, large TF1 increase, BOS crossover swing high, scale-outs on lower bands (crossunder then crossover).

Exits include comments for chart labeling (e.g., 'Full ATR', '1x 50%').

#### 6. Alert Conditions
Alerts fire in real-time or on bar close, resetting flags at new bars to avoid duplicates:
- **Band Touches** (if enabled): Touch from below/above for each 1x/2x/3x upper/lower band.
- **BOS Touches** (if enabled): Touch from above/below for SL/SH.
- **BOS Cross & Close** (if enabled): Cross and close below SL (longs) or above SH (shorts) – once per bar close.

This setup provides comprehensive notifications for potential entries, exits, or reversals.

In summary, the strategy enters on aligned multi-timeframe momentum, adds on Red Line breaks, and exits via protective stops or profit-taking at adaptive bands, making it a robust trend-capture tool with risk controls. For presentation, emphasize its modularity – users can disable features to simplify or focus on specific signals. If backtesting, test on various assets/timeframes to tune parameters like multipliers.

Clause de non-responsabilité

Les informations et les publications ne sont pas destinées à être, et ne constituent pas, des conseils ou des recommandations en matière de finance, d'investissement, de trading ou d'autres types de conseils fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.