Range: OHLC vs Previous OHLC - Version 2Version 1 here -
This is essentially the same as version 1 with one update. You have the freedom to independently choose OHLC for current candle and prior candle.
To elaborate further, Version 1 had 1 choice. For example, Close; you could only compare the close of prior candle to the current candle.
Version 2; you can compare close of the current candle to the low of the prior candle.
Pesquisar nos scripts por "乌德勒支+VS+赫拉克勒斯"
stock gain% vs index gain %This shows the relative strength or weakness of a stock vs an index on any given candle price movement.
Negative stock candle and relative strength shows accumulation
Positive stock candle and relative weakness shows distribution
accumulation will plot an 'A'
distribution will plot a 'D'
Range: OHLC vs Previous OHLCThis will plot your choice of OHLC (or any of the averaging choices) of the current candle compared to the previous candle.
For example if you choose "high" for the input and set the chart to daily, you'll see the currently daily high vs the previous daily high.
Green candle represent a higher high and the length of the candle represents how much higher.
Red candles represent a lower high than the previous day and the length is by how much lower.
This indicator is pretty straight forward, look for me to build on this with something a little more elaborate in the near future.
200/100 vs 190/80 EMA [jarederaj]Track the 200/100 EMA cross Vs the 180/90 EMA cross. Also, see the dates when these periods start on the chart.
Bitfinex Long vs Short RatiosWas impressed with the 'Longs vs Shorts Ratio' idea from the tweet below so I coded an indicator, enjoy.
twitter.com
Compare - Oscillator vs BTC momentumI've made a simple indicator to compare the momentum of a trading pair against the momentum of BTC to the dollar. I use it to see how a pair is affected by BTC's momentum... I wouldnt use it to trade off alone, but it can be a useful tool alongside other indicators.
The time range can be adjusted, but I wouldnt reccomend setting it to anything over 12M, or under 1W.... as I'm not sure if it would work.
Any feedback is welcome!
This is an idea I had after looking at a wonderful visualisation made by BarclayJames, link below:
www.tradingview.com
비트코인 한국 프리미엄 캔들 차트 (Bithumb vs Bitfinex) by 호재박스 슈퍼스타지표명: 비트코인 한국 프리미엄 캔들 차트 (Bithumb vs Bitfinex)
제작자: 호재박스 슈퍼스타
홈페이지: hozaebox.com
BTCUSD long vs short ratio+rsiJust a script I want to share with friends on a discord
orange/green line : longs vs short ratio (100 = only longs, 0 = only shorts)
purple line : RSI of (longs-shorts)
Bitcoin Exchanges Premium (Incl Int & GBTC) vs GdaxShows the exchange premiums internationally (Hong Kong, Luxembourg, Korea, Japan, China) vs Gdax. Also includes GBTC Trust price (adjusted).
Index Vs Futures v4.0 (dashed edition)Generalized script of
Originally designed for bitcoin, but can be used to compare between futures and index (or any two symbol expressions).
Conventions:
- green background := futures deviates 'way above' index
- red background := futures deviates 'way below' index
VS Score [SpiritualHealer117]An experimental indicator that uses historical prices and readings of technical indicators to give the probability that stock and crypto prices will be in a certain range on the next close. This indicator may be helpful for options traders or for traders who want to see the probability of a move.
It classifies returns into five categories:
Extreme Rise - Over 2 standard deviations above normal returns
Rise - Between 0.5 standard deviations and 2 standard deviations above normal returns
Flat - Falling in the range of +/- 0.5 standard deviations of normal returns
Fall - Between 0.5 standard deviations and 2 standard deviations below normal returns
Extreme Fall - Over 2 standard deviations below normal returns
It is an adaptive probability model, which trains on the previous 1000 data points, and is calculated by creating probability vectors for the current reading of the PPO, MA, volume histogram, and previous return, and combining them into one probability vector.
Volatility-Targeted Momentum Portfolio [BackQuant]Volatility-Targeted Momentum Portfolio
A complete momentum portfolio engine that ranks assets, targets a user-defined volatility, builds long, short, or delta-neutral books, and reports performance with metrics, attribution, Monte Carlo scenarios, allocation pie, and efficiency scatter plots. This description explains the theory and the mechanics so you can configure, validate, and deploy it with intent.
Table of contents
What the script does at a glance
Momentum, what it is, how to know if it is present
Volatility targeting, why and how it is done here
Portfolio construction modes: Long Only, Short Only, Delta Neutral
Regime filter and when the strategy goes to cash
Transaction cost modelling in this script
Backtest metrics and definitions
Performance attribution chart
Monte Carlo simulation
Scatter plot analysis modes
Asset allocation pie chart
Inputs, presets, and deployment checklist
Suggested workflow
1) What the script does at a glance
Pulls a list of up to 15 tickers, computes a simple momentum score on each over a configurable lookback, then volatility-scales their bar-to-bar return stream to a target annualized volatility.
Ranks assets by raw momentum, selects the top 3 and bottom 3, builds positions according to the chosen mode, and gates exposure with a fast regime filter.
Accumulates a portfolio equity curve with risk and performance metrics, optional benchmark buy-and-hold for comparison, and a full alert suite.
Adds visual diagnostics: performance attribution bars, Monte Carlo forward paths, an allocation pie, and scatter plots for risk-return and factor views.
2) Momentum: definition, detection, and validation
Momentum is the tendency of assets that have performed well to continue to perform well, and of underperformers to continue underperforming, over a specific horizon. You operationalize it by selecting a horizon, defining a signal, ranking assets, and trading the leaders versus laggards subject to risk constraints.
Signal choices . Common signals include cumulative return over a lookback window, regression slope on log-price, or normalized rate-of-change. This script uses cumulative return over lookback bars for ranking (variable cr = price/price - 1). It keeps the ranking simple and lets volatility targeting handle risk normalization.
How to know momentum is present .
Leaders and laggards persist across adjacent windows rather than flipping every bar.
Spread between average momentum of leaders and laggards is materially positive in sample.
Cross-sectional dispersion is non-trivial. If everything is flat or highly correlated with no separation, momentum selection will be weak.
Your validation should include a diagnostic that measures whether returns are explained by a momentum regression on the timeseries.
Recommended diagnostic tool . Before running any momentum portfolio, verify that a timeseries exhibits stable directional drift. Use this indicator as a pre-check: It fits a regression to price, exposes slope and goodness-of-fit style context, and helps confirm if there is usable momentum before you force a ranking into a flat regime.
3) Volatility targeting: purpose and implementation here
Purpose . Volatility targeting seeks a more stable risk footprint. High-vol assets get sized down, low-vol assets get sized up, so each contributes more evenly to total risk.
Computation in this script (per asset, rolling):
Return series ret = log(price/price ).
Annualized volatility estimate vol = stdev(ret, lookback) * sqrt(tradingdays).
Leverage multiplier volMult = clamp(targetVol / vol, 0.1, 5.0).
This caps sizing so extremely low-vol assets don’t explode weight and extremely high-vol assets don’t go to zero.
Scaled return stream sr = ret * volMult. This is the per-bar, risk-adjusted building block used in the portfolio combinations.
Interpretation . You are not levering your account on the exchange, you are rescaling the contribution each asset’s daily move has on the modeled equity. In live trading you would reflect this with position sizing or notional exposure.
4) Portfolio construction modes
Cross-sectional ranking . Assets are sorted by cr over the chosen lookback. Top and bottom indices are extracted without ties.
Long Only . Averages the volatility-scaled returns of the top 3 assets: avgRet = mean(sr_top1, sr_top2, sr_top3). Position table shows per-asset leverages and weights proportional to their current volMult.
Short Only . Averages the negative of the volatility-scaled returns of the bottom 3: avgRet = mean(-sr_bot1, -sr_bot2, -sr_bot3). Position table shows short legs.
Delta Neutral . Long the top 3 and short the bottom 3 in equal book sizes. Each side is sized to 50 percent notional internally, with weights within each side proportional to volMult. The return stream mixes the two sides: avgRet = mean(sr_top1,sr_top2,sr_top3, -sr_bot1,-sr_bot2,-sr_bot3).
Notes .
The selection metric is raw momentum, the execution stream is volatility-scaled returns. This separation is deliberate. It avoids letting volatility dominate ranking while still enforcing risk parity at the return contribution stage.
If everything rallies together and dispersion collapses, Long Only may behave like a single beta. Delta Neutral is designed to extract cross-sectional momentum with low net beta.
5) Regime filter
A fast EMA(12) vs EMA(21) filter gates exposure.
Long Only active when EMA12 > EMA21. Otherwise the book is set to cash.
Short Only active when EMA12 < EMA21. Otherwise cash.
Delta Neutral is always active.
This prevents taking long momentum entries during obvious local downtrends and vice versa for shorts. When the filter is false, equity is held flat for that bar.
6) Transaction cost modelling
There are two cost touchpoints in the script.
Per-bar drag . When the regime filter is active, the per-bar return is reduced by fee_rate * avgRet inside netRet = avgRet - (fee_rate * avgRet). This models proportional friction relative to traded impact on that bar.
Turnover-linked fee . The script tracks changes in membership of the top and bottom baskets (top1..top3, bot1..bot3). The intent is to charge fees when composition changes. The template counts changes and scales a fee by change count divided by 6 for the six slots.
Use case: increase fee_rate to reflect taker fees and slippage if you rebalance every bar or trade illiquid assets. Reduce it if you rebalance less often or use maker orders.
Practical advice .
If you rebalance daily, start with 5–20 bps round-trip per switch on liquid futures and adjust per venue.
For crypto perp microcaps, stress higher cost assumptions and add slippage buffers.
If you only rotate on lookback boundaries or at signals, use alert-driven rebalances and lower per-bar drag.
7) Backtest metrics and definitions
The script computes a standard set of portfolio statistics once the start date is reached.
Net Profit percent over the full test.
Max Drawdown percent, tracked from running peaks.
Annualized Mean and Stdev using the chosen trading day count.
Variance is the square of annualized stdev.
Sharpe uses daily mean adjusted by risk-free rate and annualized.
Sortino uses downside stdev only.
Omega ratio of sum of gains to sum of losses.
Gain-to-Pain total gains divided by total losses absolute.
CAGR compounded annual growth from start date to now.
Alpha, Beta versus a user-selected benchmark. Beta from covariance of daily returns, Alpha from CAPM.
Skewness of daily returns.
VaR 95 linear-interpolated 5th percentile of daily returns.
CVaR average of the worst 5 percent of daily returns.
Benchmark Buy-and-Hold equity path for comparison.
8) Performance attribution
Cumulative contribution per asset, adjusted for whether it was held long or short and for its volatility multiplier, aggregated across the backtest. You can filter to winners only or show both sides. The panel is sorted by contribution and includes percent labels.
9) Monte Carlo simulation
The panel draws forward equity paths from either a Normal model parameterized by recent mean and stdev, or non-parametric bootstrap of recent daily returns. You control the sample length, number of simulations, forecast horizon, visibility of individual paths, confidence bands, and a reproducible seed.
Normal uses Box-Muller with your seed. Good for quick, smooth envelopes.
Bootstrap resamples realized returns, preserving fat tails and volatility clustering better than a Gaussian assumption.
Bands show 10th, 25th, 75th, 90th percentiles and the path mean.
10) Scatter plot analysis
Four point-cloud modes, each plotting all assets and a star for the current portfolio position, with quadrant guides and labels.
Risk-Return Efficiency . X is risk proxy from leverage, Y is expected return from annualized momentum. The star shows the current book’s composite.
Momentum vs Volatility . Visualizes whether leaders are also high vol, a cue for turnover and cost expectations.
Beta vs Alpha . X is a beta proxy, Y is risk-adjusted excess return proxy. Useful to see if leaders are just beta.
Leverage vs Momentum . X is volMult, Y is momentum. Shows how volatility targeting is redistributing risk.
11) Asset allocation pie chart
Builds a wheel of current allocations.
Long Only, weights are proportional to each long asset’s current volMult and sum to 100 percent.
Short Only, weights show the short book as positive slices that sum to 100 percent.
Delta Neutral, 50 percent long and 50 percent short books, each side leverage-proportional.
Labels can show asset, percent, and current leverage.
12) Inputs and quick presets
Core
Portfolio Strategy . Long Only, Short Only, Delta Neutral.
Initial Capital . For equity scaling in the panel.
Trading Days/Year . 252 for stocks, 365 for crypto.
Target Volatility . Annualized, drives volMult.
Transaction Fees . Per-bar drag and composition change penalty, see the modelling notes above.
Momentum Lookback . Ranking horizon. Shorter is more reactive, longer is steadier.
Start Date . Ensure every symbol has data back to this date to avoid bias.
Benchmark . Used for alpha, beta, and B&H line.
Diagnostics
Metrics, Equity, B&H, Curve labels, Daily return line, Rolling drawdown fill.
Attribution panel. Toggle winners only to focus on what matters.
Monte Carlo mode with Normal or Bootstrap and confidence bands.
Scatter plot type and styling, labels, and portfolio star.
Pie chart and labels for current allocation.
Presets
Crypto Daily, Long Only . Lookback 25, Target Vol 50 percent, Fees 10 bps, Regime filter on, Metrics and Drawdown on. Monte Carlo Bootstrap with Recent 200 bars for bands.
Crypto Daily, Delta Neutral . Lookback 25, Target Vol 50 percent, Fees 15–25 bps, Regime filter always active for this mode. Use Scatter Risk-Return to monitor efficiency and keep the star near upper left quadrants without drifting rightward.
Equities Daily, Long Only . Lookback 60–120, Target Vol 15–20 percent, Fees 5–10 bps, Regime filter on. Use Benchmark SPX and watch Alpha and Beta to keep the book from becoming index beta.
13) Suggested workflow
Universe sanity check . Pick liquid tickers with stable data. Thin assets distort vol estimates and fees.
Check momentum existence . Run on your timeframe. If slope and fit are weak, widen lookback or avoid that asset or timeframe.
Set risk budget . Choose a target volatility that matches your drawdown tolerance. Higher target increases turnover and cost sensitivity.
Pick mode . Long Only for bull regimes, Short Only for sustained downtrends, Delta Neutral for cross-sectional harvesting when index direction is unclear.
Tune lookback . If leaders rotate too often, lengthen it. If entries lag, shorten it.
Validate cost assumptions . Increase fee_rate and stress Monte Carlo. If the edge vanishes with modest friction, refine selection or lengthen rebalance cadence.
Run attribution . Confirm the strategy’s winners align with intuition and not one unstable outlier.
Use alerts . Enable position change, drawdown, volatility breach, regime, momentum shift, and crash alerts to supervise live runs.
Important implementation details mapped to code
Momentum measure . cr = price / price - 1 per symbol for ranking. Simplicity helps avoid overfitting.
Volatility targeting . vol = stdev(log returns, lookback) * sqrt(tradingdays), volMult = clamp(targetVol / vol, 0.1, 5), sr = ret * volMult.
Selection . Extract indices for top1..top3 and bot1..bot3. The arrays rets, scRets, lev_vals, and ticks_arr track momentum, scaled returns, leverage multipliers, and display tickers respectively.
Regime filter . EMA12 vs EMA21 switch determines if the strategy takes risk for Long or Short modes. Delta Neutral ignores the gate.
Equity update . Equity multiplies by 1 + netRet only when the regime was active in the prior bar. Buy-and-hold benchmark is computed separately for comparison.
Tables . Position tables show current top or bottom assets with leverage and weights. Metric table prints all risk and performance figures.
Visualization panels . Attribution, Monte Carlo, scatter, and pie use the last bars to draw overlays that update as the backtest proceeds.
Final notes
Momentum is a portfolio effect. The edge comes from cross-sectional dispersion, adequate risk normalization, and disciplined turnover control, not from a single best asset call.
Volatility targeting stabilizes path but does not fix selection. Use the momentum regression link above to confirm structure exists before you size into it.
Always test higher lag costs and slippage, then recheck metrics, attribution, and Monte Carlo envelopes. If the edge persists under stress, you have something robust.
Advanced Correlation Monitor📊 Advanced Correlation Monitor - Pine Script v6
🎯 What does this indicator do?
Monitors real-time correlations between 13 different asset pairs and alerts you when historically strong correlations break, indicating potential trading opportunities or changes in market dynamics.
🚀 Key Features
✨ Multi-Market Monitoring
7 Forex Pairs (GBPUSD/DXY, EURUSD/GBPUSD, etc.)
6 Index/Stock Pairs (SPY/S&P500, DAX/NASDAQ, TSLA/NVDA, etc.)
Fully configurable - change any pair from inputs
📈 Dual Correlation Analysis
Long Period (90 bars): Identifies historically strong correlations
Short Period (6 bars): Detects recent breakdowns
Pearson Correlation using Pine Script v6 native functions
🎨 Intuitive Visualization
Real-time table with 6 information columns
Color coding: Green (correlated), Red (broken), Gray (normal)
Visual states: 🟢 OK, 🔴 BROKEN, ⚫ NORMAL
🚨 Smart Alert System
Only alerts previously correlated pairs (>80% historical)
Detects breakdowns when short correlation <80%
Consolidated alert with all affected pairs
🛠️ Flexible Configuration
Adjustable Parameters:
📅 Periods: Long (30-500), Short (2-50)
🎯 Threshold: 50%-99% (default 80%)
🎨 Table: Configurable position and size
📊 Symbols: All pairs are configurable
Default Pairs:
FOREX: INDICES/STOCKS:
- GBPUSD vs DXY • SPY vs S&P500
- EURUSD vs GBPUSD • DAX vs S&P500
- EURUSD vs DXY • DAX vs NASDAQ
- USDCHF vs DXY • TSLA vs NVDA
- GBPUSD vs USDCHF • MSFT vs NVDA
- EURUSD vs USDCHF • AAPL vs NVDA
- EURUSD vs EURCAD
💡 Practical Use Cases
🔄 Pairs Trading
Detects when strong correlations break for:
Statistical arbitrage
Mean reversion trading
Divergence opportunities
🛡️ Risk Management
Identifies when "safe" assets start moving independently:
Portfolio diversification
Smart hedging
Regime change detection
📊 Market Analysis
Understand underlying market structure:
Forex/DXY correlations
Tech sector rotation
Regional market disconnection
🎓 Results Interpretation
Reading Example:
EURUSD vs DXY: -98.57% → -98.27% | 🟢 OK
└─ Perfect negative correlation maintained (EUR rises when DXY falls)
TSLA vs NVDA: 78.12% → 0% | ⚫ NORMAL
└─ Lost tech correlation (divergence opportunity)
Trading Signals:
🟢 → 🔴: Broken correlation = Possible opportunity
Large difference: Indicates correlation tension
Multiple breaks: Market regime change
Crypto Correlation Oscillator# Crypto Correlation Oscillator
**Companion indicator for Tri-Align Crypto Trend**
## Overview
The Crypto Correlation Oscillator helps you identify **alpha opportunities** and **market regime changes** by showing how closely your coin follows Bitcoin and other assets over time. It displays rolling correlations as an oscillator in a separate pane below your price chart.
## What It Does
This indicator calculates **Pearson correlations** between different trading pairs on a rolling window (default: 100 bars). Correlations range from **-1.0** (perfect inverse relationship) to **+1.0** (perfect positive relationship), with **0** meaning no correlation.
### The 5 Correlation Lines
1. **Blue (thick line) - Coin vs BTC**: The most important metric
- **High correlation (>0.7)**: Your coin is just following BTC - no independent movement
- **Low correlation (<0.3)**: Your coin has **alpha** - it's moving independently from BTC
- **Negative correlation**: Your coin moves opposite to BTC (rare but powerful)
2. **Purple - Coin/BTC vs BTC**: Inverse relationship check
- **Negative values**: When BTC rises, your coin weakens relative to BTC
- **Positive values**: When BTC rises, your coin strengthens against BTC
3. **Orange - Coin vs Coin/BTC**: Structural consistency check
- Shows how well the Coin/USDT and Coin/BTC pairs maintain their mathematical relationship
- Unusual values can indicate liquidity issues or market inefficiencies
4. **Light Red - Coin vs USDT.D** (optional): Stablecoin dominance correlation
- Shows how your coin correlates with USDT dominance
- Useful for understanding flight-to-safety dynamics
5. **Light Green - Coin vs BTC.D** (optional): Bitcoin dominance correlation
- Shows how your coin correlates with BTC dominance
- Helps identify altcoin season vs BTC dominance cycles
## How to Read It
### Finding Alpha Opportunities
- **Low blue line (<0.3)**: Your coin is decoupled from BTC → potential alpha
- **Blue line dropping**: Coin is gaining independence from BTC
- **Blue line spiking to >0.9**: Coin is a "BTC clone" with no independent movement
### Regime Change Detection
- **Blue line crossing 0.5**: Major shift in correlation behavior
- **Purple line turning negative**: Coin starting to weaken when BTC rises (warning sign)
- **Sharp correlation changes**: Market structure is shifting - adjust strategy
### Visual Zones
- **Blue background**: High correlation zone (>0.7) - coin just following BTC
- **Red background**: Inverse correlation zone (<-0.5) - coin moving opposite to BTC
### Reference Lines
- **+1.0 / -1.0**: Perfect correlation boundaries (dotted gray)
- **+0.5 / -0.5**: Moderate correlation thresholds (dotted gray)
- **0.0**: Zero correlation line (solid gray)
## Dynamic Legend
The legend table (top-right) automatically shows the actual symbol names based on your chart:
- **Example on SOLUSDT**: Shows "SOL vs BTC", "SOL/BTC vs BTC", "SOL vs SOL/BTC", etc.
- **Color boxes**: Match the plot colors for easy identification
- **Live values**: Current correlation numbers update in real-time
- **Tooltips**: Hover over labels for interpretation guidance
## Configuration
### Key Inputs
- **Correlation Lookback** (default: 100): Number of bars for rolling correlation window
- Shorter = more reactive, noisier
- Longer = smoother, slower to detect changes
- **Correlation Smoothing** (default: 5): EMA smoothing period for raw correlations
- Reduces noise while preserving trends
- **Symbol Detection**: Auto-detects symbols from your chart, or use manual overrides
- **Dominance Pairs**: Toggle USDT.D and BTC.D correlations on/off
## Usage Tips
1. **Combine with main Tri-Align indicator**: Use correlation for context, Tri-Align for entry/exit signals
2. **Watch for divergences**: Correlation changing while price moves in sync can signal upcoming shift
3. **Adjust lookback period**: Use shorter (50-70) for day trading, longer (150-200) for position trading
4. **Focus on the blue line**: It's your primary alpha indicator
## Technical Details
- **Calculation**: Pearson correlation coefficient with EMA smoothing
- **Data source**: Close prices from `request.security()` (multi-timeframe capable)
- **Update frequency**: Every bar on your selected timeframe
- **Overlay**: False (displays in separate pane)
## Quick Interpretation Guide
| Blue Line Value | Interpretation | Action |
|----------------|----------------|--------|
| > 0.9 | Coin is a BTC clone | Avoid - no alpha opportunity |
| 0.7 - 0.9 | High correlation | Standard altcoin behavior |
| 0.3 - 0.7 | Moderate correlation | Some independence emerging |
| < 0.3 | Low correlation | **Strong alpha opportunity** |
| < 0 | Inverse correlation | Rare - potential hedge asset |
| Purple Line | Interpretation |
|-------------|----------------|
| Strongly negative | Coin weakens when BTC rises - risky |
| Near zero | Coin/BTC pair moves independently of BTC |
| Positive | Coin strengthens with BTC - ideal |
## Version History
### v1.0 (Initial Release)
- Pearson correlation calculation with configurable lookback
- 5 correlation pairs: Coin vs BTC, Coin/BTC vs BTC, Coin vs Coin/BTC, USDT.D, BTC.D
- EMA smoothing to reduce noise
- Visual zones for high/inverse correlation
- Dynamic legend with symbol name extraction
- Auto-symbol detection matching main Tri-Align indicator






















