ابحث في النصوص البرمجية عن "电脑桌面显示BTC"
BTC Prices (BFX,BITS,CB,BINANCE)Minimal price tracker. Publishing just in case it deletes itself two times. Haha.
Color coded. It will be easy to add other exchanges if need be.
BTC Approximation (BETI) - Bitcoin Exponential Trend//based on
//https://www.wolframalpha.com/input/?i=e+%5E+(+0.00331836433279664++(+number+of+seconds+since+jul+17,+2010+12pm+UTC%2F86400%2Fseconds+)+-0.120774828196607+)
//https://bitcointalk.org/index.php?topic=470453.680
BTC Price Spread - Coinbase & Futs - Premiums & DiscountsThis indicator takes the price of Bitcoin on Coinbase and the futures price on Mex, and compares it the average price of Bitcoin across other major exchanges.
This essentials give us a spread at which Bitcoin is going for.
In turn, this could be a possible tool to help determine market sentiment.
This indicator was created for experimental purposes.
Use at your own digression.
BTC Futures Settlement DatesShows the CBOE and CME settlement dates as horizontal lines, with the option to show a 7 day warning in the background. This should hopefully give ample warning.
I intend to update the script as new dates become available but please PM if I've forgotten.
BTC: CME Futures vs. Exchange SpreadsAs you can see, this script plots the current (10-min. delayed) CME Futures price versus Bitfinex, Bitstamp, and Coinbase prices.
It's displayed here on a 30 minute view because at the time of writing the futures have been alive for approximately one day. The script will likely be more useful on longer time frames as a macro-level indicator.
It's pretty simple to adapt this to additional exchanges
OKCoin future diffThis indicator checks the accuracy of okcoin futures against the current index. Example, check how the 1W future from 7 days ago matches the current spot value. The matches are on the 1W, 2W, 3M futures
The indicator bundles them together, makes a weighted average and shows it all.
the thin lines are the futures deltas for each of the futures(check the code to see the color of each).
the thick line is the compound indicator, the line is red when the value is too far off the spot price, black when it's <5%
background is green on "bullish", red for "bearish", take it as you want with many grains of salt :)
there is an input value (default = 1) to adjust time scales. the value is a multiplier for the number of periods in a day.
Example:
1D chart, input = 1
4h chart, input = 4h * 6 = 24h
using the incorrect adjustment for the wrong time scale, makes the indicator (even more) meaningless ;)
MTF MACD 2 By YuthavithiIf you want a good strategy without repaint. This one might be for you. Excellent profitable for BTCUSD3M for OKCoin.
It uses multiple time frame MACD for trading decision. To avoid repaint, set the delay period = 1 for both long term and midterm.
The idea is that, if long term, mid term and current time frame all agree on traidng direction, the trade will take place.
I also uses it in my automated trading bot with good result.
www.tradingview.com
(CRISIS) aggregateBTCvol v0.2.4Aggregate multiple exchange volumes into single indicator
This update adds:
*Moving Average
*Add/change/disable to up 6 securities without touching code.
*Monochrome mode for dark themes.
BTC Volume Index 1.1 beta [Dia]Indicator calculates total volume across multiple bitcoin exchanges. The influence of each exchange can be adjusted seperately.
0 fee exchanges default to 50%
0 fee futures default to 10%
Define custom lookback periods for price breakout detection.
Look for low-volume price reversals in those candles immediately following high volume peaks. The lower the volume and the greater the open/close price difference of that 2nd candle is compared to the previous one, the higher the likelihood of a local top/bottom being in.
Note:
Bar highlighting is still experimental, future versions will include better filtering options.
Use for confirmation only, not as standalone trading system.
Algorithm Predator - ML-liteAlgorithm Predator - ML-lite
This indicator combines four specialized trading agents with an adaptive multi-armed bandit selection system to identify high-probability trade setups. It is designed for swing and intraday traders who want systematic signal generation based on institutional order flow patterns , momentum exhaustion , liquidity dynamics , and statistical mean reversion .
Core Architecture
Why These Components Are Combined:
The script addresses a fundamental challenge in algorithmic trading: no single detection method works consistently across all market conditions. By deploying four independent agents and using reinforcement learning algorithms to select or blend their outputs, the system adapts to changing market regimes without manual intervention.
The Four Trading Agents
1. Spoofing Detector Agent 🎭
Detects iceberg orders through persistent volume at similar price levels over 5 bars
Identifies spoofing patterns via asymmetric wick analysis (wicks exceeding 60% of bar range with volume >1.8× average)
Monitors order clustering using simplified Hawkes process intensity tracking (exponential decay model)
Signal Logic: Contrarian—fades false breakouts caused by institutional manipulation
Best Markets: Consolidations, institutional trading windows, low-liquidity hours
2. Exhaustion Detector Agent ⚡
Calculates RSI divergence between price movement and momentum indicator over 5-bar window
Detects VWAP exhaustion (price at 2σ bands with declining volume)
Uses VPIN reversals (volume-based toxic flow dissipation) to identify momentum failure
Signal Logic: Counter-trend—enters when momentum extreme shows weakness
Best Markets: Trending markets reaching climax points, over-extended moves
3. Liquidity Void Detector Agent 💧
Measures Bollinger Band squeeze (width <60% of 50-period average)
Identifies stop hunts via 20-bar high/low penetration with immediate reversal and volume spike
Detects hidden liquidity absorption (volume >2× average with range <0.3× ATR)
Signal Logic: Breakout anticipation—enters after liquidity grab but before main move
Best Markets: Range-bound pre-breakout, volatility compression zones
4. Mean Reversion Agent 📊
Calculates price z-scores relative to 50-period SMA and standard deviation (triggers at ±2σ)
Implements Ornstein-Uhlenbeck process scoring (mean-reverting stochastic model)
Uses entropy analysis to detect algorithmic trading patterns (low entropy <0.25 = high predictability)
Signal Logic: Statistical reversion—enters when price deviates significantly from statistical equilibrium
Best Markets: Range-bound, low-volatility, algorithmically-dominated instruments
Adaptive Selection: Multi-Armed Bandit System
The script implements four reinforcement learning algorithms to dynamically select or blend agents based on performance:
Thompson Sampling (Default - Recommended):
Uses Bayesian inference with beta distributions (tracks alpha/beta parameters per agent)
Balances exploration (trying underused agents) vs. exploitation (using proven winners)
Each agent's win/loss history informs its selection probability
Lite Approximation: Uses pseudo-random sampling from price/volume noise instead of true random number generation
UCB1 (Upper Confidence Bound):
Calculates confidence intervals using: average_reward + sqrt(2 × ln(total_pulls) / agent_pulls)
Deterministic algorithm favoring agents with high uncertainty (potential upside)
More conservative than Thompson Sampling
Epsilon-Greedy:
Exploits best-performing agent (1-ε)% of the time
Explores randomly ε% of the time (default 10%, configurable 1-50%)
Simple, transparent, easily tuned via epsilon parameter
Gradient Bandit:
Uses softmax probability distribution over agent preference weights
Updates weights via gradient ascent based on rewards
Best for Blend mode where all agents contribute
Selection Modes:
Switch Mode: Uses only the selected agent's signal (clean, decisive)
Blend Mode: Combines all agents using exponentially weighted confidence scores controlled by temperature parameter (smooth, diversified)
Lock Agent Feature:
Optional manual override to force one specific agent
Useful after identifying which agent dominates your specific instrument
Only applies in Switch mode
Four choices: Spoofing Detector, Exhaustion Detector, Liquidity Void, Mean Reversion
Memory System
Dual-Layer Architecture:
Short-Term Memory: Stores last 20 trade outcomes per agent (configurable 10-50)
Long-Term Memory: Stores episode averages when short-term reaches transfer threshold (configurable 5-20 bars)
Memory Boost Mechanism: Recent performance modulates agent scores by up to ±20%
Episode Transfer: When an agent accumulates sufficient results, averages are condensed into long-term storage
Persistence: Manual restoration of learned parameters via input fields (alpha, beta, weights, microstructure thresholds)
How Memory Works:
Agent generates signal → outcome tracked after 8 bars (performance horizon)
Result stored in short-term memory (win = 1.0, loss = 0.0)
Short-term average influences agent's future scores (positive feedback loop)
After threshold met (default 10 results), episode averaged into long-term storage
Long-term patterns (weighted 30%) + short-term patterns (weighted 70%) = total memory boost
Market Microstructure Analysis
These advanced metrics quantify institutional order flow dynamics:
Order Flow Toxicity (Simplified VPIN):
Measures buy/sell volume imbalance over 20 bars: |buy_vol - sell_vol| / (buy_vol + sell_vol)
Detects informed trading activity (institutional players with non-public information)
Values >0.4 indicate "toxic flow" (informed traders active)
Lite Approximation: Uses simple open/close heuristic instead of tick-by-tick trade classification
Price Impact Analysis (Simplified Kyle's Lambda):
Measures market impact efficiency: |price_change_10| / sqrt(volume_sum_10)
Low values = large orders with minimal price impact ( stealth accumulation )
High values = retail-dominated moves with high slippage
Lite Approximation: Uses simplified denominator instead of regression-based signed order flow
Market Randomness (Entropy Analysis):
Counts unique price changes over 20 bars / 20
Measures market predictability
High entropy (>0.6) = human-driven, chaotic price action
Low entropy (<0.25) = algorithmic trading dominance (predictable patterns)
Lite Approximation: Simple ratio instead of true Shannon entropy H(X) = -Σ p(x)·log₂(p(x))
Order Clustering (Simplified Hawkes Process):
Tracks self-exciting event intensity (coordinated order activity)
Decays at 0.9× per bar, spikes +1.0 when volume >1.5× average
High intensity (>0.7) indicates clustering (potential spoofing/accumulation)
Lite Approximation: Simple exponential decay instead of full λ(t) = μ + Σ α·exp(-β(t-tᵢ)) with MLE
Signal Generation Process
Multi-Stage Validation:
Stage 1: Agent Scoring
Each agent calculates internal score based on its detection criteria
Scores must exceed agent-specific threshold (adjusted by sensitivity multiplier)
Agent outputs: Signal direction (+1/-1/0) and Confidence level (0.0-1.0)
Stage 2: Memory Boost
Agent scores multiplied by memory boost factor (0.8-1.2 based on recent performance)
Successful agents get amplified, failing agents get dampened
Stage 3: Bandit Selection/Blending
If Adaptive Mode ON:
Switch: Bandit selects single best agent, uses only its signal
Blend: All agents combined using softmax-weighted confidence scores
If Adaptive Mode OFF:
Traditional consensus voting with confidence-squared weighting
Signal fires when consensus exceeds threshold (default 70%)
Stage 4: Confirmation Filter
Raw signal must repeat for consecutive bars (default 3, configurable 2-4)
Minimum confidence threshold: 0.25 (25%) enforced regardless of mode
Trend alignment check: Long signals require trend_score ≥ -2, Short signals require trend_score ≤ 2
Stage 5: Cooldown Enforcement
Minimum bars between signals (default 10, configurable 5-15)
Prevents over-trading during choppy conditions
Stage 6: Performance Tracking
After 8 bars (performance horizon), signal outcome evaluated
Win = price moved in signal direction, Loss = price moved against
Results fed back into memory and bandit statistics
Trading Modes (Presets)
Pre-configured parameter sets:
Conservative: 85% consensus, 4 confirmations, 15-bar cooldown
Expected: 60-70% win rate, 3-8 signals/week
Best for: Swing trading, capital preservation, beginners
Balanced: 70% consensus, 3 confirmations, 10-bar cooldown
Expected: 55-65% win rate, 8-15 signals/week
Best for: Day trading, most traders, general use
Aggressive: 60% consensus, 2 confirmations, 5-bar cooldown
Expected: 50-58% win rate, 15-30 signals/week
Best for: Scalping, high-frequency trading, active management
Elite: 75% consensus, 3 confirmations, 12-bar cooldown
Expected: 58-68% win rate, 5-12 signals/week
Best for: Selective trading, high-conviction setups
Adaptive: 65% consensus, 2 confirmations, 8-bar cooldown
Expected: Varies based on learning
Best for: Experienced users leveraging bandit system
How to Use
1. Initial Setup (5 Minutes):
Select Trading Mode matching your style (start with Balanced)
Enable Adaptive Learning (recommended for automatic agent selection)
Choose Thompson Sampling algorithm (best all-around performance)
Keep Microstructure Metrics enabled for liquid instruments (>100k daily volume)
2. Agent Tuning (Optional):
Adjust Agent Sensitivity multipliers (0.5-2.0):
<0.8 = Highly selective (fewer signals, higher quality)
0.9-1.2 = Balanced (recommended starting point)
1.3 = Aggressive (more signals, lower individual quality)
Monitor dashboard for 20-30 signals to identify dominant agent
If one agent consistently outperforms, consider using Lock Agent feature
3. Bandit Configuration (Advanced):
Blend Temperature (0.1-2.0):
0.3 = Sharp decisions (best agent dominates)
0.5 = Balanced (default)
1.0+ = Smooth (equal weighting, democratic)
Memory Decay (0.8-0.99):
0.90 = Fast adaptation (volatile markets)
0.95 = Balanced (most instruments)
0.97+ = Long memory (stable trends)
4. Signal Interpretation:
Green triangle (▲): Long signal confirmed
Red triangle (▼): Short signal confirmed
Dashboard shows:
Active agent (highlighted row with ► marker)
Win rate per agent (green >60%, yellow 40-60%, red <40%)
Confidence bars (█████ = maximum confidence)
Memory size (short-term buffer count)
Colored zones display:
Entry level (current close)
Stop-loss (1.5× ATR)
Take-profit 1 (2.0× ATR)
Take-profit 2 (3.5× ATR)
5. Risk Management:
Never risk >1-2% per signal (use ATR-based stops)
Signals are entry triggers, not complete strategies
Combine with your own market context analysis
Consider fundamental catalysts and news events
Use "Confirming" status to prepare entries (not to enter early)
6. Memory Persistence (Optional):
After 50-100 trades, check Memory Export Panel
Record displayed alpha/beta/weight values for each agent
Record VPIN and Kyle threshold values
Enable "Restore From Memory" and input saved values to continue learning
Useful when switching timeframes or restarting indicator
Visual Components
On-Chart Elements:
Spectral Layers: EMA8 ± 0.5 ATR bands (dynamic support/resistance, colored by trend)
Energy Radiance: Multi-layer glow boxes at signal points (intensity scales with confidence, configurable 1-5 layers)
Probability Cones: Projected price paths with uncertainty wedges (15-bar projection, width = confidence × ATR)
Connection Lines: Links sequential signals (solid = same direction continuation, dotted = reversal)
Kill Zones: Risk/reward boxes showing entry, stop-loss, and dual take-profit targets
Signal Markers: Triangle up/down at validated entry points
Dashboard (Configurable Position & Size):
Regime Indicator: 4-level trend classification (Strong Bull/Bear, Weak Bull/Bear)
Mode Status: Shows active system (Adaptive Blend, Locked Agent, or Consensus)
Agent Performance Table: Real-time win%, confidence, and memory stats
Order Flow Metrics: Toxicity and impact indicators (when microstructure enabled)
Signal Status: Current state (Long/Short/Confirming/Waiting) with confirmation progress
Memory Panel (Configurable Position & Size):
Live Parameter Export: Alpha, beta, and weight values per agent
Adaptive Thresholds: Current VPIN sensitivity and Kyle threshold
Save Reminder: Visual indicator if parameters should be recorded
What Makes This Original
This script's originality lies in three key innovations:
1. Genuine Meta-Learning Framework:
Unlike traditional indicator mashups that simply display multiple signals, this implements authentic reinforcement learning (multi-armed bandits) to learn which detection method works best in current conditions. The Thompson Sampling implementation with beta distribution tracking (alpha for successes, beta for failures) is statistically rigorous and adapts continuously. This is not post-hoc optimization—it's real-time learning.
2. Episodic Memory Architecture with Transfer Learning:
The dual-layer memory system mimics human learning patterns:
Short-term memory captures recent performance (recency bias)
Long-term memory preserves historical patterns (experience)
Automatic transfer mechanism consolidates knowledge
Memory boost creates positive feedback loops (successful strategies become stronger)
This architecture allows the system to adapt without retraining , unlike static ML models that require batch updates.
3. Institutional Microstructure Integration:
Combines retail-focused technical analysis (RSI, Bollinger Bands, VWAP) with institutional-grade microstructure metrics (VPIN, Kyle's Lambda, Hawkes processes) typically found in academic finance literature and professional trading systems, not standard retail platforms. While simplified for Pine Script constraints, these metrics provide insight into informed vs. uninformed trading , a dimension entirely absent from traditional technical analysis.
Mashup Justification:
The four agents are combined specifically for risk diversification across failure modes:
Spoofing Detector: Prevents false breakout losses from manipulation
Exhaustion Detector: Prevents chasing extended trends into reversals
Liquidity Void: Exploits volatility compression (different regime than trending)
Mean Reversion: Provides mathematical anchoring when patterns fail
The bandit system ensures the optimal tool is automatically selected for each market situation, rather than requiring manual interpretation of conflicting signals.
Why "ML-lite"? Simplifications and Approximations
This is the "lite" version due to necessary simplifications for Pine Script execution:
1. Simplified VPIN Calculation:
Academic Implementation: True VPIN uses volume bucketing (fixed-volume bars) and tick-by-tick buy/sell classification via Lee-Ready algorithm or exchange-provided trade direction flags
This Implementation: 20-bar rolling window with simple open/close heuristic (close > open = buy volume)
Impact: May misclassify volume during ranging/choppy markets; works best in directional moves
2. Pseudo-Random Sampling:
Academic Implementation: Thompson Sampling requires true random number generation from beta distributions using inverse transform sampling or acceptance-rejection methods
This Implementation: Deterministic pseudo-randomness derived from price and volume decimal digits: (close × 100 - floor(close × 100)) + (volume % 100) / 100
Impact: Not cryptographically random; may have subtle biases in specific price ranges; provides sufficient variation for agent selection
3. Hawkes Process Approximation:
Academic Implementation: Full Hawkes process uses maximum likelihood estimation with exponential kernels: λ(t) = μ + Σ α·exp(-β(t-tᵢ)) fitted via iterative optimization
This Implementation: Simple exponential decay (0.9 multiplier) with binary event triggers (volume spike = event)
Impact: Captures self-exciting property but lacks parameter optimization; fixed decay rate may not suit all instruments
4. Kyle's Lambda Simplification:
Academic Implementation: Estimated via regression of price impact on signed order flow over multiple time intervals: Δp = λ × Δv + ε
This Implementation: Simplified ratio: price_change / sqrt(volume_sum) without proper signed order flow or regression
Impact: Provides directional indicator of impact but not true market depth measurement; no statistical confidence intervals
5. Entropy Calculation:
Academic Implementation: True Shannon entropy requires probability distribution: H(X) = -Σ p(x)·log₂(p(x)) where p(x) is probability of each price change magnitude
This Implementation: Simple ratio of unique price changes to total observations (variety measure)
Impact: Measures diversity but not true information entropy with probability weighting; less sensitive to distribution shape
6. Memory System Constraints:
Full ML Implementation: Neural networks with backpropagation, experience replay buffers (storing state-action-reward tuples), gradient descent optimization, and eligibility traces
This Implementation: Fixed-size array queues with simple averaging; no gradient-based learning, no state representation beyond raw scores
Impact: Cannot learn complex non-linear patterns; limited to linear performance tracking
7. Limited Feature Engineering:
Advanced Implementation: Dozens of engineered features, polynomial interactions (x², x³), dimensionality reduction (PCA, autoencoders), feature selection algorithms
This Implementation: Raw agent scores and basic market metrics (RSI, ATR, volume ratio); minimal transformation
Impact: May miss subtle cross-feature interactions; relies on agent-level intelligence rather than feature combinations
8. Single-Instrument Data:
Full Implementation: Multi-asset correlation analysis (sector ETFs, currency pairs, volatility indices like VIX), lead-lag relationships, risk-on/risk-off regimes
This Implementation: Only OHLCV data from displayed instrument
Impact: Cannot incorporate broader market context; vulnerable to correlated moves across assets
9. Fixed Performance Horizon:
Full Implementation: Adaptive horizon based on trade duration, volatility regime, or profit target achievement
This Implementation: Fixed 8-bar evaluation window
Impact: May evaluate too early in slow markets or too late in fast markets; one-size-fits-all approach
Performance Impact Summary:
These simplifications make the script:
✅ Faster: Executes in milliseconds vs. seconds (or minutes) for full academic implementations
✅ More Accessible: Runs on any TradingView plan without external data feeds, APIs, or compute servers
✅ More Transparent: All calculations visible in Pine Script (no black-box compiled models)
✅ Lower Resource Usage: <500 bars lookback, minimal memory footprint
⚠️ Less Precise: Approximations may reduce statistical edge by 5-15% vs. academic implementations
⚠️ Limited Scope: Cannot capture tick-level dynamics, multi-order-book interactions, or cross-asset flows
⚠️ Fixed Parameters: Some thresholds hardcoded rather than dynamically optimized
When to Upgrade to Full Implementation:
Consider professional Python/C++ versions with institutional data feeds if:
Trading with >$100K capital where precision differences materially impact returns
Operating in microsecond-competitive environments (HFT, market making)
Requiring regulatory-grade audit trails and reproducibility
Backtesting with tick-level precision for strategy validation
Need true real-time adaptation with neural network-based learning
For retail swing/day trading and position management, these approximations provide sufficient signal quality while maintaining usability, transparency, and accessibility. The core logic—multi-agent detection with adaptive selection—remains intact.
Technical Notes
All calculations use standard Pine Script built-in functions ( ta.ema, ta.atr, ta.rsi, ta.bb, ta.sma, ta.stdev, ta.vwap )
VPIN and Kyle's Lambda use simplified formulas optimized for OHLCV data (see "Lite" section above)
Thompson Sampling uses pseudo-random noise from price/volume decimal digits for beta distribution sampling
No repainting: All calculations use confirmed bar data (no forward-looking)
Maximum lookback: 500 bars (set via max_bars_back parameter)
Performance evaluation: 8-bar forward-looking window for reward calculation (clearly disclosed)
Confidence threshold: Minimum 0.25 (25%) enforced on all signals
Memory arrays: Dynamic sizing with FIFO queue management
Limitations and Disclaimers
Not Predictive: This indicator identifies patterns in historical data. It cannot predict future price movements with certainty.
Requires Human Judgment: Signals are entry triggers, not complete trading strategies. Must be confirmed with your own analysis, risk management rules, and market context.
Learning Period Required: The adaptive system requires 50-100 bars minimum to build statistically meaningful performance data for bandit algorithms.
Overfitting Risk: Restoring memory parameters from one market regime to a drastically different regime (e.g., low volatility to high volatility) may cause poor initial performance until system re-adapts.
Approximation Limitations: Simplified calculations (see "Lite" section) may underperform academic implementations by 5-15% in highly efficient markets.
No Guarantee of Profit: Past performance, whether backtested or live-traded, does not guarantee future performance. All trading involves risk of loss.
Forward-Looking Bias: Performance evaluation uses 8-bar forward window—this creates slight look-ahead for learning (though not for signals). Real-time performance may differ from indicator's internal statistics.
Single-Instrument Limitation: Does not account for correlations with related assets or broader market regime changes.
Recommended Settings
Timeframe: 15-minute to 4-hour charts (sufficient volatility for ATR-based stops; adequate bar volume for learning)
Assets: Liquid instruments with >100k daily volume (forex majors, large-cap stocks, BTC/ETH, major indices)
Not Recommended: Illiquid small-caps, penny stocks, low-volume altcoins (microstructure metrics unreliable)
Complementary Tools: Volume profile, order book depth, market breadth indicators, fundamental catalysts
Position Sizing: Risk no more than 1-2% of capital per signal using ATR-based stop-loss
Signal Filtering: Consider external confluence (support/resistance, trendlines, round numbers, session opens)
Start With: Balanced mode, Thompson Sampling, Blend mode, default agent sensitivities (1.0)
After 30+ Signals: Review agent win rates, consider increasing sensitivity of top performers or locking to dominant agent
Alert Configuration
The script includes built-in alert conditions:
Long Signal: Fires when validated long entry confirmed
Short Signal: Fires when validated short entry confirmed
Alerts fire once per bar (after confirmation requirements met)
Set alert to "Once Per Bar Close" for reliability
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
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
Other alts compensated capitalization [Peregringlk]DISCLAIMER: I'm not a native English speaker, so let me know please about mistakes in my wording.
Introduction
==========
This indicator (the middle one in the image) shows how the "others altcoins" (all altcoins except coins with high capitalization) are adding own value to its capitalization by removing BTC price changes. By "own value" I mean USD value gaining by actual buys in BTC markets beyong arbitrage effects of BTC price changes.
The main idea is that, if bitcoin has increased is value by 20%, and the other altcoins has increased its capitalization by 30%, the chart will only plot an increased of 10%. In other words, it will show its increased capitalization measured in BTC (the combined altcoin/BTC market is uptrending). Its purpose is to try to identify altseasons. A bit more concisely, the graph will only grow when both USD and BTC capitalization are growing. If any of them are going down, the graph will go down as well.
Rationale
========
- Altseasons are characterized by an incresed in BTC value of almost every altcoin during some period of time, although not all at once, but distributed over the altseason. For example, in the crazy altseason of Dec17/Jan18, almost every (low capitalized) altcoin increased its BTC value by a minimum of +300%, some at the beginning of the season, some at the end.
- When this happens, BTC loss capitalization dominance, but this also can happen if BTC is downtrending while altcoins are being bought in BTC markets but its USD value doesn't change too much. This happens when altcoins are uptrending in BTC price, but there are actually no gain of USD value because the BTC gain in value is not enough to compensate the BTC fall in price. Since BTC is losing USD price, but altcoins are not, dominance falls. So, looking at BTC dominance is not enough to spot possible beginnings of altseasons, because of arbitrage of other effects.
- The "big altcoins" are removed from the counting because one single big capitalized altcoin that grows, let's say, a 20%, will have an observable effect on the total altcoin capitalization, even if the rest of the altcoins are stagnated in price. For example, at today's date (8th April 2020), Ethereum by itself has the 23.89% of the total altcoins capitalization. A +10% in Ethereum price will increase the total altcoin capitalization by a +2.38%. I wanted to remove that effect to focus on generalized price changes of all altcoins. Remember that there are only 9 big altcoins 9 coins representing the 71% of the alts capitalization, while there are exists more than 5000 altcoins in total.
- Another key factor is that I want to focus on what happens in alt/BTC markets, because almost every altcoin can be traded against BTC, and most of them can only be traded against BTC. However, big altcoins can usually be traded against USD or other alt coins or fiat currencies as well. Removing the big alts from the equation helps (just a bit) to simplify the interpretation of the chart because arbitrage effects of those "impactfull" alts are limited (although not removed, because arbitrage also happens cross-markets).
- There are situations where BTC price is going up, alts USD capitalization is going up as well, but alts BTC capitalization is going down because altcoins are being sold in BTC markets, it just happens that the speed of the selling is not high enough as to compensated the increased in BTC price. That makes the USD capitalization grows, while alts are really being dumped in BTC markets. I wanted to reflect that effect as well by making sure that the graph is growing only when both USD and BTC capitalization of alts are growing.
Interpretation
============
If you want, you can see this chart as if plotting the Other alts capitalization as if priced against a fictional coin FCOIN, that start by having a price of 1, that combines the up and downs of both BTC price and alts USD capitalization in a very conservative way: if FCOIN price goes up, means that the other alts are gained USD value but only when they have overcome BTC price changes. Otherwise, it goes down.
If this fictional FCOIN has went up during some days straight with a total gain of maybe, greater than 10%, we are maybe in front of the start of an altseason. Sometimes, maybe (it requires some more years to extract a theory out of here), it can be used as proxy of the BTC near future (trend changes or continuations): if this FCOIN goes up, while BTC is doing nothing relevant or even is going down, it could signal that "people" is getting prepared and a generalized altcoin accumulation process has started, because of a combined people's assumption that BTC will start to have an stable uptrend, or will continue the current trend soon. There's some matches in the past about that, but there are also false positives, as usual.
Additionally, four customizable EMAs are added to the script, by default 21, 50, 100 and 150.
Definitions
=========
- Let's call `altcap_btc` the altcoin capitalization in USD, divided by BTC price. In other words, `altcap_btc` is the capitalization in terms of BTC.
- Let's call `x` the BTC price change rate as `btc_price_current_candle / btc_price_previous_candle`. So, if BTC has grown a +20%, `x = 1.20`, and if BTC has gone down a -20%, `x = 0.80`.
- Let's call `y` the `altcap_btc` price change rate, calculated as before but for `altcap_btc`.
- For pure math equivalence, `x * y` is thus the USD capitalization change rate.
Calculation
=========
For plotting the graph, for each candle, I choose a change rate, and then I plot the total accumulated change rate as by `ch0 * ch1 * ch2 * .... * ch_today`, where each `chX` is the choosen change rate of each candle since the beginning of the chart. So, if the "alts compensated value" has grown yesterday +20% and today's -10%, `1.20 * 0.9 = 1.08`, which means that in two days the compensated value has grown an 8% in total.
- If `x * y > 1` (USD cap is growing), I take `y` as change rate (alt/btc change rate).
- If both `x` and `y` are `> 1`, then the graph grows because I'm taking `y`.
- If `x > 1` and `y < 1`, the graph goes down because I'm taking `y`, reflecting the BTC markets are dumping.
- If `x < 1` and `y > 1`, the graph goes up because I'm taking `y`, reflecting the BTC markets are pumping so much that it overcomes the btc fall.
- `x < 1` and `y < 1` is impossible here because `x * y` must be `> 1` by precondition.
- If `x * y < 1` (USD cap is going down), I take `y` or `x * y` depending on the individual change rates:
- If `x` and `y` go in different directions (one up and the other down), I take `x * y` to reflect that USD capitalization has gone down. I don't take `y` here because it could be `> 1`, and I don't want to make the graph grow if alts are lossing USD value. Also, if `y < 1` and I take `y` the graph will go down faster than USD capitalization and I want to show that "alts compensated value is gown down slower than BTC because some boughts are happening". I don't take `x` either here for the same reasons.
- If both `x` and `y` are `< 1`, I take `y`, because otherwise the graph would be less than 0.000001 today after two years of bleeding, making literally impossible to see if alts "grow tomorrow".
- `x > 1` and `y > 1` is impossible here because `x * y` must be `< 1` by precondition.
Spot Symbols for CryptoLibrary "CryptoSpotSymbols"
This Library has one purpose only. It generate Symbols for the Crypto Spot Market, like all the currencies pairs of most Crypto Exchanges available to TradingView.
Have a look at .find() , which is an all in one function.
Binance(basecurrency)
Generate 27 Symbols for the Spot Market of Binance.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
BinanceUS(basecurrency)
Generate seven Symbols for the Spot Market of BinanceUS.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Bitfinex(basecurrency)
Generate 12 Symbols for the Spot Market of Bitfinex.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
bitFlyer(basecurrency)
Generate three Symbols for the Spot Market of bitFlyer.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Bitget(basecurrency)
Generate seven Symbols for the Spot Market of Bitget.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Bithumb(basecurrency)
Generate two Symbols for the Spot Market of Bithumb.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
bitkub(basecurrency)
Generate one Symbol for the Spot Market of bitkub.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: THB
BitMEX(basecurrency)
Generate two Symbols for the Spot Market of BitMEX.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
bitpanda_pro(basecurrency)
Generate six Symbols for the Spot Market of bitpanda pro.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
bitrue(basecurrency)
Generate nine Symbols for the Spot Market of bitrue.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Bitstamp(basecurrency)
Generate eight Symbols for the Spot Market of Bitstamp.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
BITTREX(basecurrency)
Generate six Symbols for the Spot Market of BITTREX.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
BTSE(basecurrency)
Generate 15 Symbols for the Spot Market of BTSE.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
BYBIT(basecurrency)
Generate five Symbols for the Spot Market of BYBIT.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
CapitalCom(basecurrency)
Generate five Symbols for the Spot Market of capital.com.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
coinbase(basecurrency)
Generate seven Symbols for the Spot Market of coinbase.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
CoinEx(basecurrency)
Generate three Symbols for the Spot Market of CoinEx.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
CurrencyCom(basecurrency)
Generate 30 Symbols for the Spot Market of currency.com.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Delta(basecurrency)
Generate one Symbol for the Spot Market of Delta.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: USDT
Deribit(basecurrency)
Generate two Symbols for the Spot Market of Deribit.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
easyMarkets(basecurrency)
Generate one Symbol for the Spot Market of easyMarkets.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: USD
Eightcap(basecurrency)
Generate one Symbol for the Spot Market of Eightcap.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: USD
ExMo(basecurrency)
Generate ten Symbols for the Spot Market of ExMo.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
FOREXcom(basecurrency)
Generate four Symbols for the Spot Market of FOREX.com.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
FXCM(basecurrency)
Generate three Symbols for the Spot Market of FXCM.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
GateIO(basecurrency)
Generate five Symbols for the Spot Market of Gate.io.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Gemini(basecurrency)
Generate ten Symbols for the Spot Market of Gemini.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Kraken(basecurrency)
Generate 14 Symbols for the Spot Market of Kraken.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
KuCoin(basecurrency)
Generate 13 Symbols for the Spot Market of KuCoin.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
MEXC(basecurrency)
Generate six Symbols for the Spot Market of MEXC.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
OANDA(basecurrency)
Generate one Symbol for the Spot Market of OANDA.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: USD
OKX(basecurrency)
Generate six Symbols for the Spot Market of OKX.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Pepperstone(basecurrency)
Generate one Symbol for the Spot Market of Pepperstone.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns: USD
phemex(basecurrency)
Generate four Symbols for the Spot Market of phemex.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
POLONIEX(basecurrency)
Generate nine Symbols for the Spot Market of POLONIEX.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Pyth(basecurrency)
Generate three Symbols for the Spot Market of Pyth.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
Skilling(basecurrency)
Generate four Symbols for the Spot Market of Skilling.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
TimeX(basecurrency)
Generate six Symbols for the Spot Market of TimeX.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
TradeStation(basecurrency)
Generate four Symbols for the Spot Market of TradeStation.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
UpBit(basecurrency)
Generate four Symbols for the Spot Market of UpBit.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
whitebit(basecurrency)
Generate 13 Symbols for the Spot Market of whitebit.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
WOOX(basecurrency)
Generate two Symbols for the Spot Market of WOO.
Parameters:
basecurrency (simple string) : Its the Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`.
Returns:
find(exchange, basecurrency)
Generate up to 30 Symbols for the Spot Market, depending on the market picked.
Parameters:
exchange (simple string) : The name of an Exchange. Case insensitivity. Optional. Default value is `syminfo.prefix`. If something else is put in here it will return `na` values.
basecurrency (simple string) : The Basecurrency to generate the Symbols with. Optional. Default value is `syminfo.basecurrency`
Returns: 30x string as tuple






















