OPEN-SOURCE SCRIPT
Adaptive Statistical Location + Pressure Engine V1

Adaptive Statistical Location + Pressure Engine — V1
ASLP describes where price sits relative to historical daily and session excursions, whether the current movement is directional or two-sided, and whether expansion is strengthening or deteriorating. When enough comparable resolved events exist, it also displays empirical first-touch outcome estimates.
Its distinguishing design combines separate upside/downside excursion distributions, independent daily/session context, non-overlapping pressure observations, and a causal event database. It keeps statistical location, movement consumption and future outcomes separate.
A high percentile describes an extended location. It does not, by itself, imply a reversal or provide a buy/sell instruction.
1. Reading the display
Curves deliberately break when their session/day reference changes or a valid estimate is unavailable. Connecting different opens would imply continuity that does not exist. The subtle daily boundary tint appears in the indicator pane.
2. What location measures
For each completed historical period, the engine stores percentage Open-to-High and Open-to-Low excursions separately. During an active period it compares the current close's displacement from that period's open with the appropriate historical distribution.
Upper location = 100 × fraction of matched historical upper excursions less than or equal to the current upward displacement.
Lower location = 100 × fraction of matched historical lower excursions less than or equal to the current downward displacement.
For example, an upper reading of 90 means the current upward displacement equals or exceeds 90% of sampled historical upper excursions. It does not mean a 90% chance of continuation or reversal. Finite-sample readings can reach 100 without imposing a price ceiling.
Movement matching uses weekday, session, completed-day volatility regime and previous completed-period state where supported, then relaxes conditioning when samples are sparse. The selected historical distributions are frozen at the start of the active period.
Default location regions
The direction is reported separately as Upper or Lower. These are empirical descriptive regions, not fair-value estimates. Daily and session location use independent opens and distributions; a stretched session can coexist with a normal daily reading. Benchmarks are completed-period distributions, not same-minute-of-session distributions, so an early session can naturally look compressed.
3. Range, efficiency and pressure
Marginal progress is ranked against historical blocks from the same session and elapsed-age bucket. The direction must remain consistent across the block. Default blocks are 30 minutes.
Pressure categories
Pressure reflects completed blocks and can remain unchanged between them. Efficiency and close ranks use completed-period benchmarks; they are descriptive comparisons, not calibrated future-outcome probabilities.
4. State and exhaustion logic
States follow an explicit precedence rather than displaying overlapping categories. Exhaustion requires deterioration after expansion. The separate toward-open event outcome below can occur before any cross of the session open.
5. Empirical first-touch outcomes
Eligible observations come from expansion, extreme-entry and post-expansion weakening states. Their forecasts and barriers are frozen at the confirmed entry close. Observation starts on the following candle.
With default settings, an event records which of these happens first:
Invalid/gapped observations can be censored and excluded from outcome training. There is one pending event across the engine at a time. Each session instance can admit each direction/family combination only once, with optional admission at completed-block checkpoints. This prevents repeatedly labeling every candle of one sustained condition.
The dashboard percentages belong to the timestamped last admitted event. They are not continuously recalculated predictions for the latest candle. Compact shows C and R; Detailed also shows Timeout and Ambiguous. The four classes sum to 100% before display rounding.
6. Samples, fallback and uncertainty
A forecast requires at least 40 resolved events in its selected bucket by default. Total learned events can be much larger than the number matching a particular state.
Core matching uses session, location and pressure, while always preserving direction, elapsed-age bucket and event family. Fallback progressively removes session, pressure and location. The optional broadest fallback also pools event families while retaining direction and age. Such estimates are explicitly labeled broad/pooled; they are not precise forecasts for one narrow state.
When at least 20 records exist in the broader parent group outside the selected bucket, estimates are shrunk toward that disjoint group's frequencies. The default prior weight is 20. Otherwise raw frequencies are used. Prior weight never increases the reported observed sample count.
Optional regime, weekday or previous-state refinement is selected only when supported by paired historical forecast errors: at least 60 evaluations and mean Brier improvement greater than 2.4 estimated standard errors. Only one additional feature is selected at a time. This is a practical screening rule, not proof that a feature will remain useful.
Reliability labels follow explicit rules:
Research mode reports raw 95% Wilson intervals for C and R. These are nominal binomial intervals around unshrunk class frequencies, not posterior intervals around the displayed shrunk probabilities. Serial dependence and market change can make actual uncertainty larger.
7. Setup and daily/session timing
Default independent session windows:
These are configurable analytical windows, not universal exchange definitions. The overlap window is London-timed and does not automatically recalculate the true intersection of London and New York hours during differing DST transition weeks. Auto priority selects the highest-numbered enabled active session: NY PM, New York, overlap, London, then Asia. Independent session statistics continue to update, but event admission follows the focus session.
8. Parameter guide
9. Historical evaluation and alerts
Research mode compares forecasts frozen at entry with later first-touch outcomes. It reports model and broader-base Brier loss on the same supported events, Brier skill, most-likely-class accuracy, and mean predicted versus observed R frequency. Lower Brier loss is better. Zero skill means no improvement over the baseline; negative skill means worse performance. This is a forecast-quality audit, not a trading strategy backtest: it has no entries/exits, costs, slippage or portfolio P&L.
Supported historical entry forecasts, barrier prices and entry/result timestamps are available in the Data Window. Use the entry timestamp to associate an outcome with its original forecast. Unscored warm-up observations are not retroactively assigned predictions using later data.
Available alerts cover upper/lower extreme entry, strong expansion, weakening pressure, upper/lower exhaustion candidates, empirical C/R thresholds, and resolved C/R outcomes. Configure alerts for Once Per Bar Close. Statistical alerts describe observed conditions or empirical event forecasts; they are not order instructions.
10. Training and limitations
Author and license
V1 is the first public release by uPaSKaL. Source code is distributed under the Mozilla Public License 2.0.
ASLP describes where price sits relative to historical daily and session excursions, whether the current movement is directional or two-sided, and whether expansion is strengthening or deteriorating. When enough comparable resolved events exist, it also displays empirical first-touch outcome estimates.
Its distinguishing design combines separate upside/downside excursion distributions, independent daily/session context, non-overlapping pressure observations, and a causal event database. It keeps statistical location, movement consumption and future outcomes separate.
A high percentile describes an extended location. It does not, by itself, imply a reversal or provide a buy/sell instruction.
1. Reading the display
- Teal curve: signed location relative to the selected session open.
- Purple curve: signed location relative to the trading-day open.
- Positive values: price is above the corresponding open; magnitude is its upper-excursion percentile.
- Negative values: price is below the corresponding open; magnitude is its lower-excursion percentile. A reading of -90 means the 90th percentile of downside excursion, not the 10th percentile of a symmetric price distribution.
- Zero: the corresponding open. Location is not a distance scale: a 10-point change on the pane does not mean a fixed price change.
- State ribbon: green indicates expansion, darker green strong expansion, gold two-sided volatility, blue an extreme state, orange/red an exhaustion candidate, and purple reversion in progress. Gray shades represent normal, compressed or unavailable context. The ribbon's vertical position is a layout choice, not a score.
- Small pane markers: circles identify extreme entries; red diamonds identify exhaustion candidates. Price-chart text and event paths are off by default.
- Dashboard: Compact emphasizes location, state, pressure and the most recent event forecast. Detailed and Research expose additional diagnostics.
Curves deliberately break when their session/day reference changes or a valid estimate is unavailable. Connecting different opens would imply continuity that does not exist. The subtle daily boundary tint appears in the indicator pane.
2. What location measures
For each completed historical period, the engine stores percentage Open-to-High and Open-to-Low excursions separately. During an active period it compares the current close's displacement from that period's open with the appropriate historical distribution.
Upper location = 100 × fraction of matched historical upper excursions less than or equal to the current upward displacement.
Lower location = 100 × fraction of matched historical lower excursions less than or equal to the current downward displacement.
For example, an upper reading of 90 means the current upward displacement equals or exceeds 90% of sampled historical upper excursions. It does not mean a 90% chance of continuation or reversal. Finite-sample readings can reach 100 without imposing a price ceiling.
Movement matching uses weekday, session, completed-day volatility regime and previous completed-period state where supported, then relaxes conditioning when samples are sparse. The selected historical distributions are frozen at the start of the active period.
Default location regions
- Below 25: Central.
- 25 to below 75: Normal.
- 75 to below 90: Stretch.
- 90 to below 95: Extreme.
- 95 and above: Tail.
The direction is reported separately as Upper or Lower. These are empirical descriptive regions, not fair-value estimates. Daily and session location use independent opens and distributions; a stretched session can coexist with a normal daily reading. Benchmarks are completed-period distributions, not same-minute-of-session distributions, so an early session can naturally look compressed.
3. Range, efficiency and pressure
- Range percentile: ranks the active High-Low range against historical completed ranges. It measures total movement, not where the close sits.
- Consumption: current range divided by historical Q50, Q75 or Q90 range. Consumption above 100% means that historical quantile has been exceeded; it does not mean price has exhausted a fixed allowance.
- Directional efficiency: abs(Close-Open)/(High-Low). High values indicate net displacement accounts for much of the observed range.
- Close Location Value: ((Close-Low)-(High-Close))/(High-Low). Its -1 to +1 scale identifies where the close sits inside the active range. A separate direction-adjusted close rank evaluates proximity to the movement's own extreme.
- Marginal progress: over completed non-overlapping blocks, the engine divides signed close progress by incremental range, with a denominator floor of 0.05 × frozen Q50 by default. This limits instability when range barely grows. The value can exceed 1 and is not a probability.
Marginal progress is ranked against historical blocks from the same session and elapsed-age bucket. The direction must remain consistent across the block. Default blocks are 30 minutes.
Pressure categories
- Strengthening: efficiency and direction-adjusted close ranks are at least the 75th percentile, marginal progress rank is at least the 50th percentile, signed progress is positive, and price extends the directional extreme.
- Weakening: efficiency declines, price retreats from the directional extreme, and either marginal rank is at or below the 25th percentile or signed progress is negative.
- Stable: a rated block meets neither condition.
- Unrated: insufficient valid block history. This is not evidence of stable pressure.
Pressure reflects completed blocks and can remain unchanged between them. Efficiency and close ranks use completed-period benchmarks; they are descriptive comparisons, not calibrated future-outcome probabilities.
4. State and exhaustion logic
- Compressed so far: range percentile is below the Central boundary. This does not predict that the completed session will remain compressed.
- Directional expansion: range percentile reaches the Stretch threshold, while efficiency and directed-close ranks both reach 75.
- Strong expansion: directional expansion plus strengthening pressure.
- Two-sided volatility: range reaches the Stretch threshold while efficiency rank is 25 or lower.
- Statistical extreme: location reaches the Extreme threshold when a higher-priority state does not apply.
- Exhaustion candidate: the same direction previously expanded during this session, location remains extreme, range reaches the Stretch threshold, and pressure weakens.
- Reversion in progress: after an exhaustion candidate, price crosses the session open in the opposing direction.
States follow an explicit precedence rather than displaying overlapping categories. Exhaustion requires deterioration after expansion. The separate toward-open event outcome below can occur before any cross of the session open.
5. Empirical first-touch outcomes
Eligible observations come from expansion, extreme-entry and post-expansion weakening states. Their forecasts and barriers are frozen at the confirmed entry close. Observation starts on the following candle.
With default settings, an event records which of these happens first:
- Continuation first (C): price travels another 0.25 × frozen session Q50 in the event direction.
- Toward-open first (R): price travels 0.35 × Q50 against that direction, capped at the distance back to the session open. R means a retracement toward the open, not necessarily a full trend reversal.
- Timeout: neither barrier is reached within 120 minutes or before the source session ends, whichever comes first.
- Ambiguous: both barriers are touched in the same candle and OHLC cannot establish their order. If the candle opens beyond a barrier, that known first observation is used; otherwise the event remains a separate ambiguous class.
Invalid/gapped observations can be censored and excluded from outcome training. There is one pending event across the engine at a time. Each session instance can admit each direction/family combination only once, with optional admission at completed-block checkpoints. This prevents repeatedly labeling every candle of one sustained condition.
The dashboard percentages belong to the timestamped last admitted event. They are not continuously recalculated predictions for the latest candle. Compact shows C and R; Detailed also shows Timeout and Ambiguous. The four classes sum to 100% before display rounding.
6. Samples, fallback and uncertainty
A forecast requires at least 40 resolved events in its selected bucket by default. Total learned events can be much larger than the number matching a particular state.
Core matching uses session, location and pressure, while always preserving direction, elapsed-age bucket and event family. Fallback progressively removes session, pressure and location. The optional broadest fallback also pools event families while retaining direction and age. Such estimates are explicitly labeled broad/pooled; they are not precise forecasts for one narrow state.
When at least 20 records exist in the broader parent group outside the selected bucket, estimates are shrunk toward that disjoint group's frequencies. The default prior weight is 20. Otherwise raw frequencies are used. Prior weight never increases the reported observed sample count.
Optional regime, weekday or previous-state refinement is selected only when supported by paired historical forecast errors: at least 60 evaluations and mean Brier improvement greater than 2.4 estimated standard errors. Only one additional feature is selected at a time. This is a practical screening rule, not proof that a feature will remain useful.
Reliability labels follow explicit rules:
- Insufficient: fewer observations than Minimum outcome bucket n.
- Low / broad fallback: location-only, family-base or pooled-family matching.
- Moderate: a more specific bucket with at least 80 events and maximum raw class-wise Wilson interval width no greater than 22 percentage points.
- Good (nominal): a more specific bucket with at least 160 events and maximum interval width no greater than 16 percentage points.
- Low: other supported forecasts.
Research mode reports raw 95% Wilson intervals for C and R. These are nominal binomial intervals around unshrunk class frequencies, not posterior intervals around the displayed shrunk probabilities. Serial dependence and market change can make actual uncertainty larger.
7. Setup and daily/session timing
- Use standard time-based candles on a positive-priced instrument. Start with 5-minute or 15-minute charts. The script accepts 1–30 minutes; pressure blocks and outcome horizons must be exact multiples of the selected timeframe.
- Leave Daily reset reference at Symbol trading day to follow the data feed's daily-bar boundaries. Use Custom timezone boundary only when a different analytical day is intended. DAY START shows the active anchor and its timezone.
- Configure sessions to match available trading hours. Session candles must not straddle configured boundaries. Each session's IANA timezone handles its own daylight-saving changes; changing the chart's display timezone does not redefine these sessions.
- For 24/7 crypto, enable Include weekends. Defaults exclude weekends.
- Wait for movement and event warm-up. Start with Compact, then use Detailed to inspect consumption and Research to inspect forecast evidence.
Default independent session windows:
- Asia: 09:00–17:00, Asia/Tokyo.
- London: 08:00–12:00, Europe/London.
- London/NY overlap: 12:00–16:00, Europe/London.
- New York: 09:00–15:00, America/New_York.
- NY PM: 15:00–17:00, America/New_York; disabled by default.
These are configurable analytical windows, not universal exchange definitions. The overlap window is London-timed and does not automatically recalculate the true intersection of London and New York hours during differing DST transition weeks. Auto priority selects the highest-numbered enabled active session: NY PM, New York, overlap, London, then Asia. Independent session statistics continue to update, but event admission follows the focus session.
8. Parameter guide
- Sampling: completed session/day/block caps default to 1200/500/2400. Minimum distribution n is 30. These caps bound retained records, not how much data TradingView loads. Completed-day regime mean length defaults to 10; the period-range data guard is 50%. Regime and previous-state movement conditioning are enabled.
- Daily gap treatment: Observed feed permits maintenance closures inside daily aggregation. Strict contiguous rejects gaps. The default cannot distinguish planned closures from missing data; analytical sessions, pressure blocks and outcome labels still apply gap checks.
- Location / pressure: Central/Stretch/Extreme/Tail boundaries default to 25/75/90/95. Pressure blocks default to 30 minutes; the marginal denominator floor is 0.05 × Q50. These thresholds are explicit model choices, not statistically optimized constants.
- Outcome storage and support: retain up to 1200 resolved events; minimum bucket size 40; prior strength 20. Pooled-family fallback and completed-block checkpoint admission are enabled by default.
- Outcome definition: horizon 120 minutes, continuation distance 0.25 × Q50, toward-open distance 0.35 × Q50, minimum entry displacement 0.10 × Q50. Changing these settings changes the question being estimated and rebuilds the historical labels.
- Optional feature gate: enabled by default; paired evaluation window 200 and minimum evaluations 60. Turning it off uses the core/fallback model rather than forcing every optional feature into conditioning.
- Probability alerts: default threshold 60%. These can fire only on a newly admitted event with sufficient empirical support.
- Display: Compact, Detailed or Research; Light/Dark theme; Small/Normal/Large font. Dashboard, historical location and state ribbon are enabled by default. Price labels, nearest-level tags, active price zone and event paths are optional.
- Label controls: text on price requires the master Research: allow text labels on price switch plus the relevant marker/path option. Marker cap defaults to 100; event-path retention defaults to 70. These affect drawing retention, not learning.
- Historical research / audit: defaults to the last 300 eligible resolved observations. Entry-from and resolution-through timestamps filter audit inclusion, not the underlying training history. The audit table appears only in Research mode. Session-reset dots can be enabled independently.
9. Historical evaluation and alerts
Research mode compares forecasts frozen at entry with later first-touch outcomes. It reports model and broader-base Brier loss on the same supported events, Brier skill, most-likely-class accuracy, and mean predicted versus observed R frequency. Lower Brier loss is better. Zero skill means no improvement over the baseline; negative skill means worse performance. This is a forecast-quality audit, not a trading strategy backtest: it has no entries/exits, costs, slippage or portfolio P&L.
Supported historical entry forecasts, barrier prices and entry/result timestamps are available in the Data Window. Use the entry timestamp to associate an outcome with its original forecast. Unscored warm-up observations are not retroactively assigned predictions using later data.
Available alerts cover upper/lower extreme entry, strong expansion, weakening pressure, upper/lower exhaustion candidates, empirical C/R thresholds, and resolved C/R outcomes. Configure alerts for Once Per Bar Close. Statistical alerts describe observed conditions or empirical event forecasts; they are not order instructions.
10. Training and limitations
- State changes use confirmed chart bars. Resolved outcomes enter training only on a later bar, never while their future outcome is unknown.
- Training is reconstructed from the chart data available on each execution. There is no persistent external model, imported pretrained weights, or hidden additional intraday history.
- A historical lookup buffer is different from the total number of executed chart bars. Increasing record caps cannot manufacture older candles or independent events.
- Session coverage, symbol feed, chart timeframe and loaded start date affect samples and results. Some instruments cannot supply complete coverage for the default sessions.
- Incomplete starting periods and invalid observations are excluded where applicable. Missing estimates remain unavailable instead of being filled with invented values.
- No lower-timeframe reconstruction is used to resolve within-candle ordering. Ambiguous outcomes remain visible as their own class.
- Changing parameters, chart history or feed data rebuilds the study and can change results. Confirmed-bar processing does not make the study invariant to those changes.
- Adjacent events can remain dependent despite de-duplication. Small samples, feature selection and changing market structure limit inference. No predictive advantage or profitability is claimed.
Author and license
V1 is the first public release by uPaSKaL. Source code is distributed under the Mozilla Public License 2.0.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.