QV 1D/1W 2BX & FVB Strategy

### Overview of the Strategy
The "QV 1D/1W 2BX & FVB Strategy" is a custom trading strategy implemented in Pine Script v5 for the TradingView platform. It is designed for directional trading (long or short positions) on any asset, using a combination of momentum oscillators, trailing stops, fair value deviation bands, and structure breaks to generate entry and exit signals. The strategy name likely refers to "QuantVault" (the creator), using two timeframes (1D daily and 1W weekly) for "2BX" (possibly "2-Bar Xtrender" or similar), and "FVB" for Fair Value Bands.
This is not an overlay strategy (it plots indicators in a separate pane below the price chart), and it supports pyramiding (adding to positions) with a limit of 1 additional entry. It uses 5% of equity per trade by default, with an initial capital of $50,000 and commission accounted for. The strategy can be toggled for long-only or short-only modes and includes customizable enables/disables for various entry/exit rules and alerts. It aims to capture trends by entering on momentum confirmation across multiple timeframes and exiting based on reversals, profit targets (via bands), or stops.
The core idea is trend-following with risk management: Enter when higher-timeframe momentum aligns with lower-timeframe improvements, add to winners when price breaks a trailing level, and exit via multiple protective mechanisms or scaled profit-taking at deviation levels.
### Key Indicators and Calculations
The strategy relies on several custom indicators plotted on the chart or used for signals:
1. **Xtrender Oscillators (Short-Term and Long-Term)**:
- These are momentum indicators based on RSI (Relative Strength Index) applied to differences in EMAs (Exponential Moving Averages).
- **Short-Term Xtrender (on TF1 and TF2)**: Calculated as `RSI(EMA(close, short_l1) - EMA(close, short_l2), short_l3) - 50`. This creates an oscillator centered around 0.
- TF1 (default: 1D) is used for precise timing.
- TF2 (default: 1W) provides broader trend direction, with persistent state to detect if it's increasing or decreasing.
- Plotted as histograms: Green shades for positive/upward momentum, red for negative/downward. Special colors highlight 2-bar confirmations or centerline crosses.
- **Long-Term Xtrender**: Simpler RSI of EMA(close, long_l1) over long_l2, but it's defined and not directly used in the provided logic (possibly a remnant or for future expansion).
- A centerline at 0 separates bullish (above) from bearish (below) territories.
- 2-Bar Conditions: Checks for consecutive bars where the TF1 oscillator is red/green and decreasing/increasing, used for exits.
2. **Red ATR Line (Trailing Stop)**:
- A volatility-based trailing line similar to SuperTrend, using ATR (Average True Range) over a length (default: 10) multiplied by a factor (default: 2.5).
- It flips direction based on price closes: Upward trailing for longs (below price), downward for shorts (above price).
- Plotted as a red line on the price chart (forced overlay).
- Used for entries (pyramiding on cross), exits (full exit on adverse cross), and conditional checks.
3. **Fair Value Bands (FVB)**:
- These are dynamic deviation bands around a "fair price" middle line, which is an SMA (Simple Moving Average) of OHLC4 (average of open/high/low/close) over a length (default: 33).
- **Deviation Calculation**: Analyzes spreads from highs/lows to the fair price, using medians of historical deviations and pivot highs/lows (over 5 bars left/right).
- Upper bands (for longs): Boosted deviations above fair price, multiplied by factors (0.6 for 1x, 1.0 for 2x, 1.4 for 3x).
- Lower bands (for shorts): Similar but below fair price.
- Plotted only for the selected direction: Yellow (1x), orange (2x), red (3x) lines on the price chart.
- Acts as profit targets: Scale out or exit fully when price touches/crosses these bands.
- Uses arrays to store historical deviations/pivots, capped at 1000-2000 elements for efficiency.
4. **Break of Structure (BOS)**:
- Identifies the last swing low (for longs) or high (for shorts) using pivot lows/highs (5 bars left/right).
- Plotted as a white line on the price chart if enabled.
- Used as a stop-loss level: Exit if price breaks below (longs) or above (shorts).
5. **Other Elements**:
- Custom T3 (Tillson Moving Average) function is defined but not used in the script—possibly for future or removed features.
- Persistent variables track position states (e.g., initial quantity, doubled status, waiting for exits) to manage scaling and prevent re-entries after full exits until conditions reset.
### How the Strategy Works: Entry Logic
Entries are direction-specific and require alignment between timeframes for momentum.
- **Main Entry**:
- **For Longs**: Enabled if `enable_main_entry` is true.
- TF2 condition: Either increasing or above a threshold (default: 10).
- TF1 condition: Oscillator is increasing (current > previous).
- Position check: No current long position (or fully exited previously), and price is at or below the 2x upper band (to avoid chasing highs).
- Triggers a long entry with 5% equity.
- **For Shorts**: Symmetric but inverted.
- TF2 decreasing or below -threshold.
- TF1 decreasing.
- No short position (or fully exited), price at or above 2x lower band.
- Triggers a short entry.
- **Pyramiding (Adding to Position)**:
- If `enable_pyramiding` is true and not already doubled.
- For longs: When price crosses above the red ATR line (breaking resistance).
- For shorts: Crosses below red ATR.
- Adds the same initial quantity, effectively doubling the position (pyramiding=1 limits to one add).
Upon entry, it resets state variables (e.g., records initial qty, sets BOS level to last swing low/high).
### How the Strategy Works: Exit Logic
Exits are multifaceted, with full closes for protection and partial scale-outs for profit-taking. All are conditional on enabled inputs and position direction.
- **Full Exits (Close Entire Position)**:
1. **ATR Exit** (`enable_atr_exit`): For longs, if price crosses below red ATR (trailing stop hit). Symmetric for shorts (cross above).
2. **2-Bar Exit** (`enable_2bar_exit`): For longs, if TF1 is red and decreasing for 2 bars, and price is below red ATR. For shorts, green and increasing for 2 bars, price above red ATR.
3. **TF1 Centerline Exit** (`enable_tf1_below0_exit`): For longs, TF1 crosses below 0 and price below red ATR. For shorts, crosses above 0 and price above red ATR.
4. **Large TF1 Change Exit** (`enable_large_decrease_exit`): For longs, TF1 decreases by more than `exit_amount` (default: 40). For shorts, increases by that amount.
5. **BOS Exit** (`enable_bos_exit`): For longs, price crosses below swing low. For shorts, above swing high.
6. **3x Band Full Exit** (`enable_3x_exit`): Waits for crossover above 3x upper (longs) or below 3x lower (shorts), then closes on cross back under/over.
- **Partial Scale-Outs (50% of Position)**:
- Use "waiting" flags to detect touch and retreat from bands.
- **1x Scale-Out** (`enable_1x_scaleout`): Unlimited repeats. For longs, crossover above 1x upper, then close 50% on crossunder. Symmetric for shorts at 1x lower.
- **2x Scale-Out** (`enable_2x_scaleout`): Similar, at 2x bands.
After a full exit, it sets `has_fully_exited` to prevent immediate re-entry until price retreats to the 2x band.
### Alerts
- **Band Touch Alerts** (`enable_band_alerts`): Triggers on price touching any 1x/2x/3x upper/lower band from either side (e.g., "Price touched 1x Upper Deviation band from below").
- **BOS Touch Alert** (`enable_bos_touch_alert`): On touching BOS level.
- **BOS Cross Alert** (`enable_bos_cross_alert`): On crossing and closing beyond BOS.
- Alerts reset per bar and use `alert.freq_all` or `once_per_bar_close` to avoid spam.
### Additional Notes
- The strategy is backtestable in TradingView, with performance depending on parameters (e.g., timeframes, multipliers).
- It's momentum-driven on higher TFs for bias, with lower TF for timing, and volatility/fair value for risk/reward.
- No external data or ML; all calculations are self-contained using TA-Lib functions.
- Potential improvements: The unused T3 and long-term Xtrender could be integrated for filtering.
Скрипт с ограниченным доступом
Только пользователи, одобренные автором, могут получить доступ к этому скрипту. Вам нужно отправить запрос и получить разрешение на его использование. Обычно доступ предоставляется после оплаты. Для получения подробной информации следуйте инструкциям автора ниже или свяжитесь с QuantVault напрямую.
TradingView НЕ рекомендует платить за скрипт или использовать его, если вы не доверяете его автору и не понимаете, как скрипт работает. Вы всегда можете найти бесплатные скрипты с открытым исходным кодом в Скриптах сообщества.
Инструкции от автора
Отказ от ответственности
Скрипт с ограниченным доступом
Только пользователи, одобренные автором, могут получить доступ к этому скрипту. Вам нужно отправить запрос и получить разрешение на его использование. Обычно доступ предоставляется после оплаты. Для получения подробной информации следуйте инструкциям автора ниже или свяжитесь с QuantVault напрямую.
TradingView НЕ рекомендует платить за скрипт или использовать его, если вы не доверяете его автору и не понимаете, как скрипт работает. Вы всегда можете найти бесплатные скрипты с открытым исходным кодом в Скриптах сообщества.