Pine Library · 145 open-source scripts

Free AI and Machine Learning Pine Scripts (page 3)

Open-source Pine scripts that use machine learning ideas, such as nearest-neighbour classification, regression and adaptive filters, inside TradingView.

Pine scripts145
Code shown here72open licence
Updated in a year90
No repaint flag120

AI / machine learning: Indicators, Strategies and Libraries

FunctionNNLayer

by ricardosantos79
261 stars

FunctionNNLayer is a Pine Script v5 library providing a generalized neural network layer computation. It accepts an input array, a weight matrix flattened into an array, the target number of nodes, a bias value, and an activation function name. It computes per

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of FunctionNNLayer

An indicator that converts RSI, MACD histogram, Bollinger position, ATR, Stochastic, OBV change, ADX and VWAP deviation into z-scores, combines them with adjustable weights into one composite score, and smooths it with a Kalman filter. Buy and sell labels appe

Indicator v5 Oscillators & momentumAI / machine learning

FunctionNNPerceptron

by ricardosantos79
261 stars

This library exports a generalized perceptron node for neural networks. The function takes float arrays of inputs and weights, adds a bias, and applies a named activation function to the weighted sum. Bias defaults to 1.0 and the activation defaults to sigmoid

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of FunctionNNPerceptron
1 stars

This indicator draws the 5-minute closing price on the chart for multi-timeframe analysis. It takes the number of bars for prediction as an input and initializes an array of predictors with recent close prices. A matrix is prepared for heuristic logic but rema

Indicator v5 AI / machine learning
Updated yesterday · None stated GitHub repository of Omni-Resolution Matrix Machine

Adaptive Spectral Forecast

by vedkanani123
1 stars

A cycle-analysis indicator on the price chart. It analyzes a lookback window of 144 bars by default, extracts up to five dominant cycles, and projects a forecast line 55 bars ahead with confidence bands. Buy and sell signals can be limited to the direction of

Indicator v6 TrendAI / machine learning Repaints
Updated 2 months ago · None stated GitHub repository of Adaptive Spectral Forecast
261 stars

This script provides a function implementation of a Markov Chain Monte Carlo (MCMC) simulation. On the initial chart bar, it generates a probabilistic random walk path where each step has a configured probability of moving up, moving down, or staying unchanged

Indicator v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Markov Chain Monte Carlo Simulation (MCMC)

This indicator scans the chart for 101 distinct patterns, including single-bar, two-bar, and multi-bar candlestick patterns, classic chart patterns, and harmonic patterns. It features a complex situation context engine for confluence detection and displays a B

Indicator v5 Candlestick patternsSupport & resistance Repaints

Poi-Scalp v2

by majixai
1 stars

A strategy that scores market conditions with many weighted components: head and shoulders and double top or bottom pivots, a regression channel with an R-squared filter, polynomial slope, a cosh-based term, skew, divergence, volume flow, VWAP and an ADX plus

Strategy v5 ScalpingSupport & resistance
Updated yesterday · None stated GitHub repository of Poi-Scalp v2

Knn Filter A007

by ruckard
13 stars

Knn Filter A007 is a strategy that applies a K-Nearest Neighbors classification algorithm to evaluate historical feature performance and filter out low-probability trade setups. It executes long and short entries based on learned historical patterns. Risk mana

Strategy v5 AI / machine learningVolatility & bands
Updated 1 year ago · None stated GitHub repository of Knn Filter A007

Lastguru KNN A002

by ruckard
13 stars

This strategy applies k-nearest neighbors machine learning to fast and slow moving average crossovers to filter entry signals. It overlays directly on the price chart and incorporates built-in Zignaly alert triggers for automated execution. Traders can configu

Strategy v5 AI / machine learningMoving averages
Updated 1 year ago · None stated GitHub repository of Lastguru KNN A002

Atomic Tick Predictor — Statistical Next-Candle Engine estimates the likelihood of the next candle direction by combining a K-Nearest Neighbors algorithm with live tick updates. It tracks up and down ticks, tick volume, and price pressure within the active bar

Indicator v5 AI / machine learningVolume Repaints

Markov State Engine classifies market conditions into six distinct regimes, including strong trends, weak trends, compression, and expansion. It evaluates historical state transitions using an exit-conditional Markov model with Laplace smoothing to estimate re

Indicator v6 AI / machine learningTrend
Updated 2 days ago · MIT GitHub repository of Markov State Engine [WavesUnchained]

TN kNN Matrix ML

by raybird
1 stars

A machine learning strategy using k-nearest neighbours with a Lorentzian distance. Four normalised features, RSI, price rate of change, CCI and volume rate of change, are stored in a rolling matrix with a label for whether the next close was higher. Each bar i

Strategy v6 AI / machine learning
Updated 2 months ago · None stated GitHub repository of TN kNN Matrix ML
1 stars

This strategy stores a rolling matrix of RSI, ATR relative to price, and rate of change, together with each bar’s close direction. It averages outcomes from historical rows inside a fixed distance and treats that score as confidence. It enters long when confid

Strategy v6 AI / machine learningOscillators & momentum
Updated 2 months ago · None stated GitHub repository of TN Matrix kNN ML Sovereign

An overlay indicator that tracks pivot, session, previous-day and flipped support and resistance levels and records how price reacts when it tests them. Each trial resolves into break, fade, fail or expire, and a Bayesian-style model sorted into twelve context

Indicator v6 Support & resistanceSessions & time Repaints
Updated 7 days ago · GPL-3.0 GitHub repository of Trading Coach - Hybrid S/R Reaction Probability

This strategy combines a simplified Lorentzian distance-based machine learning prediction with a three-factor filter matrix to generate trade signals. It normalizes RSI, CCI, ADX, and momentum over rolling windows to evaluate feature distance, while scoring tr

Strategy v6 AI / machine learningTrend
Updated 2 months ago · None stated GitHub repository of TN ML Matrix Ensemble Sovereign v6
3 stars

Farid Makram Custom Levels is a multi-signal indicator for TradingView that combines RSI momentum analysis with MOBO oscillator signals based on the DPO. It generates buy and sell signals when RSI crosses its moving average or when DPO crosses zero, with confi

Indicator v5 Oscillators & momentumMoving averages
Updated 5 months ago · None stated GitHub repository of Farid Makram Custom Levels

MLActivationFunctions

by ricardosantos79
261 stars

MLActivationFunctions is a Pine Script v5 library that provides standard activation functions and their derivatives for neural network models built directly in Pine Script. It exports mathematical functions including binary step, linear, sigmoid, hyperbolic ta

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of MLActivationFunctions

MLLossFunctions

by ricardosantos79
261 stars

MLLossFunctions is a Pine Script v5 library that exports loss-function methods for machine learning calculations. It computes mean squared error as the average of squared differences between expected and predicted float arrays. It also computes binary cross-en

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of MLLossFunctions
114 stars

This strategy estimates price behavior using ordinary least squares regression between higher-timeframe data and a generated dataset, smoothed by a Karobein oscillator. It enters long positions when the oscillator turns upward and short positions when it turns

Strategy v4 Oscillators & momentumAI / machine learning Repaints
47 stars

Calculates and plots a forward price prediction directly on the main chart using an on-chart multilayer perceptron neural network. The model processes technical input features including moving average ratios, RSI, normalized ATR, and Bollinger bandwidth throug

Indicator v6 AI / machine learning
Updated 8 months ago · MIT GitHub repository of Multilayer Perceptron Predictor

This overlay classifies the chart into bull, bear, or neutral regimes from moving-average zone position and an adaptive engine driven by the efficiency ratio and ATR entry and exit bands. A volatility percentile rank adds quiet, normal, or volatile context, pl

Indicator v6 TrendMoving averages
Updated 2 days ago · MIT GitHub repository of Regime Detector (MA Zones Overlay) [WavesUnchained]

Function Markov Process

by ricardosantos79
261 stars

Function Markov Process is a Pine Script indicator function that models market state transitions using a three-by-three Markov chain transition matrix. It evaluates historical data categorized into bullish, bearish, or stagnant regimes (represented by values 1

Indicator v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Function Markov Process
1 stars

A separate-pane momentum indicator that combines fast and slow RSI, smoothed momentum, an ATR trend band and a memory of past similar setups to score each bar. A weighted confidence and rank are built from similarity, momentum agreement, trend alignment, volat

Indicator v6 Oscillators & momentumAI / machine learning
Updated 2 months ago · None stated GitHub repository of Neural Momentum Matrix AI Pro
114 stars

This strategy calculates normalized price or on-balance volume differentials across a user-defined timeframe and passes them through an activation function such as Swish, Step, or LeakyReLU. It opens long positions when the activated vector crosses above a pos

Strategy v4 Oscillators & momentumAI / machine learning Repaints
Updated 1 year ago · None stated GitHub repository of Scaled Normalized Vector Strategy

Function K-Means Clustering

by ricardosantos79
261 stars

This indicator implements a K-means clustering algorithm in Pine Script to partition two-dimensional data points into user-defined clusters. It features an internal pseudo-random number generator for centroid initialization and computes Euclidean distances acr

Indicator v4 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Function K-Means Clustering

Function: Decision Tree

by ricardosantos79
261 stars

Function: Decision Tree is a Pine Script v4 study that demonstrates a weighted decision-tree path sampler in a separate pane. A small pseudo-random generator reseeds itself from a stored float and picks node indices whose weights are at least the random draw.

Indicator v4 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Function: Decision Tree
1 stars

TN Sovereign Lorentzian v6 is a quantitative strategy that classifies price action regimes using multi-dimensional indicators and causal volume auditing. It generates entry signals based on RSI center-line crossovers, 10-period momentum, and price alignment re

Strategy v6 AI / machine learningTrend
Updated 2 months ago · None stated GitHub repository of TN Sovereign Lorentzian v6
114 stars

Volume Weighted Distance applies statistical and machine learning distance metrics between source prices and their rolling mean, weighted by volume, to identify local trend reversals. Users can select from Manhattan, Euclidean, Mahalanobis, Cosine Similarity,

Indicator v4 Oscillators & momentumVolume Repaints
Updated 1 year ago · None stated GitHub repository of Volume Weighted Distance

Live Tick Counter

by morindok
1 stars

This indicator calculates and plots a multi-factor order-flow analysis using tick counts, volume ratios, big player volume, recent delta momentum, and a K-nearest neighbors pattern matching algorithm. It evaluates bull and bear thresholds across multiple weigh

Indicator v5 VolumeScreeners & dashboards Repaints
Updated 7 weeks ago · None stated GitHub repository of Live Tick Counter

Test 025 K-Means

by ricardosantos79
261 stars

This script demonstrates an experimental implementation of the K-means clustering algorithm in Pine Script using array structures and a custom pseudo-random number generator. It partitions a dataset into a specified number of clusters based on Euclidean distan

Indicator v4 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Test 025 K-Means

This overlay indicator builds exponential harmonic price levels from a resonance factor that combines the golden ratio, pi and a fractal multiplier. On confirmed bars it maps the close to the nearest level, records upward and downward transitions in a Markov c

Indicator v5 Support & resistanceAI / machine learning
1 stars

A SuperTrend-style indicator on the price chart that can tune its ATR length and multiplier automatically from a profile of the instrument over a lookback window. It adds multi-timeframe confluence with selectable strictness and an optional machine-learning si

Indicator v6 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of StealthTrail SuperTrend ML Pro

Trailering P010

by ruckard
13 stars

A trading strategy that combines k-nearest neighbors (KNN) classification logic with custom position management and automated Zignaly signal execution. It evaluates historical price excursions and KNN patterns to identify entry opportunities and set dynamic ex

Strategy v5 AI / machine learning
Updated 1 year ago · None stated GitHub repository of Trailering P010

This indicator calculates a volatility-adaptive SuperTrend by applying k-means clustering to ATR values over a user-defined training period. It segments historical volatility into high, medium, and low clusters to dynamically adjust the SuperTrend bands to shi

Indicator v5 TrendVolatility & bands
Updated 8 months ago · None stated GitHub repository of Machine Learning Adaptive SuperTrend [AlgoAlpha]
1 stars

This indicator plots dynamic parallel lines based on logarithmic fractal price grid levels adjusted by a phi ratio multiplier. It scores price levels using a weighted quantitative model incorporating estimated order flow delta, kinetic volatility energy, liqui

Indicator v5 Support & resistanceSMC / ICT / price action
Updated 7 weeks ago · None stated GitHub repository of Parallel Lines Live V2
2 stars

This indicator calculates a custom RSI oscillator enhanced with machine learning using the K-nearest neighbors algorithm. It combines the standard RSI with KNN predictions for improved signal generation. The script applies smoothing using ALMA and Kalman filte

Indicator v5 AI / machine learningOscillators & momentum
Updated 8 months ago · None stated GitHub repository of Machine Learning RSI BullVision
2 stars

This indicator applies a k-Nearest Neighbors machine learning algorithm to calculate price predictions and direction on the main chart. It analyzes sequences of historical price data points to locate similar patterns and averages nearest neighbor matches. User

Indicator v5 AI / machine learningTrend Repaints
Updated 8 months ago · None stated GitHub repository of Machine Learning: kNN (New Approach)

TnSovereign NeuraRL

by raybird
1 stars

An experimental strategy that applies a small reinforcement learning agent, a dueling deep Q-network built with the NeuraLib library, to chart data. An eight-value state vector from price z-score, RSI, ATR ratio, EMA slope, volume, MACD and candle features fee

Strategy v6 AI / machine learning
Updated 2 months ago · None stated GitHub repository of TnSovereign NeuraRL

MC Bias Strategy Example

by regalouisei
2 stars

MC Bias Strategy Example is a Pine Script strategy designed to demonstrate automated trade execution driven by an external Markov Chain bias indicator. The script accepts a user-selected data source to determine directional bias and executes trades based on th

Strategy v5 AI / machine learningTrend
Updated 8 months ago · None stated GitHub repository of MC Bias Strategy Example
99 stars

This indicator applies the rectified linear unit to the difference between the selected source and a 20-period simple moving average. Positive deviations plot in green and negative deviations plot in red in a separate pane. The only input changes the price ser

Indicator v6 Moving averagesAI / machine learning
Updated 4 weeks ago · Apache-2.0 GitHub repository of Rectified Linear Unit (ReLU)

More Pine Script Categories

Browse the whole Pine Library

Third-party code. ForexR lists open-source Pine scripts from GitHub; it did not write, test or endorse them, and their summaries are generated automatically from each script's code and README. Indicators describe the past, and a strategy's backtest can look better than live trading. Check a script on a demo account before you rely on it. CFDs and leveraged forex are complex instruments with a high risk of losing money rapidly.

Learn to Use Pine Scripts

Free, plain-English guides: add a script to TradingView, read what it does, test it and avoid the common traps.

  1. 1Using this librarySearch, filters, licences and what the badges mean.
  2. 2Add a script to TradingViewCopy, paste into the Pine Editor, save and add to chart.
  3. 3Indicators, strategies and librariesWhat each type does and how to tell them apart.
  4. 4Spot a script that repaintsWhy some signals change after the bar closes.
  5. 5Backtest a strategyStrategy Tester settings that keep results honest.
  6. 6Send alerts to MT4 or MT5From a TradingView alert to an order in MetaTrader.
  7. 7What Pine Script isThe language, what it can and cannot do, and where to start.
  8. 8Write your first indicatorA complete script, line by line, in the Pine Editor.
  9. 9Read a script before you trust itA routine for checking inputs, logic and red flags.
  10. 10Edit a script safelyChange colours and lengths, add a filter or an alert.
  11. 11Pine Script alertsalertcondition(), alert(), placeholders and webhooks.
  12. 12Build a crossover strategyAn EMA cross strategy with an ATR stop, ready to test.

Trade Your Charts With a Regulated Broker

Compare regulated brokers on platforms, spreads, minimum deposit and leverage.

Compare brokers