OPEN-SOURCE SCRIPT
Updated

Perpetual Basis Drift Map [AGPro Series]

437
Perpetual Basis Drift Map [AGPro Series]

🧠 Core Idea

Is the perpetual market quietly drifting away from spot, or is the basis relationship compressing back toward neutral?


📌 Overview / What it does

Perpetual Basis Drift Map is a crypto derivatives context tool designed to monitor how the active perpetual or futures market behaves against a matching spot reference.

The script compares the active chart price with an automatically selected spot reference, measures basis percentage, basis drift, normalized basis z-score, drift velocity, persistence, and trend context. It converts that relationship into an open three-rail basis drift meter, state labels, right-side tags, alerts, and an AG Pro dashboard.

It does not read official funding payments, automate trades, predict future price direction, or promise that basis must mean-revert. It is a structured visual map for interpreting perpetual premium, perpetual discount, basis expansion, basis compression, reset, and spot-reference mismatch conditions.


🎯 Purpose & Design Philosophy

This script was built to separate basis drift from generic funding or premium talk.

Funding pressure can be noisy, and a raw premium number is often not enough. Traders need to know whether the relationship between perp/futures and spot is widening, compressing, persisting, or simply resetting.

The design goal is to make basis behavior visible as a chart story, not just a number in a panel.


⚡ Why This Script Is Different

Most tools show a spread or premium value and leave the interpretation to the user.

This script does NOT treat basis as a simple buy or sell signal, does NOT claim that premium must reverse, and does NOT hide reference mismatch risk.

Instead, it maps the basis relationship into states: Positive Drift, Negative Drift, Basis Expansion, Basis Compression, Reset, and Check Spot Ref, while the chart labels use Premium Drift, Discount Drift, Spread Expansion, and Basis Compression for faster visual reading. It uses spot-reference comparison, baseline drift, z-score, velocity, persistence, and trend context together.


⚙️ Methodology

1. Context Detection
The script builds a spot reference from the active chart base currency, selected exchange, and selected quote.

2. Reference Mapping
It compares the active market against the spot reference and calculates basis percentage.

3. Reaction Evaluation
The model evaluates basis drift from baseline, normalized basis z-score, drift velocity, persistence, and trend context.

4. Visual Output
The result is shown as a compact open basis drift meter, centered meter label, right-side tags, event labels, and dashboard panel.


🗺️ How to Read the Chart

The basis drift meter separates the current read into three visible layers: state rail, basis value rail, and pressure score rail. It is intentionally open-ended rather than a closed corridor, so the visual story feels different from zone-first tools.

Labels mark state changes such as Premium Drift, Discount Drift, Spread Expansion, and Basis Compression. Optional compact pulse markers add additional context when premium, discount, expansion, or compression pressure appears without turning the script into a signal engine.

Colors communicate context:
• Teal = positive/perp-premium drift pressure
• Pink = negative/perp-discount drift pressure
• Yellow = spread expansion or reference warning
• Indigo = compression/reset regime

The panel summarizes state, score, basis, basis z-score, velocity, persistence, direction, quality, spot reference, trend, and meter values.


🚦 Signals & States

• Positive Drift → perpetual/futures market is drifting above the spot reference

• Negative Drift → perpetual/futures market is drifting below the spot reference

• Basis Expansion → basis deviation and drift velocity are widening

• Basis Compression → basis deviation is compressing back toward neutral

• Reset → no active drift state is strong enough to dominate the read

• Check Spot Ref → selected spot reference appears mismatched or unavailable


🔔 Alerts Logic

Alerts trigger when the script transitions into selected basis states.

Positive Basis Drift alerts mark meaningful upward perp-versus-spot drift.

Negative Basis Drift alerts mark meaningful downward perp-versus-spot drift.

Basis Expansion alerts mark widening basis deviation and drift velocity.

Basis Compression alerts mark movement back toward a neutral basis relationship.

Alerts are attention markers, not trade instructions.


🧩 Confluence Logic

The strongest context appears when multiple components align:

Basis percentage + normalized basis z-score + drift velocity + persistence + trend context.

When basis widens and persists, the relationship may deserve closer attention. When basis compresses, the market may be returning toward a more neutral perp-versus-spot condition.


📊 When to Use

• Crypto perpetual and futures charts

• Markets where spot reference comparison is meaningful

• Perp/spot monitoring on BTC, ETH, and liquid crypto pairs

• Basis expansion, basis compression, and drift-context analysis

• Sessions where derivatives premium or discount behavior matters


⚠️ When NOT to Use

• Symbols with poor spot-reference alignment

• Illiquid markets with unreliable pricing

• Spot-only charts if the user expects a derivatives basis story

• Extreme news events where spread behavior can become unstable

• Markets where the active symbol and selected reference are not comparable


🎛️ Key Inputs

• Auto Spot Reference → automatically builds a matching spot reference

• Basis Baseline Length → controls how quickly the normal basis relationship adapts

• Basis Normalization Lookback → controls how unusual basis drift must be

• Drift Velocity Lookback → measures whether basis is widening or tightening

• Persistence Window → measures whether basis behavior continues across bars

• Reference Mismatch Guard % → prevents mismatched references from being interpreted as real basis drift

• Visual Settings → control meter projection, labels, right-side tags, and font sizes


🖥️ Interface & Visual Design

The interface is designed around a premium chart-first story.

The basis drift meter provides the main visual anchor. Centered meter text explains the state without relying on weak transparent labels or a large corridor box. Right-side tags keep the current state, basis, and score visible near the active price area.

The panel follows the AG Pro standard with a merged blue header row, adjustable location, adjustable theme, and adjustable font size.


🧪 Practical Usage Workflow

1. Apply the script to a crypto perpetual or futures chart.

2. Keep Auto Spot Reference enabled for the first pass.

3. Confirm the Spot Ref row matches the active market base currency.

4. Read State, Score, Basis, Basis Z, and Velocity.

5. Inspect whether basis is drifting, expanding, compressing, or resetting.

6. Confirm the read with broader market structure, liquidity, volatility, and risk management.


🔍 Interpretation Guidelines

Positive basis drift can show perp premium building, but it does not automatically mean price must fall.

Negative basis drift can show perp discount building, but it does not automatically mean price must rise.

Basis expansion is a context marker, not a trade instruction.

Basis compression can indicate normalization, but normalization does not guarantee direction.


🚫 What This Script Is NOT

This script is not a prediction engine.

This script is not financial advice.

This script is not an auto trading system.

This script is not a guaranteed signal engine.

This script does not read official funding payments directly.

This script does not claim that basis drift must immediately reverse.


⚠️ Limitations & Transparency

The script estimates basis from active-symbol versus spot-reference price behavior.

Reference quality matters. If the selected reference is wrong or unavailable, the script shows Check Spot Ref rather than presenting the spread as valid basis drift.

Different exchanges, contract types, liquidity conditions, and timeframes can produce different basis behavior.

Very low basis values can be visually clean but may not produce a dramatic story.


🧠 Market Context Notes

Perpetual basis can help traders understand whether derivatives pricing is leaning above or below spot.

The value of this tool is strongest when combined with structure, volatility, liquidity, open interest, and disciplined risk management.

Basis tells context. It does not create certainty.


🧾 Use Case Examples

When a perpetual chart trades persistently above spot and basis velocity expands, the script may classify Positive Drift or Basis Expansion.

When a perpetual chart trades persistently below spot and basis velocity expands downward, the script may classify Negative Drift.

When basis returns toward its baseline, Basis Compression can help show normalization.


🧱 System Philosophy

Perpetual Basis Drift Map follows the AGProLabs principle of building decision-support maps rather than prediction tools.

The script is designed to make hidden derivatives context easier to see, not to replace judgment.


🔐 Non-Promise Statement

No basis model can guarantee future price direction.

No drift score removes uncertainty.

This tool helps organize context; it does not create certainty.


📉 Risk Disclosure

Trading involves risk.

Crypto derivatives can be highly volatile and may involve leverage, liquidation risk, exchange risk, funding-cost changes, and rapid market movement.

This script is for educational and analytical purposes only.

It does not provide financial advice or guaranteed trading outcomes.

Users remain responsible for their own decisions.


📚 Educational Note

Use the script as a learning layer for understanding how perpetual premium, perpetual discount, basis drift, basis velocity, and spot-reference behavior can combine into a cleaner derivatives-context read.
Release Notes
🔧 UPDATE NOTES - V1.3

This update focuses on readability, contrast discipline, panel structure, and cleaner derivatives-context presentation.

The core purpose of the script remains unchanged.
This release improves how the existing basis drift logic is presented, organized, and interpreted on the chart.

This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.


------------------------
What Changed
------------------------

• Reworked the AG Pro panel into a cleaner two-column layout.
The panel now uses the standard single merged blue header row with only the script name in the header.

• Standardized panel theme controls.
The panel now uses Dark and Light theme options for consistency with current AGPro public-release formatting.

• Improved label and tag contrast.
Meter labels, right-side tags, and event labels now use contrast-aware text coloring so light labels do not become hard to read.

• Refined basis meter presentation.
The open three-rail meter remains distinct from broad corridor-style scripts while improving first-glance readability.

• Adjusted event label rhythm.
The default label cadence and maximum visible label count were tuned to preserve chart activity without excessive clutter.


------------------------
Visual Improvements
------------------------

• Improved chart readability by adjusting label contrast, right-side tags, and meter text handling.

• Reduced visual friction by keeping the meter open and avoiding heavy closed zones.

• Refined visual hierarchy so state, basis value, and score remain easy to separate.

• Adjusted default label density to keep the chart informative without overwhelming price action.


------------------------
Interface & Usability
------------------------

• Optimized panel layout for clearer information flow.

• Improved label readability for better chart interaction.

• Adjusted default visual settings for a more balanced appearance.

• Preserved configurable panel visibility, location, theme, and font size controls.


------------------------
Behavior Notes
------------------------

This update does not change the core analytical logic of the script.

The goal is to improve clarity and usability, not to introduce new predictive behavior.

Users should interpret outputs the same way as before, but with improved visual structure.


------------------------
Limitations Reminder
------------------------

The script remains a rule-based analytical tool.

Reference-symbol selection, exchange differences, contract type, liquidity, funding conditions, and timeframe differences may affect how basis states appear.

Outputs should always be interpreted within broader market context.


------------------------
Risk Reminder
------------------------

This script is for educational and analytical purposes only.

It does not provide financial advice or guaranteed trading outcomes.

Crypto derivatives can involve leverage, liquidation risk, exchange risk, and rapid market movement.

Users remain responsible for their own decisions.
Release Notes
🔧 UPDATE NOTES - v1.4

This update adds a reversion-rate proof, an imperative next-action readout,
and a spot-symbol guard.

The core purpose of the script remains unchanged.
It continues to map perpetual-versus-spot basis drift, expansion, compression, reset and
reference-mismatch conditions with the same three-rail basis meter.

This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.

------------------------
What Changed
------------------------

- Reversion Rate proof layer
The panel now reports how often an active drift or expansion historically reset back toward
neutral, shown with the sample count for transparency.

- Reset-versus-continuation proof logic
The Reversion Rate resolves as a race: a drift episode is counted as a reset only if basis
returns to neutral before it widens to a meaningfully larger extreme, so the rate reflects
genuine basis behavior rather than trivially-always-true compression.

- Reversion proof inputs
New settings control the window and the widen margin used to measure post-drift behavior.

- Spot-symbol guard
On spot charts, where there is no perpetual-versus-spot basis, the panel now shows a clear
"Spot - No Basis" state and a "Load Perp Symbol" cue instead of a misleading reading. The
guard only activates when basis is effectively absent and does not affect perpetual charts.

- Imperative Action readout
The Action row now states a clear next-action context such as Track Premium Drift, Watch
Expansion, Watch Reset, Wait Drift or Match Reference, instead of a descriptive phrase.

- Honest, conservative counting
Each drift episode is counted once, and widening first or a window expiry without a reset is
treated as not-reverted, so the rate stays realistic on the selected market and timeframe.

------------------------
Visual Improvements
------------------------

- Moved basis-compression labels off the candles so they no longer overlap price action

- Preserved the open three-rail basis meter, its rail tags and centered badge

- Kept contrast-safe, auto-adjusting label text on every badge and tag

- Standardized label sizes to the Label Font Size setting

- Maintained a clean, uncluttered first-glance read

------------------------
Interface & Usability
------------------------

- Added a Reversion Rate row for an at-a-glance mean-reversion track record

- Added window and widen-margin settings so the proof measures genuine resets

- Reworded the Action row into a direct, imperative next-action cue

- Added a helpful spot-chart hint so the tool is never confusing on the wrong symbol type

- Enhanced overall user experience without changing the core basis logic

------------------------
Behavior Notes
------------------------

This update does not change the core analytical logic of the script.

The basis score, states, meter and drift engine are unchanged. The Reversion Rate is a
separate historical track-record layer and does not alter how basis drift is computed.

------------------------
Limitations Reminder
------------------------

The script remains a rule-based analytical tool.

This indicator is designed for perpetual or futures symbols measured against a matching spot
reference. On spot symbols there is no basis to measure. Market conditions such as volatility,
liquidity, reference quality and timeframe differences may affect how basis states and the
rate appear.

Outputs should always be interpreted within broader market context.

------------------------
Risk Reminder
------------------------

This script is for educational and analytical purposes only.

It does not provide financial advice or guaranteed trading outcomes.

Users remain responsible for their own decisions.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.