OseriesOpen of every bar. Also Open.
182 functions in 19 groups, written for array thinking: one line describes the whole history of a symbol. Every example runs as it is β press βΆ to open it in the workstation.
The bars themselves, their dates, and facts about the symbol.
OseriesOpen of every bar. Also Open.
HseriesHigh of every bar. Also High.
LseriesLow of every bar. Also Low.
CseriesClose of every bar. Also Close.
VseriesVolume of every bar. Also Volume.
AvgseriesTypical price, (H + L + C) / 3.
BarCountnumberNumber of bars loaded for this symbol.
BarIndex()series0, 1, 2 β¦ for each bar.
DateTime()seriesBar time as Unix seconds (UTC).
DateNum()seriesCompact date number: (year β 1900)Β·10000 + monthΒ·100 + day. 1250131 is 31 Jan 2025.
Year()seriesCalendar year of each bar.
Month()seriesMonth 1β12.
Day()seriesDay of month 1β31.
DayOfWeek()series0 = Sunday β¦ 6 = Saturday.
DayOfYear()series1β366.
Name()stringTicker of the symbol being processed.
FullName()stringCompany or asset name.
SectorName()stringSector, where known.
IndustryName()stringIndustry, where known.
MarketName()stringListing market code: US, IDX, TSE, CRYPTO β¦
Currency()stringCurrency the prices are quoted in.
What a formula hands back: signals, filters, columns and plots.
Buy = conditionoutputLong entry signal. Read at the bar's close and filled on the next bar (trade delay 1) at the open by default.
Sell = conditionoutputLong exit signal.
Short = conditionoutputShort entry signal. Needs direction 'short' or 'both' in the settings, or SetOption("AllowShort", true).
Cover = conditionoutputShort exit signal.
BuyPrice = seriesoutputPrice to buy at instead of the open/close. Clamped into the bar's highβlow range.
SellPrice = seriesoutputPrice to sell at.
ShortPrice = seriesoutputPrice to short at.
CoverPrice = seriesoutputPrice to cover at.
Filter = conditionoutputWhich bars appear in an Exploration. Without Filter only the last bar of every symbol is listed.
Title = "text"outputCaption shown above the chart.
Plot(series, name, { color, style, pane, width })outputDraw a line on the chart. style: line, histogram, dots, area, step. pane: "price" overlays the candles, any other name opens a separate pane, "auto" decides by scale.
PlotShapes(condition, shape, name, { color, position })outputMark bars on the chart. shape: arrowUp, arrowDown, circle, square. position: aboveBar, belowBar.
AddColumn(series, name, format | { format, color, bg })outputAdd a column to the Exploration table. format: 1.2 (two decimals), "pct" (0.12 β 12%), "int", "money", "date". color: a colour name, a series (positive green, negative red) or ColorIf().
AddTextColumn(text | fn(i), name, { color })outputText column. Pass a string, an array with one entry per bar, or a function of the bar index.
SetSort(columnName, descending = true)outputDefault sort of the Exploration table.
ColorIf(condition, colorIfTrue, colorIfFalse)arrayPer-bar colour list for AddColumn / AddTextColumn.
print(...values)outputWrite to the formula log (first 200 lines). Same as _TRACE.
Sliders, switches and values the optimiser can vary.
Param(name, default, min, max, step)numberA number the user can change with a slider without editing the code.
ParamToggle(name, default)numberAn on/off switch.
ParamList(name, "A|B|C", default)stringA choice from a list. Returns the chosen text.
Optimize(name, default, min, max, step)numberA parameter the optimiser and walk-forward test vary. In every other run it takes its default (or the value set in the parameter panel).
Smoothing lines of every flavour.
MA(series, period)seriesSimple moving average.
EMA(series, period)seriesExponential moving average, seeded with the simple average of the first period.
WMA(series, period)seriesLinearly weighted moving average.
DEMA(series, period)seriesDouble exponential moving average.
TEMA(series, period)seriesTriple exponential moving average.
HMA(series, period)seriesHull moving average.
Wilders(series, period)seriesWilder's smoothing (used inside RSI and ATR).
AMA(series, factor)seriesAdaptive average with a per-bar smoothing factor between 0 and 1.
VWMA(period)seriesVolume-weighted moving average of the close.
Momentum readings that swing within a range.
RSI(period = 14)seriesRelative Strength Index of the close.
RSIa(series, period = 14)seriesRSI of any series.
MACD(fast = 12, slow = 26)seriesEMA(fast) β EMA(slow) of the close.
Signal(fast = 12, slow = 26, signal = 9)seriesSignal line: EMA of MACD.
MACDHist(fast, slow, signal)seriesMACD β Signal.
StochK(period = 14, smooth = 3)seriesSlow stochastic %K.
StochD(period = 14, smooth = 3, d = 3)seriesStochastic %D.
WilliamsR(period = 14)seriesWilliams %R, 0 to β100.
CCI(period = 20)seriesCommodity Channel Index.
MFI(period = 14)seriesMoney Flow Index.
ROC(series, period = 1)seriesPercent change over the period, in percent (5 means +5%).
Momentum(series, period)seriesseries β series n bars ago.
AroonUp(period = 25)seriesAroon up.
AroonDown(period = 25)seriesAroon down.
How strong a trend is and how much prices move.
ATR(period = 14)seriesAverage True Range.
NATR(period = 14)seriesATR as a percent of the close.
TrueRange()seriesTrue range of every bar.
ADX(period = 14)seriesAverage Directional Index.
PDI(period = 14)series+DI.
MDI(period = 14)seriesβDI.
BBandTop(series, period = 20, width = 2)seriesUpper Bollinger band.
BBandBot(series, period = 20, width = 2)seriesLower Bollinger band.
KeltnerTop(period = 20, mult = 2)seriesEMA + multΒ·ATR.
KeltnerBot(period = 20, mult = 2)seriesEMA β multΒ·ATR.
SAR(acceleration = 0.02, max = 0.2)seriesParabolic SAR.
Supertrend(period = 10, mult = 3)seriesSupertrend line. .dir is +1 in an uptrend, β1 in a downtrend.
GapUp()seriesLow above the previous high.
GapDown()seriesHigh below the previous low.
Inside()seriesInside bar.
Outside()seriesOutside bar.
What traded volume says about a move.
OBV()seriesOn-balance volume.
CMF(period = 20)seriesChaikin Money Flow.
Crosses, look-backs and memory of past events.
Ref(series, -n)seriesValue n bars ago. Offsets must be negative or zero β a positive offset would read the future and is refused.
Cross(a, b)series1 on the bar where a moves from at or below b to above b.
IIf(condition, a, b)seriesBar-by-bar choice.
And(a, b, β¦)series1 where every argument is true.
Or(a, b, β¦)series1 where any argument is true.
Not(a)series1 where a is false.
Flip(a, b)series1 from a bar where a is true until b becomes true.
ExRem(a, b)seriesRemoves repeated a signals until b appears. Buy = ExRem(Buy, Sell) keeps the first buy of each run.
Hold(a, n)series1 for n bars after a was true.
BarsSince(condition)seriesBars since the condition was last true.
ValueWhen(condition, series, nth = 1)seriesValue of series at the nth most recent bar where condition was true.
HHV(series, period)seriesHighest value over the period, including this bar.
LLV(series, period)seriesLowest value over the period.
HHVBars(series, period)seriesBars since the highest value of the period.
LLVBars(series, period)seriesBars since the lowest value of the period.
Highest(series)seriesHighest value since the first bar.
Lowest(series)seriesLowest value since the first bar.
HighestSince(condition, series)seriesHighest value since condition was last true.
LowestSince(condition, series)seriesLowest value since condition was last true.
Count(condition, period)seriesHow many of the last n bars were true.
Sum(series, period)seriesRolling sum.
Cum(series)seriesRunning total.
Rolling statistics and regressions.
StDev(series, period)seriesPopulation standard deviation.
ZScore(series, period)series(series β MA) / StDev.
Correlation(a, b, period)seriesRolling Pearson correlation.
LinRegSlope(series, period)seriesSlope of the least-squares line per bar.
LinearReg(series, period)seriesEnd value of the least-squares line.
LinRegIntercept(series, period)seriesStart value of the least-squares line.
PercentRank(series, period)seriesPercent of the previous n values below today's (period up to 500).
Arithmetic that works on whole series at once.
Abs(x)seriesAbsolute value.
Max(a, b)seriesLarger of two values per bar.
Min(a, b)seriesSmaller of two values per bar.
Sqrt(x)seriesSquare root.
Log(x)seriesNatural log.
Log10(x)seriesBase-10 log.
Exp(x)seriese to the power x.
Pow(x, y)seriesx to the power y.
Round(x, digits = 0)seriesRound per bar.
Floor(x)seriesRound down.
Ceil(x)seriesRound up.
Sign(x)seriesβ1, 0 or 1.
Nz(x, default = 0)seriesReplace empty values (warm-up bars, missing data).
IsNull(x)series1 where the value is empty.
Add(a, b)seriesa + b. Same as a.add(b).
Sub(a, b)seriesa β b.
Mul(a, b)seriesa Γ b.
Div(a, b)seriesa Γ· b, empty where b is zero.
Series(arrayOrNumber)seriesTurn a number or a plain array (one value per bar) into a series.
Annual report figures, switched on at their filing date.
Fundamental(key) or F(key)seriesFiscal-year figure as a step series. Each year's numbers start on the filing date (or 90 days after the year end), so a backtest never sees a report before it was public. Keys: revenue, gross_profit, operating_income, net_income, eps, equity, assets, liabilities, cash, shares, cfo, capex, fcf, dividends, gross_margin, operating_margin, net_margin, roe, roa, debt_to_equity, current_ratio, revenue_growth, eps_growth.
PE()seriesPrice Γ· split-adjusted EPS. Empty when earnings are negative or the report is in another currency without a stored rate.
PB()seriesPrice Γ· book value per share.
PS()seriesPrice Γ· revenue per share.
EarningsYield()seriesEPS Γ· price.
FCFYield()seriesFree cash flow per share Γ· price.
DivYield()seriesDividends paid per share Γ· price.
MarketCap()seriesClose Γ split-adjusted shares.
EPS()seriesSplit-adjusted earnings per share.
How a symbol behaves against its market index.
Benchmark()seriesClose of the symbol's market index (S&P 500 for US, IHSG for IDX, Bitcoin for crypto β¦) aligned to its bars.
BenchmarkName()stringTicker of that index.
RelStrength()seriesClose Γ· benchmark, rebased to 100 at the first bar.
Beta(period = 60)seriesRolling beta of daily returns against the benchmark.
TimeFrame(period, function () { return series; })seriesRun part of the formula on hourly, daily, weekly, monthly, quarterly or yearly bars built from the chart's bars (on 5-minute or hourly charts, "daily" gives the previous day's values), then bring the result back to every daily bar. Each day sees only the last finished period, so there is no look-ahead: a weekly value appears on the first bar of the next week. Plot, AddColumn and Rank must stay outside.
Foreign(symbol, field = "C")seriesAnother symbol's O, H, L, C or V aligned to this symbol's dates (last known value on each bar). Write the ticker as plain text so it can be loaded before the run; up to 6 per formula. Use "~NAME" for one of your composites.
Composite(name, field = "C")seriesOne of your saved composites. C is the combined value, V is how many symbols went into it that day.
AddToComposite(value, "~NAME", method = "avg")outputBuild your own index across every symbol in an Explore or Scan run. method: avg, sum, median, min, max, or pct (share of symbols where the value is true, 0β100). Saved under your account after the run and readable from any formula with Composite() or Foreign("~NAME").
Rank(value, "name")seriesWhere this symbol ranks on the value against every other symbol on the same day: 1 = highest. Works in Analysis runs (the server runs the formula twice); on a single chart it is blank.
RankPercent(value, "name")seriesSame ranking as a percentile: 100 = best on that day, 0 = worst.
RankCount("name")seriesHow many symbols had a value for that ranking on each day.
Study(name, ratio = 0)seriesValue of a line you drew on this symbol's chart, on every bar. A horizontal line is constant; a trendline starts at its first point and extends right; a Fibonacci drawing returns the retracement level for ratio (0 = the second point, 1 = the first, 0.618 = the golden ratio). Blank on symbols without a drawing of that name. Drawings are saved with your account, so scans and backtests see them too.
AlertIf(condition, text, kind = "info")outputRaise an alert when the condition is true. kind: buy, sell, info, warning. Explore shows every alert in the range; a Daily scan records alerts on the newest bar, keeps a history and sends an in-app notification. At most 10 per formula.
CandlePattern(name) or CdlName()series1 on bars that complete the pattern. 33 patterns: Doji, LongLeggedDoji, DragonflyDoji, GravestoneDoji, SpinningTop, Hammer, HangingMan, InvertedHammer, ShootingStar, BullMarubozu, BearMarubozu, BullBeltHold, BearBeltHold, BullEngulfing, BearEngulfing, BullHarami, BearHarami, Piercing, DarkCloudCover, TweezerBottom, TweezerTop, BullKicker, BearKicker, MorningStar, EveningStar, ThreeWhiteSoldiers, ThreeBlackCrows, ThreeInsideUp, ThreeInsideDown, ThreeOutsideUp, ThreeOutsideDown, RisingThree, FallingThree. Reversal patterns (hammer, stars, tweezers, belt holds) require the matching 5-bar move before them. Every one also exists as Cdl + name, e.g. CdlHammer(). Run the Candle patterns analysis to see which ones actually worked on your list.
CandlePatterns()arrayThe list of pattern names with their bars and bias (bullish, bearish, neutral).
include("Formula title")outputRun one of your saved formulas first, so its functions and variables can be used here β build your own indicator library once and reuse it. Matches the exact title of a formula you own; up to 8 includes, nested at most 3 deep. Library code should define values and functions, not Buy/Plot.
StaticVarSet(name, value)outputRemember a value (number, text or series) after this run ends. In an analysis the runtime that ran one symbol keeps it for the next symbols it runs, so it can count or collect across symbols β but the order of symbols is not fixed; use Rank() or AddToComposite() for cross-symbol values you rely on.
StaticVarGet(name, fallback)numberRead a remembered value, or the fallback if there is none.
StaticVarRemove(name?)outputForget one remembered value, or all of them when called without a name.
PlotText(textOrSeries, barsOrCondition, price?, { color, position })outputWrite a label above (or below, position: "below") the bars where the condition is true, or at one bar number (negative counts from the end). Pass a series as the text to print its value at each bar.
PlotOHLC(o, h, l, c, name, { pane, style })outputDraw your own candles (or bars with style: "bars") β e.g. a spread, a ratio or Heikin-Ashi computed in the formula. Goes to its own pane unless pane: "price".
PlotGrid(level, { pane, color, label })outputA horizontal reference line at a fixed level in a pane (e.g. 30 and 70 for RSI).
PlotBand(top, bottom, name, { color, pane })outputShade the area between two series β a channel, a cloud or a band.
PlotBackground(condition, color)outputTint the price pane behind every bar where the condition is true, e.g. to show regimes.
SetBarColor(colorOrColorList)outputColor each candle, usually with ColorIf.
Ranking, sizing, stops and settings inside the formula.
PositionScore = seriesoutputWhen more symbols signal than there are free positions, the highest absolute score is bought first.
PositionSize = number | seriesoutputNegative = percent of equity (β20 is 20%). Positive = an amount of money per trade.
ApplyStop(type, mode, amount)outputtype: loss, profit, trailing, nbar. mode: percent, point, bars. The amount can be a series β its value on the signal bar is used, so ATR-based stops work. A gap through the stop fills at the open. If one bar touches both the stop and the target, the stop is assumed first.
SetOption(name, value)outputOverride a setting from inside the formula: InitialEquity, MaxOpenPositions, CommissionPercent, CommissionMinimum, CommissionPerShare, SlippagePercent, AllowShort, TradeDelay, TradePrice, RoundLot, PositionSizePercent, PointValue, MarginDeposit, TickSize, MaxScaleIns, ScaleOutPercent, BacktestMode, RebalanceBars, WorstRankHeld.
SetPositionSize(amount, mode, stopDistance?)outputHow much to buy on each entry. mode percent: % of equity. value: money per trade. shares: a number of shares or contracts. risk: risk amount % of equity on the stop distance (in price points) β the size is chosen so hitting the stop loses exactly that much. Amount can be a series.
ScaleIn = conditionoutputWhile a trade is open, add another position of the normal size on bars where this is true (pyramiding). Limited by MaxScaleIns (default 3) and free cash. The entry price becomes the average.
ScaleOut = conditionoutputWhile a trade is open, sell ScaleOutPercent (default 50%) of it on bars where this is true. Each partial sale is listed as its own trade with reason scale-out.
SetBacktestMode("regular" | "rotation")outputrotation ignores Buy and Sell: every RebalanceBars bars it ranks all symbols by PositionScore, holds the top MaxOpenPositions and sells a holding once its rank is worse than WorstRankHeld. Negative scores are shorted when shorts are allowed.
TradeMetric(name, series)outputRecord a value on the signal bar of every trade. The backtest report adds a Trade metrics tab comparing winners with losers and splitting trades into groups by this value β a quick way to find a filter.
Methods available on every series.
a.gt(b) .ge .lt .le .eq .neseriesComparisons. JavaScript cannot overload > on series, so write C.gt(MA(C, 20)) instead of C > MA(C, 20).
a.add(b) .sub .mul .div .pow .neg .absseriesArithmetic on series or numbers.
a.and(b) .or .notseriesCombine conditions.
a.ref(-n)seriesSame as Ref(a, -n).
a.crosses(b)seriesSame as Cross(a, b).
a.at(i)numberValue at bar i; negative counts from the end (a.at(-1) is the last bar).
a.lastnumberValue on the last bar.
a.map((value, i) => number)seriesBar-by-bar custom calculation. Use .v for the raw Float64Array when writing loops.