Strategy · Pine Script v6 · On the chart

PF UDT probe 18 - method calls method

by pineforge-4pass· code credited to PineForge contributors 2026

This Pine Script v6 strategy is a validation probe for nested method calls on a user-defined type.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code98
Settings0inputs
LicenceApache-2.0
Last update7 days ago23 Oct 2026

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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

98 lines of Pine Script v6 from validation/udt-method-calls-sibling-cumulative-01/strategy.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

strategy.pine
// This Pine Script® code is licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// © PineForge contributors 2026
//
// UDT method probe 18 (stretch) — method body calls another method
// on the same UDT
//
// Purpose: a UDT method can invoke a sibling method on ``self`` —
// e.g. ``method refresh(Box self) => self.update(close); self.normalize()``.
// The C++ runtime must resolve the inner ``self.update`` and
// ``self.normalize`` to the right ``_udt_Box_update(self, ...)``
// free-function calls and pass ``self`` (the reference) through.
// Stretch probe: this is a deeper nesting than the basic dispatch
// tests in test_udt_methods.py — the chain here is
//   refreshAndScore -> feed
//   refreshAndScore -> zscore -> mean
//   refreshAndScore -> zscore -> variance -> mean
// so ``self`` has to thread through three live frames.
//
// Design note (rev 2): the previous revision used a CUMULATIVE Stat
// (``self.sum`` / ``self.sumsq`` / ``self.n`` accumulating from bar 0).
// That made the trade list sensitive to chart history — TV's chart
// reaches further back than our reference OHLCV CSV's warmup region,
// so the cumulative variance — and therefore the entry gate ``z > 1``
// — diverged by months between the engine and TV. This rev keeps the
// same multi-level method-calls-method surface but routes Pine's
// bounded-window ``ta.sma`` / ``ta.stdev`` THROUGH the method chain
// instead of accumulating an unbounded stat. The engine's UDT
// dispatch is still the contract under test (probe 21 covers the
// shallow variant); the math is just bounded so the trade list is
// reproducible from the OHLCV CSV alone — any TV/engine drift here
// is attributable to nested-method dispatch and not to pre-CSV
// chart history.
//
// Trade shape: long-only EMA crossover. Each bar we call
// ``stat.refreshAndScore(close, sma, sd)`` which internally calls
// ``self.feed(close, sma, sd)`` and then ``self.zscore()``;
// ``zscore`` itself dispatches into ``self.mean()`` and
// ``self.variance()`` (which dispatches into ``self.mean()`` again).
// Entry fires on z > 1 with EMA crossover, exit on the opposing cross.
//
// TV setup: 15m chart, ETH-USDT-USDT, same window as
// data/ohlcv_ETH-USDT-USDT_15m.csv. Export the trade list to trades.csv
// in this folder.
//@version=6
strategy("PF UDT probe 18 - method calls method", shorttitle="UDT_p18_M2M", overlay=true,
     initial_capital=1000000,
     commission_type=strategy.commission.percent, commission_value=0, slippage=0,
     default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=1,
     process_orders_on_close=false)

type Stat
    float last  = na
    float xMean = na
    float xSd   = na
    int   n     = 0

method feed(Stat self, float v, float m, float s) =>
    self.last  := v
    self.xMean := m
    self.xSd   := s
    self.n     := self.n + 1
    self.n

method mean(Stat self) =>
    self.xMean

// Calls ``mean`` only to keep the nested-dispatch contract live —
// the actual variance comes from the externally-provided sd.
method variance(Stat self) =>
    float _m = self.mean()
    self.xSd * self.xSd

method zscore(Stat self) =>
    float m  = self.mean()
    float v2 = self.variance()
    float sd = math.sqrt(v2)
    na(sd) or sd == 0.0 ? 0.0 : (self.last - m) / sd

method refreshAndScore(Stat self, float v, float m, float s) =>
    int _ = self.feed(v, m, s)
    self.zscore()

var Stat stat = Stat.new(na, na, na, 0)

int   statLen = 50
float smaVal  = ta.sma(close, statLen)
float sdVal   = ta.stdev(close, statLen)

float z = stat.refreshAndScore(close, smaVal, sdVal)

emaFast = ta.ema(close, 9)
emaSlow = ta.ema(close, 21)

if ta.crossover(emaFast, emaSlow) and z > 1.0 and strategy.position_size == 0
    strategy.entry("L", strategy.long, qty=1, comment="entry long")
if ta.crossunder(emaFast, emaSlow) and strategy.position_size > 0
    strategy.close("L", comment="exit long")

Overview

Each bar it feeds close, a simple moving average, and standard deviation through a method chain that returns a z-score. It enters long only when that z-score is above one and an EMA crossover occurs, then exits on the opposing cross. The statistic window is fifty bars. Signals are drawn on the price chart. Position size is fixed at one unit, and no stop loss is defined.

Details

Published by

pineforge-4pass on GitHub

Code credit

PineForge contributors 2026, as written in the script's header

Draws

On the price chart

Markets

Crypto

Timeframes

M15-H1

Risk Notes

  • The strategy enters trades without a stop loss

Topics

algorithmic-tradingbacktestingparitypine-scriptpinescriptquantitative-financetest-corpustradingview

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 overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated 2 days ago · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 7 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint
228 stars

The Mean Reversion Strategy Template calculates a baseline mean using SMA, EMA, or VWAP alongside upper and lower deviation bands based on standard deviation, ATR, or percentage offsets. It generates long and short entries when price touches, bounces from, or

Strategy v6 Mean reversionMoving averages
Updated 3 months ago · None stated GitHub repository of Mean Reversion Strategy Template

STRG-BBForce

by harryguiacorn
220 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

More Moving averages scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers