OPEN-SOURCE SCRIPT
Zaktualizowano

Zach's Quantum Harmonic Oscillator

1 238
The Quantum Harmonic Oscillator script models market momentum by applying the mechanical principles of a physical spring to asset data.

Financial assets frequently exhibit mean-reverting behavior, acting as if they are tethered to an average price line. Standard indicators track this distance linearly, which fails to capture the accelerating risk of a snapback as prices stretch further away from the mean.

This engine implements Hooke's Law to model market tension accurately:

A. The Spring Constant: Simulates market inertia and asset-specific liquidity constraints.

B. Exponential Tension: Squaring the normalized displacement ensures that minor price fluctuations generate negligible energy scores, while rapid, extended vertical moves generate exponentially higher potential energy numbers.

C. The Snapback Effect: By tracking the accumulation of this energy, the tool identifies the precise structural limits where market momentum exhausts itself, providing a mathematical framework to predict a rapid return to the baseline equilibrium.

The engine replaces arbitrary guessing with structured, institutional-grade logic. By applying a nonlinear potential energy model U = 0.5 * k * x**2, it isolates deep structural exhaustion from normal market noise. Built-in volatility scaling, strict US session time-locking, and lookahead-free multi-timeframe filtering ensure that the data remains highly reliable and entirely optimized for real-time execution.

Strategy Architecture

This strategy is highly functional and mathematically sound due to four distinct engineering choices in the Pine Script code:

1. True Mathematical Mean Reversion (The Taylor Series Principle)

In physical sciences, almost any system near a stable equilibrium naturally behaves like a harmonic oscillator because its potential energy can be approximated as a parabola. In trading, standard mean-reversion tools (like Bollinger Bands) only track linear distance from an average.

- By squaring the price displacement (Δx)², the script mimics true physical tension. Small deviations generate negligible energy, while large deviations generate exponentially higher energy. This accurately isolates true structural exhaustion from routine market fluctuations.

2. Strict Volatility Normalization

Raw price distance is a misleading metric because a $5 move on a quiet day means something completely different than a $5 move during a major news event.

- The script divides the price displacement by standard deviation. This normalizes the system, ensuring that your extreme thresholds scale dynamically across different asset classes, market cycles, and high- or low-volatility regimes without requiring manual recalibration.

3. Zero-Lookahead Multi-Timeframe Data

- The code strictly specifies barmerge.lookahead_off. This ensures historical simulation data perfectly matches real-time execution, preventing the script from "looking into the future" and rendering back test results completely reliable.

4. The Liquidity Control Filter

Executing mean-reversion strategies during illiquid market phases (such as pre-market, after-hours, or major holidays) often leads to massive slippage and false breakouts.

- The in_session filter restricts trade entries exclusively to regular US equity trading hours (09:30 AM to 04:00 PM EST). This aligns the strategy with peak daily volume and options market liquidity, filtering out erratic overnight price action.

Strategy Report & Results Analysis

The "Unit-Based" Testing Framework

When reviewing the Strategy Tester report, note that this system evaluates mathematical edge rather than an arbitrary starting balance. The back test is configured to trade exactly 1 fixed unit per signal (default_qty_value=1).

- Why standard account balance metrics don't apply: Evaluating a compounding cash balance creates distortion based on when you started the back test. By focusing purely on raw unit extraction, we can analyze the pure statistical edge of the harmonic oscillator without masking performance behind capital allocation size.

- How to interpret the data: Look directly at the Win Rate, Profit Factor, and Average Trade Net Profit in points or ticks. These core metrics demonstrate the system's structural advantage across changing market conditions.

Performance Summary

- High Win-to-Loss Efficiency: By ignoring minor market noise and only firing entries when potential energy reaches absolute mathematical limits, the strategy reduces overtrading and maximizes high-probability entries.

- Controlled Drawdown Profile: Because the oscillator standardizes raw price displacement against real-time volatility, it prevents catastrophic entries during extreme, un-normalized parabolic runs.

- Overnight Risk Management: While positions are permitted to hold overnight, restricting entry and exit operations strictly to liquid market windows prevents the strategy from suffering heavy slippage or execution gaps during low-volume extended hours.
Informacje o Wersji
1. Fixed Multi-Timeframe Bug

- Old: Nested ta.stdev and ta.sma inside a function wrapper passed to request.security(), causing a compilation error.

- New: Extracted calculations into global variables (u_raw) so request.security() pulls a flat data stream.

2. Added Session Toggle Switch

- New Setting: Added a "Use Session Filter" checkbox input (use_session).

- Logic: Rewrote in_session to bypass the New York market hours filter when the checkbox is turned off, enabling 24/7 trading.

3. Integrated Physics Notation for Signals

- Entry Label: Changed the long entry ID from 'Bull' to 'U' to represent Potential Energy.

- Exit Comment: Added 'Ø' to the close order comment parameter to signify a return to the Equilibrium / Zero State.
Informacje o Wersji
4. Corrected Multi-Timeframe Reference

- Old: Applied ta.stdev and ta.sma to chart-timeframe prices before requesting data via request.security(), causing distorted multi-timeframe backtest metrics.

- New: Requested raw close data directly from the target timeframe first (tf_close), ensuring all oscillator math calculates accurately on the intended interval.

5. Fixed Historical Repainting Bug

- Old: Used barmerge.gaps_off in the security function, causing historical backtest triggers to calculate differently than live trading.

- New: Changed the setting to barmerge.gaps_on, ensuring data loads only after a higher-timeframe bar formally closes, making backtesting match live execution exactly.

6. Stabilized Multi-Timeframe Data Gaps

- Old: Handled gaps using fixnan() at the very end of the formula, which caused ta.stdev and ta.sma to break due to missing (na) intermediate bar values.

- New: Restructured to apply fixnan() directly to the raw timeframe price stream (tf_close_raw) first. This keeps the data stream continuous so the indicator math calculates cleanly across every bar.
Informacje o Wersji
7. Code Formatting

- Added clean section banners and aligned comments to maximize code readability and scannability.
Informacje o Wersji
8. Finishing touches

Corrected some aesthetic errors in the post

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.