ICT 7/8/9am lines NY session + 7.30/8.30/9.30 linesThis script show the 7, 8, 9 AM NY session lines, together with the 7.30, 8.30 and 9.30AM lines, like ICT teaches in the 2024 Mentorship, lesson 2.
Feel free to use it!
Indicadores e estratégias
Daily Inputs - The Prometheus InitiativeDaily ES inputs from the Prometheus Initiative is a clean, customizable overlay indicator designed specifically for ES (S&P 500 E-mini futures) day traders who rely on manually selected key price levels each session.
Instead of spending time manually drawing horizontal lines every day, this tool lets you quickly input the daily price levels directly in the settings and instantly see them plotted as horizontal lines across your chart.
Key Features:
• 15 fully editable price inputs with customizable settings.
Why this indicator was created:
Manually drawing 10–15 lines each morning is time-consuming. This indicator was developed to eliminate that friction — allowing fast, accurate plotting of levels so you can focus on execution rather than drawing tools. The largest benefit is that you can toggle the indicator on/off to keep a clean chart as to not interfere with your existing visual levels.
Perfect for:
- ES / NQ futures traders
- Anyone who wants a clean, no-nonsense way to visualize custom horizontal levels
How to use:
1. Add to your chart
2. Open Settings → Enter the daily levels provided
3. Watch price interact with the levels!
Note: This is a manual input tool. Levels do NOT auto-calculate. It's meant to reflect the exact levels posted each day.
Happy trading! 📈
Feel free to leave feedback or suggestions in the comments.
Disclaimer: This indicator is for educational/visual purposes only. Trading futures involves substantial risk of loss and is not suitable for all investors.
HTB Reversal Pattern - RSI DivergenceHow this Script Works
Pivot Points: The script looks for "peaks" and "valleys" in the RSI indicator.
Divergence Logic: * Bullish: If the current price low is lower than the previous low, but the RSI low is higher than the previous RSI low, it indicates the selling pressure is fading despite the price drop.
Bearish: If the current price high is higher than the previous high, but the RSI high is lower than the previous RSI high, it suggests buying momentum is weakening.
The "Lookback" Offset: Because pivot points require a few bars to the right to be confirmed (defined by lbR), the labels will appear on the chart with a small delay (default is 5 bars). This is necessary to prevent "repainting" (signals that disappear after they appear).
Squeeze Indicator Squeeze Indicator is a volatility-focused indicator designed to identify periods of compression and the early transition into expansion.
It measures Bollinger Band Width (BBW) using a 20-period Bollinger Band to quantify how tightly price is coiling, then smooths BBW with a 16-period SMA and a faster 8-period EMA to distinguish structural compression from short-term changes in volatility.
The BBW itself is displayed as a subtle grey filled area to emphasize relative contraction and expansion, while a squeeze condition is highlighted whenever BBW falls below both its SMA and EMA, signaling an environment where volatility is suppressed and a directional move is more likely to follow.
Crossovers of the EMA above or below the SMA provide early warnings of volatility expansion or renewed compression, making the indicator especially useful for timing breakouts, anticipating regime shifts from range to trend, and managing options strategies that depend on changes in volatility rather than price direction.
Needle Below 20, Sub-chart## 指标名称
**单针下20副图(Needle Below 20, Sub-chart)**
## 一句话概述
在**中周期保持强势**的背景下,用短周期的“快速降温”来定位**强势回撤/错杀**,并额外标记**极端超卖(双线归零)**的情绪极值窗口。
---
## 指标逻辑与构成
本指标包含两条强弱线(随机指标风格的区间归一化):
* **短期线(默认 3)**
反映近短周期内价格在区间的位置,敏感度高,用于捕捉短线回撤与情绪快速降温。
* **长期线(默认 21)**
反映中周期强弱分布,用作“趋势/强势背景”的过滤。
并提供两类柱状提示(STICK):
1. **双线归零(默认:短期≤6 且 长期≤6)**
代表“情绪极端恐慌/极端超卖”的窗口,更多用于观察**反弹可能性**与“风险释放阶段”。
2. **单针下20(默认:短期≤20 且 长期≥80)**
代表“中周期强势未破 + 短线急跌/下探”的典型回撤信号,用于寻找趋势交易中的**回撤介入候选**。
图中绘制 **80/20** 参考线,帮助快速判断分位区域。
---
## 使用方法(推荐工作流)
### 1)先定“背景”:只在你认可的趋势环境使用
本指标本质是“**强势回撤定位器**”,并不负责替你判断大盘/板块/个股是否处于可交易趋势。建议搭配以下任一类过滤器:
* **趋势过滤(强烈推荐)**
* 价格位于中长期均线之上(例:MA50/MA200 上方)
* 或者你自己的趋势线/多空线系统显示多头趋势(如:快线>慢线、结构未破)
* **结构过滤(强烈推荐)**
* 回撤仍然在关键支撑之上(前高、趋势线、箱体上沿回踩等)
* 避免在明显“破位下跌”的结构中把信号当作抄底依据
### 2)信号触发后的处理:不要“看到就买”,而是“进入观察与触发”
* **单针下20(黄柱)**:
作为“候选提示”,下一步关注是否出现:
* 回踩关键位后的止跌K线(锤子线/吞没/放量止跌等)
* 次日/后续重新站回关键位或出现趋势延续确认
* 量价关系转好(缩量回撤、放量反转等)
* **双线归零(红柱)**:
更偏“情绪极值”提示,常见用途是:
* 提醒你风险已经释放到极端区域,观察是否出现反弹结构
* 不建议无过滤硬抄底;更适合与“结构止跌/大盘企稳”一起使用
---
## 风险控制与止损思路(示例,不构成建议)
以下仅提供“如何把信号落到可执行”的框架示例:
* **入场触发(示例)**
* 黄柱出现后:等待价格在关键位止跌,或出现确认K线再介入
* 分批:先小仓试错,确认后再加
* **止损锚点(示例)**
* 关键支撑位下破(趋势线/前低/箱体下沿)
* 或“信号触发后的反弹失败又破前低”
* **仓位建议(原则)**
* 把仓位大小与止损距离联动:止损距离越大,仓位越小
* 避免单次信号重仓;这类信号更适合“低风险试错 + 确认加仓”的趋势回撤逻辑
---
## 参数说明与调参建议
### 1)为什么是 3 / 21?
* **3**:强调“短期情绪/回撤”的敏感度,适合捕捉快速下探
* **21**:近似一个月交易日,刻画中周期强弱背景,适合作为“强势过滤”
如果你交易周期更短(更偏日内/隔日):
* 可考虑 **短期 2–5**、长期 **13–34** 区间做测试。
如果你交易周期更长(偏波段/中线):
* 可考虑 **短期 5–8**、长期 **34–55**。
### 2)为什么阈值是 6 / 20 / 80?
* **6**:更接近“极端”区域,用于标记情绪极值(双线归零)
* **20/80**:经典分位阈值,表示低位/高位区域,用于区分“短弱/长强”的错位状态
### 3)如何调参更贴合你的市场与标的?
建议按“信号密度—胜率—回撤”三者权衡:
* 信号太多:
* 降低“长期≥”阈值的触发频率(如 80→85)
* 或提高“短期≤”门槛的严苛度(20→15)
* 或把长期周期加长(21→34)
* 信号太少:
* 放宽阈值(长期 80→75、短期 20→25)
* 或缩短长期周期(21→13)
调参务必结合你常交易的品种波动特征,建议在同一市场同一类标的上做一致性回测/复盘。
---
## 免责声明
本脚本仅用于教育与研究目的,展示一种技术分析可视化方法,不构成任何形式的投资建议、交易建议或收益承诺。市场有风险,交易需谨慎。使用者应基于自身风险承受能力独立决策,并对交易结果自行负责。作者不对任何因使用本脚本导致的直接或间接损失承担责任。
---
## 致谢与来源
* **策略/思路来源**:B站 UP 主 **z哥** 的相关分享与讲解。
* **实现说明**:本脚本为 TradingView(Pine Script)版本的复现与可视化实现,便于在 TradingView 环境中使用与研究。
* 如原作者对公开引用有额外要求,请以原作者说明为准;若有侵权或需要修改归因方式,请联系我调整/下架相关描述。
下面给你补齐一份**英文版(可直接用于 TradingView 发布页)**,并与中文版结构对齐,符合社区常见写法(Overview / How it works / How to use / Inputs / Risk / Credits)。
---
## Title
**Needle Below 20 (Sub-chart) — TDX Style Recreation**
## Overview
This indicator is an auxiliary tool designed to spot **sharp short-term pullbacks (shakeouts) within a strong mid-term regime**, and to highlight **extreme oversold “panic” zones**. It is best used as a **candidate filter and timing aid** inside a broader trend-following framework, rather than as a standalone buy/sell signal.
## How it works
The script plots two normalized strength lines (stochastic-style normalization over a lookback window):
* **Short-term line (default: 3 bars)**
Captures fast sentiment cooling and short-term compression (high sensitivity).
* **Long-term line (default: 21 bars)**
Represents the mid-cycle regime strength, used as a context filter.
It also provides two stick/column signals:
1. **Double-Line Near-Zero (Red stick)**
Triggered when **Short-term ≤ 6 AND Long-term ≤ 6** (defaults).
This typically represents an **extreme oversold / capitulation-like** window, often used to monitor potential technical rebounds (confirmation recommended).
2. **Needle Below 20 (Yellow stick)**
Triggered when **Short-term ≤ 20 AND Long-term ≥ 80** (defaults).
This is commonly interpreted as a **strong regime intact + sudden short-term dump/pullback**, useful for spotting potential **trend pullback re-entry candidates**.
Reference levels **80/20** are drawn for quick zone reading.
### How to use (recommended workflow)
1. **Define the regime first (strongly recommended)**
This indicator does not decide whether a market is tradable. Use a trend/structure filter, for example:
* Price above a medium/long MA (e.g., MA50/MA200), or your own trend model
* Structure not broken (support holds, pullback into a valid support zone)
2. **Treat signals as “watchlist triggers,” not instant entries**
* **Yellow stick (Needle Below 20):**
After it prints, look for confirmation such as:
* A hold/reclaim of a key level (prior high, trendline, range top retest, etc.)
* A reversal candle or continuation confirmation
* Constructive volume/price behavior (e.g., pullback on lighter volume, rebound with demand)
* **Red stick (Double-Line Near-Zero):**
Best viewed as an **extreme sentiment/oversold marker**. Avoid blind bottom-fishing; combine with structure stabilization and broader market context.
## Risk management (examples, not financial advice)
* **Entry trigger (example):** scale in after confirmation rather than buying the first signal
* **Stop reference (example):** below the key support / prior swing low / structural invalidation level
* **Position sizing principle:** size positions based on stop distance; larger stop = smaller size
## Inputs / Parameters
* **Lookbacks (3 / 21):**
* 3 bars: short-term sensitivity for fast pullback detection
* 21 bars: mid-cycle regime context (roughly one trading month)
Suggested adjustments:
* Shorter-term trading: try **2–5** (short) and **13–34** (long)
* Longer swing trading: try **5–8** (short) and **34–55** (long)
* **Thresholds (6 / 20 / 80):**
* 6: “extreme” zone for near-zero panic marker
* 20/80: classic zone thresholds for low/high regime separation
If signals are too frequent:
* tighten thresholds (e.g., long ≥ 80 → 85, short ≤ 20 → 15), or lengthen long lookback (21 → 34)
If signals are too rare:
* loosen thresholds (e.g., long ≥ 80 → 75, short ≤ 20 → 25), or shorten long lookback (21 → 13)
## Disclaimer
This script is provided for **educational and research purposes only**. It does **not** constitute financial advice, investment recommendations, or any guarantee of performance. Trading involves risk. You are solely responsible for your decisions and outcomes.
## Credits / Attribution
* **Concept origin:** Inspired by the Bilibili creator **“z哥”**.
* **Implementation:** This is a TradingView (Pine Script) recreation for visualization and study.
If the original creator has specific attribution requirements, please follow the creator’s instructions. If any changes are needed, attribution text can be updated accordingly.
## Citation snippet
> Concept inspired by Bilibili creator “z哥”. Pine Script recreation for educational/research use.
Bradley Industries IndicatorThe Bradley Industries Indicator is a confluence-based trading system designed to identify early trend impulses while filtering out late or low-probability entries.
It combines four independent indicators, each measuring a different market dimension, and only generates a primary signal when all four align on the same bar.
The philosophy of the system is simple:
Enter only when structure, momentum, volatility, and directional flow agree at the start of a move.
Risk Manager & ATR TS Strategy📌 Overview
This script is not a simple indicator mashup. It is a Risk & Trade Planning Engine that combines a strategy-based signal generator with a snapshot-based risk, sizing, and expectancy model. It is designed to support real trading decisions, not just to generate cosmetic signals or overfitted backtests.
The core idea is to separate market logic from risk logic, evaluating each trade only at the moment it becomes actionable using fixed reference points that do not change afterward.
🎯 What makes this script original Unlike most tools that merely combine indicators or visualize entries, this script introduces several non-standard design choices:
Snapshot-based risk sizing (The "Time Machine" logic).
Expected Value (EV) calculation in both Money and R-multiples.
Kelly Criterion applied with weighted multi-target logic.
Strict architectural separation between the signal engine and the risk engine.
Decision-oriented dashboard instead of decorative plots.
These components are not merged for convenience; they are architecturally dependent on each other.
🧠 Conceptual Architecture
1️⃣ Signal Engine (Market Context) The signal engine is based on an ATR Trailing Stop system combined with trend regime filters (ADX and Choppiness Index). Its only responsibility is to answer one question: "Is this a valid directional opportunity right now?" It does not manage risk; it only identifies the opportunity.
2️⃣ Snapshot Logic (Key Design Choice) When a valid signal occurs, the script captures a Snapshot of the Entry price, Initial Stop-Loss, and Risk Distance. This snapshot is frozen at signal time. It is never updated, even if the trailing stop moves later. This avoids the most common error in TradingView scripts: recalculating position size using a moving stop, which falsifies the risk data.
3️⃣ Risk Engine (Sizing & Control) Using the snapshot values, the script computes:
Monetary risk per trade (capped at your user-defined max).
Position size derived from the fixed stop distance.
Effective leverage (informational).
4️⃣ Multi-Target Reward Model Instead of assuming a single take-profit, the script supports multiple targets with user-defined probability weights. From this, it derives a Weighted Risk/Reward Ratio, which feeds directly into the EV and Kelly calculations.
5️⃣ Expected Value (EV) in Money & R The script calculates EV in your account currency (real impact) and normalized in R-multiples (statistical quality). This allows you to compare trade quality across different assets and timeframes objectively.
6️⃣ Kelly Criterion (Conservative) The Kelly Criterion is applied using the weighted reward model and is always subordinated to your hard risk cap. If Kelly suggests a negative value, the script advises "NO TRADE". It is used as a filter, not a leverage amplifier.
📊 Dashboard & Alerts The on-chart dashboard summarizes everything you need at the moment of the signal:
Risk % and Position Size
Expected Value (Money + R)
Kelly Suggestion
Signal Strength
Alerts are triggered once per signal (on bar close) using snapshot data, ensuring no repainting and no spam.
🔍 How this is NOT a mashup Each component exists because another component depends on it. Snapshot logic is required for valid risk sizing; Risk sizing is required for EV normalization; Weighted RR is required for meaningful Kelly. Removing any part breaks the system’s logic.
📘 How to use
Choose your account size and risk parameters in the settings.
Configure your stop logic and reward targets.
Wait for a valid signal.
Evaluate the dashboard: Decide if the trade quality (EV, R, Risk) justifies participation.
⚖️ Open-Source Notice This script is published under the Mozilla Public License 2.0 (MPL-2.0). It does not copy or replicate any single public script. Standard concepts (ATR, ADX) are used as building blocks, but the architecture and calculations are original.
🚫 Disclaimer This script is a planning and evaluation engine designed to help traders think in terms of risk, expectancy, and discipline. It does not guarantee profitability.
✅ Summary This is a professional-grade framework built to answer one core question: “Is this trade worth taking, given my risk and my expectations?” Not every signal is a trade, and not every trade deserves capital. This script helps you make that distinction.
Elite Risk-On/Risk-Off Oscillator (6 pairs) The Elite Risk-On / Risk-Off Oscillator is a market-regime indicator designed to determine whether conditions favor aggressive risk-taking or defensive capital preservation rather than to predict price direction.
It combines six carefully selected relative-strength pairs that measure risk appetite across the most important parts of the market:
IEI/HYG (credit stress, weighted most heavily because credit often leads equities)
SPHB/SPLV (equity risk appetite via high-beta versus low-volatility stocks)
IWM/SPY (liquidity and growth sensitivity through small-caps versus large-caps)
MTUM/QUAL (trend durability versus balance-sheet quality)
XLY/XLP (consumer cyclicality, wants versus needs)
EEM/SPY (global risk and dollar-sensitive capital flows)
Each pair is evaluated using relative performance against a moving-average and slope filter to classify it as risk-on (+1), neutral (0), or risk-off (-1), with defensive ratios inverted so that positive readings always indicate risk-on conditions; the weighted signals are then aggregated, normalized to a -100 to +100 scale, and smoothed into a single oscillator. Readings above approximately +40 indicate a supportive risk-on environment where trends are more likely to persist, readings between -40 and +40 reflect transitional or choppy conditions with lower conviction, and readings below -40 signal a risk-off regime where capital preservation and defense should be prioritized.
The indicator is intended as a context and position-sizing tool, helping traders align strategy aggressiveness with underlying market conditions rather than relying on forecasts or narratives.
MLMatrixLibOverview
MLMatrixLib is a comprehensive Pine Script v6 library implementing machine learning algorithms using native matrix operations. This library provides traders and developers with a toolkit of statistical and ML methods for building quantitative trading systems, performing data analysis, and creating adaptive indicators.
How It Works
The library leverages Pine Script's native matrix type to perform efficient linear algebra operations. Each algorithm is implemented from first principles, using matrix decomposition, iterative optimization, and statistical estimation techniques. All functions are designed for numerical stability with careful handling of edge cases.
---
Library Contents (34 Sections)
Section 1: Utility Functions & Matrix Operations
Core building blocks including:
• identity(n) - Creates n×n identity matrix
• diagonal(values) - Creates diagonal matrix from array
• ones(rows, cols) / zeros(rows, cols) - Matrix constructors
• frobeniusNorm(m) / l1Norm(m) - Matrix norm calculations
• hadamard(m1, m2) - Element-wise multiplication
• columnMeans(m) / rowMeans(m) - Statistical aggregations
• standardize(m) - Z-score normalization (zero mean, unit variance)
• minMaxNormalize(m) - Scale values to range
• fitStandardScaler(m) / fitMinMaxScaler(m) - Reusable scaler parameters
• addBiasColumn(m) - Prepend column of ones for regression
• arrayMedian(arr) / arrayPercentile(arr, p) - Array statistics
Section 2: Activation Functions
Numerically stable implementations:
• sigmoid(x) / sigmoidMatrix(m) - Logistic function with overflow protection
• tanhActivation(x) / tanhMatrix(m) - Hyperbolic tangent
• relu(x) / reluMatrix(m) - Rectified Linear Unit
• leakyRelu(x, alpha) - Leaky ReLU with configurable slope
• elu(x, alpha) - Exponential Linear Unit
• Derivatives for backpropagation: sigmoidDerivative, tanhDerivative, reluDerivative
Section 3: Linear Regression (OLS)
Ordinary Least Squares implementation using the normal equation (X'X)⁻¹X'y:
• fitLinearRegression(X, y) - Fits model, returns coefficients, R², standard error
• fitSimpleLinearRegression(x, y) - Single-variable regression
• predictLinear(model, X) - Generate predictions
• predictionInterval(model, X, confidence) - Confidence intervals using t-distribution
• Model type stores: coefficients, R-squared, residuals, standard error
Section 4: Weighted Linear Regression
Generalized least squares with observation weights:
• fitWeightedLinearRegression(X, y, weights) - Solves (X'WX)⁻¹X'Wy
• Useful for downweighting outliers or emphasizing recent data
Section 5: Polynomial Regression
Fits polynomials of arbitrary degree:
• fitPolynomialRegression(x, y, degree) - Constructs Vandermonde matrix
• predictPolynomial(model, x) - Evaluate polynomial at points
Section 6: Ridge Regression (L2 Regularization)
Adds penalty term λ||β||² to prevent overfitting:
• fitRidgeRegression(X, y, lambda) - Solves (X'X + λI)⁻¹X'y
• Lambda parameter controls regularization strength
Section 7: LASSO Regression (L1 Regularization)
Coordinate descent algorithm for sparse solutions:
• fitLassoRegression(X, y, lambda, maxIter, tolerance) - Iterative soft-thresholding
• Produces sparse coefficients by driving some to exactly zero
• softThreshold(x, lambda) - Core shrinkage operator
Section 8: Elastic Net (L1 + L2 Regularization)
Combines LASSO and Ridge penalties:
• fitElasticNet(X, y, lambda, alpha, maxIter, tolerance)
• Alpha balances L1 vs L2: alpha=1 is LASSO, alpha=0 is Ridge
Section 9: Huber Robust Regression
Iteratively Reweighted Least Squares (IRLS) for outlier resistance:
• fitHuberRegression(X, y, delta, maxIter, tolerance)
• Delta parameter defines transition between L1 and L2 loss
• Downweights observations with large residuals
Section 10: Quantile Regression
Estimates conditional quantiles using linear programming approximation:
• fitQuantileRegression(X, y, tau, maxIter, tolerance)
• Tau specifies quantile (0.5 = median, 0.25 = lower quartile, etc.)
Section 11: Logistic Regression (Binary Classification)
Gradient descent optimization of cross-entropy loss:
• fitLogisticRegression(X, y, learningRate, maxIter, tolerance)
• predictProbability(model, X) - Returns probabilities
• predictClass(model, X, threshold) - Returns binary predictions
Section 12: Linear SVM (Support Vector Machine)
Sub-gradient descent with hinge loss:
• fitLinearSVM(X, y, C, learningRate, maxIter)
• C parameter controls regularization (higher = harder margin)
• predictSVM(model, X) - Returns class predictions
Section 13: Recursive Least Squares (RLS)
Online learning with exponential forgetting:
• createRLSState(nFeatures, lambda, delta) - Initialize state
• updateRLS(state, x, y) - Update with new observation
• Lambda is forgetting factor (0.95-0.99 typical)
• Useful for adaptive indicators that update incrementally
Section 14: Covariance and Correlation
Matrix statistics:
• covarianceMatrix(m) - Sample covariance
• correlationMatrix(m) - Pearson correlations
• pearsonCorrelation(x, y) - Single correlation coefficient
• spearmanCorrelation(x, y) - Rank-based correlation
Section 15: Principal Component Analysis (PCA)
Dimensionality reduction via eigendecomposition:
• fitPCA(X, nComponents) - Power iteration method
• transformPCA(X, model) - Project data onto principal components
• Returns components, explained variance, and mean
Section 16: K-Means Clustering
Lloyd's algorithm with k-means++ initialization:
• fitKMeans(X, k, maxIter, tolerance) - Cluster data points
• predictCluster(model, X) - Assign new points to clusters
• withinClusterVariance(model) - Measure cluster compactness
Section 17: Gaussian Mixture Model (GMM)
Expectation-Maximization algorithm:
• fitGMM(X, k, maxIter, tolerance) - Soft clustering with probabilities
• predictProbaGMM(model, X) - Returns membership probabilities
• Models data as mixture of Gaussian distributions
Section 18: Kalman Filter
Linear state estimation:
• createKalman1D(processNoise, measurementNoise, ...) - 1D filter
• createKalman2D(processNoise, measurementNoise) - Position + velocity tracking
• kalmanStep(state, measurement) - Predict-update cycle
• Optimal filtering for noisy measurements
Section 19: K-Nearest Neighbors (KNN)
Instance-based learning:
• fitKNN(X, y) - Store training data
• predictKNN(model, X, k) - Classify by majority vote
• predictKNNRegression(model, X, k) - Average of k neighbors
• predictKNNWeighted(model, X, k) - Distance-weighted voting
Section 20: Neural Network (Feedforward)
Multi-layer perceptron:
• createNeuralNetwork(architecture) - Define layer sizes
• trainNeuralNetwork(nn, X, y, learningRate, epochs) - Backpropagation
• predictNN(nn, X) - Forward pass
• Supports configurable hidden layers
Section 21: Naive Bayes Classifier
Gaussian Naive Bayes:
• fitNaiveBayes(X, y) - Estimate class-conditional distributions
• predictNaiveBayes(model, X) - Maximum a posteriori classification
• Assumes feature independence given class
Section 22: Anomaly Detection
Statistical outlier detection:
• fitAnomalyDetector(X, contamination) - Mahalanobis distance-based
• detectAnomalies(model, X) - Returns anomaly scores
• isAnomaly(model, X, threshold) - Binary classification
Section 23: Dynamic Time Warping (DTW)
Time series similarity:
• dtw(series1, series2) - Compute DTW distance
• Handles sequences of different lengths
• Useful for pattern matching
Section 24: Markov Chain / Regime Detection
Discrete state transitions:
• fitMarkovChain(states, nStates) - Estimate transition matrix
• predictNextState(transitionMatrix, currentState) - Most likely next state
• stationaryDistribution(transitionMatrix) - Long-run probabilities
Section 25: Hidden Markov Model (Simple)
Baum-Welch algorithm:
• fitHMM(observations, nStates, maxIter) - EM training
• viterbi(model, observations) - Most likely state sequence
• Useful for regime detection
Section 26: Exponential Smoothing & Holt-Winters
Time series smoothing:
• exponentialSmooth(data, alpha) - Simple exponential smoothing
• holtWinters(data, alpha, beta, gamma, seasonLength) - Triple smoothing
• Captures trend and seasonality
Section 27: Entropy and Information Theory
Information measures:
• entropy(probabilities) - Shannon entropy in bits
• conditionalEntropy(jointProbs, marginalProbs) - H(X|Y)
• mutualInformation(probsX, probsY, jointProbs) - I(X;Y)
• kldivergence(p, q) - Kullback-Leibler divergence
Section 28: Hurst Exponent
Long-range dependence measure:
• hurstExponent(data) - R/S analysis
• H < 0.5: mean-reverting, H = 0.5: random walk, H > 0.5: trending
Section 29: Change Detection (CUSUM)
Cumulative sum control chart:
• cusumChangeDetection(data, threshold, drift) - Detect regime changes
• cusumOnline(value, prevCusumPos, prevCusumNeg, target, drift) - Streaming version
Section 30: Autocorrelation
Serial dependence analysis:
• autocorrelation(data, maxLag) - ACF for all lags
• partialAutocorrelation(data, maxLag) - PACF via Durbin-Levinson
• Useful for time series model identification
Section 31: Ensemble Methods
Model combination:
• baggingPredict(models, X) - Average predictions
• votingClassify(models, X) - Majority vote
• Improves robustness through aggregation
Section 32: Model Evaluation Metrics
Performance assessment:
• mse(actual, predicted) / rmse / mae / mape - Regression metrics
• accuracy(actual, predicted) - Classification accuracy
• precision / recall / f1Score - Binary classification metrics
• confusionMatrix(actual, predicted, nClasses) - Multi-class evaluation
• rSquared(actual, predicted) / adjustedRSquared - Goodness of fit
Section 33: Cross-Validation
Model validation:
• trainTestSplit(X, y, trainRatio) - Random split
• Foundation for walk-forward validation
Section 34: Trading Convenience Functions
Trading-specific utilities:
• priceMatrix(length) - OHLC data as matrix
• logReturns(length) - Log return series
• rollingSlope(src, length) - Linear trend strength
• kalmanFilter(src, processNoise, measurementNoise) - Filtered price
• kalmanFilter2D(src, ...) - Price with velocity estimate
• adaptiveMA(src, sensitivity) - Kalman-based adaptive moving average
• volAdjMomentum(src, length) - Volatility-normalized momentum
• detectSRLevels(length, nLevels) - K-means based S/R detection
• buildFeatures(src, lengths) - Multi-timeframe feature construction
• technicalFeatures(length) - Standard indicator feature set (RSI, MACD, BB, ATR, etc.)
• lagFeatures(src, lags) - Time-lagged features
• sharpeRatio(returns) - Risk-adjusted return measure
• sortinoRatio(returns) - Downside risk-adjusted return
• maxDrawdown(equity) - Maximum peak-to-trough decline
• calmarRatio(returns, equity) - Return/drawdown ratio
• kellyCriterion(winRate, avgWin, avgLoss) - Optimal position sizing
• fractionalKelly(...) - Conservative Kelly sizing
• rollingBeta(assetReturns, benchmarkReturns) - Market exposure
• fractalDimension(data) - Market complexity measure
---
Usage Example
```
import YourUsername/MLMatrixLib/1 as ml
// Create feature matrix
matrix X = ml.priceMatrix(50)
X := ml.standardize(X)
// Fit linear regression
ml.LinearRegressionModel model = ml.fitLinearRegression(X, y)
float prediction = ml.predictLinear(model, X_new)
// Kalman filter for smoothing
float smoothedPrice = ml.kalmanFilter(close, 0.01, 1.0)
// Detect support/resistance levels
array levels = ml.detectSRLevels(100, 3)
// K-means clustering for regime detection
ml.KMeansModel km = ml.fitKMeans(features, 3)
int cluster = ml.predictCluster(km, newFeature)
```
---
Technical Notes
• All matrix operations use Pine Script's native matrix type
• Numerical stability ensured through:
- Clamping exponential arguments to prevent overflow
- Division by zero protection with epsilon thresholds
- Iterative algorithms with convergence tolerance
• Designed for bar-by-bar execution in Pine Script's event-driven model
• Compatible with Pine Script v6
---
Disclaimer
This library provides mathematical tools for quantitative analysis. It does not constitute financial advice. Past performance of any algorithm does not guarantee future results. Users are responsible for validating models on their specific use cases and understanding the limitations of each method.
JOBJABB - Risk Management Calculator1. Script Title (ชื่อสคริปต์)
JOBJABB - Risk Management Calculator
2. Description (รายละเอียดสคริปต์)
JOBJABB - Risk Management Calculator is a minimalist tool designed for traders who prioritize professional risk management. It calculates the optimal Lot Size based on your account balance and desired risk percentage, specifically optimized for Gold (XAUUSD) and Forex markets.
Key Features:
Automatic Lot Calculation: Instant position sizing for accurate risk control.
Gold & Forex Optimized: Built-in logic for different contract sizes (100 for Gold, 100k for Forex).
Multi-RR Targets: Automatically calculates TP prices for Risk-to-Reward ratios of 1:2, 1:3, and 1:5.
Minimalist Design: Clean black-and-white UI that won't clutter your chart.
Smart Alerts: Get notified when price hits Entry, SL, or TP levels.
JOBJABB - Risk Management Calculator คือเครื่องมือคำนวณขนาดไม้ (Lot Size) สไตล์ Minimalist ที่เน้นความเรียบง่ายแต่ทรงพลัง ออกแบบมาเพื่อช่วยให้เทรดเดอร์ควบคุมความเสี่ยงได้อย่างแม่นยำ โดยเฉพาะในตลาดทองคำ (XAUUSD) และ Forex
ฟีเจอร์หลัก:
คำนวณ Lot อัตโนมัติ: คำนวณจากเงินทุนและ % ความเสี่ยง ไม่ต้องกดเครื่องคิดเลขเอง
แม่นยำสำหรับทองคำ: รองรับค่า Contract Size ของทองคำ (100) และ Forex (100,000)
เป้าหมายกำไร (TP): แสดงราคาระดับ TP 1:2, 1:3 และ 1:5 ให้ทันที
ดีไซน์สะอาดตา: โทนขาว-ดำ อ่านง่าย ไม่รบกวนการวิเคราะห์กราฟ
ระบบแจ้งเตือน: แจ้งเตือนเมื่อราคาถึงจุด Entry, Stop Loss และ TP
3. How to Setup (วิธีการใช้งาน)
Risk Settings: Input your Account Balance and the % Risk you want to take per trade.
Trade Config: * Choose Direction (Buy or Sell).
Select Asset Type (Gold or Forex).
Set your Entry Price and Stop Loss Price.
Execution: Use the Recommended LOT shown in the table to open your position.
Alerts: Create an alert by selecting this script and choosing "Any alert() function call".
KJ Sessions : Asia/London/US + OverlapKJ Sessions : Asia/London/US + Overlap.
times are set as per dubai time.
Duggan Capital ValueScript with lines for previous Vwaps.
GOD VIEW $$$$$$$$$$ WE ARE SHAKING VOL WHEN YOU SLEEP
WatchmenThe Watchmen Indicator tracks potential market maker breakeven zones using dynamic open/close ranges (no wicks in Fib calc). It expands the range until the 50% level is breached by the full candle range, then resets. Green = long/down setups (buy retrace), Red = short/up setups (sell retrace). Uses only open/close for levels, high/low for breaches. Ideal for mean-reversion in trends.
XAUUSD Bullish Continuation StrategyThis strategy is designed for trading Gold (XAUUSD) on the M15 timeframe using a bullish continuation and breakout structure.
It identifies strong uptrend conditions using EMA trend confirmation and enters buy positions on either a breakout above resistance or a retest of the breakout zone. The strategy follows a disciplined risk-management model with a fixed stop loss and multiple take-profit targets for partial profit scaling.
Core Features:
• Trend confirmation using EMA 20 & EMA 50
• Breakout and retest buy entries
• Strong momentum continuation logic
• Fixed stop-loss protection
• Multi take-profit scaling (TP1, TP2, TP3)
• Backtest-ready TradingView strategy
Best Market Conditions:
Works best during strong bullish sessions (London & New York) when gold shows high volatility and directional momentum.
Recommended Timeframe:
M15 (can be optimized for M5–M30)
4MAs+5VWAPs+FVG+ Fractals4MAs + 5VWAPs + FVG + Fractals
All-in-one market structure indicator combining 4 moving averages, 5 VWAP timeframes, fair value gaps, fractals, and order blocks.
🔧 Features:
· 4 MAs - SMA/EMA, customizable lengths & colors
· 5 VWAPs - Daily, Weekly, Monthly, RTH, Custom sessions
· Fractals - Market structure with breakout lines & custom colors
· FVG/Imbalances - Bullish/bearish gap detection with alerts
· Order Blocks - Dynamic institutional levels
· Smart Labels - VWAP labels with color matching
⚙️ Quick Setup:
1. Toggle groups in Master Control Panel
2. Customize colors for each component
3. Set sessions for RTH/Custom VWAP
4. Adjust fractal periods (default: 2)
📈 Trading Use:
· Identify market structure with fractals
· Find confluence at VWAP + MA levels
· Trade FVG fills and order block reactions
· Multiple timeframe analysis with 5 VWAPs
Customizable • Color-Coordinated • Performance Optimized
EMA20-EMA50 Separation Impulse**EMA20–EMA50 Separation Impulse Indicator**
This indicator is a **trend phase classifier**, not a signal generator.
It evaluates the **structural quality of a trend** by measuring the separation between the EMA20 and EMA50, **normalized by ATR**. By using volatility-adjusted distance instead of raw price or percentage, it provides a robust and comparable measure across different instruments and timeframes.
### Key characteristics
* **Discrete states**, not a continuous oscillator
* **Independent from price scale** (displayed in a lower panel)
* **Contextual indicator**, not a timing tool
* **Fully backtestable without ambiguity**
### Logic
The indicator computes:
```
|EMA20 − EMA50| / ATR
```
Based on this normalized separation, each bar is classified into one of three market phases:
* **Green (State 1)**
Ordered trend. EMA structure is compact and stable.
The EMA-based pullback setup has a statistical edge.
* **Blue (State 2)**
Extended trend. Separation is increasing.
Edge is reduced. Trades require more selectivity or reduced position size.
* **Red (State 3)**
Overextended trend. EMAs are widely separated.
Pullbacks to EMA20 lose effectiveness. The setup has no edge.
### How to integrate it into an EMA-based system
This indicator should be used strictly as a **context filter**, not as an entry or exit trigger.
Typical integration rules:
* Allow long entries **only when State = 1 (Green)**
* Reduce position size or require stronger confirmation when State = 2 (Blue)
* Disable EMA pullback entries entirely when State = 3 (Red)
Used correctly, the indicator helps distinguish **when an EMA trend-following system is operating in its optimal environment**, and when market conditions degrade its expectancy.
It answers the question:
> *“Is this still a healthy trend for EMA pullback trading?”*
—not *“Should I buy or sell now?”*
Bar Count & EMABar Count & EMA Indicator
A clean and lightweight indicator designed for intraday price action traders.
Features:
1. Bar Count
Displays bar numbers only on 3-minute and 5-minute timeframes
Works during Regular Trading Hours (RTH) only
Shows bar 1 and multiples of 3 (3, 6, 9, 12, 15...)
Color-coded for key bars: Bar 18 & 48 (Red), Bar 6 (Light Green), Multiples of 12 (Sky Blue), Others (Gray)
2. EMA 20
Simple 20-period Exponential Moving Average
Customizable source, length, offset, and color
Why these specific timeframes?
5-Minute Chart (US Markets):
Bar 6, 12, 18, 24... represent 30-min, 1-hour, 1.5-hour intervals
Bar 18 and 48 often mark significant intraday turning points
Best for: ES, NQ, SPY, QQQ
3-Minute Chart (China A-Share Markets):
Bar 10, 20, 30... represent 30-min, 1-hour, 1.5-hour intervals
Designed for CSI 1000 Index Futures (IM) and other China futures
Helps track the 4-hour trading session rhythm (9:30-11:30, 13:00-15:00)
Why Bar Count Matters:
Tracking bar numbers helps traders identify market rhythm, timing cycles, and potential reversal zones throughout the trading session.
XAUUSD Mean Reversion Strategy Gold (ATR and RSI)The XAUUSD Mean Reversion Strategy – Gold v6 is a non-repainting TradingView strategy designed specifically for Gold (XAUUSD). It capitalizes on price overextensions and statistically probable pullbacks toward the mean, a behavior Gold frequently exhibits during active market sessions.
🔍 Strategy Logic
Uses EMA 50 as the mean price reference
Detects overextended conditions with RSI (14)
Trades are taken only when price deviates significantly from the mean
Designed for both long and short positions
📈 Entry Conditions
Long Trades
Price below EMA 50
RSI below oversold level
Short Trades
Price above EMA 50
RSI above overbought level
📉 Exit & Risk Management
ATR-based Stop Loss adapts to Gold’s volatility
Take Profit Options
Mean reversion back to EMA
Fixed ATR-based risk-to-reward
One trade at a time to control exposure
⚙️ Features
Fully backtestable
Non-repainting
Optimized for XAUUSD volatility
Adjustable inputs for optimization
Works best on 5m–30m timeframes
📊 Recommended Use
XAUUSD (Gold)
London & New York sessions
Intraday mean-reversion traders
⚠️ This strategy is for educational and research purposes only. Always perform your own testing and risk management before using it in live markets.
4 Period Momentum Composite IndicatorThe 4‑Period Momentum Indicator blends four lookback windows (1m, 3m, 6m, 12m) into a single zero‑centered momentum line. The value recalculates from whatever candle you anchor on, giving you full control when scrolling through historical price action. Positive readings reflect upward momentum, negative readings show weakness, and zero‑line crossovers highlight potential trend shifts. Designed for multi‑timeframe use and ETF relative‑strength comparison.
Look-back Value V1新增 MA10 與 MA120 的計算、繪圖、表格顯示。
新增 table_pos 參數,可選擇表格顯示位置(top_left, top_right, bottom_left, bottom_right)。
所有 table.cell 改用 具名參數 text_color,避免誤判成 width。
這樣你就能靈活選擇表格位置,並同時觀察 MA5、MA10、MA20、MA60、MA120、MA240 的扣抵分析。
John Trade AlertsImagine you are watching a ball bounce up and down on a graph.
This script is like a set of rules that says:
When to start playing
When to stop playing
When you got some prize levels
and it yells to you (alerts) when those things happen.
The main ideas
Breakout Buy (ball jumps high)
There is a line drawn high on the chart called the breakout level.
If the price (the ball) closes above that line, and some extra “good conditions” are true (enough volume, uptrend, etc.),
the script says: “We entered a Breakout trade now.”
Pullback Buy (ball dips into a box)
There is a zone (a small box) between a low line and a high line: the pullback zone.
If the price closes inside that zone, and the pullback looks “healthy” (not too much volume, still above a moving average, etc.),
the script says: “We entered a Pullback trade now.”
Stops (when to get out if it goes wrong)
For each entry type (Breakout or Pullback), there is a red stop line under the price.
If the price falls below that stop line, the script says:
“Stop hit, we’re out of the trade.”
Hard Support / Invalidation (big no‑no level)
There is a special hard support line.
The script also looks at the 1‑hour chart in the background.
If a 1‑hour candle closes below that hard support, it says:
“Hard invalidation – idea is broken, get out.”
Targets (prize levels)
Above the current price there are several orange lines: Target 1, 2, 3A, 3B, 4A, 4B.
If the price goes up and crosses one of these lines, the script says:
“Target X reached!”
Trend and Volume “health checks”
It checks if the short‑term average price (SMA20) is going up → “uptrend.”
It can check if price is above a long‑term average (SMA200).
For breakouts, it checks if volume is stronger than usual (good push).
For pullbacks, it prefers quieter than usual volume (calm dip).
It can also check an Anchored VWAP line (a special average price from a chosen starting time) and only trade if price is above that too.
Remembering if you are “in a trade”
The script keeps a little memory:
Are we currently in a position (inPos) or not?
Was it a Breakout or a Pullback entry?
What is our entry price and active stop?
When it gets a new entry signal, it turns inPos to true, picks the right stop, and draws that stop line.
When a stop or hard invalidation happens, it sets inPos to false again.
It can also “forget” and reset at the start of a new trading day if you want.
Alerts
When:
you get a Breakout entry
or a Pullback entry
or a Stop is hit
or the hard support is broken on 1‑hour
or a Target is reached
the script sends a message you can use in TradingView alerts (pop‑ups, email, webhook, etc.).
Things you see on the chart
Teal line: Breakout level
Green lines: Pullback zone low & high
Red line: Active stop (only when you’re “in” a trade)
Orange lines: Targets 1, 2, 3A, 3B, 4A, 4B
Blue line: Anchored VWAP (if you turn it on)
Purple faint line: SMA20 (short‑term trend)
Gray faint line: SMA200 (long‑term trend)
Little label near the last bar that says:
if you’re IN or Flat
which type of entry (Breakout/Pullback)
what your current stop is
So in kid words:
It draws important lines on the chart.
It watches the price move like a ball.
When the ball does something special (jump above, fall below, hit a prize line),
it shouts to you with alerts.
It remembers if you’re in the game or not, and where your safety line (stop) is.
Chart This in GoldProduces a historical line chart in the bottom pane to reflect how many units of spot gold (XAU) could be exchanged for one unite of the underlying asset.






















