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.
Indicators and strategies
HazMeed Session Highs/Lows)Marks out Asia Session Highs and Lows
Marks out London Session Highs and Lows
Marks out NYAM Session Highs and Lows
NVentures Liquidity Radar ProInstitutional Liquidity Radar Pro
OVERVIEW
This indicator combines three institutional trading concepts into a unified confluence scoring system: Liquidity Zones (swing-based), Order Blocks, and Fair Value Gaps. The unique value lies not in these individual concepts, but in HOW they interact through the confluence scoring algorithm to filter high-probability zones.
HOW THE CONFLUENCE SCORING WORKS
The core innovation is the calcConfluence() function that assigns a numerical score to each detected level:
1. Base Score: Every swing pivot starts with score = 1
2. Zone Overlap Detection: The algorithm iterates through all active zones within confDist * ATR proximity. Each overlapping zone adds +1 to the score
3. Order Block Proximity: If an Order Block's midpoint (top + bottom) / 2 falls within the confluence distance, +1 is added
4. HTF Validation: Using request.security(), the indicator fetches higher timeframe swing pivots. If the current zone aligns with an HTF swing within 2 * confDist * ATR_htf, a +2 bonus is awarded
Zones scoring 4+ are highlighted as high confluence - these represent areas where multiple institutional concepts converge.
HOW LIQUIDITY ZONES ARE CALCULATED
Detection: ta.pivothigh() and ta.pivotlow() with configurable lookback (default: 5 bars left/right)
Zone Width - Three modes available:
- ATR Dynamic: ATR(14) * multiplier (default 0.25)
- Fixed %: close * (percentage / 100)
- Wick Based: max(upperWick, lowerWick) * 1.5
Proximity Filter: isTooClose() prevents clustering by enforcing minimum ATR * minATRdist between zones
HOW ORDER BLOCKS ARE DETECTED
The detectBullishOB() / detectBearishOB() functions identify the last opposing candle before an impulse move:
1. Check if candle is opposing direction (bearish before bullish impulse, vice versa)
2. Validate consecutive candles in impulse direction (configurable, default: 3)
3. Volume confirmation: volume >= volMA * volMult (using 50-period SMA)
4. Minimum move validation: abs(close - close ) > ATR
This filters out weak OBs and focuses on those with institutional volume footprints.
HOW FAIR VALUE GAPS ARE DETECTED
FVGs represent price imbalances:
- Bullish FVG: low - high > ATR * fvgMinSize
- Bearish FVG: low - high > ATR * fvgMinSize
The ATR-relative sizing ensures gaps are significant relative to current volatility.
HOW SWEEP DETECTION WORKS
The checkSweep() function identifies false breakouts through wick analysis:
1. Calculate wick percentage: upperWick / totalRange or lowerWick / totalRange
2. Sweep conditions for resistance: high > zone.upper AND close < zone.price AND wickPct >= threshold
3. Sweep conditions for support: low < zone.lower AND close > zone.price AND wickPct >= threshold
A sweep indicates liquidity was grabbed without genuine continuation - often preceding reversals.
HOW FRESHNESS DECAY WORKS
The calcFreshness() function implements linear decay:
freshness = 1.0 - (age / decayBars)
freshness = max(freshness, minFresh)
This ensures old, tested zones fade visually while fresh zones remain prominent.
WHY THESE COMPONENTS WORK TOGETHER
The synergy is based on the principle that institutional activity leaves multiple footprints:
- Swing Pivots = where retail stops cluster
- Order Blocks = where institutions entered
- FVGs = where aggressive institutional orders created imbalances
- HTF Alignment = where higher timeframe participants are active
When these footprints converge at the same price level (high confluence score), the probability of significant price reaction increases.
CONFIGURATION
- Swing Detection Length: 5-8 for intraday, 8-15 for swing trading
- HTF Timeframe: One level above trading TF (e.g., D for H4)
- Min Confluence to Display: 2 for comprehensive view, 3-4 for high-probability only
- FVGs: Disabled by default for cleaner charts
STATISTICS PANEL
Displays: Active resistance/support zones, high confluence count, swept zones, active OBs, active FVGs, current ATR, selected HTF.
ALERTS
- Price approaching high confluence zone
- Liquidity sweep detected
- Bullish/Bearish Order Block formed
- Bullish/Bearish FVG detected
TECHNICAL NOTES
- Uses User-Defined Types (UDTs) for clean data structure management
- Respects Pine Script drawing limits (500 boxes/labels/lines)
- All calculations are ATR-normalized for cross-market compatibility
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".
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?”*
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
Levels BY Lukelevel two continuation
level 3 reversal zone---
work in combination with your system
luke
check out my youtube page ADHD Traders channel
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.
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 的扣抵分析。
Ichimoku Multi-BG System by Pranojit Dey (Exact Alignment)It shows trend of different levels with the help of Ichimoku, VWAP, SMA and Pivot. Use it as a strong confluence for any entry. Lets trade guys...
Value Area PRO (TPO/Volume Session VAH/VAL/POC) 📌 AP Capital Value Area PRO (TPO / Volume)
AP Capital Value Area PRO is a session-based value area indicator designed for Gold (XAUUSD), NASDAQ (NAS100), and other CFD instruments.
It focuses on where the market has accepted price during the current session and highlights high-probability interaction zones used by professional traders.
Unlike rolling lookback volume profiles, this indicator builds a true session value area and provides actionable signals around VAH, VAL, and POC.
🔹 Core Features
Session-Anchored Value Area
Value Area is built only during the selected session
Resets cleanly at session start
Levels develop during the session and can be extended forward
No repainting or shifting due to lookback changes
TPO or Volume Mode
TPO (Time-at-Price) mode – ideal for CFDs and tick-volume data
Volume mode – uses broker volume if preferred
Same logic, different weighting method
Fixed Price Bin Size
Uses a fixed bin size (e.g. 0.10 for Gold, 0.25–0.50 for NAS100)
Produces cleaner, more realistic VAH/VAL levels
Avoids distorted profiles caused by dynamic bin scaling
VAH / VAL / POC Levels
VAH (Value Area High)
VAL (Value Area Low)
POC (Point of Control) (optional)
Lines can be extended to act as forward reference levels
🔹 Trading Signals & Alerts
Value Re-Entry
Identifies false breakouts where price:
Trades outside value
Then closes back inside
Often seen before strong mean-reversion or continuation moves.
Acceptance
Detects initiative activity using:
Multiple consecutive closes outside value
Filters out weak single-candle breaks
Rejection
Flags strong rejection candles:
Large candle body
Wick outside value
Close back inside the value area
These conditions are especially effective on Gold intraday.
🔹 Optional Profile Histogram
Right-side volume/TPO histogram
Buy/sell imbalance visualization
Fully optional to reduce chart clutter and improve performance
🔹 Best Use Cases
Recommended markets
XAUUSD (Gold)
NAS100 / US100
Other index or metal CFDs
Recommended timeframes
5m, 15m, 30m
Suggested settings
Mode: TPO
Value Area: 70%
Bin size:
Gold: 0.10
NAS100: 0.25 or 0.50
🔹 How Traders Use It
Trade rejections at VAH / VAL
Look for acceptance to confirm trend days
Use re-entries to fade failed breakouts
Combine with trend filters, EMA structure, or session context
⚠️ Disclaimer
This indicator is provided for educational and analytical purposes only and does not constitute financial advice. Always manage risk appropriately.
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.
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.
Momentum Scanner: Low Float + Volume Spike + 3 Green CandlesScanner for low-float stocks with volume spikes and 3 consecutive bullish candles
Thick Wick OverlayI have a hard time seeing the wick and made a simple overlay indicator to create a "thicker wick". You can change the thickness and wick color to your desired color and thickness.
MyNigmaPOICoreLibrary "MyNigmaPOICore"
fun(x)
TODO: add function description here
Parameters:
x (float) : TODO: add parameter x description here
Returns: TODO: add what function returns
get_safe_atr(atr_val, atr_14)
Parameters:
atr_val (float)
atr_14 (float)
is_deep_value(is_buy, hh, ll, c, val_buy, val_sell)
Parameters:
is_buy (bool)
hh (float)
ll (float)
c (float)
val_buy (float)
val_sell (float)
draw_capsule(x1, x2, start_price, end_price, col, r_outer, r_mid, tr_transp, mid_transp, c_mid_glass)
Parameters:
x1 (int)
x2 (int)
start_price (float)
end_price (float)
col (color)
r_outer (int)
r_mid (int)
tr_transp (int)
mid_transp (int)
c_mid_glass (color)
method create_trade(is_long, price, zone_limit, safe_atr, sl_atr_mult, target_rr, c_tp_glass, c_sl_glass, c_mid_glass, r_outer, r_mid, tr_transp, mid_transp)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
is_long (bool)
price (float)
zone_limit (float)
safe_atr (float)
sl_atr_mult (float)
target_rr (float)
c_tp_glass (color)
c_sl_glass (color)
c_mid_glass (color)
r_outer (int)
r_mid (int)
tr_transp (int)
mid_transp (int)
method create_pending_order(is_bull, fvg_top, fvg_btm, zone_limit)
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
is_bull (bool)
fvg_top (float)
fvg_btm (float)
zone_limit (float)
detect_pivots(len_pivot)
Parameters:
len_pivot (int)
create_pivot_line(pivot_idx, pivot_price, is_high)
Parameters:
pivot_idx (int)
pivot_price (float)
is_high (bool)
method update_pivot_point(pp, h, l, c)
Namespace types: PivotPoint
Parameters:
pp (PivotPoint)
h (float)
l (float)
c (float)
detect_fvg(mode_scalp, safe_atr, fvg_atr_mult_scalp, fvg_atr_mult_normal)
Parameters:
mode_scalp (bool)
safe_atr (float)
fvg_atr_mult_scalp (float)
fvg_atr_mult_normal (float)
create_fvg(is_bull, top, btm, line_col, fvg_line_width, active_extend)
Parameters:
is_bull (bool)
top (float)
btm (float)
line_col (color)
fvg_line_width (int)
active_extend (int)
create_ifvg(is_bull, top, btm, active_extend)
Parameters:
is_bull (bool)
top (float)
btm (float)
active_extend (int)
method update_fvg(f, active_extend, closed_extend, base_col, is_bright)
Namespace types: FVG
Parameters:
f (FVG)
active_extend (int)
closed_extend (int)
base_col (color)
is_bright (bool)
method update_ifvg(f, active_extend)
Namespace types: iFVG
Parameters:
f (iFVG)
active_extend (int)
calculate_ob_strengths(bar_idx, swing_length)
Parameters:
bar_idx (int)
swing_length (int)
create_order_block(top, btm, bar_start, bull_str, bear_str, is_bull)
Parameters:
top (float)
btm (float)
bar_start (int)
bull_str (float)
bear_str (float)
is_bull (bool)
method update_order_block(ob)
Namespace types: OrderBlock
Parameters:
ob (OrderBlock)
method delete_order_block(ob)
Namespace types: OrderBlock
Parameters:
ob (OrderBlock)
detect_pullback(pullback_pct)
Parameters:
pullback_pct (float)
create_cisd(price, is_bull, future_bars, bull_color, bear_color, bull_label, bear_label, line_width, line_style)
Parameters:
price (float)
is_bull (bool)
future_bars (int)
bull_color (color)
bear_color (color)
bull_label (string)
bear_label (string)
line_width (int)
line_style (string)
method update_cisd(c, future_bars)
Namespace types: CISD
Parameters:
c (CISD)
future_bars (int)
method delete_cisd(c)
Namespace types: CISD
Parameters:
c (CISD)
process_breakers(lines, is_high_breaker, len_pivot, active_extend, mitigated_style, mitigated_transp, mitigated_color, delete_after_mit, mit_delete_bars)
Parameters:
lines (array)
is_high_breaker (bool)
len_pivot (int)
active_extend (int)
mitigated_style (string)
mitigated_transp (int)
mitigated_color (color)
delete_after_mit (bool)
mit_delete_bars (int)
Trade
Fields:
is_long (series bool)
entry (series float)
sl (series float)
tp (series float)
tp_bg (series box)
tp_mid_fill (series box)
tp_out_fill (series box)
sl_bg (series box)
sl_mid_fill (series box)
sl_out_fill (series box)
start_idx (series int)
result (series int)
l_tp (series line)
l_sl (series line)
icon (series label)
lbl_entry (series label)
lbl_tp (series label)
lbl_sl (series label)
FVG
Fields:
top_line (series line)
btm_line (series line)
top (series float)
btm (series float)
is_bull (series bool)
is_uni (series bool)
mitigated (series bool)
trade_ref (Trade)
creation_bar (series int)
trade_closed (series bool)
iFVG
Fields:
zone_box (series box)
zone_label (series label)
top (series float)
btm (series float)
is_bull (series bool)
mitigated (series bool)
creation_bar (series int)
PendingOrder
Fields:
is_bull (series bool)
fvg_top (series float)
fvg_btm (series float)
entry_price (series float)
zone_limit (series float)
signal_bar (series int)
filled (series bool)
expired (series bool)
BreakerLine
Fields:
id (series line)
price (series float)
creation_bar (series int)
breach_bar (series int)
mitigated (series bool)
wick_touched (series bool)
stopped (series bool)
PivotPoint
Fields:
id (series line)
price (series float)
pivot_bar (series int)
is_high (series bool)
broken (series bool)
wick_touched (series bool)
OrderBlock
Fields:
ob_box (series box)
bullish_box (series box)
bearish_box (series box)
separator_line (series line)
text_separator (series line)
top (series float)
btm (series float)
bar_start (series int)
bullish_strength (series float)
bearish_strength (series float)
is_bull (series bool)
broken (series bool)
CISD
Fields:
level (series line)
txt (series label)
completed (series bool)
start_bar (series int)
price (series float)
is_bull (series bool)
15m MR v2.4-HF FINAL v2 (Looser Kill + Better RR) - Long Only Summary
In short, this is a long-only, ATR-normalized mean reversion strategy that:
buys only after a deep oversold deviation and reversal evidence,
avoids extreme selloff regimes using a Kill Zone,
controls downside via structure + risk-cap stops,
and improves reward via partial profits + FV-based targets + optional trailing.
If you want, I can also write a one-paragraph “super simple” English version (for non-traders) or a presentation-style bullet slide version.
able bigtrades dom + liquidity sweep This Pine Script is a sophisticated **Order Flow and Liquidity analysis tool** designed for TradingView. It combines volume analysis, multi-exchange data, and price action to identify where institutional "whales" are entering the market.
Below is a detailed guide on how to interpret and use the **BigTrades DOM** indicator.
---
## 1. Core Concept: Big Trades Detection
Instead of looking at raw volume, this indicator uses **Z-Scores** (Standard Deviations). It compares current volume to the average of the last 30 bars (customizable).
* **Tier 1 (Small Circles):** Significant volume, slightly above average.
* **Tier 2 (Medium Circles):** High volume ( by default). These often act as local support/resistance.
* **Tier 3 (Large Circles):** Extreme volume. These represent institutional "Big Trades" that usually lead to trend reversals or major continuations.
---
## 2. Initiative (INIT) vs. Absorbed (ABS)
This is a powerful feature located in the **Confirmation** settings. It looks at what happens *after* a Tier 3 big trade occurs:
* **Initiative (Purple Circle `●`):** High volume occurs, and price **moves strongly** in that direction within bars. This confirms aggressive "Initiative" buying or selling.
* **Absorbed (Yellow Cross `✕`):** High volume occurs, but price **fails to move**. This indicates "Absorption"—where a large limit order (passive seller) is soaking up all the aggressive market buys, often leading to a reversal.
---
## 3. Liquidity Sweep Detection
The script tracks "Pivots" (old highs and lows) and watches for **Stop Runs**.
* **Bullish Sweep (LTL-SWEEP):** Price dips below a previous Low (Liquidity) but immediately closes back above it, usually accompanied by a Big Trade. This is a classic "Stop Hunt" before a move up.
* **Bearish Sweep (LTH-SWEEP):** Price spikes above a previous High but closes below it. This indicates "trapped longs" and potential downside.
* **Visuals:** The script draws a **Dotted Box** and a **Horizontal Line** to mark the swept liquidity zone.
---
## 4. The Mini DOM & Volume Profile
On the right side of your chart, you will see a real-time table:
* **Profile:** A visual histogram of volume distributed at specific price levels.
* **Bid/Ask:** Shows the estimated volume of sellers (Bid) and buyers (Ask) at those specific levels.
* **Delta (Δ):** The net difference. Green means more aggressive buyers; Red means more aggressive sellers.
* **Current Price:** Highlighted in Green to help you see where the "Value" is currently sitting.
---
## 5. Multi-Exchange Aggregation (Crypto Only)
If you are trading a crypto pair (e.g., BTCUSD), the script can fetch volume data from **Binance, Bybit, OKX, Coinbase, and Kraken** simultaneously.
> **Why it matters:** It gives you a "Global" view of volume. If you see a Big Trade on your chart, but the Multi-Exchange data shows high volume across all 5 exchanges, the signal is much more reliable.
---
## 6. How to Trade with this Indicator
### **Strategy A: The Liquidity Reversal**
1. Look for a **Liquidity Sweep** (LTL-SWEEP).
2. Wait for a **Big Trade (Tier 2 or 3)** to appear at the bottom of the sweep.
3. **Entry:** Long when the bar closes back above the sweep level.
4. **Target:** The opposite Liquidity High.
### **Strategy B: Following Initiative**
1. Wait for an **INIT (Purple Circle)** signal.
2. This confirms that the "Big Trade" has successfully pushed the market.
3. **Entry:** Enter in the direction of the INIT signal on the next pullback.
### **Strategy C: Fading Absorption**
1. Price reaches a resistance level.
2. An **ABS (Yellow Cross)** appears.
3. This means buyers are exhausted and being "absorbed" by a large seller.
4. **Entry:** Short on the break of the Absorption candle's low.
---
## 7. Recommended Settings
* **Sensitivity (Sigma):** Set to `2.5` for volatile markets (Crypto) or `2.0` for slower markets (Forex/Stocks).
* **Normalize by ATR:** Keep this **ON**. it ensures that "Big Trades" are calculated relative to current market volatility.
* **Require Big Trade (Sweep):** Keep this **ON** to filter out "fake" sweeps that don't have institutional backing.
Nerot YapanimCandle Patterns Pro: Momentum & Multilingual
Overview
Candle Patterns Pro is an advanced, high-conviction candlestick pattern detector built for Pine Script v5. Unlike standard indicators that trigger on every technical occurrence, this script utilizes Momentum-Verified Logic to filter out market noise and "indecisive" price action.
Designed for clarity and precision, it features a unique Multilingual Toggle, allowing users to switch between professional English and Hebrew terminology instantly.
Key Features
1. Momentum-Verified Logic (Anti-Doji Filter)
Most pattern detectors fail by triggering on small-bodied "Doji" candles that lack direction. This indicator uses a custom isStrong algorithm: a signal only triggers if the real body of the candle represents at least 50% of the total candle range. This ensures you only see patterns where bulls or bears have shown true dominance.
2. "Real Body" Engulfing
To prioritize high-probability reversals, the Engulfing logic is calculated using Real Bodies (Open to Close) rather than wicks. By ignoring the "noise" of the thicks/wicks, the signals identify much stronger shifts in institutional pressure.
Shutterstock
3. Integrated Trend Filter (Moving Average)
Align your trades with the primary trend. When the MA Filter is enabled, bullish signals are only displayed if the price is above the Moving Average, while bearish signals appear only when the price is below it.
4. Professional Multilingual Support
This indicator is built for a global audience. Through the settings menu, users can toggle between English and Professional Hebrew labels.
English: Engulfing, 3 Soldiers, 3 Crows, Dark Cloud, etc.
Hebrew: בולען, שלושה חיילים, שלושה עורבים, ענן כהה, etc.
Supported Patterns
Engulfing (Body-Only): Clean reversal signals optimized for momentum.
Three Soldiers & Three Crows: Momentum-verified (Filtered for strength).
Morning & Evening Star: Three-candle structural reversals.
Meeting Line: Precise alignment strike patterns.
Piercing Line & Dark Cloud: Deep-penetration momentum shifts.
Harami: Traditional inside-bar setups.
User Instructions
Selection: Toggle specific patterns on or off in the inputs tab.
Clean UI: The indicator is pre-configured to keep your Status Line clean by hiding values and inputs by default.
Y-Axis Fix: If labels appear "static" or do not move with price, right-click your Price Scale and select "Merge All Scales into One (Right)".
Language: Switch between English and Hebrew via the "Language / שפה" dropdown in settings.
Technical Specifications
Version: Pine Script v5
Execution: Real-time calculation on bar close.
Alerts: Fully compatible with TradingView alerts (Push, Email, Webhook).
Scalping EMA + Fixed Range Volume Profile (Stable)//@version=5
indicator("Scalping EMA + Fixed Range Volume Profile (Stable)", overlay=true)
// =========================
// EMA SETTINGS
// =========================
ema9 = ta.ema(close, 9)
ema15 = ta.ema(close, 15)
ema21 = ta.ema(close, 21)
plot(ema9, "EMA 9", color=color.yellow, linewidth=2)
plot(ema15, "EMA 15", color=color.orange, linewidth=2)
plot(ema21, "EMA 21", color=color.red, linewidth=2)
// =========================
// FIXED RANGE SETTINGS
// =========================
rangeBars = input.int(100, "Fixed Range Bars", minval=20, maxval=500)
rangeHigh = ta.highest(high, rangeBars)
rangeLow = ta.lowest(low, rangeBars)
// =========================
// SAFETY CHECK
// =========================
bins = 24
rangeSize = rangeHigh - rangeLow
validRange = rangeSize > 0
step = validRange ? rangeSize / bins : na
// =========================
// VOLUME PROFILE
// =========================
var float volBins = array.new_float(bins, 0.0)
// Reset bins
if validRange
for i = 0 to bins - 1
array.set(volBins, i, 0)
// Fill bins
if validRange
for i = 0 to rangeBars - 1
price = hlc3
idx = int((price - rangeLow) / step)
if idx < 0
idx := 0
if idx > bins - 1
idx := bins - 1
array.set(volBins, idx, array.get(volBins, idx) + volume )
// =========================
// POC
// =========================
pocIndex = validRange ? array.indexof(volBins, array.max(volBins)) : na
pocPrice = validRange ? rangeLow + (pocIndex + 0.5) * step : na
// =========================
// VALUE AREA (70%)
// =========================
float vah = na
float val = na
if validRange
totalVol = array.sum(volBins)
targetVol = totalVol * 0.7
float cumVol = array.get(volBins, pocIndex)
int lowVA = pocIndex
int highVA = pocIndex
while cumVol < targetVol and (lowVA > 0 or highVA < bins - 1)
leftVol = lowVA > 0 ? array.get(volBins, lowVA - 1) : 0
rightVol = highVA < bins - 1 ? array.get(volBins, highVA + 1) : 0
if rightVol > leftVol and highVA < bins - 1
highVA += 1
cumVol += rightVol
else if lowVA > 0
lowVA -= 1
cumVol += leftVol
vah := rangeLow + (highVA + 1) * step
val := rangeLow + lowVA * step
// =========================
// PLOTS
// =========================
plot(pocPrice, "POC", color=color.blue, linewidth=2)
plot(vah, "VAH", color=color.green, linewidth=1)
plot(val, "VAL", color=color.green, linewidth=1)
SMA 14/28 CrossBy analyzing the XAUUSD chart on the 2H timeframe, we can observe that after a strong bullish market structure, Gold continued to trade higher and successfully expanded toward the 4,850 – 4,890 region, which is marked as a key liquidity and resistance zone on the chart.
Following this impulsive upside move, price is now showing short-term exhaustion, with multiple rejections forming just below the recent highs. The market is currently trading around 4,825, where we can see repeated attempts to break higher, increased volatility, and signs that buy-side liquidity above the highs has been partially taken.
This price behavior has created a short-term liquidity imbalance, and based on the current structure, a pullback is expected before any further bullish continuation. As highlighted on the chart, price may retrace toward the 4,760 – 4,600 support zone, which aligns with previous consolidation, internal structure, and resting liquidity below current price.





















