Indicator · Pine Script v5 · Own pane

Markov Chain Monte Carlo Simulation (MCMC)

by ricardosantos79· code credited to RicardoSantos

This script provides a function implementation of a Markov Chain Monte Carlo (MCMC) simulation.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code57
Settings3inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

57 lines of Pine Script v5 from beta/libs/v4_to_v5_conversions/Function - simple* Markov Chain Monte Carlo Simulation (MCMC).pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Function - simple* Markov Chain Monte Carlo Simulation (MCMC).pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=5
indicator(title='Function - simple* Markov Chain Monte Carlo Simulation (MCMC)')

f_markov_chain(_T, _position, _base, _dev) =>  //{
//  @function: a basic implementation of the markov chain algorithm
//  @parameters:
//      _T: float[], target path array.
//      _base: base value to increment.
//      _dev: expected deviation.
//  @returns: void, updates target array
    float _distance = math.random() * _dev
    float _p = math.random()  // hit value
    if _p < 0.3  // 30% chance of up movement
        array.set(_T, _position, _base + _distance)
    else if _p < 0.6
        // 30% chance of down movement
        array.set(_T, _position, _base - _distance)
    else
        // 40% of remaining at value
        array.set(_T, _position, _base)
//}

f_mcmc(_n_iterations, _start_value, _deviation_ammount) =>  //{
//  @function: uses a monte carlo algorithm to simulate a markov chain at each step.
//  @parameters:
//      _n_iterations: integer, number of iterations to run.
//      _start_value: float, base value to start simulation.
//      _deviation_ammount: float maximum deviation allowed.
//  @references:
//      https://stephens999.github.io/fiveMinuteStats/MH-examples1.html
//      https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html
//  @returns: float[], array with path.
    float[] _T = array.new_float(_n_iterations, 0.0)
    array.set(_T, 0, _start_value)
    for _i = 1 to _n_iterations - 1 by 1
        float _current = array.get(_T, _i - 1)
        f_markov_chain(_T, _i, _current, _deviation_ammount)
    _T
//}

i_iterations = input(100)
i_start = input(500.)
i_deviation = input(25.)

var float[] M = array.new_float(0)
if barstate.isfirst
    M := f_mcmc(i_iterations, i_start, i_deviation)
    M

float output = na
if bar_index < i_iterations
    output := array.get(M, bar_index)
    output
plot(output)

Overview

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 by a random deviation. The script plots the resulting simulated values across bars up to the designated iteration count in a separate pane.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

AI / machine learning

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
i_iterationsint100i_iterations
i_startinput500.i_start
i_deviationinput25.i_deviation
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This indicator combines a dynamic Seasonal Random Index (SRI) with a dynamic Karobein Oscillator and a pattern-similarity search algorithm in a separate pane. It normalizes SRI into seasoned and deseasoned series, shading the area green or red to signal trend

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of Similarity Search, Karobein and Seasonal Random Index

This indicator plots an oscillator in a separate pane. It builds several SuperTrend series across a user-defined factor range and step, using ATR as the band width. On each bar it measures the distance between the close and each SuperTrend output, then groups

Indicator v5 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of AI SuperTrend Clustering Oscillator [LuxAlgo]
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)
7 stars

Lorentzian Classification is a machine learning indicator that applies a k-nearest neighbors algorithm using Lorentzian distance to analyze market patterns. It processes configurable technical indicators, including RSI, WaveTrend, CCI, and ADX, as feature vect

Indicator v6 AI / machine learningOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of Lorentzian Classification
257 stars

This indicator uses a Lorentzian distance k-nearest neighbors classification algorithm to predict market direction based on up to five technical features, such as RSI, WaveTrend, CCI, and ADX. It compares current feature values against historical bar patterns

Indicator v5 AI / machine learningOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of Donald - Machine Learning Options

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers