Indicator · Pine Script v4 · On the chart

Test-035-Montecarlo

by ricardosantos79· code credited to RicardoSantos

This indicator overlays the price chart and prepares a fixed set of fifty lines for a Monte Carlo-style test.

View on GitHub

GitHub stars261on the repository
Pine versionv4older, still runs
Lines of code145
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

145 lines of Pine Script v4 from beta/arrays/test-035-montecarlo.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

test-035-montecarlo.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=4
study("test-035-montecarlo", overlay=true, max_bars_back=5000)
//t = ''

//| Line functions:
f_initline()=>line.new(time, 0., time, 0., xloc.bar_time, width=2)
f_line_updater(_id, _x1, _y1, _x2, _y2)=>
    line.set_xy1(id=_id, x=_x1, y=_y1)
    line.set_xy2(id=_id, x=_x2, y=_y2)
    line.set_color(id=_id, color=_y2 > _y1 ? color.teal : color.orange)

var line L00 = f_initline(), var line L10 = f_initline(), var line L20 = f_initline(), var line L30 = f_initline(), var line L40 = f_initline()
var line L01 = f_initline(), var line L11 = f_initline(), var line L21 = f_initline(), var line L31 = f_initline(), var line L41 = f_initline()
var line L02 = f_initline(), var line L12 = f_initline(), var line L22 = f_initline(), var line L32 = f_initline(), var line L42 = f_initline()
var line L03 = f_initline(), var line L13 = f_initline(), var line L23 = f_initline(), var line L33 = f_initline(), var line L43 = f_initline()
var line L04 = f_initline(), var line L14 = f_initline(), var line L24 = f_initline(), var line L34 = f_initline(), var line L44 = f_initline()
var line L05 = f_initline(), var line L15 = f_initline(), var line L25 = f_initline(), var line L35 = f_initline(), var line L45 = f_initline()
var line L06 = f_initline(), var line L16 = f_initline(), var line L26 = f_initline(), var line L36 = f_initline(), var line L46 = f_initline()
var line L07 = f_initline(), var line L17 = f_initline(), var line L27 = f_initline(), var line L37 = f_initline(), var line L47 = f_initline()
var line L08 = f_initline(), var line L18 = f_initline(), var line L28 = f_initline(), var line L38 = f_initline(), var line L48 = f_initline()
var line L09 = f_initline(), var line L19 = f_initline(), var line L29 = f_initline(), var line L39 = f_initline(), var line L49 = f_initline()
f_line_id(_i)=>(_i==00?L00:(_i==01?L01:(_i==02?L02:(_i==03?L03:(_i==04?L04:(_i==05?L05:(_i==06?L06:(_i==07?L07:(_i==08?L08:(_i==09?L09:
     (_i==10?L10:(_i==11?L11:(_i==12?L12:(_i==13?L13:(_i==14?L14:(_i==15?L15:(_i==16?L16:(_i==17?L17:(_i==18?L18:(_i==19?L19:
     (_i==20?L20:(_i==21?L21:(_i==22?L22:(_i==23?L23:(_i==24?L24:(_i==25?L25:(_i==26?L26:(_i==27?L27:(_i==28?L28:(_i==29?L29:
     (_i==30?L30:(_i==31?L31:(_i==32?L32:(_i==33?L33:(_i==34?L34:(_i==35?L35:(_i==36?L36:(_i==37?L37:(_i==38?L38:(_i==39?L39:
     (_i==40?L40:(_i==41?L41:(_i==42?L42:(_i==43?L43:(_i==44?L44:(_i==45?L45:(_i==46?L46:(_i==47?L47:(_i==48?L48:(_i==49?L49:na
     )))))))))) )))))))))) )))))))))) )))))))))) ))))))))))


//| -------------------------------------------------------------------------------|
var float[] seed = array.new_float(size=1, initial_value=42.0)                  //-|
f_prng(_range)=>                                                              //---|
//| pseudo random function:                                                 // O O |
    var float _return = 1.0                                                 //- V -|
    float _seed = array.get(id=seed, index=0)                                //NNNN|
    float _reseed =  271.828                                                  // A |
    _return := ((3.1416 * _return % _seed) * _reseed) % _range                // V |
    array.set(id=seed, index=0, value=(1 + (_seed * 1.618) % _range) + _return) //||
    _return                                                                    // ||
//| -------------------------------------------------------------------------------|


f_decision_tree(_node_weights, _depth)=>
    int[] _path = array.new_int(size=0, initial_value=0)
    int _nweights = array.size(id=_node_weights)
    int _sumweights = ceil(array.sum(id=_node_weights))
    if _nweights > 0 and _depth > 0 and _sumweights == 1
        for _d = 1 to _depth
            for _w = 0 to 999
                int _select_weight_index = int(f_prng(_nweights))
                float _rng = f_prng(1.0)
                float _weight = array.get(id=_node_weights, index=_select_weight_index)
                if _weight >= _rng
                    array.push(id=_path, value=_select_weight_index)
                    break
    _path

//|----------------------------------------------------------------------------||
//| find the price change distribution:
int data_size = input(500)

var float max_range = 0.0
var float min_range = 0.0

float range = change(close)
//float avg_range = cum(range) / (bar_index + 1)

if bar_index > 1
    max_range := max(range, max_range)
    min_range := min(range, min_range)
else
    max_range := range
    min_range := range

int rate = int((range - min_range) / (max_range - min_range) * 100)


// var float[] node_weights = array.new_float(size=0, initial_value=0)
// if barstate.isfirst
//     array.push(id=node_weights, value=0.25)
//     array.push(id=node_weights, value=0.4)
//     array.push(id=node_weights, value=0.35)

int depth = input(10)
int simulations = input(10)

var int[] paths = array.new_int(size=0, initial_value=0)


if barstate.ishistory[1] and barstate.islast and bar_index > data_size
    
    var float[] node_weights = array.new_float(size=0, initial_value=0.)

    var int[] distribution_counters = array.new_int(size=101, initial_value=1)

    for _i = 0 to data_size
        array.set(id=distribution_counters, index=rate[_i], value=array.get(id=distribution_counters, index=rate[_i]) + 1)

    int _total = array.sum(id=distribution_counters)
    
    for _i = 0 to array.size(id=distribution_counters)-1
        array.push(id=node_weights, value=array.get(id=distribution_counters, index=_i) / _total)
        
    //t := t + tostring(node_weights) + '\n'

    // run simulations:
    for _s = 0 to simulations-1
        _path = f_decision_tree(node_weights, depth)
        
        for _d = 0 to depth-1
            for _w = 0 to array.size(id=node_weights) - 1
                int _v = array.get(id=_path, index=_d)
                if _v == _w
                    array.push(id=paths, value=_w)

    // Find the best fit path:
    int[] _path_bestfit = array.new_int(size=0, initial_value=0)
    
    for _d = 0 to depth-1
        int[] _weight_counters = array.new_int(size=array.size(id=node_weights), initial_value=0)
        
        for _s = 0 to simulations-1
            int _i = array.get(id=paths, index=_d + _s * depth)
            int _new_count = array.get(id=_weight_counters, index=_i) + 1
            array.set(id=_weight_counters, index=_i, value=_new_count)
        
        int _best_fit_weight = array.indexof(id=_weight_counters, value=array.max(id=_weight_counters))
        array.push(id=_path_bestfit, value=_best_fit_weight)
        //t := t + tostring(_best_fit_weight) + ', '
    
    //draw the path
    int _time_shift = time-time[1]
    float _previous_price = close
    for _i = 0 to array.size(id=_path_bestfit)-1
        float _new_price = _previous_price + min_range + ((max_range - min_range) / 100) * array.get(id=_path_bestfit, index=_i)
        f_line_updater(f_line_id(_i), time + _time_shift * _i, _previous_price, time + _time_shift * (_i + 1), _new_price)
        //t := t + tostring(_new_price) + ' --- ' + tostring(_time_shift) + '\n'
        _previous_price := _new_price
        
// var label la = label.new(bar_index, 0.0, '')
// label.set_xy(id=la, x=bar_index, y=0.0)
// label.set_text(id=la, text=t)

Overview

A custom pseudo-random function updates a stored seed and returns values inside a chosen range. Inputs set the historical data size, the depth of each path, and how many simulations run. Line endpoints are updated in time and price, and each line is colored teal when the second point is higher than the first and orange otherwise. No trading signals, entries, exits, or risk rules appear in the visible code.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

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
data_sizeint500data_size
depthint10depth
simulationsint10simulations
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

948 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
575 stars

The indicator plots ICT displacement candles on the price chart and can switch to retracement scanning. Displacement requires a move larger than a set share of the 14-bar average high-low range, lasting at least a chosen number of bars, with optional close, pr

Indicator v6 SMC / ICT / price actionCandlestick patterns
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Displacement Candles Indicator
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

1833 Tracker

by Allen1212
303 stars

1833 Tracker is an overlay indicator that visualizes historical buy and sell transactions executed by ARK Invest ETFs for the stock on the main price chart. It displays trade dates using green buy and red sell labels positioned relative to price bars, indicati

Indicator v4
Updated 2 years ago · None stated GitHub repository of 1833 Tracker

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