Chart/CharmScript Documentation

CharmScript Documentation

How to write your own indicators and strategies for the chart: how a script runs, the 18 examples the editor starts from, a library of 50 classic scripts converted from Pine Script, and all 489 built-in functions and values. Write scripts in the chart's script editor (chart toolbar → Scripts).

CharmScript is Eclipse's scripting language for the chart. You write a script in the script editor (chart toolbar → Scripts, on any account, the free one included), press Add to chart (Ctrl/Cmd+Enter; it reads Update chart once the script is on), and it draws on the chart: over the candles, in its own pane underneath, or both. New script starts an indicator; the arrow on its end also offers New strategy (entries and exits marked on the chart, and backtested in the Backtests panel) and Start from an example, a ready-made script to build on.

CharmScript 1.0
script("EMA cross", tool = indicator, chart = main)

fastLen = input.int(9, "Fast", min = 1)
slowLen = input.int(21, "Slow", min = 1)

fast = ind.ema(p.close, fastLen)
slow = ind.ema(p.close, slowLen)

plot.line(fast, "Fast", color = #00d79e, linewidth = 2)
plot.line(slow, "Slow", color = #a396ff)
plot.shape(math.crossover(fast, slow), "Cross up", style = style.triangleup, y = y.belowbar, color = #00d79e)

How a script runs

The whole script runs once per bar, from the oldest bar on the chart to the newest. On each run:

  • p.open, p.high, p.low, p.close, p.volume are that bar's values, and bars.count is its number (0 on the oldest bar).
  • [ ] reads other bars like a Python list of the bars so far, ending at the bar the script is on:
    • p.close[0] is the first candle on the chart, p.close[1] the second. The first candle is the oldest one the chart has loaded, so it moves back when older history loads.
    • p.close[-1] is the last (live) bar on the chart. p.close[-2] is the second-to-last bar, p.close[-6] five bars back. It's indexed like Python.
    • p.close denotes the series: pass it whole to a function (ind.sma(p.close, 20)) or keep it in a variable (x = p.close, then x[-2]). On its own in a sum or a comparison (p.close - p.open) it reads the bar the script is on, the same as p.close[-1].
    • A bar that doesn't exist yet reads none (missing): one before the first, or a later bar than the one the script is on (a script never sees ahead, so p.close[5] is none until the 6th bar).
    • Any variable works the same way: myValue[-2] is its value on the bar before.
    • x.ago(n) is any value n bars back, the same as x[-(n + 1)] (p.close.ago(1) is p.close[-2]), but whatever it holds: on an array, a map or a matrix [ ] reads an item, so data.ago(1) is the array as it stood when the bar before ended (Pine's data[1]), even one kept in a var and changed since. x.ago(0) is now.
  • name = value makes a variable the first time, as in Python, and it starts fresh on every bar (none until something sets it). One made inside an if or a loop can be used after it. var keeps its value from one bar to the next instead (it is set up once, on the first bar):

body = p.close - p.open // fresh on every bar var count = 0 if body > 0: count += 1 // counts green bars so far

let x = … and const x = … still work, and neither is needed. Both end with the block they're made in, and no later line can change a const (that's an error), though its own line still runs every bar, like JavaScript's const. A new variable that is never read gets a warning, since it's usually a typo (sume = sum + x).

  • On the live bar the script re-runs on every price update, starting from the state at the last closed bar, so a var never counts a tick twice. varip (Pine's word) is a var that keeps every tick instead: varip ticks = 0 then ticks += 1 counts the updates of the live bar, where a var counts one a bar. A closed bar runs once, so on the bars before the live one, after a reload, in a backtest and in an alert, it is a var. It holds numbers, true / false, text and colours (an array goes back with the bar, as a var's does), one variable at a time.

Blocks are indentation

A line that ends in : (if, elif, else, for, while) or => (a function) opens a block: the lines indented under it. Indent with four spaces (the editor does it for you; a tab counts to the next four columns). The block ends at the first line that comes back out.

if rsi > 70:
    state = "overbought"
elif rsi < 30:
    state = "oversold"
else:
    state = "neutral"

if bar.isLast: debug(rsi)      // a one-line block can sit on the same line

To pick a value in one line, write the same if, elif and else on one line, each followed by the value it gives:

state = if rsi > 70: "overbought" elif rsi < 30: "oversold" else: "neutral"

It works anywhere a value goes (after =, inside a call, after return); a line that starts with if is always the block kind. It needs an else, since a value has to come out either way (its colon can be left out: else "neutral"). Inside ( ) it can spread over lines, one branch a line:

state = (
    if rsi > 70: "overbought"
    elif rsi < 30: "oversold"
    else: "neutral"
)

Python's a if condition else b and Pine's condition ? a : b work too, and mean the same.

pass is a line that does nothing, for a block you'll fill in later. A long line can carry on to the next one inside ( ) or [ ], after a line ending in an operator, a comma or =, or before a line starting with an operator, ? or :. Comments start with // (or sit between /* and */).

The first two lines

CharmScript 1.0
script("Name", tool = indicator, chart = main)

CharmScript 1.0 says which version of the language the script is written in (Charm 1.0, the short name, works too; a script saved while the language was called EclipseCode or EclipseLS still runs, and the editor says what its first line is called now). script() names it:

OptionMeaning
tool = indicatorAn indicator (the default)
tool = strategyA strategy: it can use strategy.enter and strategy.exit
chart = mainDraw over the candles
chart = oscillatorDraw in a pane of its own below the candles (the default)
legendtitle = "N"The name the chart shows for it (its Tools row and its pane), when that should be shorter than the title
precision = 2Decimals on the pane's axis and value pills
tooltip = "…"What the script says about itself: its card (just below)
history = allRun it from the first candle of the whole history on every chart (see "How much history it runs on", below)
history = windowRun it from 2,000 candles before the ones the chart draws
compounding = 50A strategy's Compounding %: how much of its profit it reinvests, 0 to 100 (see "Sizes, partial exits, stops and targets", below)
labels = detailedA strategy's Long, Short and Close labels each with its trade's number beside its word; labels = simple (the default) the words alone (see "Strategies", below)

How much history it runs on: history

A chart runs a script from 2,000 candles before the ones it draws, not from the first candle of the market's history. Most scripts have settled long before that: an average, a band, a cross, a value set again and again. A script whose values never settle draws something different depending on where its run began: a count of every green bar so far, a running total, bars.count, odds learned from every past bar. Such a script needs the whole history, and its charts then load all of it and run it from the first candle.

You rarely have to say which: saving a script checks it. The chart page runs it twice on a long history, on a background thread so the chart never waits: once from the first candle and once as a chart runs it. It then compares what it draws on the newest 2,000 candles: every value, colour, text and alert. Numbers may differ by a few hundredths of a percent; anything else must match exactly. If they match, the script runs on the window. If not, it needs the whole history, and its charts run it from the first candle; there is nothing for you to do. The check runs with the script's default inputs and with the inputs of its copies on the chart, so a long length that reaches past the 2,000 candles is caught too.

Say it yourself with history = when you know better, and saving then skips the check:

CharmScript 1.0
script("Green bars so far", history = all)
var count = 0
if p.close > p.open:
    count += 1
plot.line(count, "Count")
  • history = all: from the first candle of the whole history, on every chart. It costs what a strategy costs: the chart loads the whole history for it.
  • history = window: from 2,000 candles before the drawn ones, whatever the check would say.
  • Without it: the check decides, once per save. Until a save has been checked (a few seconds), the script runs on the window.

What the script says about itself: tooltip

tooltip = "…" in script() is the script's card, the one every Eclipse indicator has. It shows when the script's name is hovered in the Tools list (on a phone, from the ? on its row), and from the i beside its name in its settings. The card is headed by the script's title.

CharmScript 1.0
script("Bands", chart = main, tooltip = "An average with a band either side\n- Above the top band: strong\n- Below the bottom band: weak")
  • The text is the card's description.
  • \n starts a new line, and a line that starts with - (or • ) is a bullet under the description. Keep a bullet to about 43 characters, so that it stays on one line of the card.
  • It is at most 600 characters, and plain text in quotes.
  • A script with no tooltip has no card on its Tools row, and its i says only that it is a script written in the editor.

Where it draws: chart = main or oscillator

chart in script() says where the script's drawings go. Any drawing can go somewhere else with its own chart =, so one script can draw on the candles AND in a pane of its own:

CharmScript 1.0
script("EMA and RSI", chart = main)

plot.line(ind.ema(p.close, 20), "EMA")                        // on the candles
plot.line(ind.rsi(p.close, 14), "RSI", chart = oscillator)    // in the pane
plot.level(70, "Overbought", chart = oscillator)

Every drawing takes chart =: plot.*, paint.background and the strategy markers. A paint.fill() goes where its two lines are, so it needs none (two lines on different charts can't be shaded between). It is always the word main or oscillator, never a variable: where a drawing goes is settled before the script runs.

Settings (inputs)

Inputs become the script's settings on the chart (the gear on its row, or a double-click in its pane). They must be at the top level, with plain defaults:

CallSetting
input.int(14, "Length", min = 1, max = 200)whole number
input.float(2.0, "Multiplier", min = 0.5, step = 0.1)decimal
input.bool(true, "Show labels")switch
input.string("Fast", "Mode", options = ["Fast", "Slow"])dropdown
input.color(#00d79e, "Colour")colour
input.source(p.close, "Source")which price: open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4
input.timeframe("1D", "Period")a dropdown of timeframes: written as the chart writes them ("60" an hour, "240" four, "D" or "1D" a day, "W" a week), or "1M" for a month; input.timeframe(chart.timeframe, "Period") starts at the chart's own
input.session("0700-1600", "Hours")session hours, as text: "0700-1600" (the end not included), several as "0800-0900,1230-1630", the days after a colon ("0930-1600:23456", 1 is Sunday)
input.time("2024-01-15 09:30", "From")a date and time, written in UTC in the settings box; the script gets it as a time to compare with bar.time (bar.time >= from). Its default is a date in quotes ("2024-01-15", or "2024-01-15 09:30 +0200" in another zone) or a time in milliseconds

Add tooltip = "…" for the ? help, and group = "…" to put inputs under a heading. A colour is on the settings' Appearance tab, not General: on the row of the drawing that wears it, or on a row of its own when none does (see "The Appearance tab" below).

A setting's value on the pane: badge = true

Add badge = true to a setting and its value, as each copy is set, shows in a box beside the script's name on its pane, the way an order-flow pane shows Aggregate beside CVD. It is off unless written.

CharmScript 1.0
script("Flow", chart = oscillator)

exchanges = input.string("Aggregate", "Exchanges", options = ["This market", "Aggregate"], badge = true)
length = input.int(14, "Length", badge = true)

The pane's name then reads Flow | Aggregate | 14, a box for each, and changes as the settings do.

  • A number shows as it is set (14, 2.5), a dropdown or text its choice, a price source its name (close, hl2), an enum its choice's title.
  • A switch shows its own name while it is on, and nothing while it is off.
  • A timeframe shows as the chart writes it (4H, 1D, 15M; a month in words, "Chart" for the chart's own), hours as written (0700-1600), a date as 2024-01-15 09:30 in UTC.
  • A colour has no value to show: badge = true on one is an error.
  • A box holds 32 characters at most. The boxes are on the script's pane, so a script with chart = main that draws nothing in a pane has none.

Price, bars and the chart

NameWhat
p.open p.high p.low p.close p.volumethe bar's prices and volume, always: nothing in a script can be called p (a variable, a parameter, a function, a type). Their old names, price.close and the rest, still run, with a warning naming the new one
p.hl2 p.hlc3 p.ohlc4 p.hlcc4averages of them
bars.countthe bar's number, 0 on the oldest; bars.last is the newest bar's
bar.time bar.year bar.month bar.day bar.weekday bar.week bar.hour bar.minutewhen the bar opened (UTC); bar.week is the ISO week, 1 to 53 (weeks start on Monday)
bar.closeTime · bars.lastTimewhen the bar closes (its open and one bar of the chart's timeframe) · the newest bar's bar.time
bar.openTimeOf("1D") · bar.closeTimeOf("1D")when the period of a timeframe the bar is in opened and closes, in UTC (Pine's time("1D") and time_close("1D"))
bar.isFirst bar.isLast bar.isConfirmed bar.isRealtime bar.isHistorywhere the bar is
bar.isLastClosedtrue on the newest closed bar when the script runs from the start (Pine's barstate.islastconfirmedhistory); a bar that closes later never is
bar.isFirstOf("1D")true on the first bar of each new period of a timeframe, in UTC: a day, a week from Monday ("W"), a month ("1M"), four hours ("240"); false on the chart's first bar
bar.inSession("0700-1600")true while the bar opens inside the hours (UTC, or a time zone: bar.inSession("0930-1600", "America/New_York"), or an offset like "UTC+2"); a session past midnight ("2000-0400") belongs to the day it ends on
chart.symbol chart.asset chart.timeframe chart.secondsthe chart: chart.symbol is its ticker ("BTCUSDT"), chart.asset the venue and ticker ("BINANCE:BTCUSDT", Pine's syminfo.tickerid), what data.fetch() takes
chart.isIntraday chart.isDaily chart.isWeekly chart.isMonthlyits timeframe
chart.secondsOf("1D") · chart.timeframeOf(14400) · chart.multipliera timeframe's length in seconds (86400; a month counts 2,628,003, as in Pine) · the shortest timeframe that many seconds long ("240") · the number in the chart's timeframe (240 for "240", 3 for "3D")
chart.fgColor · chart.bgColorthe chart's own text and background colours, its theme's: a script that reads them runs again when the theme changes
chart.isStandardtrue while the chart draws the coin's own candles (false under Heikin Ashi, Renko, Range, Line Break, nOHLC and nHA: see "On another kind of candle" below)
chart.isHeikinAshi chart.isRenko chart.isRange chart.isLineBreak chart.isNohlc chart.isNhawhich kind of candle the chart draws
chart.exchange · chart.timezone · chart.assetType · chart.pointValuethe part of chart.asset before its colon ("BINANCE") · "UTC" (every market here trades around the clock) · "crypto", or "index" for a market index · 1
chart.tickthe step the chart writes this coin's prices to (0.01 where it shows two decimals); format(x, "tick") writes a price so. It can be finer than the exchange's own tick

Dates and times

A time is milliseconds since 1970 in UTC, as bar.time is. A zone is "UTC", an offset ("UTC+2", "GMT-5", "UTC+05:30") or a place ("America/New_York", "Europe/London", with their summer time).

CallWhat
time.of(2024, 1, 15, 9, 30, zone = "America/New_York")the time of a date and a clock time (Pine's timestamp()): in UTC with no zone; the hour, minute and second may be left out. A clock time summer time skips is moved on by the gap, one it repeats is the earlier
time.of("2024-01-15 09:30")a date in text: "2024-01-15", "2024-01-15T09:30:00+02:00", "15 Jan 2024 09:30 +0200" (UTC where it names no zone)
time.year(t) time.month(t) time.day(t) time.weekday(t) time.week(t) time.hour(t) time.minute(t) time.second(t)a part of a time, in UTC or zone = …: time.hour(bar.time, "America/New_York") is the bar's hour in New York (Pine's hour(time, "America/New_York"))
time.format(t, "yyyy-MM-dd HH:mm", zone = "UTC")a time as text (Pine's str.format_time): yyyy MM MMM (Jan) dd EEE (Mon) HH hh with a (AM, PM) mm ss Z (+0200), words in 'single quotes'
time.nowthe time now (Pine's timenow), the same on every bar

time alone is still a name a script can give a variable of its own.

Indicators and maths

  • ind.: sma ema rma wma hma vwma alma swma linreg rsi macd stoch cci wpr mfi cmo mom roc atr tr bb kc supertrend dmi sar vwap pivothigh pivotlow, and the running series ind.obv, ind.accdist, ind.pvt, ind.vwap, ind.tr.
  • math.: over a series, highest lowest highestbars lowestbars range change cum sum stdev variance dev median percentrank correlation percentile cummax cummin (math.percentile(p.close, 20, 50) is the median of the last 20, nearest = true one of them; cummax and cummin the highest and lowest so far, Pine's ta.max and ta.min). A percentile between two values is Pine's: the value at rank p% of the count less a half (20% of 5 values is halfway between the first and the second), the first and the last at the ends. (highestbars and lowestbars give an index for [ ], -1 being this bar, so x[math.highestbars(x, 10)] is the high); events, crossover crossunder cross barssince valuewhen rising falling; and plain maths, abs ceil floor round trunc sign sqrt pow exp log log10 min max avg sin cos tan …, math.pi (math.trunc is Pine's int(): toward 0).
  • A function giving back several values is unpacked with [ ]: [mid, upper, lower] = ind.bb(p.close, 20, 2).
  • ind.pivothigh(5, 5) is a high above the 5 bars after it and not under the 5 before it: of two equal highs in a row, the later is the pivot (as Pine marks it). ind.pivotlow the same way down.

Each call keeps its own memory: ind.ema called in two places keeps two averages, and a function called from two places keeps one set per place.

Another timeframe or coin: data.fetch()

data.fetch(asset, timeframe, value) works value out on another timeframe's candles, of the chart's coin or another, and brings it back to the chart's bars, as Pine's request.security does. The asset comes first, then the timeframe, then the value:

dailyEma = data.fetch(chart.asset, "1D", ind.ema(p.close, 50))   // the 50-day average on an hourly chart
[o, h, l, c] = data.fetch(chart.asset, "1D", [p.open, p.high, p.low, p.close])
weekly = data.fetch(chart.asset, input.timeframe("W", "Period"), p.close)
ethDaily = data.fetch("BINANCE:ETHUSDT", "1D", p.close)
quarters = data.fetch(chart.asset, "15", p.volume, all = true)  // an hour's four 15-minute volumes
  • The asset is chart.asset for the chart's own coin ("" is the same), another one as the chart writes it ("BINANCE:ETHUSDT", "HYPERLIQUID:HYPE"; a ticker with no venue, "ETHUSDT", is Binance's), or a text setting made with input.string. On-chain tokens can't be read this way. Another coin's candles come in live, as a Compare line's do.
  • The calculation runs on those candles, with their own history: a 50-day average, not 50 hours. A variable made above the call is worked out again there, with every line above it that makes or changes it (as Pine does): ma = ind.sma(p.close, 20) then data.fetch(chart.asset, "1D", ma) is the 20-day average. A line after the call is not run there.
  • Which day each bar reads: the newest one that has closed by the bar's close. An hour shows yesterday's day until the day's last hour, whose close is the day's own. A bar never reads a candle that is still forming at its close, so the chart draws the same live as after a reload, and an alert fires on what the chart shows. (Pine draws its past bars this way; its live bar shows today so far, and changes after a reload.)
  • forming = true reads the candle the bar is in, as it stood at the bar's close: data.fetch(chart.asset, "1D", p.high, forming = true) is today's high so far, on every bar, live and after a reload alike. With a value one bar back, data.fetch(chart.asset, "1D", p.high[-2], forming = true), it is yesterday's high all day: Pine's high[1] with lookahead = barmerge.lookahead_on. A day the chart's candles start part way through (its oldest, out of sight) has none: its first part is not on the chart.
  • gaps = true gives a value only on the bar where a new one arrives (the day closed during it; with forming = true, the day's first bar), none on the others: Pine's barmerge.gaps_on.
  • A smaller timeframe than the chart's, data.fetch(chart.asset, "15", p.close) on an hourly chart, gives the newest of its candles inside the bar (the hour's last 15 minutes; on the hour that is still forming, the newest so far). With all = true it gives every one of them, oldest first, as an array: q = data.fetch(chart.asset, "15", p.volume, all = true), then q.size(), q[0], q.max() (Pine's request.security_lower_tf). A list gives an array of each value: [opens, closes] = data.fetch(chart.asset, "15", [p.open, p.close], all = true). A bar older than those candles' history gets none (an empty array). Their candles come in live too.
  • forming = true builds the candle from the chart's own bars, so it reads the chart's own coin, on a longer timeframe; for another coin, leave it out. On a smaller timeframe it reads the candle the bar opens in, the first inside it, which has closed by the bar's close, so it never redraws either (any coin): with a value one back, data.fetch(chart.asset, "60", ind.ema(p.close, 50)[-2], forming = true) on a 4-hour chart is the hourly average as the bar before closed. That is what Pine's lookahead = barmerge.lookahead_on gives on a smaller timeframe, so a script made for a 5-minute chart reads the same on a 4-hour one.
  • The timeframe is in quotes as the chart writes it ("240", "1D", "W", or "1M" for a month, which is joined from the daily candles by calendar month, UTC), chart.timeframe for the chart's own (Pine's timeframe.period), or a setting made with input.timeframe. "" and the chart's own timeframe written out are the chart's own too: then it is the value the chart's bars give.
  • candles = heikinashi works the value out on that timeframe's Heikin Ashi candles, made from the coin's own (Pine's ticker.heikinashi), on any chart. candles = standard is the coin's own candles: on a chart drawn as another kind of candle, data.fetch(chart.asset, chart.timeframe, p.close, candles = standard) is each bar's real close, where the same call without it reads the bars drawn (Pine's ticker.standard).
  • It gives numbers, true / false, text, colours or a list of them; an array, a map or a drawing stays on the candles it was made on.
  • It goes at the top level of the script, in an if, or in a for loop whose turns are known before the script runs (for c in ["BINANCE:ETHUSDT", "BINANCE:SOLUSDT"]: asks once a turn); not in a while loop or a function. A data.fetch() can be inside what another asks for, 3 deep at most.
  • Until the chart has loaded those candles (a moment after the script is added), its values are none; then the script runs again with them. A strategy's backtest waits for them. Its alerts read them too: the server fetches them each time it checks.
  • Enigma doesn't tune a strategy that uses it yet (it is sent the chart's own candles only).

Order flow: funding, open interest, liquidations, buys and sells

Six values a script reads on each candle, each the number the chart's pane of that data draws on it:

rate = data.funding()                      // the funding rate, in percent (0.01 is 0.01%)
oi = data.openInterest()                   // the open interest at the candle's close, in coins
oiHigh = data.openInterest(value = high)   // or its open, high or low during the candle
longs = data.longLiquidations()            // dollars of longs liquidated in the candle
shorts = data.shortLiquidations()
buys = data.buyVolume()                    // bought at the market (taker buys), in dollars
sells = data.sellVolume()
cvd = math.cum(buys - sells)               // the cumulative volume delta
  • Where it comes from. A Binance pair: the funding, open interest and liquidations of its perpetual future, and buys and sells from the pair's own candles (spot pairs too). HyperLiquid, its stocks and metals: all four. Anything else (on-chain tokens, the market-cap indices, ratios): none.
  • Another coin: give its asset as data.fetch() takes one, data.funding("BINANCE:ETHUSDT"), or a text setting.
  • Another timeframe: inside a data.fetch() value it reads that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the open interest at the close of the newest day that has closed.
  • Funding is the rate of the newest settlement at or before the candle's open, held until the next (the Funding pane's Close mode), per settlement period: 8, 4 or 1 hour on Binance, 1 hour on HyperLiquid. Not the pane's Predicted mode, which on older candles leans toward the next settlement: a backtest would trade on a rate nobody had yet.
  • Liquidations are 0 on a candle the venue's record covers with nothing liquidated (a Binance pair with no perpetual reads 0 too, as the pane draws it).
  • Buys and sells are in the pair's quote currency where the candle carries it: dollars on a USDT pair and on HyperLiquid.
  • None before a dataset begins, on a market that has none of it, in a stretch the venue's archive lacks, and on Renko, Range and Line Break bricks. How far back each goes: funding to each market's listing (2.6 years on HyperLiquid); open interest years back on Binance from 1 hour up (5-minute candles since 28 Sep 2025), since Sep 2026 on HyperLiquid; liquidations since 27 Sep 2026 on Binance and 25 May 2025 on HyperLiquid (charts under an hour read minutes, the last 90 days); HyperLiquid's buys and sells since 25 May 2025 (none on 1- and 3-minute charts). So a strategy that trades on Binance's liquidations has trades from 27 Sep 2026 only.
  • The newest candle is read again every 30 seconds while the chart is in view. A value a bar back, data.openInterest()[-2], is the bar before's own, wherever the call is.
  • Anywhere in the script (an if, a loop, a function), as long as its asset is known before the script runs, as data.fetch()'s is. Not in a data.fetch(…, forming = true) value: order flow is known for whole candles only.
  • Its alerts read it on the server, from the same archives. Enigma doesn't tune a strategy that reads it yet.
  • From Pine: an open-interest ticker, request.security("BINANCE:BTCUSDT.P_OI", "60", close), converts to data.fetch("BINANCE:BTCUSDT", "60", data.openInterest()).

Drawing

A drawing's look and place are names: its shape or kind of plot is a style. name (style = style.labelup, style = style.step), how a line is drawn a line. name (linestyle = line.dashed, plot.level(70, style = line.dotted), border_style = line.dashed), and where it goes a y. name (y = y.belowbar). Type style., line. or y. in the editor for the list. Each name is its word, so the text works too (style = "labelup", linestyle = "dashed", y = "belowbar"). A script may still call its own variable style or y; while it has one, write the word as text.

CallDraws
plot.line(value, "Title", color = …, linewidth = 2, linestyle = line.dashed)a line; linestyle is solid (the default), dashed or dotted
plot.step plot.area plot.histogram plot.column plot.circles plot.crossthe same value drawn as steps, a shaded area, bars, columns, dots or crosses
plot.shape(when, "Title", style = style.triangleup, y = y.belowbar, color = …, text = "…", textcolor = …, size = 2)a shape on bars where when is true; style is labelup, labeldown, box, text, triangleup, triangledown, circle, diamond, square, cross, xcross, flag, arrowup or arrowdown; y is where: y.abovebar / y.belowbar (a little gap from the candle), y.high / y.low (on the high or the low itself, a label's point touching it), y.top / y.bottom (the pane's edges), or a value to draw at, like y = emaLine or y = p.low (when stays the condition; a bar where the value is none draws nothing). The places can also be written as text (y = "belowbar"), and y = y.absolute (or y.price) makes when the price, as Pine's location.absolute; size is 1 to 4. text sits inside a labelup / labeldown / box, is all a text shape draws, and sits beside any other shape, in textcolor (left out: black or white inside a label, the shape's colour otherwise)
plot.char(when, "★")a character on those bars
plot.arrow(value, "Title", colorup = …, colordown = …, size = 2)an arrow on each bar where value isn't 0 (Pine's plotarrow): plot.shape's arrowup under the bar where it is above 0, in colorup (left out: the chart's green), and its arrowdown over the bar where it is below 0, in colordown (the chart's red). Every arrow is one size: size is 1 to 4
plot.level(70, "Overbought", style = line.dashed)a horizontal level: solid, dashed or dotted (linestyle = works too)
paint.fill(a, b, color = …)shading between two lines or two levels (what plot.line() / plot.level() gave back)
paint.fill(a, b, top = 100, bottom = 80, top_color = #ff5252, bottom_color = color.hex(#ff5252, 100))a shade that fades, from top_color at the value top to bottom_color at bottom, each end colour kept past it: with one end fully clear, only the part past the other value shows
paint.background(when, #ff5252)a background tint behind bars where when is true
plot.candles(open, high, low, close, "Title", color = …, wickcolor = …, bordercolor = …)candles drawn from four values, as the chart draws its own: in a pane of their own, or over the chart's candles with chart = main (a Heikin Ashi). A candle with no colour (left out, or none on a bar) takes the chart's up or down colour; wickcolor and bordercolor give its wick and its body's edge colours of their own
paint.candles(color, "Title")the chart's own candles in a colour of yours, bar by bar, as Trend Oracle's Candle Coloring paints them; none on a bar keeps that candle's own colour. Always on the candles
plot.bars(open, high, low, close, "Title", color = …)OHLC bars from four values (Pine's plotbar), drawn as the chart's OHLC type draws its own: a line from the low to the high, the open's tick on its left, the close's on its right. A bar with no colour takes the chart's up or down colour

They are drawn exactly as the built-in indicators draw them. A plot.line, a dashed or dotted line, a step line, an area, columns, a histogram and circles are the chart's own series draw, and a labelup, labeldown, box, text, triangleup, triangledown, circle and diamond are the chart's own signal labels: the same font, the same sizes (1 to 4, one size smaller on a phone, as every label; a label given no size is 1, and so are a strategy's trade labels), the same distance from the candle. Shapes on one side of one bar stack instead of covering each other, and a shape that points one way goes to that side of its candle (a labelup sits under it) as a built-in label does. Columns round their ends when Rounded candles is on. A shape pinned to the top or the bottom of a pane stays inside it, words and all. Clicking a script's line or label on the chart opens its settings, as for every indicator.

A colour can change per bar (color = if p.close > p.open: #00d79e else: #ff5252), and none as a colour leaves that bar out. A line style holds for the whole line; it works on plot.step and on the edge of a plot.area too, and linestyle = input.string("solid", "Line style", options = ["solid", "dashed", "dotted"]) makes it a setting. A background given a solid colour is drawn 90% see-through so the candles show; give it one with its own transparency to choose. paint.background(if up: #00d79e else: none) works too. Each of them also takes chart = main or chart = oscillator (see above), and tooltip = "…": the text behind the ? on its row in the settings (next).

A plot's newest value sits in a pill on the price scale, in its colour, as a built-in indicator's does, and it moves with the live candle. pricelabel = false leaves the pill out and keeps the line: plot.line(slow, "Slow", pricelabel = false). Every plot.line style above takes it, and so do plot.candles and plot.bars (their pill is the newest close). pricelabel = input.bool(true, "Value on the price scale") leaves the choice to whoever uses the script. A level, a shape and a label never have a pill.

Labels, lines, boxes and tables

plot.label, plot.segment, plot.polyline, plot.box and plot.table draw too, but in a different way from the calls above:

plot.line, plot.shape and the rest aboveplot.label, plot.segment, plot.polyline, plot.box, plot.table
What one line of code drawsone drawing, with a value on every bar (a line through them, a mark on each bar where when is true)one label, line, box or table each time the line runs
Whereon the bars, at the value it was given on eachat any bar and price the code gives (bars still to come too), or a table in a corner
Afterwardsnothing to change: each bar's value is what it drawsgiven back, so a variable keeps it and a later bar moves it, changes it or deletes it
Where in the codethe top level, outside loops and functionsanywhere: an if, a loop, a function
The settings boxa row each on the Appearance tabno row: drawn as the code says

So a mark on every bar where RSI crosses 70 is plot.shape; a label that follows the close, or one on each swing high written with its price, is plot.label. A moving average is plot.line; a line from one swing low to the next is plot.segment (the chart's Segment tool; plot.line already means the line through a value on every bar).

// A label on every swing high, with its price.
ph = ind.pivothigh(5, 5)
if not none(ph):
    plot.label(bars.count - 5, ph, format(ph, "#.##"), style = style.labeldown, color = #ff5252)

// One line, made once and moved on every bar: from 20 bars back to now.
var ln = plot.segment(0, 0, 0, 0, color = #a396ff, style = line.dashed)
ln.xy1(bars.count - 20, p.close[-21])
ln.xy2(bars.count, p.close)

// A table over the candles, filled on the newest bar. The RSI is worked
// out on every bar (outside the if), so it has the history it needs.
rsi = ind.rsi(p.close, 14)
var t = plot.table("top_right", 2, 2, bgcolor = color.hex(#131722, 15), chart = main)
if bar.isLast:
    t.cell(0, 0, "RSI")
    t.cell(1, 0, format(rsi, "#.0"))
CallMakes
plot.label(x, y, "text", color = …, style = style.labeldown, textcolor = …, size = 2, yloc = y.price)a label at bar x; y is a price, or a place as plot.shape's: y.high / y.low (on the bar's high or low itself, its point touching it), y.abovebar / y.belowbar (a little gap from it), y.top / y.bottom (the pane's edges), like plot.label(bars.count, y.low, "Up", style = style.labelup); yloc takes the same places (and y.price, at y), as Pine's yloc, and wins over a place in y; style is labeldown (over the point, pointing at it), labelup, labelleft, labelright, box, text (the words alone), triangleup, triangledown, arrowup, arrowdown, circle, square, diamond, cross, xcross or flag; color = none leaves only the words
plot.segment(x1, y1, x2, y2, color = …, style = line.solid, width = 1, extend = "none")a straight line between two points; style is solid, dashed, dotted, arrowleft, arrowright or arrowboth (an arrowhead on that end); extend is none, left, right or both (carried on past that end to the chart's edge)
plot.box(left, top, right, bottom, border_color = …, bgcolor = …, text = "…", text_halign = "center", text_valign = "center", radius = 0)a box from bar left to bar right, price top to price bottom, with words inside it; border_style is solid, dashed or dotted, extend carries it to the chart's edge, text_size = "auto" (the default) fits its words to it; radius rounds its corners (below)
plot.table("top_right", columns, rows, bgcolor = …, border_color = …, border_width = 1, frame_color = …, frame_width = 1, radius = 0)a table in one place on its pane, over everything: top_left, top_center, top_right, middle_left, middle_center, middle_right, bottom_left, bottom_center or bottom_right; radius rounds its outer corners (below)
t.cell(column, row, "text", text_color = …, bgcolor = …, text_size = "normal", text_halign = "center", width = 0, height = 0)a table's cell (columns and rows count from 0, -1 the last); width and height are % of the pane (0 fits the words)
plot.linefill(line1, line2, color)a shade between two segments (what plot.segment() gave back), as far as both reach, their extensions too, so it moves when they do; it goes where its segments are, and goes when either is deleted. lf.color(…), lf.line1(), lf.line2(), lf.delete()
plot.polyline(points, curved = false, closed = false, color = …, fill = …, style = line.solid, width = 1, xloc = "bar")one line through many points (Pine's polyline.new): points is an array of [x, y] pairs, pts.push([bars.count, p.high]) adding this bar's high. curved = true bends it smoothly through them, closed = true joins the last back to the first, fill shades what it encloses; style is solid, dashed, dotted, arrowleft, arrowright or arrowboth. Its points are taken when it is made, so changing the array afterwards doesn't move it: delete it and make another. A point with no value is left out. pl.points() gives them back, pl.delete()

Rounded corners. radius rounds a box's corners, or a table's outer corners, in pixels: 0 (the default) is square, and the bigger the number the rounder they are, up to fully round ends (a radius past half the shorter side draws as half of it). A table's corner cells follow the rounding, and its frame is drawn along it. A side of a box carried to the chart's edge (extend) stays square. bx.radius(12) changes it later and bx.radius() reads it. To let whoever uses the script choose, make it an input:

r = input.int(8, "Corner radius", min = 0, max = 40)
if bar.isLast:
    plot.box(bars.count - 20, p.high, bars.count, p.low, bgcolor = color.hex(#a396ff, 80), radius = r)

Its setting then shows in the script's settings box, like any input. Colours take a transparency too (color.hex(c, 70) is 70% see-through), for a fill that lets the candles show.

Where they are. x is a bar's number as bars.count counts it: bars.count is this bar, bars.count - 10 ten bars back, and bars.count + 5 five bars still to come (a drawing can reach into the future). Give xloc = "time" to place it by time instead, in milliseconds like bar.time. y is a price. A table is not on the bars at all: it sits where its position says and stays there as the chart scrolls.

Where they go. Over the candles or in the script's pane: each call takes chart = main or chart = oscillator, else it goes where the script draws. So a script in its own pane can put a table over the candles too, and the other way round. In a pane of its own, the labels, lines and boxes widen the pane's axis to fit them (over the candles they never stretch the price axis).

Changing them. Each of a drawing's values is a method named for it, called after a dot. With a value it changes it, with nothing it gives it back: lbl.text("Buy") changes a label's words and lbl.text() reads them. The names are the ones its call takes: lbl.xy(x, y), lbl.color(…), lbl.style("labelup"), ln.xy2(x, y), ln.width(2), bx.top(p.high), bx.rightbottom(x, y), t.position("bottom_left"), t.cell_bgcolor(column, row, …). One of two values gives both back as a list: [x, y] = lbl.xy(). ln.price_at(x) is the line's price at bar x, t.merge_cells(0, 0, 1, 0) and t.clear(…) change a table's cells, and .delete() takes one off the chart (.copy() makes another the same). label.text(lbl, "…") is the same as lbl.text("…"): every one of these is a function of the namespace too. Pine's lbl.set_xy(…) and lbl.get_text() say what to write instead. label.all (and line.all, box.all, table.all) is an array of the ones on the chart now. The Reference lists them all under Labels, Lines, Boxes and Tables.

How many. The chart keeps a script's newest 500 labels, 500 lines and 500 boxes, 100 polylines (of up to 10,000 points each) and 20 tables, with nothing to set (Pine keeps 50 unless a script asks for up to 500 with max_labels_count); making one more deletes the oldest. So making a table or a line on every bar keeps only the last ones: make it once in a var and change it, as above. A script that wants fewer deletes its own (old = kept.shift() then old.delete()).

They are drawn as the chart's own. A label with a built-in shape is the chart's own signal label (the same font, sizes and distance from its candle as plot.shape), stacks with the shapes on that side of that bar, and opens the script's settings when clicked. Words given no colour are black or white to suit a label's colour, and the chart's own text colour (light or dark with the theme) where there is no fill.

On every live tick the newest bar runs again from where the last closed bar left everything, so a label made on the newest bar is made once, not once a tick. Drawings have no rows on the Appearance tab: they are drawn as the code says.

The Appearance tab: one row per drawing

A script's settings have two tabs. General holds its inputs. Appearance holds ONE ROW FOR EVERY DRAWING, the row every built-in indicator has: a box that shows or hides the drawing, its colour box, a dropdown for its look, and a ?. You write nothing for the rows; they come from the drawings.

DrawingIts row's dropdown
plot.line plot.step plot.area plot.histogram plot.column plot.circles plot.crossLine, Dashed, Dotted, Step line, Area, Columns, Histogram, Circles (and Crosses on a plot.cross), and a thickness of 1 to 4
plot.shapeLabel up, Label down, Box, Text only, Arrow up, Arrow down, Circle, Diamond, and a size of 1 to 4
plot.charits size (a character keeps its shape)
plot.arrowits size (an arrow points up or down by its value)
plot.levelLine, Dashed, Dotted, and a thickness of 1 to 4
paint.fill paint.background plot.candles paint.candlesnone: the box alone (paint.candles off gives the chart its own candles back)
strategy.enter.… strategy.exit.…its size (a strategy's labels keep their shape)
  • The row is named by the drawing's title. plot.line(x, "Fast") is the row "Fast"; paint.fill(a, b, colour, "Band") and paint.background(when, colour, "Tint") take theirs third. Give every drawing a title: one without is "Plot 3". A look is kept under the name, so it stays with the drawing when you reorder the lines and starts again when you rename it.
  • What the code says is where a row starts: linestyle = line.dashed, linewidth = 2, style = style.labelup, size = 3, plot.column(…). What is then picked on the row is kept with the chart and wins, until Reset.
  • tooltip = "…" is the text behind the row's ?. Every drawing takes it: plot.line(fast, "Fast", tooltip = "The 9-bar average"). The ? also says what the row starts as.
  • A colour box is an input.color. A drawing coloured with one shows that setting's box on its own row; coloured with two (color = if up: upColor else: downColor) it shows both, and color.hex(upColor, 80) still counts. A drawing with a plain colour (color = #00d79e), or one worked out from the bars, has no box: make the colour an input to let it be changed. A colour no drawing wears gets a row of its own under the drawings.
  • Every shape a label's row offers can be coded: style = style.labelup, "labeldown", "box" (a label with no pointer), "text" (the words alone), "triangleup" (the row's Arrow up), "triangledown", "circle", "diamond". square, cross, xcross, flag, arrowup and arrowdown still work, and a row lists one of those for a shape coded with it. Picking Label up on a row puts the label under its candle and Label down over it, wherever y had it (a shape at top, bottom or a price stays there).
  • size is 1 to 4, the row's slider (tiny, small, normal and large are the same four).
  • A hidden plot has no value on the price scale either.
  • script("Name", …, tooltip = "…") is the script's own card, the i beside its name: see "What the script says about itself" above.
CharmScript 1.0
script("Bands", chart = main, tooltip = "An average with a band either side")

length = input.int(20, "Length", min = 2, tooltip = "How many bars the average looks back over")
upColor = input.color(#00d79e, "Up colour")       // the colour boxes on the rows below
downColor = input.color(#6a5ebc, "Down colour")

[mid, upper, lower] = ind.bb(p.close, length, 2)

// A line row with two colour boxes, starting solid at thickness 2.
plot.line(mid, "Average", color = if mid > mid[-2]: upColor else: downColor, linewidth = 2,
    tooltip = "The moving average, in the up colour while it rises")
// A line row starting dashed.
plot.line(upper, "Upper band", color = upColor, linestyle = line.dashed, tooltip = "Two deviations above the average")
// A label row starting as a box, size 3.
plot.shape(math.crossover(p.close, upper), "Breakout", style = style.box, y = y.belowbar, text = "Break",
    color = upColor, size = 3, tooltip = "A close back above the upper band")
// A series row in a pane of its own, starting as columns.
plot.column(ind.rsi(p.close, 14) - 50, "Momentum", chart = oscillator, color = downColor,
    tooltip = "RSI minus 50")

Start from an example → Appearance rows in the editor is a script with every kind of row.

On another kind of candle

On a chart drawn as Heikin Ashi, Renko, Range, Line Break, nOHLC or nHA, a script runs on the candles drawn: p.close is the Heikin Ashi close, a brick's close, a neural candle's close, as in Pine. But none of those prices ever traded, so a strategy decides on the candles drawn and trades on the real ones:

  • An order the script places fills at the real close of the candle it was placed on, never at the drawn candle's price.
  • Stops, targets, trailing stops and orders at a price are checked against the real candles' highs and lows.
  • Sizes, fees, profit, the equity curve and drawdown all come from real prices, and so does strategy.entryPrice.
  • On Renko, Range and Line Break a brick is known only once the real candle that finished it has closed, so its trade fills at that candle's close. Its stops are checked on every real candle between bricks: the price can reach a stop without drawing a brick. Bricks one candle finished all happen at that candle's close, one after another: an entry and an exit among them are one round trip at one price, which costs only the fees.

The chart's marks, the Backtests panel and the copy's alerts are the same trades. The Backtests card says what they were decided on ("Signals: Heikin Ashi · Fills: real prices"). To compare a drawn price with a real one, read the real one with data.fetch(chart.asset, chart.timeframe, p.close, candles = standard). Enigma and the machine-learning sizers tune on the real candles, so they stay off for a script on another kind of candle.

Strategies

A script made with tool = strategy marks its trades on the chart:

strategy.enter.long(math.crossover(fast, slow), "Long")
strategy.exit.long(math.crossunder(fast, slow))
strategy.enter.short(rsi > 80, "Short")
strategy.exit.short(rsi < 50)

A strategy holds one position at a time: entering long turns a short around, and an entry while already in that position, or an exit with nothing to close, marks nothing. The marks are the labels Ceres and Enzo mark their trades with: an outlined chip on the chart's background in the signal's colour, "Long" under the candle in green, "Short" over it in red, and "Close" in grey where a trade ends (over the candle when a long closes, under it when a short does). On a light chart they take Ceres' and Enzo's light-theme colours. The second value names a mark (strategy.exit.long(when, "Take profit")), and color = … changes its colour. The marks go where script() says, like every drawing: a strategy that works on an oscillator can keep its trades on the candles with script(…, chart = main) and draw the oscillator with chart = oscillator (the RSI reversals example does this). A Pine strategy in a pane of its own (overlay = false) converts with chart = main on each strategy call, so its marks are on the candles, where Pine draws them; take it out of a call to put that call's marks in the pane.

With labels = detailed each mark carries its trade's number: an entry's size, as a share of the account, beside its word ("Long | 37%"), and an exit's return in green or red ("Close | +0.84%"), in a second part of the label filled with its colour. They are the numbers of its backtest, as the Backtests panel's Trades card shows them; a mark with no trade there (the candle still open, an entry the ROI Curve Filter skips) is the label alone. Without it (or with labels = simple, the default) the labels are alone. Either is where its copies start: the Labels row under Show Backtest on the Strategy tab of its settings changes it, as it does for Ceres, Enzo and PerpKit.

Sizes, partial exits, stops and targets

strategy.enter.long(buy, percent = 25)        // a quarter of the account
strategy.enter.short(sell, cash = 100)        // $100
strategy.exit.long(sl = 2, tp = 4)            // a stop 2% and a target 4% from the entry price
strategy.exit.long(sl = 60000, tp = 70000, type = price)   // at those prices
strategy.exit.long(math.crossunder(fast, slow), percent = 50)
  • An entry's size. percent = 25 puts 25% of the account in, counted the way the Compounding % setting counts the account (at 100%, all of it as it is now; at 0%, the account as it started). cash = 100 puts in that much money of an account that starts at the Strategy tab's Initial Capital (shown for such a script with Execution off too). Give one or the other. Left out, the whole account goes in (a full position). A script's sizes are its code's: its Strategy tab has no Position Size. Leverage multiplies either. A size can be worked out on each bar; none on a bar puts the whole account in there, and 0 or less is no entry.
  • Compounding. script("My strategy", tool = strategy, compounding = 50) is how much of its profit the strategy reinvests: its Compounding % (0 = none, the account as it started; 100 = all of it). A plain number from 0 to 100, written by name. The copy's Strategy tab starts there and can still change it; without it, 99.
  • Capital and costs. script("My strategy", tool = strategy, capital = 10000, fee = 0.05, slippage = 0.02, leverage = 2) are its Strategy tab's Initial Capital, Fee % and Slippage % (on each entry and exit) and Leverage, where the copy starts and can still change them; a fee or a slippage switches Execution on. Plain numbers, written by name, in the rows' own ranges (capital 100 to 1,000,000,000, fee and slippage 0 to 5, leverage 0.1 to 100). Pine's 100% of equity is an entry with no size and compounding = 100.
  • Reading the position. strategy.isLong, strategy.isShort and strategy.isFlat say what is open, and strategy.entryPrice the open trade's entry price (none while flat), as the bar's code starts: after the bar's stops and targets have filled, before its own calls. So on the bar a trade is signalled they still read as before, as Pine's strategy.position_size does. if strategy.isLong: strategy.exit.long(sl = strategy.entryPrice * 0.97, type = price) sets a stop 3% under the entry. strategy.isLong[-2] reads the bar before.
  • With Enigma on (the Strategy tab's Optimisations), every entry is sized by volatility (Volatility-Adjusted: smaller as the market swings more), in place of the sizes the code gives. A size of 0 or less is still no entry.
  • A partial exit. percent = 33 on an exit closes a third of what the trade entered, never more than is still open; the rest stays open at the same entry price. Left out (or 100), it closes all that is open. So three take-profits of 33%, 33% and none close a third of the entry each, as Pine's qty_percent does, and an exit of 50% then one of 100% closes the 25% you put in, in two halves. With pyramiding it is a share of every entry the trade made. Each part closed is a trade of its own in the backtest (its Trades list shows "Exit 33%" beside the side), and the mark says "Close 33%".
  • Stops and targets. sl = 2 is a stop 2% from the entry price (under a long's, over a short's) and tp = 4 a target 4% from it. type = price makes both numbers prices instead (sl = 60000, tp = 70000, type = price); type = percent is the default, so it is never needed. One type covers both numbers of a call: a stop in percent with a target at a price is two lines (strategy.exit.long(sl = 2) and strategy.exit.long(tp = 70000, type = price)), each closing everything, so the first to fill ends the trade. They are orders that stand from the bar after the call runs until they fill: inside a bar, at their own price, or at the bar's open when it opens past one (so a price the market is already past fills at the next open). A level set on every bar (sl = p.close * 0.95, type = price) trails. When a bar reaches both a stop and a target, the one nearer the bar's open is taken first (as Pine assumes); when they are as near, the stop. A call that only sets orders needs no when. Each exit call has its own stop and target, so two calls can scale out at two targets (tp = 3, percent = 50 and tp = 6); when one of a call's two fills, the other stands down for the rest of that trade. When a trade closes, every order for its side goes, and an exit call later on that bar sets none (if strategy.isLong: still reads the trade as the bar began): its stop was the closed trade's, and would otherwise stop the next one at that trade's levels. A filled stop is marked "Stop" and a target "Target", at the price it filled. The open trade's stop shows on the Backtests panel's Position card.
  • Inside a bar only its open, high, low and close are known: a stop and a target reached in one bar follow the rule above, never a finer path.
  • A fixed amount. qty = 0.5 buys half a coin (Pine's qty, and strategy.fixed), whatever the account holds; one past what the account can buy, with its leverage, buys what it can. One size an entry: percent, cash or qty.
  • Entering at a price. strategy.enter.long(setup, "Breakout", stop = p.high[-2]) waits for the price to rise to that level, limit = … for it to fall to one (a short's the other way round), and both together are a stop-limit: a limit that stands once its stop was reached. The order stands from the next bar until it fills, at its price inside a bar or at the open of a bar that opens past it (as a stop does), until strategy.cancel("Breakout") takes it back (strategy.cancelAll() every one), or until the call runs again with new prices. Its mark sits where it filled. It cannot fill while its side is already open (unless the strategy pyramids, below); one for the other side turns the trade around at its price. oca = "range" puts entries in one group (Pine's one-cancels-all, oca_name with strategy.oca.cancel): when one of the group fills, the group's other orders are taken back at once, in the same bar too. So a breakout with a stop over a range and another under it is one trade even on a bar that crosses both.
  • A trailing stop. strategy.exit.long(trail = 2) is a stop 2% under the highest price since the entry (a short's, over the lowest), which never moves back; trailstart = 1 starts it once the trade is 1% up. With type = price, trail is a distance and trailstart a price. It follows the bar's whole path, its close too: a bar that rose to a new high and fell back past the stop fills there. It shows on the Position card as the trade's stop.
  • Several entries on one side (pyramiding). script("Scale in", tool = strategy, pyramiding = 3) lets three entries be open on one side at once, as Pine's pyramiding does: an entry while its side is open adds to the position (without it, such an entry is nothing). Each entry is its own trade in the Backtests panel, and an exit closes the oldest first (percent = 50 closes half of all that is open, from the first entry on). The position has ONE stop and target: an exit's sl, tp and trailstart in percent count from strategy.entryPrice, the entries' average price, each counted by the units it bought (so equal percent = entries average at the prices' harmonic mean, as Pine's does). Pine counts each entry's stop from its own price, so a converted strategy that scales in exits a little differently. An entry with no size of its own takes 1/N of the account (a third, with pyramiding = 3); one past what the account holds is not taken. Enigma does not tune a strategy that pyramids.

script("Scale in", tool = strategy, pyramiding = 3) dip = p.close < ind.ema(p.close, 20) * 0.98 strategy.enter.long(dip, "Add", percent = 25) strategy.exit.long(sl = 5, tp = 10) // 5% under the average entry, 10% over it

  • A loss limit for the day. strategy.risk.maxDayLoss(percent = 2) (Pine's strategy.risk.max_intraday_loss) stops the strategy for the rest of the day once its equity is 2% under the day's highest; cash = 500 gives the limit in money instead. The account (the Backtests panel's, as the Strategy tab sets it) is checked at each bar's open, high, low and close, and each time an order fills. When the limit is reached, orders at a price are taken back, the open trade is closed at that price (marked "Day loss" on its side's exit call, whose alert it fires), and no enter call does anything until the next day: a UTC day, or the next bar on a chart of a day or more. A setting works as the limit (strategy.risk.maxDayLoss(percent = lossLimit)).

Every strategy is backtested in the chart's Backtests panel, as Ceres, Enzo and PerpKit are, its numbers worked out by the same code: net return, profit factor, drawdown, the equity curve, every trade, and the position open now. Each trade is taken at the close of the bar whose mark opens or closes it (a stop or a target at its own price), in the order made: a bar's stops and targets first, then its lines in the order they run (a turn from long to short is an exit and an entry on one bar). The newest bar is still forming: a mark on it shows, but its trade is taken only once the bar closes. The backtest runs over the whole history the chart has loaded (up to 25,000 bars). On the chart a script runs from 2,000 loaded bars before the oldest bar drawn, so its lines are settled and its marks are the backtest's trades from the first bar drawn, a trade opened before it included; only a script whose values never settle (a var count of every bar) can mark a trade near the oldest drawn bars differently from its backtest. An entry order at a price is taken at its own price, as a stop or a target is. Its settings are on the copy's Strategy tab: Show Backtest, Compounding % (from the script's compounding =, else 99), a Custom Date Range (trades outside it are neither counted nor marked) and Execution (capital, leverage, fee, slippage). There is no Position Size: an entry puts in what its code says, else the whole account (the built-in strategies cap a full position at 80%), and with Enigma on every entry is sized by volatility. Backtest: Long / Short on the panel narrows the numbers to one side. If the run over the whole history stops (an error on a bar the chart does not draw, or the time limit), the panel says why in place of numbers.

The strategy's numbers

Every number the Backtests panel shows can be read in the script, as a strategy. value:

PanelValue
Net Returnstrategy.roi
Profit Factorstrategy.profitFactor
Max Drawdownstrategy.maxDrawdown
Recovery Factorstrategy.recoveryFactor
Hit Ratestrategy.hitRate
Total Tradesstrategy.totalTrades
Best Trade · Worst Trade · Mean Tradestrategy.bestTrade · strategy.worstTrade · strategy.meanTrade
CAGRstrategy.cagr
Sharpe Ratiostrategy.sharpe
Expectancy (in R)strategy.expectancy
Kurtosis · Skewnessstrategy.kurtosis · strategy.skewness

and the money behind them: strategy.initialCapital (the Initial Capital), strategy.equity (what the account holds now, the open trade included), strategy.netProfit (what the closed trades made, after costs), strategy.openProfit (the open trade at this bar's close, before the costs of closing it), strategy.grossProfit and strategy.grossLoss (what the winning trades made and the losing ones lost, both above 0), and strategy.wins and strategy.losses (how many trades made or lost money).

// A quarter of what the account holds now on each trade
strategy.enter.long(math.crossover(fast, slow), cash = strategy.equity / 4)
plot.line(strategy.roi, title = "Net return %")
if strategy.totalTrades >= 20 and strategy.sharpe < strategy.sharpe[-2]:
    debug("Sharpe fell to " + format(strategy.sharpe))
  • The panel's own numbers. They come from the same account as the panel's, with the copy's Strategy-tab settings (capital, compounding, costs, leverage, the Custom Date Range), so on the newest bar each is the panel's number. Changing a setting runs the script again. On the chart too: the chart runs a copy from 2,000 candles before the bars it draws, and takes the trades its backtest made before them, so a table drawn on the newest bar shows the panel's numbers. Such a copy appears once its backtest has run.
  • As the bar's code starts, like strategy.isLong: the trades closed by then, and the open trade valued at this bar's close. A trade signalled on a bar counts from the next bar. On the newest bar, still forming, a stop or a target it reached counts once it closes, as on the panel.
  • Percentages are plain numbers: strategy.roi is 12.5 for 12.5%, as ind.rsi is 70, not 0.7.
  • A bar back like any value: strategy.sharpe[-2] (or strategy.sharpe.ago(1)) is the Sharpe ratio as the bar before read it; none on the first bar.
  • Money is in the Initial Capital (10,000 until changed, or the script's own capital =), with Execution on or off. Before a Custom Date Range starts nothing is counted: strategy.equity is the Initial Capital and strategy.totalTrades 0.
  • The strategy as set. With Enigma or the ROI Curve Filter on, the panel shows the optimised copy, but the script reads its strategy as set (the panel's Original); Backtest: Long / Short narrows the panel, not these.
  • In an alert, and in the runs Enigma tunes, there are no copy settings: the values use the script's own (script(…, capital = …, fee = …)) over the defaults, from the first of the candles that run reads.

Alerts

On every plan, free included. A script's alerts follow the plan's rules for every alert: they take places in its alerts (5 on the free plan, 10 on Pro, 20 on Premium), and on the free plan they work on every timeframe but 6H, 12H and custom ones and reach your phone and the chart, not a webhook (Pro and Premium send alerts to a webhook too).

alert(when, "Title", "message") is an alert the script offers. It fires on a bar where when is true, when that bar closes (never part way through a candle, as every Eclipse alert):

alert(math.crossover(fast, slow), "Cross up", "Fast " + math.round(fast, 2) + " crossed above slow")
alert(math.crossunder(fast, slow), "Cross down")
  • Switch it on in the script's settings, on its Alerts tab (the one every indicator has), for the coin and timeframe on the chart. The tab lists each alert() by its title, then a strategy's entries and exits (Long Entry, Long Exit, Short Entry, Short Exit) when the script is one: those need no alert(). A stop or a target that fills is its exit's alert, at the price it filled, and says "Stop" or "Target" (a partial exit says "Close 50%"). Expiration, the alarm's sound and length, and where it is sent (Desktop, Mobile or Both) are the same rows as for every indicator.
  • The title is its name: in quotes, at most 32 characters, on its row, its card in the Alerts popup and the notification. Two with one title are "Cross up" and "Cross up 2". One without is "Alert 3".
  • The message is what the notification says under it, worked out on the bar that fired, so it can carry values ("RSI " + rsi). It is optional.
  • It runs what Update chart put on the chart, with that copy's settings, on the chart and on the server: it reaches your phone with every browser closed. Update chart saves the script as it puts it on the chart, so the alert runs what the chart shows; the Alerts tab says so if that save has not gone through.
  • Like every alert it looks at the newest 1,500 candles of its coin and timeframe. A script whose answer depends on where the history starts (a count from the first bar, p.close[0]) can see something there that it does not see over the chart's longer history.
  • alert() goes at the top level (an if is fine: it fires only on bars where the if ran), not inside a function or a loop. A script can offer 20.
  • A strategy's entry alert has no "Position size" line yet: an alert does not read the script's backtest, as Ceres' reads its own. Deleting a script deletes its alerts.
  • An alert's run has limits, on the chart and on the server alike: 1 second for the whole run, its data.fetch() values included, and at most 5,000,000 items made in arrays, matrices and maps. A run past either stops and fires nothing, and is looked at again when the next candle closes. A typical script takes a few milliseconds over 1,500 candles; what takes longer is a loop that goes round thousands of times on every candle, loops inside loops, functions calling functions many times over, or new large arrays on every candle. A data.fetch() coin must be a market the chart offers (an exchange's coin, a stock, a metal, a market cap index), or the alert waits.

Missing values and colours

  • none is the missing value; none(x) is true when x is missing; replace(x, 0) is x, or 0 when x is missing; fixnone(x) repeats the last value that wasn't missing.
  • Two numbers a hair apart (within a ten-billionth of the larger) are equal to ==, <=, >=, < and >, as they are in Pine: 0.1 + 0.2 == 0.3 is true, and a share worked out as 0.09999999999999998 passes >= 0.1. A price tick is far wider, so prices compare as they always did.
  • A division by zero is none, as in Pine: 10 / 0 is none, never an infinity, so an average or a sum that meets one starts again once the values are there.
  • ln.delete() on a line that is none (not made yet) does nothing, as Pine's line.delete(na) does; anything else on it says it is none. [a, b] = x where x is none makes a and b none.
  • Colours are #rrggbb (or #rrggbbaa). color.hex(#00d79e, 80) is that colour 80% transparent; color.rgb(0, 215, 158); color.gradient(value, low, high, lowColor, highColor); and names like color.red, color.eclipse_green, color.eclipse_purple.

Arrays, matrices and maps

Values a script keeps together and changes in place, as Python's lists and dicts are. Each is made by its own word: array(), matrix() and map(). They hold any kind of value (numbers, text, colours, true / false, and arrays, maps, labels and the rest), so there is no type to name. Kept in a var, one lasts from bar to bar; made by x = …, it starts again each bar.

var closes = array()              // an empty array: array(size = 10, fill = 0) is ten 0s
closes.push(p.close)          // add at the end
if closes.size() > 20:
    closes.shift()                // take the first off: the last 20 closes
newest = closes[-1]               // [ ] reads items as a Python list does:
oldest = closes[0]                // 0 the first, -1 the last (a list's too:
                                  // [x, y] = …, or pair[1] for its second)
closes[0] = oldest * 2            // and sets them
middle = closes.median()
a = array(3, 1, 2)                // an array of these values
for x in a:                       // walks its items
    debug(x)

var counts = map()                // values under keys, like a Python dict
side = if p.close > p.open: "up" else: "down"
counts[side] = replace(counts[side], 0) + 1   // none until a key is put
for k in counts:                  // walks its keys, in the order first put
    debug(k, counts[k])

m = matrix(2, 3, 0)               // 2 rows × 3 columns of 0
m[0, 1] = 5                       // m[row, column] reads and sets one item
product = m.mult(m.transpose())   // matrix maths: det, inv, rank, pow, sum …
  • Each value's functions are called after a dot, a.push(1), and are also the namespace's functions, array.push(a, 1), as in Pine. The Reference lists them under Arrays, Matrices and Maps.
  • Indexes count as Python's: 0 the first, -1 the last. Reading outside the items gives none (as reading a bar before the first does); writing outside them is an error, so add items with push, unshift or insert.
  • A variable holds one by reference: b = a is the same array under two names, and a function given an array changes the caller's (use a.copy() for a separate one). An array can hold arrays: rows[0][1] reads into one.
  • An array on an earlier bar is a.ago(n) ([ ] reads its items): as it stood when that bar ended, a copy, so a var array changed since reads back as it was.
  • [x, y] = a unpacks an array's first items. An empty array, matrix or map is false in an if (as in Python).
  • Statistics (sum, avg, min, max, median, mode, stdev, variance, percentile …) are over the numbers in it, leaving none out. a.percentile(40, nearest = true) is always one of them, the one at that rank rounded up (Pine's array.percentile_nearest_rank).
  • A live tick changes nothing twice: a var array the newest bar pushed to is put back before the bar runs again, so it holds what a run over the closed bars and the newest one once would.
  • At most 100,000 items in an array or a matrix, and 50,000 keys in a map.

Loops and functions

for i in range(1, 11):        // 1 to 10
    total += p.close[-i]  // the last 10 closes, this bar's first
for i in range(3, 10, 2):     // 3, 5, 7, 9
    …
for x in [fast, slow]:
    …
while w < 7:
    w += 2

Counting back starts at 1: as in Python, -0 is 0, so p.close[-i] with i at 0 reads the chart's first candle, not this bar.

break leaves a loop, continue goes on to the next turn.

double(x) => x * 2            // a one-line function

band(src, len, mult = 2) =>   // a function block ends with return
    [mid, upper, lower] = ind.bb(src, len, mult)
    return [upper, lower]

[top, bottom] = band(p.close, 20)

Functions are defined at the top of the script (not inside if or loops), can read the script's variables but not change them, and draw nothing themselves: give back the value and draw it at the top level.

Inside a function, [ ] and .ago() count its calls, not bars (Pine's rule): the function's own values, its settings and what it works out, read at the call before. Called on every bar, that is the bar before, as anywhere. Called only on some bars, or several times in a loop, it is that place's last call:

prev(src) =>
    return src[-2]

if bars.count % 3 == 0:
    x = prev(bars.count)      // on bar 3: 0, on bar 6: 3 (its call before)

The script's own variables count bars, read from a function too (p.close[-2] is always the bar before), and so does each ind. call, which works on the bars it ran on.

Types, methods and enums

A type of your own holds several values together under names, its fields, as Pine's type does. It is made at the top of the script, its fields under it, one a line; a field may have a default, written out:

type Pivot:
    index
    price
    kind = "high"

pv = Pivot(bars.count, p.high)        // its fields in order
low = Pivot(price = p.low, kind = "low")   // or by name; index is none
pv.price = p.low                      // a field is set with =
pv.index += 1                             // and changed with +=, -= …
debug(pv.price, pv.kind)                  // read with a dot
  • A field holds any value (a number, text, an array, another object …), and none until it is set, or its default. A default is a value written out: a number, text, true / false, a colour, a list, none or an enum's choice.
  • Pivot.new(bars.count, p.high) (Pine's way) works too.
  • A variable holds an object, not a copy of it, as it holds an array: after same = pv, both names are one pivot, and changing same.price changes pv.price. pv.copy() makes a separate one with the same fields.
  • Objects go in arrays and maps like any value: pivots.push(Pivot(…)), pivots[-1].price, pivots[0].price = p.low. A field holding an array is called on like one: zone.touches.push(bars.count).
  • Kept in a var, one lasts from bar to bar, and a live tick puts back what the last tick changed in it, as for an array.
  • format(pv) writes it out: Pivot(index = 5, price = 101.2, kind = high). A field of none is none (var last = none, then last.price).
  • CharmScript names no types for fields: float price = 0, Pine's, is price = 0 here.

A method is a function called after a dot on one kind of value, as Pine's method is. Its first value names that kind, then its name; it may change the object's fields, or give back a value:

method moveTo(Pivot pv, newPrice) =>
    pv.price = newPrice
    pv.index = bars.count

method height(Zone z) => z.top - z.bottom

pv.moveTo(p.low)                      // or moveTo(pv, p.low)

A method can be for a type of the script's, or for an array, a matrix, a map, a label, a line, a box, a table or a polyline: method middle(array a) => a[math.floor(a.size() / 2)], then closes.middle(). Several types can each have a method of one name (area for a Box2 and for a Circle); the one for what the value is runs. A method can't have the name of one the kind has already (an array's push). Like a function, it is made at the top of the script and keeps its own memory at each place it is called.

An enum is a fixed set of choices, as Pine's enum is. Each has a name and a title (its name where it is given none):

enum Trend:
    up = "Rising"
    down = "Falling"
    flat

pick = input.enum(Trend.up, "Trend")      // a dropdown: Rising, Falling, flat
t = if p.close > p.open: Trend.up else: Trend.down
if t == pick:
    paint.background(true)
word = match t:
    Trend.up: "Rising"
    else: "Other"
  • Trend.upp is an error before the script runs: a misspelt choice is caught, where a misspelt text in input.string never matches.
  • input.enum(Trend.up, "Trend") is a setting that offers the titles and gives the choice picked; options = [Trend.up, Trend.down] offers only those.
  • A choice is compared with == and != and picked in a match, and format(t) is its title.

Choosing one value of several: match

width = match bandsFrom:                    // Pine's switch
    "Average true range": ind.atr(atrLength)
    "True range": ind.tr()
    else: ind.ema(p.high - p.low, length)

avg = match kind:
    "SMA", "EMA": ind.sma(p.close, 20)  // several values for one choice
    else: ind.wma(p.close, 20)

side = match:                               // nothing after match: conditions
    p.close > p.open: "up"
    p.close < p.open: "down"
    else: "flat"
  • The first choice equal to the value after match gives its value, and else the rest; with no choice taken and no else, it is none. With nothing after match, each choice is a condition and the first one true is taken. The value is worked out once a bar, and no choice past the one taken.
  • As a value (after = or return) each choice is one value on its line. As a statement, a choice holds lines, indented under it or on its own line:
match kind:
    "SMA":
        width = 1
        width += 10
    "EMA": width = 2
    else:
        width = 3
  • match is a word only where it starts a match: a variable can still be called match.

Debugging

debug(a, b, …) writes to the editor's Output tab, with the bar each line came from (if bar.isLast: debug(x) prints once). stop("message") ends the run with that message. The Values tab shows what each line drew on the newest bar, and the Console says when Run added or updated the script on the chart, with the time, and lists every problem in the code with its line (the name Pine’s editor gives it).

A Warning in the Console is a value the script can’t use as written: it still runs, but that value is dropped or read another way. A colour in quotes that isn’t one (color = "blue" draws nothing: write color.blue, or a code like #2962ff), a length under 1 or in quotes (ind.sma(p.close, 0), ind.sma(p.close, "200")), a transparency over 100, a linewidth over 10, text where a number goes, true or false as a line’s value (drawn as 1 and 0). The same lines are underlined as you type. A colour worked out as the script runs (from a text setting, say) is checked when the chart runs it, and said after the code’s own warnings.

Coming from Pine Script

Import from Pine writes a Pine Script out in CharmScript for you: New script ▾ → Import from Pine, paste the script (Pine v5 or v6, and v4's names), and Create script makes a script of yours of it, every comment kept. A Pine script pasted over the whole of a script offers the same (Convert to Charm, then the Charm takes its place: Ctrl+Z gives the Pine back), and so does a .pine file opened with More → Import a file. What it can't write the same way, it says, each with its Pine line, in the popup and then in the script's Console:

  • Not converted: a part CharmScript has no way to write yet (a library, timestamp(), strategy.equity …). The script opens with that line to write by hand.
  • Differs: converted, but it behaves a little differently from Pine (a strategy's trades fill at the close of the bar that signals them; Pine fills them at the next bar's open).
  • Note: something Pine needs that CharmScript doesn't, left out (max_labels_count, a plot's own editable).

The Library in these docs holds 50 classic indicators and strategies converted so, with no hand edits, each with the Pine it came from: New script ▾ → Start from an example → See more opens it.

Writing it by hand, these are what Pine's words are here:

PineCharmScript
//@version=5 · indicator("N", overlay = true)CharmScript 1.0 · script("N", tool = indicator, chart = main)
indicator("N", shorttitle = "S")script("N", legendtitle = "S")
input.int(14, minval = 1, maxval = 50)input.int(14, min = 1, max = 50)
close high hl2 bar_indexp.close p.high p.hl2 bars.count
close[1] (the bar before) · close[5]p.close[-2] · p.close[-6] (p.close[1] is the chart's 2nd candle)
ta.highestbars(10) (0 = this bar)math.highestbars(10) (-1 = this bar)
ta.ema ta.rsi ta.atr …ind.ema ind.rsi ind.atr …
ta.highest ta.crossover ta.barssince ta.valuewhen …math.highest math.crossover math.barssince math.valuewhen …
plot · plotshape · plotchar · hlineplot.line (or plot.column …) · plot.shape · plot.char · plot.level
location = location.belowbar · label.new(…, yloc = yloc.abovebar) · hline(…, linestyle = hline.style_dashed) · plot(…, linestyle = plot.linestyle_dashed)y = y.belowbar · plot.label(…, yloc = y.abovebar) · plot.level(…, style = line.dashed) · plot.line(…, linestyle = line.dashed)
plot(…, display = display.all - display.price_scale) · display = display.paneplot.line(…, pricelabel = false): the line, with no pill on the price scale (Import from Pine writes it so)
fill · bgcolorpaint.fill · paint.background
plotcandle · barcolorplot.candles · paint.candles
the Style tab (a plot's checkbox, colour and line style) · input(…, tooltip = "…")the settings' Appearance tab, a row per drawing, with tooltip = "…" on the drawing for its ? · the same on an input
shape.labelup · size.small · size = 16 (points, Pine v6)style = style.labelup · size = 2 (1 to 4) · the nearest name, size = "large" (about 8 points is tiny, 10 small, 12 to 14 normal, 20 large)
color.new(c, 80) · color.from_gradientcolor.hex(c, 80) · color.gradient
na · nz(x, 0) · na(x) · fixnan(x)none · replace(x, 0) · none(x) · fixnone(x)
barstate.islast · syminfo.ticker · timeframe.periodbar.isLast · chart.symbol · chart.timeframe
if x + indented lines, f(x) => + indented linesthe same, with : after the if and return in the function
c = up ? #00d79e : #ff5252c = if up: #00d79e else: #ff5252 (Pine's ? : works too)
for i = 0 to 9for i in range(10):
x = switch kind + "A" => 1 · => 2x = match kind: + "A": 1 · else: 2
x = 0 (new) · x := 1 (change) · var x = 0x = 0 · x = 1 · var x = 0
const int n = 5n = 5 (const n = 5 works too, and here can also hold a setting or a per-bar value)
log.info("{0}", x) · runtime.error("m")debug(x) · stop("m")
alertcondition(c, "T", "M")alert(c, "T", "M")
strategy.entry("L", strategy.long)strategy.enter.long(when, "L")
default_qty_type = strategy.cash · strategy.percent_of_equitystrategy.enter.long(when, cash = 100) · strategy.enter.long(when, percent = 25)
strategy.close("L", qty_percent = 50)strategy.exit.long(when, percent = 50)
strategy.exit("X", "L", stop = s, limit = l)strategy.exit.long(sl = s, tp = l, type = price) (or sl = 2, tp = 4, in percent)
strategy.position_size > 0 · < 0 · == 0 · strategy.position_avg_pricestrategy.isLong · strategy.isShort · strategy.isFlat · strategy.entryPrice
strategy("N", initial_capital = 10000, commission_type = strategy.commission.percent, commission_value = 0.05)script("N", tool = strategy, capital = 10000, fee = 0.05)
default_qty_type = strategy.percent_of_equity, default_qty_value = 100an entry with no size, and compounding = 100
strategy("N", overlay = false) (its trades marked on the candles, its plots in a pane)script("N", tool = strategy, chart = oscillator), and chart = main on each strategy call: strategy.enter.long(when, "L", chart = main)
timeframe.change("D") · input.timeframe("D")bar.isFirstOf("1D") · input.timeframe("1D")
timestamp("America/New_York", 2024, 1, 15, 9, 30) · hour(time, "America/New_York") · str.format_time(time, "HH:mm")time.of(2024, 1, 15, 9, 30, zone = "America/New_York") · time.hour(bar.time, "America/New_York") · time.format(bar.time, "HH:mm")
time_close · time("D") · time_close("D") · last_bar_time · timenowbar.closeTime · bar.openTimeOf("D") · bar.closeTimeOf("D") · bars.lastTime · time.now
input.time(timestamp("2024-01-15"), "From") · barstate.islastconfirmedhistoryinput.time("2024-01-15 00:00", "From") · bar.isLastClosed
timeframe.in_seconds() · timeframe.in_seconds("D") · timeframe.from_seconds(s) · timeframe.multiplierchart.seconds · chart.secondsOf("D") · chart.timeframeOf(s) · chart.multiplier
chart.fg_color · chart.bg_color · chart.is_standardchart.fgColor · chart.bgColor · chart.isStandard
weekofyear · time_tradingday · syminfo.session · array.percentile_nearest_rank(a, 40)bar.week · bar.openTimeOf("D") · "regular" · a.percentile(40, nearest = true)
syminfo.prefix · syminfo.timezone · syminfo.type · syminfo.pointvaluechart.exchange · chart.timezone · chart.assetType · chart.pointValue
int(x) · ta.max(high) · ta.min(low) · ta.percentile_nearest_rank(x, 20, 50)math.trunc(x) · math.cummax(p.high) · math.cummin(p.low) · math.percentile(x, 20, 50, nearest = true)
str.trim(s) · str.split(s, ",") · str.pos(s, "x") · str.repeat(s, 3) · str.replace(s, "a", "b")the same
not na(time(timeframe.period, "0930-1600", "America/New_York")) · input.session("0930-1600")bar.inSession("0930-1600", "America/New_York") · input.session("0930-1600")
fill(p1, p2, 100, 80, top_color = a, bottom_color = b)paint.fill(p1, p2, top = 100, bottom = 80, top_color = a, bottom_color = b)
plotcandle(…, wickcolor = w, bordercolor = b) · plot(…, style = plot.style_linebr)plot.candles(…, wickcolor = w, bordercolor = b) · plot.line(…) (a line leaves a gap where a value is missing)
syminfo.mintick · str.tostring(x, format.mintick) · ta.pvtchart.tick · format(x, "tick") · ind.pvt
request.security(syminfo.tickerid, "1D", ta.ema(close, 50)) · request.security(…, high[1], lookahead = barmerge.lookahead_on) · syminfo.tickeriddata.fetch(chart.asset, "1D", ind.ema(p.close, 50)) · data.fetch(chart.asset, "1D", p.high[-2], forming = true) · chart.asset
varip ticks = 0 · plotbar(o, h, l, c) · plotarrow(close - open)the same varip · plot.bars(o, h, l, c) · plot.arrow(p.close - p.open)
polyline.new(points, curved = true) · chart.point.from_index(bar_index, high)plot.polyline(points, curved = true) · [bars.count, p.high]
type Pivot with int index · float price = na under it · Pivot.new(bar_index, high) · p.price := lowtype Pivot: with index · price under it · Pivot(bars.count, p.high) (or Pivot.new(…)) · pv.price = p.low
method moveTo(Pivot this, float newPrice) =>method moveTo(Pivot pv, newPrice) =>
strategy("Scale in", pyramiding = 3) · strategy.opentradesscript("Scale in", tool = strategy, pyramiding = 3) · strategy.openTrades
strategy.equity · strategy.initial_capital · strategy.netprofit · strategy.openprofit · strategy.netprofit_percentstrategy.equity · strategy.initialCapital · strategy.netProfit · strategy.openProfit · strategy.roi
strategy.closedtrades · strategy.wintrades · strategy.losstrades · strategy.grossprofit · strategy.grossloss · strategy.max_drawdown_percentstrategy.totalTrades · strategy.wins · strategy.losses · strategy.grossProfit · strategy.grossLoss · strategy.maxDrawdown
strategy.entry(…, oca_name = "range", oca_type = strategy.oca.cancel) · strategy.close_all() · input.symbol("BINANCE:ETHUSDT")strategy.enter.long(…, oca = "range") · strategy.exit.long(when) and strategy.exit.short(when) · input.string("BINANCE:ETHUSDT")
enum Trend with up = "Rising" under it · input.enum(Trend.up, "Trend")enum Trend: with up = "Rising" under it · the same input.enum(Trend.up, "Trend")
strategy.entry("L", strategy.long, limit = l, stop = s, qty = 1) · strategy.cancel("L") · strategy.cancel_all()strategy.enter.long(when, "L", limit = l, stop = s, qty = 1) · strategy.cancel("L") · strategy.cancelAll()
strategy.exit("T", "L", trail_points = p, trail_offset = o) (ticks)strategy.exit.long(trail = 2, trailstart = 1) (percents; type = price for a distance and a price)
strategy.risk.max_intraday_loss(2, strategy.percent_of_equity) · strategy.risk.max_intraday_loss(500, strategy.cash)strategy.risk.maxDayLoss(percent = 2) · strategy.risk.maxDayLoss(cash = 500)
label.new(bar_index, high, "H", style = label.style_label_down)plot.label(bars.count, p.high, "H", style = style.labeldown)
line.new(…, extend = extend.right, style = line.style_dashed) · xloc = xloc.bar_timeplot.segment(…, extend = "right", style = line.dashed) · xloc = "time"
box.new(…) · linefill.new(l1, l2, c)plot.box(…) · plot.linefill(l1, l2, c)
table.new(position.top_right, 2, 3) · table.cell(t, 0, 0, "x", text_halign = text.align_left)plot.table("top_right", 2, 3) · t.cell(0, 0, "x", text_halign = "left")
indicator("N", max_labels_count = 500)nothing to write: a script keeps 500 of each (the editor says max_labels_count isn't needed)
label.set_xy(lbl, x, y) · label.set_text(lbl, "t") · label.get_text(lbl) · line.get_price(ln, x)lbl.xy(x, y) · lbl.text("t") · lbl.text() · ln.price_at(x)
str.tostring(x, "#.##")format(x, "#.##") (also format(x, 2) and Python's format(x, ".2f"))
array.new<float>(10, 0) · array.new_float(10) · array.from(1, 2, 3)array(size = 10, fill = 0) · array(size = 10) · array(1, 2, 3) (they hold any value)
matrix.new<float>(2, 3, 0) · map.new<string, float>()matrix(2, 3, 0) · map()
array.get(a, 0) · array.set(a, 0, x) · array.get(a, array.size(a) - 1)a[0] · a[0] = x · a[-1] (a.get(0) and array.get(a, 0) work too)
matrix.get(m, 1, 2) · map.get(m, "k")m[1, 2] · m["k"]
for x in a · for [i, x] in afor x in a: · for i in range(a.size()): and a[i]

The editor recognises the Pine names and says what each is called here.

Not there yet

forming = true on another coin's candles. An alert runs on its coin's newest 1,500 candles (and data.fetch() on the newest 1,500 of each set it reads). Of order flow, the volume at each price inside a candle (Pine's request.footprint), the order book, the Funding pane's Predicted rate and open interest in dollars (multiply by p.close) are not there. A strategy's trades fill at the close of the bar that signals them, where Pine's fill at the next bar's open unless told otherwise, so a strategy brought from Pine gives numbers here a little different from Pine's. Pine's plain line joins across a missing value; a CharmScript line leaves a gap. A label's or a table cell's tooltip (Pine's tooltip = on them) is not there. Pine's money drawdown (strategy.max_drawdown) is not there: strategy.maxDrawdown is the panel's, in percent. Of Pine's other strategy.risk rules, only the day's loss limit is here (strategy.risk.maxDayLoss). Pine's slippage is in ticks, which the converter leaves out (set Slippage % on the Strategy tab). A script's alerts can't be made from + New alert: they are switched on from the script's own settings. Enigma does not tune a strategy that makes labels, lines, boxes or tables (they would show its own settings, not the tuned ones).

Limits

A script can have 256 inputs and 64 drawings (lines, shapes, levels, fills, backgrounds and strategy markers), read 40 other timeframes and coins with data.fetch() (any number of values from one coin and timeframe count once) and 16 sets of order flow (a dataset, a coin and a timeframe each: longs and shorts are one set, buys and sells another), and keeps its newest 500 labels, 500 lines, 100 polylines, 500 boxes and 20 tables (each 100 columns and 500 rows at most). An array or a matrix holds at most 100,000 items, a map 50,000 keys. A loop stops after 100,000 turns on one bar, and a run is stopped after 3 seconds (a full chart of 25,000 bars normally takes well under 200 ms; a live tick re-runs one bar).

Saving and sharing

Your scripts are saved to your account: they are there on every computer you sign in on, and nobody else sees them. There is no Save button: what you type is kept by itself a moment after you stop typing (in this browser at once, and in your account a few seconds later), so closing the editor, reloading the page or carrying on from another computer loses nothing, and it changes nothing on the chart. Update chart puts it on the chart and saves it: the chart, its strategy's backtest and its alerts all run it from then on. Code with an error is not put on the chart (it keeps the last version that worked). A script counts toward your plan's indicators on a chart, as any indicator does. A script is named by its own script("Name", …) line: change the name there and the list and the editor show the new one at once. More → History brings back an older version (each Update chart that changed the code is one). If the script was saved somewhere else since your change (another tab or computer), a bar asks which one to keep. Export saves a script as a .charm file (Import also opens the .ecode and .els files saved while the language was called EclipseCode and EclipseLS).

New to the editor? The arrow beside Docs opens a Walkthrough that shows each part of it in turn, as the chart's own walkthrough does.

The editor's left column has a search box and + (a new indicator or strategy, an example, or a script from Pine), then a switch between two sides. Drafts is your working area: scripts kept as you type, put on the chart by Update chart, up to 200 of them. Files are your own copies, in folders, and change only when you save them: Save to Files (on the toolbar, left of Docs) saves the open script into the folder you picked, with its name ready to change, and a script dragged from Drafts onto a folder, or onto the Files tab, is saved there. Saving under a name already in that folder asks before overwriting it. Once a script is opened from a file, or saved to one, the button reads Save changes and saves straight over that file (greyed while there is nothing new to save); Ctrl+S does the same, and a dot on the script's tab shows changes not saved to its file yet. Make folders with the Add folder button over the list (they go inside one another; each folder's arrow opens and closes it), and rename or delete one from its row; while a folder is being renamed, the dot beside its name gives it a colour of its own (or type a colour's code). Drag a file onto a folder to move it there, or onto the list's empty space to take it out of its folder. Over Drafts sit + (a new empty indicator, opened), its sort, Import a file, and a bin that deletes every script in it, after asking; over Files, + (a new empty indicator file in the folder picked: type its name, press Enter, and it opens), Add folder and Collapse all. Click a file to open it in Drafts, its code exactly as you saved it; the chart changes only when you click Update chart. The search box narrows both sides. A file saved on another computer since opens as it was saved there. While Automatically save changes for files is on (More → Settings), what you type in a file's script is in your account a few seconds later too, so another computer shows it; while it is off, a file's typing stays in this browser until you save it.

Every script you open gets a tab over the code, beside the one in front, so several can be open at once. The + after the last tab starts a new indicator in a tab of its own at the end. Click a tab to bring its script forward: it is as you left it, its code, cursor, undo and scroll included. Close a tab with its ×, a middle click, or its right-click menu (Close, Close others, Close to the right, Close all); nothing is lost, since the code is kept as you type and is there when you open the script again. Closing a tab whose file has changes not saved there asks first: Save, Don't save or Cancel. Drag tabs along the row to put them in order, drop a script from Drafts on the row to open it there, or drop a tab on a Files folder to save it there. The tabs you had open come back with the page.

More → Settings holds the editor's settings, kept in your account for every device: Automatically save changes for files (off: files are saved when you choose to; on: a file is saved a second after you stop typing, and as its tab closes), Ask before closing unsaved files, the code's size, wrapping long lines, suggestions while typing (Ctrl+Space shows them either way), closing brackets and quotes, and lighting the cursor's line. A change shows at once; Cancel puts back what the box opened with, Reset puts back the defaults, and Apply closes it.

Examples

The editor's own examples (New script → Start from an example opens each as a script of yours). Copy one into a new script, or start from it in the editor.

On the candles

Averages first, then the other indicators that draw over the price.

Moving-average ribbon

Four EMAs, shaded green or red by trend.

CharmScript 1.0
script("Moving-average ribbon", tool = indicator, chart = main)

// ====================================================================
// MOVING-AVERAGE RIBBON
// Four EMAs (8, 21, 55 and 100 bars) over the candles as one ribbon:
// green while the fastest is above the slowest (an uptrend), red while
// it is below.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
upColor = input.color(#00d79e, "Up colour")
downColor = input.color(#ff5252, "Down colour")

// ---- 2. Calculation ------------------------------------------------
// Four exponential moving averages, fastest to slowest.
e1 = ind.ema(p.close, 8)
e2 = ind.ema(p.close, 21)
e3 = ind.ema(p.close, 55)
e4 = ind.ema(p.close, 100)

// The trend, as a colour: up while the fastest EMA is above the slowest.
col = if e1 > e4: upColor else: downColor

// ---- 3. Drawing ----------------------------------------------------
// The fastest line is solid and the slower ones fade (color.hex(c, 30)
// is c at 30% transparency). p1 and p4 keep the first and last lines,
// so paint.fill() can shade the ribbon between them.
p1 = plot.line(e1, "EMA 8", color = col, linewidth = 2)
plot.line(e2, "EMA 21", color = color.hex(col, 30))
plot.line(e3, "EMA 55", color = color.hex(col, 50))
p4 = plot.line(e4, "EMA 100", color = color.hex(col, 70))
paint.fill(p1, p4, color = color.hex(col, 88))

Moving averages by hand

SMA, WMA, EMA and Hull, each written out by hand.

CharmScript 1.0
script("Moving averages by hand", tool = indicator, chart = main)

// ====================================================================
// MOVING AVERAGES BY HAND
// Four moving averages written out step by step, to show how each one
// works. Each draws exactly the same line as its built-in: ind.sma,
// ind.wma, ind.ema and ind.hma.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", min = 2)

// ---- 2. The averages -----------------------------------------------
// Simple (SMA): every one of the last length bars counts the same.
my_sma(prices, length) =>
    sum = 0.0
    for i in range(length):           // i = 0 ... length - 1
        sum = sum + prices[-1 - i]    // [-1] is this bar, [-2] the one before, ...
    return sum / length

// Weighted (WMA): this bar counts length times, the one before
// length - 1 times, down to the oldest, which counts once.
my_wma(prices, length) =>
    sum = 0.0
    weights = 0.0
    for i in range(length):
        weight = length - i
        sum = sum + prices[-1 - i] * weight
        weights = weights + weight
    return sum / weights

// Exponential (EMA): each bar moves the average part of the way
// (alpha) towards the price. var keeps its value from one bar to the
// next: that is the average's memory.
my_ema(prices, length) =>
    var ema = none
    alpha = 2 / (length + 1)
    if none(ema):
        ema = prices                  // the first bar starts it off
    else:
        ema = alpha * prices + (1 - alpha) * ema
    return ema

// Hull (HMA): a WMA of (2 x the half-length WMA - the full WMA), over
// the square root of length bars. It turns quickly and stays smooth.
my_hma(prices, length) =>
    half = my_wma(prices, math.floor(length / 2))
    full = my_wma(prices, length)
    return my_wma(2 * half - full, math.floor(math.sqrt(length)))

// ---- 3. Drawing ----------------------------------------------------
// All four over the candles, each in its own colour.
plot.line(my_sma(p.close, length), "SMA", color = #a396ff, linewidth = 2)
plot.line(my_wma(p.close, length), "WMA", color = #fbbf24)
plot.line(my_ema(p.close, length), "EMA", color = #00d79e)
plot.line(my_hma(p.close, length), "Hull", color = #ff5252)

Bollinger squeeze

Bollinger Bands, shaded when they are at their tightest.

CharmScript 1.0
script("Bollinger squeeze", tool = indicator, chart = main)

// ====================================================================
// BOLLINGER SQUEEZE
// Bollinger Bands: an average of the price with a band a few standard
// deviations either side. The background turns amber while the bands
// are the narrowest they have been over the lookback: a "squeeze".
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", min = 2)
mult = input.float(2.0, "Deviations", min = 0.5, step = 0.1)
lookback = input.int(120, "Squeeze lookback", min = 10)

// ---- 2. Calculation ------------------------------------------------
// ind.bb gives back three values at once: the middle line and the
// upper and lower bands.
[mid, upper, lower] = ind.bb(p.close, length, mult)

// How wide the bands are, as a share of the price, and whether that is
// the narrowest of the last lookback bars.
width = (upper - lower) / mid
squeeze = width <= math.lowest(width, lookback)

// ---- 3. Drawing ----------------------------------------------------
// u and l keep the band lines, so paint.fill() can shade between
// them. The basis is dashed (linestyle can also be "dotted"), and the
// background turns amber during a squeeze.
u = plot.line(upper, "Upper", color = color.hex(#a396ff, 40))
plot.line(mid, "Basis", color = color.hex(#a396ff, 60), linestyle = line.dashed)
l = plot.line(lower, "Lower", color = color.hex(#a396ff, 40))
paint.fill(u, l, color = color.hex(#a396ff, 92))
paint.background(squeeze, color.hex(#fbbf24, 88))

Supertrend

Supertrend line with a marker wherever it flips.

CharmScript 1.0
script("Supertrend", tool = indicator, chart = main)

// ====================================================================
// SUPERTREND
// A trailing line that sits below the price in an uptrend and above it
// in a downtrend, a few ATRs (average true ranges) away. A label marks
// each bar where the trend flips.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// Factor: how many ATRs the line sits from the price.
// ATR length: how many bars the ATR averages over.
factor = input.float(3.0, "Factor", min = 0.5, step = 0.1)
atrLength = input.int(10, "ATR length", min = 1)

// ---- 2. Calculation ------------------------------------------------
// ind.supertrend gives back two values at once: the line, and its
// direction (below 0 while the trend is up).
[st, dir] = ind.supertrend(factor, atrLength)
up = dir < 0

// ---- 3. Drawing ----------------------------------------------------
// A stepped line: green in an uptrend, red in a downtrend.
plot.step(st, "Supertrend", color = if up: #00d79e else: #ff5252, linewidth = 2)

// A label where the trend flips: up on this bar but not on the one
// before (up[-2] is the bar before; up[-1], or just up, is this bar).
plot.shape(up and not up[-2], "Turned up", style = style.labelup, y = y.belowbar, color = #00d79e, text = "Up")
plot.shape(not up and up[-2], "Turned down", style = style.labeldown, y = y.abovebar, color = #ff5252, text = "Down")

Pivot points

Marks swing highs and lows with their price.

CharmScript 1.0
script("Pivot points", tool = indicator, chart = main)

// ====================================================================
// PIVOT POINTS
// Marks swing highs and lows with their price. A pivot high is a high
// the bars either side of it stay below; a pivot low, a low the bars
// either side stay above.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// How many bars either side must stay below a high (above a low).
left = input.int(5, "Bars to the left", min = 1)
right = input.int(5, "Bars to the right", min = 1)

// ---- 2. Calculation ------------------------------------------------
// A pivot is only known once the bars to its right have closed, so
// these give its price that many bars later, and none on other bars.
ph = ind.pivothigh(left, right)
pl = ind.pivotlow(left, right)

// ---- 3. Drawing ----------------------------------------------------
// A label with the price (format writes it with up to two
// decimals). offset = -right moves each label back onto the pivot's
// own bar.
plot.shape(ph, "Pivot high", style = style.labeldown, y = y.absolute, color = #ff5252, text = format(ph, "#.##"), offset = -right)
plot.shape(pl, "Pivot low", style = style.labelup, y = y.absolute, color = #00d79e, text = format(pl, "#.##"), offset = -right)

Swing highs and lows

Labels each swing as a higher or lower high or low, joined by lines: labels, lines and arrays.

CharmScript 1.0
script("Swing highs and lows", tool = indicator, chart = main, tooltip = "Labels each swing high and low as higher or lower than the one before, and joins each to the one before with a line")

// ====================================================================
// SWING HIGHS AND LOWS
// Finds each swing high and low (a pivot), labels it HH or LH (a higher
// or a lower high than the one before) and HL or LL, and joins it to
// the one before with a line. The pivots found so far are kept in
// arrays, which a var keeps from bar to bar.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
left = input.int(5, "Bars to the left", min = 1)
right = input.int(5, "Bars to the right", min = 1)
highColor = input.color(#ff5252, "Swing high colour")
lowColor = input.color(#00d79e, "Swing low colour")

// ---- 2. Calculation ------------------------------------------------
// A pivot is only known once the bars to its right have closed, so
// these give its price that many bars later (none on other bars), and
// its own bar is that many bars back. bars.count is this bar's number,
// the x every label and line is placed by.
ph = ind.pivothigh(left, right)
pl = ind.pivotlow(left, right)
pivotBar = bars.count - right

// Each array's newest item is its last: highs[-1] is the latest swing
// high's price, highBars[-1] its bar.
var highs = array()
var highBars = array()
var lows = array()
var lowBars = array()

// ---- 3. Drawing ----------------------------------------------------
// plot.label(x, y, text) puts a label on bar x at price y; plot.segment(x1,
// y1, x2, y2) joins two points. The chart keeps a script's newest 500 of
// each, so the oldest swings drop off as new ones are found.
if not none(ph):
    higher = highs.size() > 0 and ph > highs[-1]
    plot.label(pivotBar, ph, if higher: "HH" else: "LH", color = highColor, style = style.labeldown, size = 1)
    if highs.size() > 0:
        plot.segment(highBars[-1], highs[-1], pivotBar, ph, color = color.hex(highColor, 40))
    highs.push(ph)
    highBars.push(pivotBar)
if not none(pl):
    lower = lows.size() > 0 and pl < lows[-1]
    plot.label(pivotBar, pl, if lower: "LL" else: "HL", color = lowColor, style = style.labelup, size = 1)
    if lows.size() > 0:
        plot.segment(lowBars[-1], lows[-1], pivotBar, pl, color = color.hex(lowColor, 40))
    lows.push(pl)
    lowBars.push(pivotBar)

Range box

A box around the high and low of the last bars, its range written inside: a box moved every bar.

CharmScript 1.0
script("Range box", tool = indicator, chart = main, tooltip = "A box around the highest high and the lowest low of the last bars, with the range written inside, moving with each bar")

// ====================================================================
// RANGE BOX
// A box around the highest high and the lowest low of the last few
// bars, carried five bars to the right, with the range written inside
// it. One box, made once and moved on every bar.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(30, "Bars", min = 2, max = 500)
boxColor = input.color(#a396ff, "Colour")

// ---- 2. Calculation ------------------------------------------------
top = math.highest(p.high, length)
bottom = math.lowest(p.low, length)
rangePct = (top - bottom) / bottom * 100

// ---- 3. Drawing ----------------------------------------------------
// var makes the box once; every bar moves it, and the chart shows where
// the newest bar left it. Its corners are bars and prices: bars.count
// is this bar's number, bars.count - length + 1 the first of the last
// length bars, and bars.count + 5 five bars still to come.
var b = plot.box(0, 0, 0, 0, border_color = boxColor, bgcolor = color.hex(boxColor, 88), text_color = boxColor, text_valign = "top")
b.lefttop(bars.count - length + 1, top)
b.rightbottom(bars.count + 5, bottom)
b.text("Range " + format(rangePct, "#.##") + "%")

Stats table

A table over the candles: RSI, ATR, volume and trend for the latest bar.

CharmScript 1.0
script("Stats table", tool = indicator, chart = main, tooltip = "A table over the candles with the RSI, the ATR as a share of the price, the volume against its average and the trend")

// ====================================================================
// STATS TABLE
// A table in a corner of the chart, over the candles, with a few
// numbers about the latest bar: the RSI, the ATR as a share of the
// price, the volume against its average, and whether the close is
// above or below a long average.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
place = input.string("top_right", "Position", options = ["top_left", "top_right", "bottom_left", "bottom_right"])
trendLength = input.int(200, "Trend average", min = 10)

// ---- 2. Calculation ------------------------------------------------
rsi = ind.rsi(p.close, 14)
atrPct = ind.atr(14) / p.close * 100
volRatio = p.volume / ind.sma(p.volume, 20)
trend = ind.ema(p.close, trendLength)

// ---- 3. Drawing ----------------------------------------------------
// A table is made once (var keeps it from bar to bar) and filled on the
// newest bar, which is the only one it shows. Its columns and rows
// count from 0, like an array's items. plot.table(...) gives the table
// back, and t.cell(...) is table.cell(t, ...): a value's own functions
// can be called after a dot.
var t = plot.table(place, 2, 5, bgcolor = color.hex(#131722, 15), border_color = color.hex(#787b86, 60), border_width = 1)
if bar.isLast:
    t.cell(0, 0, "Latest bar", text_color = #a396ff)
    t.merge_cells(0, 0, 1, 0)
    t.cell(0, 1, "RSI 14")
    t.cell(1, 1, format(rsi, "#.0"), text_color = if rsi > 70: #ff5252 elif rsi < 30: #00d79e else: #d1d4dc)
    t.cell(0, 2, "ATR 14")
    t.cell(1, 2, format(atrPct, "#.00") + "%")
    t.cell(0, 3, "Volume")
    t.cell(1, 3, format(volRatio, "#.0") + "× avg", text_color = if volRatio > 2: #fbbf24 else: #d1d4dc)
    t.cell(0, 4, "Trend")
    t.cell(1, 4, if p.close > trend: "Above EMA " + trendLength else: "Below EMA " + trendLength,
        text_color = if p.close > trend: #00d79e else: #ff5252)

Returns by weekday

The average change of each day of the week, kept in maps and shown in a table.

CharmScript 1.0
script("Returns by weekday", tool = indicator, chart = main, history = all, tooltip = "How the price moved on each day of the week on average, over the whole history, in a table")

// ====================================================================
// RETURNS BY WEEKDAY
// How the price has moved on each day of the week on average, over the
// whole history (history = all runs it from the first candle), kept in
// maps under the day's name and shown in a table. Best on a daily chart.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
place = input.string("bottom_right", "Position", options = ["top_left", "top_right", "bottom_left", "bottom_right"])

// ---- 2. Calculation ------------------------------------------------
// A map keeps values under keys, like a Python dict: total[day] reads
// one (none while there is none) and total[day] = value puts one.
names = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
day = names[bar.weekday - 1]
change = (p.close - p.open) / p.open * 100
var total = map()
var count = map()
if bar.isConfirmed:
    total[day] = replace(total[day], 0) + change
    count[day] = replace(count[day], 0) + 1

// ---- 3. Drawing ----------------------------------------------------
// One row a day, filled on the newest bar. "for name in names" walks
// the array's items in order.
var t = plot.table(place, 3, 8, bgcolor = color.hex(#131722, 15), border_color = color.hex(#787b86, 70), border_width = 1)
if bar.isLast:
    t.cell(0, 0, "Day", text_color = #a396ff)
    t.cell(1, 0, "Average", text_color = #a396ff)
    t.cell(2, 0, "Bars", text_color = #a396ff)
    row = 1
    for name in names:
        if count.contains(name):
            avg = total[name] / count[name]
            t.cell(0, row, name)
            t.cell(1, row, format(avg, "#.00") + "%", text_color = if avg >= 0: #00d79e else: #ff5252)
            t.cell(2, row, format(count[name]))
            row += 1

Up and down odds

How often an up bar followed an up or a down bar, counted in a matrix, shown in a table.

CharmScript 1.0
script("Up and down odds", tool = indicator, chart = main, history = all, tooltip = "How often an up or a down bar came next after an up bar and after a down bar, over the whole history")

// ====================================================================
// UP AND DOWN ODDS
// Counts, over the whole history, which kind of bar came after each up
// bar and each down bar, in a 2 × 2 matrix (row: the bar before,
// column: the bar after), and shows the odds in a table.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
place = input.string("bottom_left", "Position", options = ["top_left", "top_right", "bottom_left", "bottom_right"])

// ---- 2. Calculation ------------------------------------------------
// counts[row, column] reads and sets one item of a matrix. Row 0 is
// after an up bar and row 1 after a down bar; column 0 is an up bar
// next and column 1 a down bar.
var counts = matrix(2, 2, 0)
side = if p.close >= p.open: 0 else: 1
if bar.isConfirmed and not none(p.close[-2]):
    before = if p.close[-2] >= p.open[-2]: 0 else: 1
    counts[before, side] += 1

// A row's odds: its count in that column against the row's whole count.
odds(row, col) => counts[row, col] / math.max(1, counts[row, 0] + counts[row, 1]) * 100

// ---- 3. Drawing ----------------------------------------------------
var t = plot.table(place, 3, 3, bgcolor = color.hex(#131722, 15), border_color = color.hex(#787b86, 70), border_width = 1)
if bar.isLast:
    t.cell(0, 0, "After", text_color = #a396ff)
    t.cell(1, 0, "Up next", text_color = #00d79e)
    t.cell(2, 0, "Down next", text_color = #ff5252)
    t.cell(0, 1, "an up bar")
    t.cell(0, 2, "a down bar")
    for r in range(2):
        for c in range(2):
            t.cell(c + 1, r + 1, format(odds(r, c), "#.0") + "%")

Appearance rows

Every kind of row a script gets in its settings, with a tooltip on each.

CharmScript 1.0
script("Appearance rows", tool = indicator, chart = main, legendtitle = "Rows", tooltip = "An example of every kind of row a script gets on the Appearance tab of its settings\n- Each row's ? is that drawing's own tooltip\n- Reset puts every row back as the code draws it")

// ====================================================================
// APPEARANCE ROWS
// Every drawing below becomes ONE ROW on the Appearance tab of this
// script's settings (the gear on its row in Tools): a box that shows
// or hides it, a colour box where its colour is an input.color, and a
// dropdown for its look. What the code says is where a row starts;
// what is picked on the row is kept with the chart, until Reset.
// tooltip = "..." is the text behind the ? on a row.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// These are the General tab. tooltip = "..." is the ? beside each.
length = input.int(20, "Length", min = 2, max = 400, tooltip = "How many bars the average and the bands look back over")
mult = input.float(2.0, "Band width", min = 0.5, max = 5, step = 0.1, tooltip = "How many standard deviations the bands sit from the average")

// A colour a drawing wears is that drawing's colour box on its own
// row, so a colour has no row on the General tab.
upColor = input.color(#00d79e, "Up colour")
downColor = input.color(#6a5ebc, "Down colour")
bandColor = input.color(#a396ff, "Band colour")

// ---- 2. Calculation ------------------------------------------------
[mid, upper, lower] = ind.bb(p.close, length, mult)
rising = mid > mid[-2]
momentum = ind.rsi(p.close, 14) - 50

// ---- 3. Drawing: one row each --------------------------------------
// A LINE. Its row's dropdown: Line, Dashed, Dotted (and Step line,
// Area, Columns, Histogram, Circles) and a thickness of 1 to 4.
// Coloured by two settings, its row has two colour boxes.
plot.line(mid, "Average", color = if rising: upColor else: downColor, linewidth = 2,
    tooltip = "The moving average, in the up colour while it rises")

// linestyle and linewidth are where a row starts.
top = plot.line(upper, "Upper band", color = bandColor, linestyle = line.dashed, linewidth = 1,
    tooltip = "The average plus the band width")
bottom = plot.line(lower, "Lower band", color = bandColor, linestyle = line.dashed, linewidth = 1,
    tooltip = "The average minus the band width")

// A FILL and a BACKGROUND: a box each. Their title names the row.
paint.fill(top, bottom, color.hex(bandColor, 92), "Band shading",
    tooltip = "The shading between the two bands")
paint.background(p.close > upper, color.hex(upColor, 90), "Breakout tint",
    tooltip = "Tints the bars that close above the upper band")

// A LABEL. Its row's dropdown: Label up, Label down, Box, Text only,
// Arrow up, Arrow down, Circle, Diamond, and a size of 1 to 4.
// style is the shape it starts as: "labelup", "labeldown", "box" (a
// label with no pointer), "text" (the words alone), "triangleup",
// "triangledown", "circle", "diamond".
plot.shape(math.crossover(p.close, upper), "Breakout", style = style.labelup, y = y.belowbar, text = "Break", color = upColor, size = 2,
    tooltip = "A close back above the upper band")
plot.shape(math.crossunder(p.close, lower), "Breakdown", style = style.box, y = y.abovebar, text = "Drop", color = downColor, size = 2,
    tooltip = "A close back below the lower band")

// A SERIES in a pane of its own. Its row's dropdown is the same list:
// here it starts as Columns.
plot.column(momentum, "Momentum", chart = oscillator, color = if momentum >= 0: upColor else: downColor,
    tooltip = "RSI minus 50: above zero, the last 14 bars rose more than they fell")

// A LEVEL. Its row's dropdown: Line, Dashed, Dotted and a thickness.
plot.level(0, "Zero", chart = oscillator, color = #787b86, style = line.dotted,
    tooltip = "The middle of the momentum pane")

In a pane of their own

Oscillators: each draws in its own pane under the candles.

RSI with bands

RSI in its own pane, with overbought / oversold levels.

CharmScript 1.0
script("RSI with bands", tool = indicator, chart = oscillator, legendtitle = "RSI")

// ====================================================================
// RSI WITH BANDS
// The Relative Strength Index (RSI) in a pane of its own, with the
// overbought and oversold levels marked, the pane tinted while the RSI
// is past either one, and an alert as it crosses each.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// Each input shows up in the script's settings on the chart.
length = input.int(14, "Length", min = 2)
src = input.source(p.close, "Source")
upper = input.int(70, "Overbought", min = 50, max = 100)
lower = input.int(30, "Oversold", min = 0, max = 50)

// ---- 2. Calculation ------------------------------------------------
// The RSI runs from 0 to 100: how strongly the price has been rising
// against falling over the last length bars.
r = ind.rsi(src, length)

// ---- 3. Drawing ----------------------------------------------------
// The levels. Each plot.level() gives back the level it draws, so
// paint.fill() can shade the band between them.
top = plot.level(upper, "Overbought", color = #787b86)
bottom = plot.level(lower, "Oversold", color = #787b86)
paint.fill(top, bottom, color = color.hex(#a396ff, 90))
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)

// The RSI line: red while overbought, green while oversold, purple in
// between. An if, elif and else on one line pick the colour, just like
// the block if. The pane is tinted red or green the same way.
col = if r > upper: #ff5252 elif r < lower: #00d79e else: #a396ff
plot.line(r, "RSI", color = col, linewidth = 2)
paint.background(r > upper, #ff5252)
paint.background(r < lower, #00d79e)

// ---- 4. Alerts -----------------------------------------------------
// Each alert() is an alert this script offers, named by its title.
// Switch it on in the script's settings, Alerts tab, for the coin and
// timeframe on the chart: it fires when its candle closes, on the chart
// and on your phone. The message is worked out on that candle.
alert(math.crossover(r, upper), "Overbought", "RSI " + math.round(r, 1) + " crossed above " + upper)
alert(math.crossunder(r, lower), "Oversold", "RSI " + math.round(r, 1) + " crossed below " + lower)

Volume spikes

Volume columns, with spikes above the average highlighted.

CharmScript 1.0
script("Volume spikes", tool = indicator, chart = oscillator, format = "volume")

// ====================================================================
// VOLUME SPIKES
// Volume as columns in a pane of its own, with its average as a line.
// A column more than a few times the average is highlighted in amber.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Average length", min = 2)
mult = input.float(2.0, "Spike at (x average)", min = 1, step = 0.1)

// ---- 2. Calculation ------------------------------------------------
// The average volume, and whether this bar's volume is a spike.
avg = ind.sma(p.volume, length)
spike = p.volume > avg * mult

// Each column's colour: amber on a spike; otherwise faded green on an
// up bar (closed at or above its open) and faded red on a down bar.
// Inside ( ) the if can spread over lines, one branch a line.
col = (
    if spike: #fbbf24
    elif p.close >= p.open: color.hex(#00d79e, 40)
    else: color.hex(#ff5252, 40)
)

// ---- 3. Drawing ----------------------------------------------------
plot.column(p.volume, "Volume", color = col)
plot.line(avg, "Average", color = #a396ff, linewidth = 2)

Up and down bars

Closes up minus closes down over the last few bars: a loop inside a function.

CharmScript 1.0
script("Up and down bars", tool = indicator, chart = oscillator, legendtitle = "Up / down")

// ====================================================================
// UP AND DOWN BARS
// A simple momentum score: over the last few bars, how many closed
// higher than the bar before them, minus how many closed lower. It
// shows a loop inside a function.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(10, "Bars", min = 2, max = 50)

// ---- 2. Calculation ------------------------------------------------
// +1 for every bar that closed higher than the bar before it, -1 for
// every bar that closed lower, over the last n bars.
score(n) =>
    total = 0
    for i in range(n):                                  // i = 0 ... n - 1
        if p.close[-1 - i] > p.close[-2 - i]:   // [-1] is this bar, [-2] the one before
            total += 1
        elif p.close[-1 - i] < p.close[-2 - i]:
            total -= 1
    return total

s = score(length)

// ---- 3. Drawing ----------------------------------------------------
// Green columns above zero, red below, and a dotted line at zero.
plot.column(s, "Score", color = if s >= 0: #00d79e else: #ff5252)
plot.level(0, "Zero", color = #787b86, style = line.dotted)

Strategies

Entries and exits marked on the chart, and backtested in the Backtests panel.

MA crossover

A strategy: long and short on average crossovers.

CharmScript 1.0
script("MA crossover", tool = strategy, chart = main, tooltip = "Long when the fast moving average crosses above the slow one, short when it crosses back below")

// ====================================================================
// MA CROSSOVER (a strategy)
// The classic crossover: long on the bar a fast moving average crosses
// above a slow one, short on the bar it crosses back below. Each cross
// closes the trade that is open and opens the other side, so once the
// first cross has happened it is always in the market. The Backtests
// panel backtests it.
//
// The defaults are a 20-bar and a 50-bar simple moving average, a
// common pair for swing trades: quick enough to trade on every
// timeframe, slow enough not to flip on every wiggle.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// The fast average must be the shorter one: a cross is the short-term
// trend moving through the longer one.
fastLength = input.int(20, "Fast length", min = 1, max = 1000, tooltip = "How many bars the fast average looks back over")
slowLength = input.int(50, "Slow length", min = 1, max = 1000, tooltip = "How many bars the slow average looks back over")
maType = input.string("SMA", "MA type", options = ["SMA", "EMA"], tooltip = "SMA: every bar counts the same\nEMA: newer bars count more, so it turns sooner")
longColor = input.color(#00d79e, "Long colour")
shortColor = input.color(#f52424, "Short colour")

// ---- 2. Calculation ------------------------------------------------
// average() picks the kind of average the setting asks for. A function
// called from two places keeps a separate memory for each, so the fast
// and the slow average never mix.
average(src, length) =>
    return if maType == "EMA": ind.ema(src, length) else: ind.sma(src, length)

fast = average(p.close, fastLength)
slow = average(p.close, slowLength)

// ---- 3. Drawing ----------------------------------------------------
// The fast average takes the long colour while it is above the slow
// one and the short colour while below; the slow average is grey.
plot.line(fast, "Fast average", color = if fast > slow: longColor else: shortColor, linewidth = 2, tooltip = "The fast moving average")
plot.line(slow, "Slow average", color = color.hex(#787b86, 30), tooltip = "The slow moving average")

// ---- 4. Trades -----------------------------------------------------
// math.crossover(a, b) is true on the bar a crosses above b, and
// math.crossunder(a, b) on the bar it crosses below. An entry while the
// other side is open closes it first, on the same bar.
strategy.enter.long(math.crossover(fast, slow), "Long", color = longColor, tooltip = "The fast average crossing above the slow one")
strategy.enter.short(math.crossunder(fast, slow), "Short", color = shortColor, tooltip = "The fast average crossing below the slow one")

MA strategy

A strategy: long above a moving average, short below, with eight kinds of average.

CharmScript 1.0
script("MA strategy", tool = strategy, chart = main, tooltip = "Long while the close is above a moving average, short while it is below")

// ====================================================================
// MA STRATEGY (a strategy)
// The simplest trend rule: long while the close is above a moving
// average, short while it is below. It turns on the bar the close
// crosses the average, so it is always in the market once the average
// has its first value. The Backtests panel backtests it.
//
// The default is a 100-bar simple moving average: halfway between the
// two classic trend lines, the 50 and the 200. The MA type setting picks
// one of eight kinds of moving average.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(100, "Length", min = 1, max = 1000, tooltip = "How many bars the average looks back over")
maType = input.string("SMA", "MA type", options = ["SMA", "EMA", "WMA", "HMA", "RMA", "VWMA", "DEMA", "TEMA"], tooltip = "The kind of moving average\nSMA: every bar counts the same\nEMA: newer bars count more, so it turns sooner\nWMA: the weights fall in a straight line, newest first\nHMA: Hull, smooth and quick, with little lag\nRMA: Wilder's, smoother and slower than an EMA\nVWMA: bars with more volume count more\nDEMA: a double EMA, with less lag than an EMA\nTEMA: a triple EMA, with less lag still")
longColor = input.color(#00d79e, "Long colour")
shortColor = input.color(#f52424, "Short colour")

// ---- 2. Calculation ------------------------------------------------
// The average the MA type setting asks for (if a: x elif b: y else: z picks
// one; inside ( ) it can spread over lines). DEMA and TEMA are built
// from EMAs of EMAs.
ema1 = ind.ema(p.close, length)
ema2 = ind.ema(ema1, length)
ema3 = ind.ema(ema2, length)
avg = (if maType == "EMA": ema1
    elif maType == "WMA": ind.wma(p.close, length)
    elif maType == "HMA": ind.hma(p.close, length)
    elif maType == "RMA": ind.rma(p.close, length)
    elif maType == "VWMA": ind.vwma(p.close, length)
    elif maType == "DEMA": 2 * ema1 - ema2
    elif maType == "TEMA": 3 * ema1 - 3 * ema2 + ema3
    else: ind.sma(p.close, length))
above = p.close > avg
below = p.close < avg

// ---- 3. Drawing ----------------------------------------------------
// The average in the long colour while the close is above it, the short
// colour while below.
plot.line(avg, "Average", color = if above: longColor else: shortColor, linewidth = 2, tooltip = "The moving average")

// ---- 4. Trades -----------------------------------------------------
// An entry asks for a side on every bar the condition holds; a strategy
// only trades when the side changes, so this turns on the bar the close
// crosses the average (a close exactly on it keeps the side it has).
strategy.enter.long(above, "Long", color = longColor, tooltip = "The close above the average")
strategy.enter.short(below, "Short", color = shortColor, tooltip = "The close below the average")

Supertrend flip

A strategy: long and short on each Supertrend flip.

CharmScript 1.0
script("Supertrend flip", tool = strategy, chart = main, tooltip = "Long when the Supertrend turns up, short when it turns down")

// ====================================================================
// SUPERTREND FLIP (a strategy)
// The Supertrend is a line a few ATRs (average true ranges) below the
// price in an uptrend and above it in a downtrend; it flips when the
// close crosses it. This strategy goes long on the bar it turns up and
// short on the bar it turns down, so each flip closes the trade that is
// open and opens the other side. The Backtests panel backtests it.
//
// The defaults are the Supertrend's usual 10-bar ATR and a factor of 3.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
// ATR length: how many bars the ATR averages over.
// Factor: how many ATRs the line sits from the price. Larger, fewer
// and longer trades.
atrLength = input.int(10, "ATR length", min = 1, max = 1000, tooltip = "How many bars the average true range looks back over")
factor = input.float(3.0, "Factor", min = 0.1, max = 20, step = 0.1, tooltip = "How many ATRs the line sits from the price")
longColor = input.color(#00d79e, "Long colour")
shortColor = input.color(#f52424, "Short colour")

// ---- 2. Calculation ------------------------------------------------
// ind.supertrend gives back two values at once: the line, and its
// direction (below 0 while the trend is up).
[st, dir] = ind.supertrend(factor, atrLength)
up = dir < 0

// ---- 3. Drawing ----------------------------------------------------
// A stepped line: the long colour in an uptrend, the short colour in a
// downtrend.
plot.step(st, "Supertrend", color = if up: longColor else: shortColor, linewidth = 2, tooltip = "The Supertrend line")

// ---- 4. Trades -----------------------------------------------------
// A flip is up on this bar but not on the one before (up[-2] is the
// bar before; up[-1], or just up, is this bar), or the other way round.
strategy.enter.long(up and not up[-2], "Long", color = longColor, tooltip = "The Supertrend turning up")
strategy.enter.short(not up and up[-2], "Short", color = shortColor, tooltip = "The Supertrend turning down")

RSI reversals

A strategy: long from oversold, short from overbought, out at the middle. The RSI in its own pane, the trades on the candles.

CharmScript 1.0
script("RSI reversals", tool = strategy, chart = main)

// ====================================================================
// RSI REVERSALS (a strategy)
// Goes long when the RSI climbs back out of oversold, short when it
// falls back out of overbought, and closes each trade when the RSI
// gets back to 50. The RSI is drawn in a pane of its own, the trades
// on the candles, and the Backtests panel backtests them.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "RSI length", min = 2)
buyBelow = input.int(30, "Long below", min = 1, max = 50)
sellAbove = input.int(70, "Short above", min = 50, max = 99)

// ---- 2. Calculation ------------------------------------------------
r = ind.rsi(p.close, length)

// ---- 3. Drawing ----------------------------------------------------
// chart = oscillator puts the RSI and its levels in a pane of their
// own; everything else goes where the script() line says: the candles.
plot.line(r, "RSI", color = #a396ff, linewidth = 2, chart = oscillator)
plot.level(buyBelow, "Long below", color = #00d79e, chart = oscillator)
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted, chart = oscillator)
plot.level(sellAbove, "Short above", color = #ff5252, chart = oscillator)

// ---- 4. Trades -----------------------------------------------------
// math.crossover(a, b) is true on the bar a crosses above b, and
// math.crossunder(a, b) on the bar it crosses below.
strategy.enter.long(math.crossover(r, buyBelow), "Long")        // back up out of oversold
strategy.exit.long(math.crossover(r, 50))                       // out at the middle
strategy.enter.short(math.crossunder(r, sellAbove), "Short")    // back down out of overbought
strategy.exit.short(math.crossunder(r, 50))                     // out at the middle

Library

50 classic indicators and strategies, written in Pine Script and turned into Charm by the converter with no hand edits, every comment kept. Copy one into a new script. The Pine it came from is under each.

On the candles

Averages, bands, channels and stops over the price, then levels, swings, patterns and sessions.

Hull moving average

A moving average built to keep up with the price: twice a weighted average over half the length, less one over the whole length, then a weighted average of that over the square root of the length.

CharmScript 1.0
script("Hull moving average", tool = indicator, chart = main, legendtitle = "HMA")

// ====================================================================
// HULL MOVING AVERAGE
// A moving average built to keep up with the price: twice a weighted
// average over half the length, less one over the whole length, then
// a weighted average of that over the square root of the length. It
// is green while it is higher than on the bar before and red while it
// is lower, so each change of colour is a turn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(55, "Length", min = 2, tooltip = "How many bars the average looks back over")
upColor = input.color(#00d79e, "Rising colour")
downColor = input.color(#ff5252, "Falling colour")
colorCandles = input.bool(false, "Colour the candles", tooltip = "Paints each candle in the line's colour")

// ---- 2. Calculation ------------------------------------------------
hma = ind.hma(source, length)

// Which way it is heading, kept from one bar to the next: up while it
// is higher than on the bar before, down while it is lower, and as it
// was while it is flat.
var direction = 0
if hma > hma[-2]:
    direction = 1
elif hma < hma[-2]:
    direction = -1

// A turn: heading up after heading down, or down after up.
turnsUp = direction == 1 and direction[-2] == -1
turnsDown = direction == -1 and direction[-2] == 1

// Green while it heads up, red while it heads down, and no colour
// until it has a direction.
lineColor = direction == 1 ? upColor : direction == -1 ? downColor : none

// ---- 3. Drawing ----------------------------------------------------
// The line, and the candles in its colour when that is switched on.
plot.line(hma, "HMA", color = lineColor, linewidth = 2)
paint.candles(colorCandles ? lineColor : none, title = "Candle colour")

// ---- 4. Alerts -----------------------------------------------------
alert(turnsUp, "HMA turns up", "Hull moving average: the average turned up")
alert(turnsDown, "HMA turns down", "Hull moving average: the average turned down")
The Pine it came from
//@version=6
indicator("Hull moving average", shorttitle = "HMA", overlay = true)

// ====================================================================
// HULL MOVING AVERAGE
// A moving average built to keep up with the price: twice a weighted
// average over half the length, less one over the whole length, then
// a weighted average of that over the square root of the length. It
// is green while it is higher than on the bar before and red while it
// is lower, so each change of colour is a turn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(55, "Length", minval = 2, tooltip = "How many bars the average looks back over")
upColor = input.color(#00d79e, "Rising colour")
downColor = input.color(#ff5252, "Falling colour")
colorCandles = input.bool(false, "Colour the candles", tooltip = "Paints each candle in the line's colour")

// ---- 2. Calculation ------------------------------------------------
hma = ta.hma(source, length)

// Which way it is heading, kept from one bar to the next: up while it
// is higher than on the bar before, down while it is lower, and as it
// was while it is flat.
var int direction = 0
if hma > hma[1]
    direction := 1
else if hma < hma[1]
    direction := -1

// A turn: heading up after heading down, or down after up.
turnsUp = direction == 1 and direction[1] == -1
turnsDown = direction == -1 and direction[1] == 1

// Green while it heads up, red while it heads down, and no colour
// until it has a direction.
lineColor = direction == 1 ? upColor : direction == -1 ? downColor : na

// ---- 3. Drawing ----------------------------------------------------
// The line, and the candles in its colour when that is switched on.
plot(hma, "HMA", color = lineColor, linewidth = 2)
barcolor(colorCandles ? lineColor : na, title = "Candle colour")

// ---- 4. Alerts -----------------------------------------------------
alertcondition(turnsUp, "HMA turns up", "Hull moving average: the average turned up")
alertcondition(turnsDown, "HMA turns down", "Hull moving average: the average turned down")

Arnaud Legoux moving average

A moving average whose weights follow a bell curve across the bars it looks back over.

CharmScript 1.0
script("Arnaud Legoux moving average", tool = indicator, chart = main, legendtitle = "ALMA")

// ====================================================================
// ARNAUD LEGOUX MOVING AVERAGE
// A moving average whose weights follow a bell curve across the bars
// it looks back over. The offset moves the peak of the bell towards
// the newest bars, which cuts the lag; sigma sets how narrow the bell
// is, and so how many bars carry real weight. The line comes out
// smooth and still close to the price.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(9, "Length", min = 1, tooltip = "How many bars the average looks back over")
almaOffset = input.float(0.85, "Offset", min = 0, max = 1, step = 0.05, tooltip = "1 weighs the newest bar most")
sigma = input.float(6.0, "Sigma", min = 0.1, step = 0.5, tooltip = "Higher makes the bell narrower")
lineColor = input.color(#a396ff, "Colour")

// ---- 2. Calculation ------------------------------------------------
// The weights follow a bell curve over the window: it peaks at the
// offset's share of the way from the oldest bar to the newest, and its
// width is the length divided by sigma. The average is each price
// times its weight, added up, over the sum of the weights.
alma = ind.alma(source, length, almaOffset, sigma)

// ---- 3. Drawing ----------------------------------------------------
plot.line(alma, "ALMA", color = lineColor, linewidth = 2)
The Pine it came from
//@version=6
indicator("Arnaud Legoux moving average", shorttitle = "ALMA", overlay = true)

// ====================================================================
// ARNAUD LEGOUX MOVING AVERAGE
// A moving average whose weights follow a bell curve across the bars
// it looks back over. The offset moves the peak of the bell towards
// the newest bars, which cuts the lag; sigma sets how narrow the bell
// is, and so how many bars carry real weight. The line comes out
// smooth and still close to the price.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(9, "Length", minval = 1, tooltip = "How many bars the average looks back over")
almaOffset = input.float(0.85, "Offset", minval = 0, maxval = 1, step = 0.05, tooltip = "1 weighs the newest bar most")
sigma = input.float(6.0, "Sigma", minval = 0.1, step = 0.5, tooltip = "Higher makes the bell narrower")
lineColor = input.color(#a396ff, "Colour")

// ---- 2. Calculation ------------------------------------------------
// The weights follow a bell curve over the window: it peaks at the
// offset's share of the way from the oldest bar to the newest, and its
// width is the length divided by sigma. The average is each price
// times its weight, added up, over the sum of the weights.
alma = ta.alma(source, length, almaOffset, sigma)

// ---- 3. Drawing ----------------------------------------------------
plot(alma, "ALMA", color = lineColor, linewidth = 2)

DEMA and TEMA

The double and triple exponential moving averages.

CharmScript 1.0
script("DEMA and TEMA", tool = indicator, chart = main)

// ====================================================================
// DEMA AND TEMA
// The double and triple exponential moving averages. Each starts from
// an exponential average of the price, averages that again (and, for
// the triple, once more), then uses the gaps between the layers to
// take out most of the lag a single average has. The triple follows
// the price the more closely of the two.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(21, "Length", min = 1, tooltip = "How many bars each exponential average looks back over")
showDema = input.bool(true, "Show DEMA")
demaColor = input.color(#2196f3, "DEMA colour")
showTema = input.bool(true, "Show TEMA")
temaColor = input.color(#fbbf24, "TEMA colour")

// ---- 2. Calculation ------------------------------------------------
// Three exponential averages, one on top of the other: the first of
// the source, the second of the first, the third of the second. The
// function gives back all three at once.
stackedEmas(src, len) =>
    e1 = ind.ema(src, len)
    e2 = ind.ema(e1, len)
    e3 = ind.ema(e2, len)
    return [e1, e2, e3]

[ema1, ema2, ema3] = stackedEmas(source, length)

// The double: twice the first, less the second. The triple: three
// times the first, less three times the second, plus the third.
dema = 2 * ema1 - ema2
tema = 3 * ema1 - 3 * ema2 + ema3

// ---- 3. Drawing ----------------------------------------------------
// A line that is switched off is drawn with no colour.
plot.line(dema, "DEMA", color = showDema ? demaColor : none, linewidth = 2)
plot.line(tema, "TEMA", color = showTema ? temaColor : none, linewidth = 2)
The Pine it came from
//@version=6
indicator("DEMA and TEMA", overlay = true)

// ====================================================================
// DEMA AND TEMA
// The double and triple exponential moving averages. Each starts from
// an exponential average of the price, averages that again (and, for
// the triple, once more), then uses the gaps between the layers to
// take out most of the lag a single average has. The triple follows
// the price the more closely of the two.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(21, "Length", minval = 1, tooltip = "How many bars each exponential average looks back over")
showDema = input.bool(true, "Show DEMA")
demaColor = input.color(#2196f3, "DEMA colour")
showTema = input.bool(true, "Show TEMA")
temaColor = input.color(#fbbf24, "TEMA colour")

// ---- 2. Calculation ------------------------------------------------
// Three exponential averages, one on top of the other: the first of
// the source, the second of the first, the third of the second. The
// function gives back all three at once.
stackedEmas(src, len) =>
    e1 = ta.ema(src, len)
    e2 = ta.ema(e1, len)
    e3 = ta.ema(e2, len)
    [e1, e2, e3]

[ema1, ema2, ema3] = stackedEmas(source, length)

// The double: twice the first, less the second. The triple: three
// times the first, less three times the second, plus the third.
dema = 2 * ema1 - ema2
tema = 3 * ema1 - 3 * ema2 + ema3

// ---- 3. Drawing ----------------------------------------------------
// A line that is switched off is drawn with no colour.
plot(dema, "DEMA", color = showDema ? demaColor : na, linewidth = 2)
plot(tema, "TEMA", color = showTema ? temaColor : na, linewidth = 2)

Kaufman adaptive moving average

A moving average that speeds up while the price moves steadily one way and all but stops while it chops sideways.

CharmScript 1.0
script("Kaufman adaptive moving average", tool = indicator, chart = main, legendtitle = "KAMA")

// ====================================================================
// KAUFMAN ADAPTIVE MOVING AVERAGE
// A moving average that speeds up while the price moves steadily one
// way and all but stops while it chops sideways. The efficiency ratio
// (how far the price got, against how far it travelled) sets its
// speed on every bar, between a fast and a slow exponential average's.
// This is Kaufman's own version, with the speed squared.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(10, "Length", min = 1, tooltip = "How many bars the efficiency ratio looks back over")
fastLength = input.int(2, "Fast length", min = 1, tooltip = "Sets its speed in a clean trend")
slowLength = input.int(30, "Slow length", min = 1, tooltip = "Sets its speed in a sideways chop")
upColor = input.color(#00d79e, "Rising colour")
downColor = input.color(#ff5252, "Falling colour")

// ---- 2. Calculation ------------------------------------------------
// The efficiency ratio, from 0 to 1: how far the price got over the
// length, against the whole distance it travelled bar by bar to get
// there. A straight run scores 1 and a sideways chop close to 0. It
// counts as 0 while there are too few bars yet, or when the price has
// not moved at all.
netChange = math.abs(source - source[-length - 1])
pathLength = math.sum(math.abs(source - source[-2]), length)
efficiency = pathLength > 0 ? netChange / pathLength : 0.0

// The share of the gap to the price that the average closes on each
// bar: the slow average's share, plus the efficiency's part of the
// way to the fast one's, then squared, so a chop slows it right down.
fastShare = 2.0 / (fastLength + 1)
slowShare = 2.0 / (slowLength + 1)
smoothing = math.pow(efficiency * (fastShare - slowShare) + slowShare, 2)

// The average, kept from one bar to the next. It starts at the source
// on the first bar, then moves towards it by that share of the gap.
var kama = none
kama = none(kama) ? source : kama + smoothing * (source - kama)

// Green while it rises, red while it falls.
lineColor = kama > kama[-2] ? upColor : downColor

// ---- 3. Drawing ----------------------------------------------------
plot.line(kama, "KAMA", color = lineColor, linewidth = 2)
The Pine it came from
//@version=6
indicator("Kaufman adaptive moving average", shorttitle = "KAMA", overlay = true)

// ====================================================================
// KAUFMAN ADAPTIVE MOVING AVERAGE
// A moving average that speeds up while the price moves steadily one
// way and all but stops while it chops sideways. The efficiency ratio
// (how far the price got, against how far it travelled) sets its
// speed on every bar, between a fast and a slow exponential average's.
// This is Kaufman's own version, with the speed squared.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(10, "Length", minval = 1, tooltip = "How many bars the efficiency ratio looks back over")
fastLength = input.int(2, "Fast length", minval = 1, tooltip = "Sets its speed in a clean trend")
slowLength = input.int(30, "Slow length", minval = 1, tooltip = "Sets its speed in a sideways chop")
upColor = input.color(#00d79e, "Rising colour")
downColor = input.color(#ff5252, "Falling colour")

// ---- 2. Calculation ------------------------------------------------
// The efficiency ratio, from 0 to 1: how far the price got over the
// length, against the whole distance it travelled bar by bar to get
// there. A straight run scores 1 and a sideways chop close to 0. It
// counts as 0 while there are too few bars yet, or when the price has
// not moved at all.
netChange = math.abs(source - source[length])
pathLength = math.sum(math.abs(source - source[1]), length)
efficiency = pathLength > 0 ? netChange / pathLength : 0.0

// The share of the gap to the price that the average closes on each
// bar: the slow average's share, plus the efficiency's part of the
// way to the fast one's, then squared, so a chop slows it right down.
fastShare = 2.0 / (fastLength + 1)
slowShare = 2.0 / (slowLength + 1)
smoothing = math.pow(efficiency * (fastShare - slowShare) + slowShare, 2)

// The average, kept from one bar to the next. It starts at the source
// on the first bar, then moves towards it by that share of the gap.
var float kama = na
kama := na(kama) ? source : kama + smoothing * (source - kama)

// Green while it rises, red while it falls.
lineColor = kama > kama[1] ? upColor : downColor

// ---- 3. Drawing ----------------------------------------------------
plot(kama, "KAMA", color = lineColor, linewidth = 2)

Moving average envelope

A moving average with a band a fixed percentage above it and one the same percentage below.

CharmScript 1.0
script("Moving average envelope", tool = indicator, chart = main, legendtitle = "Envelope")

// ====================================================================
// MOVING AVERAGE ENVELOPE
// A moving average with a band a fixed percentage above it and one
// the same percentage below. The bands do not widen when the market
// gets busier, only as the average itself rises, so they show how far
// the price has stretched from its average, in percent.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
averageType = input.string("SMA", "Average type", options = ["SMA", "EMA", "WMA", "RMA", "VWMA"])
length = input.int(20, "Length", min = 1, tooltip = "How many bars the average looks back over")
percent = input.float(2.5, "Width (%)", min = 0.1, step = 0.1, tooltip = "How far each band sits from the average")
bandColor = input.color(#2196f3, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// The chosen moving average: simple, exponential, weighted, Wilder's
// running average, or weighted by volume.
averageOf(src, len, kind) =>
    return match kind:
        "SMA": ind.sma(src, len)
        "EMA": ind.ema(src, len)
        "WMA": ind.wma(src, len)
        "RMA": ind.rma(src, len)
        else: ind.vwma(src, len)

// The bands sit the percentage above and below the average.
basis = averageOf(source, length, averageType)
upper = basis * (1 + percent / 100)
lower = basis * (1 - percent / 100)

// ---- 3. Drawing ----------------------------------------------------
// The two bands and the average, with a shade between the bands.
upperPlot = plot.line(upper, "Upper", color = bandColor)
plot.line(basis, "Basis", color = color.hex(bandColor, 40))
lowerPlot = plot.line(lower, "Lower", color = bandColor)
paint.fill(upperPlot, lowerPlot, color = color.hex(bandColor, 92), title = "Background")
The Pine it came from
//@version=6
indicator("Moving average envelope", shorttitle = "Envelope", overlay = true)

// ====================================================================
// MOVING AVERAGE ENVELOPE
// A moving average with a band a fixed percentage above it and one
// the same percentage below. The bands do not widen when the market
// gets busier, only as the average itself rises, so they show how far
// the price has stretched from its average, in percent.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
averageType = input.string("SMA", "Average type", options = ["SMA", "EMA", "WMA", "RMA", "VWMA"])
length = input.int(20, "Length", minval = 1, tooltip = "How many bars the average looks back over")
percent = input.float(2.5, "Width (%)", minval = 0.1, step = 0.1, tooltip = "How far each band sits from the average")
bandColor = input.color(#2196f3, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// The chosen moving average: simple, exponential, weighted, Wilder's
// running average, or weighted by volume.
averageOf(src, len, kind) =>
    switch kind
        "SMA" => ta.sma(src, len)
        "EMA" => ta.ema(src, len)
        "WMA" => ta.wma(src, len)
        "RMA" => ta.rma(src, len)
        => ta.vwma(src, len)

// The bands sit the percentage above and below the average.
basis = averageOf(source, length, averageType)
upper = basis * (1 + percent / 100)
lower = basis * (1 - percent / 100)

// ---- 3. Drawing ----------------------------------------------------
// The two bands and the average, with a shade between the bands.
upperPlot = plot(upper, "Upper", color = bandColor)
plot(basis, "Basis", color = color.new(bandColor, 40))
lowerPlot = plot(lower, "Lower", color = bandColor)
fill(upperPlot, lowerPlot, color = color.new(bandColor, 92), title = "Background")

Keltner channels

An exponential moving average of the price with a band either side, a few average true ranges (ATRs) away.

CharmScript 1.0
script("Keltner channels", tool = indicator, chart = main, legendtitle = "KC")

// ====================================================================
// KELTNER CHANNELS
// An exponential moving average of the price with a band either side,
// a few average true ranges (ATRs) away. The bands widen when the
// market moves a lot and narrow when it is quiet, so a close outside
// one is a move bigger than usual.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(20, "Length", min = 1, tooltip = "How many bars the average looks back over")
mult = input.float(2.0, "Multiplier", min = 0.1, step = 0.1, tooltip = "Ranges from the average to each band")
bandsFrom = input.string("Average true range", "Width from", options = ["Average true range", "True range", "Range"])
atrLength = input.int(10, "ATR length", min = 1, tooltip = "Used when the width is from the average true range")
bandColor = input.color(#a396ff, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// The middle line: an exponential moving average of the source.
basis = ind.ema(source, length)

// How far the bands sit from it, by the chosen measure of how far the
// price moves in a bar: the average true range, this bar's true range,
// or an average of the bar's high minus its low.
width = match bandsFrom:
    "Average true range": ind.atr(atrLength)
    "True range": ind.tr(true)
    else: ind.ema(p.high - p.low, length)

upper = basis + mult * width
lower = basis - mult * width

// ---- 3. Drawing ----------------------------------------------------
// The two bands and the middle line, with a shade between the bands.
upperPlot = plot.line(upper, "Upper", color = bandColor)
plot.line(basis, "Basis", color = color.hex(bandColor, 40))
lowerPlot = plot.line(lower, "Lower", color = bandColor)
paint.fill(upperPlot, lowerPlot, color = color.hex(bandColor, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
alert(math.crossover(p.close, upper), "Above the upper band", "Keltner channels: close above the upper band")
alert(math.crossunder(p.close, lower), "Below the lower band", "Keltner channels: close below the lower band")
The Pine it came from
//@version=6
indicator("Keltner channels", shorttitle = "KC", overlay = true)

// ====================================================================
// KELTNER CHANNELS
// An exponential moving average of the price with a band either side,
// a few average true ranges (ATRs) away. The bands widen when the
// market moves a lot and narrow when it is quiet, so a close outside
// one is a move bigger than usual.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(20, "Length", minval = 1, tooltip = "How many bars the average looks back over")
mult = input.float(2.0, "Multiplier", minval = 0.1, step = 0.1, tooltip = "Ranges from the average to each band")
bandsFrom = input.string("Average true range", "Width from", options = ["Average true range", "True range", "Range"])
atrLength = input.int(10, "ATR length", minval = 1, tooltip = "Used when the width is from the average true range")
bandColor = input.color(#a396ff, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// The middle line: an exponential moving average of the source.
basis = ta.ema(source, length)

// How far the bands sit from it, by the chosen measure of how far the
// price moves in a bar: the average true range, this bar's true range,
// or an average of the bar's high minus its low.
width = switch bandsFrom
    "Average true range" => ta.atr(atrLength)
    "True range" => ta.tr(true)
    => ta.ema(high - low, length)

upper = basis + mult * width
lower = basis - mult * width

// ---- 3. Drawing ----------------------------------------------------
// The two bands and the middle line, with a shade between the bands.
upperPlot = plot(upper, "Upper", color = bandColor)
plot(basis, "Basis", color = color.new(bandColor, 40))
lowerPlot = plot(lower, "Lower", color = bandColor)
fill(upperPlot, lowerPlot, color = color.new(bandColor, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
alertcondition(ta.crossover(close, upper), "Above the upper band", "Keltner channels: close above the upper band")
alertcondition(ta.crossunder(close, lower), "Below the lower band", "Keltner channels: close below the lower band")

Donchian channels

The highest high and the lowest low of the last few bars, with a line halfway between them.

CharmScript 1.0
script("Donchian channels", tool = indicator, chart = main, legendtitle = "DC")

// ====================================================================
// DONCHIAN CHANNELS
// The highest high and the lowest low of the last few bars, with a
// line halfway between them. The upper edge steps up only when the
// price makes a new high for the length, and the lower edge steps
// down only on a new low, so each step outwards marks a breakout.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", min = 1, tooltip = "How many bars the channel looks back over")
shiftBars = input.int(0, "Offset", tooltip = "Moves the lines this many bars to the right, or left when below 0")
bandColor = input.color(#2196f3, "Channel colour")
middleColor = input.color(#fbbf24, "Middle colour")

// ---- 2. Calculation ------------------------------------------------
// The channel's edges over the length, and halfway between them.
upper = math.highest(p.high, length)
lower = math.lowest(p.low, length)
middle = (upper + lower) / 2

// ---- 3. Drawing ----------------------------------------------------
// All three lines move by the offset together, with a shade between
// the edges.
upperPlot = plot.line(upper, "Upper", color = bandColor, offset = shiftBars)
plot.line(middle, "Middle", color = middleColor, offset = shiftBars)
lowerPlot = plot.line(lower, "Lower", color = bandColor, offset = shiftBars)
paint.fill(upperPlot, lowerPlot, color = color.hex(bandColor, 92), title = "Background")
The Pine it came from
//@version=6
indicator("Donchian channels", shorttitle = "DC", overlay = true)

// ====================================================================
// DONCHIAN CHANNELS
// The highest high and the lowest low of the last few bars, with a
// line halfway between them. The upper edge steps up only when the
// price makes a new high for the length, and the lower edge steps
// down only on a new low, so each step outwards marks a breakout.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", minval = 1, tooltip = "How many bars the channel looks back over")
shiftBars = input.int(0, "Offset", tooltip = "Moves the lines this many bars to the right, or left when below 0")
bandColor = input.color(#2196f3, "Channel colour")
middleColor = input.color(#fbbf24, "Middle colour")

// ---- 2. Calculation ------------------------------------------------
// The channel's edges over the length, and halfway between them.
upper = ta.highest(high, length)
lower = ta.lowest(low, length)
middle = (upper + lower) / 2

// ---- 3. Drawing ----------------------------------------------------
// All three lines move by the offset together, with a shade between
// the edges.
upperPlot = plot(upper, "Upper", color = bandColor, offset = shiftBars)
plot(middle, "Middle", color = middleColor, offset = shiftBars)
lowerPlot = plot(lower, "Lower", color = bandColor, offset = shiftBars)
fill(upperPlot, lowerPlot, color = color.new(bandColor, 92), title = "Background")

Ichimoku cloud

Five lines that show trend, momentum and support in one picture.

CharmScript 1.0
script("Ichimoku cloud", tool = indicator, chart = main, legendtitle = "Ichimoku")

// ====================================================================
// ICHIMOKU CLOUD
// Five lines that show trend, momentum and support in one picture.
// The conversion and base lines sit halfway between the highest high
// and the lowest low, over a short and a longer stretch. The two
// leading spans are drawn ahead of the price, and the space between
// them is the cloud: green while the first is above the second, red
// while it is below. The lagging span is the close, drawn back.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
conversionLength = input.int(9, "Conversion line length", min = 1)
baseLength = input.int(26, "Base line length", min = 1)
spanBLength = input.int(52, "Leading span B length", min = 1)
displacement = input.int(26, "Displacement", min = 1, tooltip = "How far ahead the spans go, and the close back")
conversionColor = input.color(#2196f3, "Conversion line colour")
baseColor = input.color(#fbbf24, "Base line colour")
laggingColor = input.color(#a396ff, "Lagging span colour")
upColor = input.color(#00d79e, "Cloud up colour")
downColor = input.color(#ff5252, "Cloud down colour")

// ---- 2. Calculation ------------------------------------------------
// Halfway between the highest high and the lowest low over a length.
midpoint(len) =>
    return (math.highest(p.high, len) + math.lowest(p.low, len)) / 2

conversion = midpoint(conversionLength)
base = midpoint(baseLength)

// The leading spans: the first halfway between the conversion and base
// lines, the second the midpoint over its own, longer length.
spanA = (conversion + base) / 2
spanB = midpoint(spanBLength)

// The cloud is green while the first span is above the second.
cloudColor = spanA > spanB ? color.hex(upColor, 90) : color.hex(downColor, 90)

// ---- 3. Drawing ----------------------------------------------------
// The spans are drawn the displacement ahead, counting this bar as the
// first, and the close the same distance back.
plot.line(conversion, "Conversion line", color = conversionColor)
plot.line(base, "Base line", color = baseColor)
plot.line(p.close, "Lagging span", color = laggingColor, offset = -displacement + 1)
spanAPlot = plot.line(spanA, "Leading span A", color = upColor, offset = displacement - 1)
spanBPlot = plot.line(spanB, "Leading span B", color = downColor, offset = displacement - 1)
paint.fill(spanAPlot, spanBPlot, color = cloudColor, title = "Cloud")
The Pine it came from
//@version=6
indicator("Ichimoku cloud", shorttitle = "Ichimoku", overlay = true)

// ====================================================================
// ICHIMOKU CLOUD
// Five lines that show trend, momentum and support in one picture.
// The conversion and base lines sit halfway between the highest high
// and the lowest low, over a short and a longer stretch. The two
// leading spans are drawn ahead of the price, and the space between
// them is the cloud: green while the first is above the second, red
// while it is below. The lagging span is the close, drawn back.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
conversionLength = input.int(9, "Conversion line length", minval = 1)
baseLength = input.int(26, "Base line length", minval = 1)
spanBLength = input.int(52, "Leading span B length", minval = 1)
displacement = input.int(26, "Displacement", minval = 1, tooltip = "How far ahead the spans go, and the close back")
conversionColor = input.color(#2196f3, "Conversion line colour")
baseColor = input.color(#fbbf24, "Base line colour")
laggingColor = input.color(#a396ff, "Lagging span colour")
upColor = input.color(#00d79e, "Cloud up colour")
downColor = input.color(#ff5252, "Cloud down colour")

// ---- 2. Calculation ------------------------------------------------
// Halfway between the highest high and the lowest low over a length.
midpoint(len) =>
    (ta.highest(high, len) + ta.lowest(low, len)) / 2

conversion = midpoint(conversionLength)
base = midpoint(baseLength)

// The leading spans: the first halfway between the conversion and base
// lines, the second the midpoint over its own, longer length.
spanA = (conversion + base) / 2
spanB = midpoint(spanBLength)

// The cloud is green while the first span is above the second.
cloudColor = spanA > spanB ? color.new(upColor, 90) : color.new(downColor, 90)

// ---- 3. Drawing ----------------------------------------------------
// The spans are drawn the displacement ahead, counting this bar as the
// first, and the close the same distance back.
plot(conversion, "Conversion line", color = conversionColor)
plot(base, "Base line", color = baseColor)
plot(close, "Lagging span", color = laggingColor, offset = -displacement + 1)
spanAPlot = plot(spanA, "Leading span A", color = upColor, offset = displacement - 1)
spanBPlot = plot(spanB, "Leading span B", color = downColor, offset = displacement - 1)
fill(spanAPlot, spanBPlot, color = cloudColor, title = "Cloud")

VWAP with bands

The volume-weighted average price since the period began: the average price paid, each bar's price counted by its volume.

CharmScript 1.0
script("VWAP with bands", tool = indicator, chart = main, legendtitle = "VWAP")

// ====================================================================
// VWAP WITH BANDS
// The volume-weighted average price since the period began: the
// average price paid, each bar's price counted by its volume. It
// starts again with each new period, a day by default. The bands sit
// one and two standard deviations either side, the deviation weighted
// by volume too, so they widen as the period's prices spread out.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
anchorPeriod = input.timeframe("1D", "Anchor period", tooltip = "The average starts again with each of these")
source = input.source(p.hlc3, "Source")
mult1 = input.float(1.0, "Band 1 multiplier", min = 0.1, step = 0.1, tooltip = "Standard deviations from the VWAP")
showBand1 = input.bool(true, "Show band 1")
mult2 = input.float(2.0, "Band 2 multiplier", min = 0.1, step = 0.1, tooltip = "Standard deviations from the VWAP")
showBand2 = input.bool(true, "Show band 2")
vwapColor = input.color(#fbbf24, "VWAP colour")
bandColor = input.color(#a396ff, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// Whether this bar starts a new period.
newPeriod = bar.isFirstOf(anchorPeriod)

// Three running totals since the period began, kept from one bar to
// the next and emptied when a new period starts: the volume, the
// price times the volume, and the price squared times the volume.
var sumVolume = 0.0
var sumPriceVolume = 0.0
var sumSquareVolume = 0.0
if newPeriod:
    sumVolume = 0.0
    sumPriceVolume = 0.0
    sumSquareVolume = 0.0
sumVolume = sumVolume + p.volume
sumPriceVolume = sumPriceVolume + source * p.volume
sumSquareVolume = sumSquareVolume + source * source * p.volume

// The VWAP is the price-volume total over the volume total. The spread
// around it is the square root of the average squared price less the
// VWAP squared, held at 0 or more (rounding can dip it just under).
vwapPrice = sumVolume > 0 ? sumPriceVolume / sumVolume : none
variance = sumVolume > 0 ? sumSquareVolume / sumVolume - vwapPrice * vwapPrice : none
deviation = math.sqrt(math.max(variance, 0))

// The bands, the chosen number of deviations either side.
upper1 = vwapPrice + mult1 * deviation
lower1 = vwapPrice - mult1 * deviation
upper2 = vwapPrice + mult2 * deviation
lower2 = vwapPrice - mult2 * deviation

// ---- 3. Drawing ----------------------------------------------------
// A band that is switched off is drawn with no colour, its shade too.
plot.line(vwapPrice, "VWAP", color = vwapColor, linewidth = 2)
upper1Plot = plot.line(upper1, "Upper band 1", color = showBand1 ? bandColor : none)
lower1Plot = plot.line(lower1, "Lower band 1", color = showBand1 ? bandColor : none)
plot.line(upper2, "Upper band 2", color = showBand2 ? color.hex(bandColor, 40) : none)
plot.line(lower2, "Lower band 2", color = showBand2 ? color.hex(bandColor, 40) : none)
paint.fill(upper1Plot, lower1Plot, color = showBand1 ? color.hex(bandColor, 92) : none, title = "Band 1 background")
The Pine it came from
//@version=6
indicator("VWAP with bands", shorttitle = "VWAP", overlay = true)

// ====================================================================
// VWAP WITH BANDS
// The volume-weighted average price since the period began: the
// average price paid, each bar's price counted by its volume. It
// starts again with each new period, a day by default. The bands sit
// one and two standard deviations either side, the deviation weighted
// by volume too, so they widen as the period's prices spread out.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
anchorPeriod = input.timeframe("1D", "Anchor period", tooltip = "The average starts again with each of these")
source = input.source(hlc3, "Source")
mult1 = input.float(1.0, "Band 1 multiplier", minval = 0.1, step = 0.1, tooltip = "Standard deviations from the VWAP")
showBand1 = input.bool(true, "Show band 1")
mult2 = input.float(2.0, "Band 2 multiplier", minval = 0.1, step = 0.1, tooltip = "Standard deviations from the VWAP")
showBand2 = input.bool(true, "Show band 2")
vwapColor = input.color(#fbbf24, "VWAP colour")
bandColor = input.color(#a396ff, "Band colour")

// ---- 2. Calculation ------------------------------------------------
// Whether this bar starts a new period.
newPeriod = timeframe.change(anchorPeriod)

// Three running totals since the period began, kept from one bar to
// the next and emptied when a new period starts: the volume, the
// price times the volume, and the price squared times the volume.
var float sumVolume = 0.0
var float sumPriceVolume = 0.0
var float sumSquareVolume = 0.0
if newPeriod
    sumVolume := 0.0
    sumPriceVolume := 0.0
    sumSquareVolume := 0.0
sumVolume := sumVolume + volume
sumPriceVolume := sumPriceVolume + source * volume
sumSquareVolume := sumSquareVolume + source * source * volume

// The VWAP is the price-volume total over the volume total. The spread
// around it is the square root of the average squared price less the
// VWAP squared, held at 0 or more (rounding can dip it just under).
vwapPrice = sumVolume > 0 ? sumPriceVolume / sumVolume : na
variance = sumVolume > 0 ? sumSquareVolume / sumVolume - vwapPrice * vwapPrice : na
deviation = math.sqrt(math.max(variance, 0))

// The bands, the chosen number of deviations either side.
upper1 = vwapPrice + mult1 * deviation
lower1 = vwapPrice - mult1 * deviation
upper2 = vwapPrice + mult2 * deviation
lower2 = vwapPrice - mult2 * deviation

// ---- 3. Drawing ----------------------------------------------------
// A band that is switched off is drawn with no colour, its shade too.
plot(vwapPrice, "VWAP", color = vwapColor, linewidth = 2)
upper1Plot = plot(upper1, "Upper band 1", color = showBand1 ? bandColor : na)
lower1Plot = plot(lower1, "Lower band 1", color = showBand1 ? bandColor : na)
plot(upper2, "Upper band 2", color = showBand2 ? color.new(bandColor, 40) : na)
plot(lower2, "Lower band 2", color = showBand2 ? color.new(bandColor, 40) : na)
fill(upper1Plot, lower1Plot, color = showBand1 ? color.new(bandColor, 92) : na, title = "Band 1 background")

Linear regression channel

The straight line that best fits the closes of the lookback (the least-squares line), with a line either side a set number of standard deviations away.

CharmScript 1.0
script("Linear regression channel", tool = indicator, chart = main, legendtitle = "LinReg")

// ====================================================================
// LINEAR REGRESSION CHANNEL
// The straight line that best fits the closes of the lookback (the
// least-squares line), with a line either side a set number of
// standard deviations away. The middle line's slope is the trend's
// direction and pace; a close near an outer line is unusually far
// from the trend. The deviation is that of the closes from the middle
// line itself, not from their average. The channel is fitted again
// on each update of the last bar, so it always shows the latest fit.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(100, "Length", min = 2, max = 500, tooltip = "How many bars the line is fitted over")
mult = input.float(2.0, "Width (deviations)", min = 0.1, step = 0.1, tooltip = "From the middle to each outer line")
extendRight = input.bool(true, "Extend to the right")
middleColor = input.color(#2196f3, "Middle line colour")
outerColor = input.color(#a396ff, "Outer lines colour")

// ---- 2. Calculation ------------------------------------------------
// The two ends of the middle line: the least-squares line's value on
// this bar and on the oldest bar of the lookback.
newestValue = ind.linreg(p.close, length, 0)
oldestValue = ind.linreg(p.close, length, length - 1)

// How much the line rises from one bar to the next.
slope = (newestValue - oldestValue) / (length - 1)

// On the last bar only: the standard deviation of the closes from the
// line, the square root of the average squared gap between each close
// and the line's value on that close's bar.
deviation = none
if bar.isLast:
    sumSquares = 0.0
    for i in range(length):
        gap = p.close[-i - 1] - (newestValue - slope * i)
        sumSquares += gap * gap
    deviation = math.sqrt(sumSquares / length)

// ---- 3. Drawing ----------------------------------------------------
// The three lines and the shade between the outer two are made once,
// then moved onto the latest fit on each update.
var middleLine = plot.segment(none, none, none, none, color = middleColor, width = 2)
var upperLine = plot.segment(none, none, none, none, color = outerColor)
var lowerLine = plot.segment(none, none, none, none, color = outerColor)
var channelFill = plot.linefill(upperLine, lowerLine, color.hex(outerColor, 92))

if bar.isLast:
    oldestBar = bars.count - (length - 1)
    spread = mult * deviation
    lineExtend = extendRight ? "right" : "none"
    middleLine.xy1(oldestBar, oldestValue)
    middleLine.xy2(bars.count, newestValue)
    upperLine.xy1(oldestBar, oldestValue + spread)
    upperLine.xy2(bars.count, newestValue + spread)
    lowerLine.xy1(oldestBar, oldestValue - spread)
    lowerLine.xy2(bars.count, newestValue - spread)
    middleLine.extend(lineExtend)
    upperLine.extend(lineExtend)
    lowerLine.extend(lineExtend)
The Pine it came from
//@version=6
indicator("Linear regression channel", shorttitle = "LinReg", overlay = true, max_bars_back = 500)

// ====================================================================
// LINEAR REGRESSION CHANNEL
// The straight line that best fits the closes of the lookback (the
// least-squares line), with a line either side a set number of
// standard deviations away. The middle line's slope is the trend's
// direction and pace; a close near an outer line is unusually far
// from the trend. The deviation is that of the closes from the middle
// line itself, not from their average. The channel is fitted again
// on each update of the last bar, so it always shows the latest fit.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(100, "Length", minval = 2, maxval = 500, tooltip = "How many bars the line is fitted over")
mult = input.float(2.0, "Width (deviations)", minval = 0.1, step = 0.1, tooltip = "From the middle to each outer line")
extendRight = input.bool(true, "Extend to the right")
middleColor = input.color(#2196f3, "Middle line colour")
outerColor = input.color(#a396ff, "Outer lines colour")

// ---- 2. Calculation ------------------------------------------------
// The two ends of the middle line: the least-squares line's value on
// this bar and on the oldest bar of the lookback.
newestValue = ta.linreg(close, length, 0)
oldestValue = ta.linreg(close, length, length - 1)

// How much the line rises from one bar to the next.
slope = (newestValue - oldestValue) / (length - 1)

// On the last bar only: the standard deviation of the closes from the
// line, the square root of the average squared gap between each close
// and the line's value on that close's bar.
float deviation = na
if barstate.islast
    sumSquares = 0.0
    for i = 0 to length - 1
        gap = close[i] - (newestValue - slope * i)
        sumSquares += gap * gap
    deviation := math.sqrt(sumSquares / length)

// ---- 3. Drawing ----------------------------------------------------
// The three lines and the shade between the outer two are made once,
// then moved onto the latest fit on each update.
var line middleLine = line.new(na, na, na, na, color = middleColor, width = 2)
var line upperLine = line.new(na, na, na, na, color = outerColor)
var line lowerLine = line.new(na, na, na, na, color = outerColor)
var linefill channelFill = linefill.new(upperLine, lowerLine, color.new(outerColor, 92))

if barstate.islast
    oldestBar = bar_index - (length - 1)
    spread = mult * deviation
    lineExtend = extendRight ? extend.right : extend.none
    line.set_xy1(middleLine, oldestBar, oldestValue)
    line.set_xy2(middleLine, bar_index, newestValue)
    line.set_xy1(upperLine, oldestBar, oldestValue + spread)
    line.set_xy2(upperLine, bar_index, newestValue + spread)
    line.set_xy1(lowerLine, oldestBar, oldestValue - spread)
    line.set_xy2(lowerLine, bar_index, newestValue - spread)
    line.set_extend(middleLine, lineExtend)
    line.set_extend(upperLine, lineExtend)
    line.set_extend(lowerLine, lineExtend)

Parabolic SAR

Stop and reverse: a trail of dots under the price in an uptrend and over it in a downtrend.

CharmScript 1.0
script("Parabolic SAR", tool = indicator, chart = main, legendtitle = "SAR")

// ====================================================================
// PARABOLIC SAR
// Stop and reverse: a trail of dots under the price in an uptrend and
// over it in a downtrend. The dots close in on the price faster the
// longer the trend runs, and when the price crosses them they jump to
// the other side: the trend has turned. This is Wilder's version.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
start = input.float(0.02, "Start", min = 0.001, step = 0.001, tooltip = "The share of the gap closed at first")
increment = input.float(0.02, "Increment", min = 0.001, step = 0.001, tooltip = "Added at each new extreme")
maximum = input.float(0.2, "Maximum", min = 0.001, step = 0.01, tooltip = "The largest the share can grow to")
upColor = input.color(#00d79e, "Uptrend colour")
downColor = input.color(#ff5252, "Downtrend colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar the dots move towards the trend's extreme (the highest high
// of an uptrend, the lowest low of a downtrend) by a share of the gap.
// The share starts at the start value and grows by the increment at
// each new extreme, up to the maximum.
sar = ind.sar(start, increment, maximum)

// Under the close is an uptrend, over it a downtrend. A flip is the
// dots changing sides between the bar before and this one.
dotColor = sar < p.close ? upColor : downColor
flipsBelow = sar < p.close and sar[-2] > p.close[-2]
flipsAbove = sar > p.close and sar[-2] < p.close[-2]

// ---- 3. Drawing ----------------------------------------------------
plot.circles(sar, "SAR", color = dotColor, linewidth = 2)

// ---- 4. Alerts -----------------------------------------------------
alert(flipsBelow, "SAR flips below", "Parabolic SAR: it flipped below the price, the trend turned up")
alert(flipsAbove, "SAR flips above", "Parabolic SAR: it flipped above the price, the trend turned down")
The Pine it came from
//@version=6
indicator("Parabolic SAR", shorttitle = "SAR", overlay = true)

// ====================================================================
// PARABOLIC SAR
// Stop and reverse: a trail of dots under the price in an uptrend and
// over it in a downtrend. The dots close in on the price faster the
// longer the trend runs, and when the price crosses them they jump to
// the other side: the trend has turned. This is Wilder's version.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
start = input.float(0.02, "Start", minval = 0.001, step = 0.001, tooltip = "The share of the gap closed at first")
increment = input.float(0.02, "Increment", minval = 0.001, step = 0.001, tooltip = "Added at each new extreme")
maximum = input.float(0.2, "Maximum", minval = 0.001, step = 0.01, tooltip = "The largest the share can grow to")
upColor = input.color(#00d79e, "Uptrend colour")
downColor = input.color(#ff5252, "Downtrend colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar the dots move towards the trend's extreme (the highest high
// of an uptrend, the lowest low of a downtrend) by a share of the gap.
// The share starts at the start value and grows by the increment at
// each new extreme, up to the maximum.
sar = ta.sar(start, increment, maximum)

// Under the close is an uptrend, over it a downtrend. A flip is the
// dots changing sides between the bar before and this one.
dotColor = sar < close ? upColor : downColor
flipsBelow = sar < close and sar[1] > close[1]
flipsAbove = sar > close and sar[1] < close[1]

// ---- 3. Drawing ----------------------------------------------------
plot(sar, "SAR", color = dotColor, style = plot.style_circles, linewidth = 2)

// ---- 4. Alerts -----------------------------------------------------
alertcondition(flipsBelow, "SAR flips below", "Parabolic SAR: it flipped below the price, the trend turned up")
alertcondition(flipsAbove, "SAR flips above", "Parabolic SAR: it flipped above the price, the trend turned down")

Chandelier exit

A trailing stop hung a few ATRs (average true ranges) below the highest point of the recent bars, like a chandelier from a ceiling, with its mirror above the lowest point.

CharmScript 1.0
script("Chandelier exit", tool = indicator, chart = main, legendtitle = "CE")

// ====================================================================
// CHANDELIER EXIT
// A trailing stop hung a few ATRs (average true ranges) below the
// highest point of the recent bars, like a chandelier from a ceiling,
// with its mirror above the lowest point. This version also follows
// the side: a close above the short stop turns it long, a close below
// the long stop turns it short, and only that side's stop is drawn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(22, "ATR length", min = 1, tooltip = "Bars for the ATR and for the highest and lowest")
mult = input.float(3.0, "Multiplier", min = 0.1, step = 0.1, tooltip = "ATRs from each extreme to its stop")
useClose = input.bool(true, "Use the close for the extremes", tooltip = "Off: the highs and lows instead")
longColor = input.color(#00d79e, "Long colour")
shortColor = input.color(#ff5252, "Short colour")

// ---- 2. Calculation ------------------------------------------------
// How far the stops hang from the extremes.
distance = mult * ind.atr(length)

// The extremes over the length: of the closes, or of the highs for the
// long stop and the lows for the short stop.
extremeHigh = math.highest(useClose ? p.close : p.high, length)
extremeLow = math.lowest(useClose ? p.close : p.low, length)

// The long stop hangs the distance below the highest. While the close
// on the bar before stayed above the long stop of the bar before, it
// can only move up; once a close falls below it, it starts again.
var longStop = none
longBase = extremeHigh - distance
longStop = p.close[-2] > longStop ? math.max(longBase, longStop) : longBase

// The short stop mirrors it: the distance above the lowest, and only
// moving down while the closes stay below it.
var shortStop = none
shortBase = extremeLow + distance
shortStop = p.close[-2] < shortStop ? math.min(shortBase, shortStop) : shortBase

// The side, kept from one bar to the next, and none until the first
// break: long once a close goes above the short stop of the bar
// before, short once a close goes below the long stop of the bar
// before.
var direction = 0
if direction != 1 and p.close > shortStop[-2]:
    direction = 1
elif direction != -1 and p.close < longStop[-2]:
    direction = -1

// A flip from one side to the other.
turnsLong = direction == 1 and direction[-2] == -1
turnsShort = direction == -1 and direction[-2] == 1

// ---- 3. Drawing ----------------------------------------------------
// Each stop is drawn only while its side is the one in force, with a
// gap at each change of side, and a label at the stop where it flips.
plot.line(direction == 1 ? longStop : none, "Long stop", color = longColor, linewidth = 2)
plot.line(direction == -1 ? shortStop : none, "Short stop", color = shortColor, linewidth = 2)
buyAt = turnsLong ? longStop : none
sellAt = turnsShort ? shortStop : none
plot.shape(buyAt, "Buy", style = style.labelup, y = y.absolute, color = longColor, text = "Buy", textcolor = #0b0f14)
plot.shape(sellAt, "Sell", style = style.labeldown, y = y.absolute, color = shortColor, text = "Sell", textcolor = #0b0f14)

// ---- 4. Alerts -----------------------------------------------------
alert(turnsLong, "Buy", "Chandelier exit: a close above the short stop turned it long")
alert(turnsShort, "Sell", "Chandelier exit: a close below the long stop turned it short")
The Pine it came from
//@version=6
indicator("Chandelier exit", shorttitle = "CE", overlay = true)

// ====================================================================
// CHANDELIER EXIT
// A trailing stop hung a few ATRs (average true ranges) below the
// highest point of the recent bars, like a chandelier from a ceiling,
// with its mirror above the lowest point. This version also follows
// the side: a close above the short stop turns it long, a close below
// the long stop turns it short, and only that side's stop is drawn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(22, "ATR length", minval = 1, tooltip = "Bars for the ATR and for the highest and lowest")
mult = input.float(3.0, "Multiplier", minval = 0.1, step = 0.1, tooltip = "ATRs from each extreme to its stop")
useClose = input.bool(true, "Use the close for the extremes", tooltip = "Off: the highs and lows instead")
longColor = input.color(#00d79e, "Long colour")
shortColor = input.color(#ff5252, "Short colour")

// ---- 2. Calculation ------------------------------------------------
// How far the stops hang from the extremes.
distance = mult * ta.atr(length)

// The extremes over the length: of the closes, or of the highs for the
// long stop and the lows for the short stop.
extremeHigh = ta.highest(useClose ? close : high, length)
extremeLow = ta.lowest(useClose ? close : low, length)

// The long stop hangs the distance below the highest. While the close
// on the bar before stayed above the long stop of the bar before, it
// can only move up; once a close falls below it, it starts again.
var float longStop = na
longBase = extremeHigh - distance
longStop := close[1] > longStop ? math.max(longBase, longStop) : longBase

// The short stop mirrors it: the distance above the lowest, and only
// moving down while the closes stay below it.
var float shortStop = na
shortBase = extremeLow + distance
shortStop := close[1] < shortStop ? math.min(shortBase, shortStop) : shortBase

// The side, kept from one bar to the next, and none until the first
// break: long once a close goes above the short stop of the bar
// before, short once a close goes below the long stop of the bar
// before.
var int direction = 0
if direction != 1 and close > shortStop[1]
    direction := 1
else if direction != -1 and close < longStop[1]
    direction := -1

// A flip from one side to the other.
turnsLong = direction == 1 and direction[1] == -1
turnsShort = direction == -1 and direction[1] == 1

// ---- 3. Drawing ----------------------------------------------------
// Each stop is drawn only while its side is the one in force, with a
// gap at each change of side, and a label at the stop where it flips.
plot(direction == 1 ? longStop : na, "Long stop", color = longColor, style = plot.style_linebr, linewidth = 2)
plot(direction == -1 ? shortStop : na, "Short stop", color = shortColor, style = plot.style_linebr, linewidth = 2)
buyAt = turnsLong ? longStop : na
sellAt = turnsShort ? shortStop : na
plotshape(buyAt, "Buy", shape.labelup, location.absolute, color = longColor, text = "Buy", textcolor = #0b0f14)
plotshape(sellAt, "Sell", shape.labeldown, location.absolute, color = shortColor, text = "Sell", textcolor = #0b0f14)

// ---- 4. Alerts -----------------------------------------------------
alertcondition(turnsLong, "Buy", "Chandelier exit: a close above the short stop turned it long")
alertcondition(turnsShort, "Sell", "Chandelier exit: a close below the long stop turned it short")

Heikin Ashi candles

Candles built from averages of the price, so a trend shows as a run of one colour with few wicks against it, and a turn as small bodies with wicks either side.

CharmScript 1.0
script("Heikin Ashi candles", tool = indicator, chart = main, legendtitle = "HA")

// ====================================================================
// HEIKIN ASHI CANDLES
// Candles built from averages of the price, so a trend shows as a run
// of one colour with few wicks against it, and a turn as small bodies
// with wicks either side. They are drawn over the chart's own candles:
// hide those to see these alone. Their prices are averages, not the
// prices that traded.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
upColor = input.color(#00d79e, "Up colour")
downColor = input.color(#ff5252, "Down colour")

// ---- 2. Calculation ------------------------------------------------
// The close: the average of the bar's open, high, low and close.
haClose = (p.open + p.high + p.low + p.close) / 4

// The open, kept from one bar to the next: halfway between the open
// and the close of the candle before. On the first bar, halfway
// between the bar's own open and close.
var haOpen = none
haOpen = none(haOpen) ? (p.open + p.close) / 2 : (haOpen + haClose[-2]) / 2

// The high and low: the bar's own, stretched to take in the candle's
// open and close where those reach further.
haHigh = math.max(p.high, haOpen, haClose)
haLow = math.min(p.low, haOpen, haClose)

// An up candle closes at or above its open.
haColor = haClose >= haOpen ? upColor : downColor

// ---- 3. Drawing ----------------------------------------------------
// The body, wicks and border all in the candle's colour.
plot.candles(haOpen, haHigh, haLow, haClose, "Heikin Ashi", color = haColor, wickcolor = haColor, bordercolor = haColor)
The Pine it came from
//@version=6
indicator("Heikin Ashi candles", shorttitle = "HA", overlay = true)

// ====================================================================
// HEIKIN ASHI CANDLES
// Candles built from averages of the price, so a trend shows as a run
// of one colour with few wicks against it, and a turn as small bodies
// with wicks either side. They are drawn over the chart's own candles:
// hide those to see these alone. Their prices are averages, not the
// prices that traded.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
upColor = input.color(#00d79e, "Up colour")
downColor = input.color(#ff5252, "Down colour")

// ---- 2. Calculation ------------------------------------------------
// The close: the average of the bar's open, high, low and close.
haClose = (open + high + low + close) / 4

// The open, kept from one bar to the next: halfway between the open
// and the close of the candle before. On the first bar, halfway
// between the bar's own open and close.
var float haOpen = na
haOpen := na(haOpen) ? (open + close) / 2 : (haOpen + haClose[1]) / 2

// The high and low: the bar's own, stretched to take in the candle's
// open and close where those reach further.
haHigh = math.max(high, haOpen, haClose)
haLow = math.min(low, haOpen, haClose)

// An up candle closes at or above its open.
haColor = haClose >= haOpen ? upColor : downColor

// ---- 3. Drawing ----------------------------------------------------
// The body, wicks and border all in the candle's colour.
plotcandle(haOpen, haHigh, haLow, haClose, "Heikin Ashi", color = haColor, wickcolor = haColor, bordercolor = haColor)

Floor pivots

The classic floor traders' levels, worked out from the high, low and close of the period before and held through the whole of the next.

CharmScript 1.0
script("Floor pivots", tool = indicator, chart = main, legendtitle = "Pivots")

// ====================================================================
// FLOOR PIVOTS
// The classic floor traders' levels, worked out from the high, low and
// close of the period before and held through the whole of the next.
// The pivot is the average of the three; three resistance levels sit
// above it and three support levels below. Traders watch them as
// places where the price may pause or turn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
pivotPeriod = input.timeframe("1D", "Pivot period", tooltip = "Each period's levels come from the one before it")
pivotColor = input.color(#fbbf24, "Pivot colour")
resistanceColor = input.color(#ff5252, "Resistance colour")
supportColor = input.color(#00d79e, "Support colour")

// ---- 2. Calculation ------------------------------------------------
// Whether this bar starts a new period.
newPeriod = bar.isFirstOf(pivotPeriod)

// The period's high and low so far, and the last close, kept from one
// bar to the next. The tracking starts with the first whole period.
var periodHigh = none
var periodLow = none
var lastClose = none

// The levels, kept from one bar to the next until the next period.
var pivot = none
var r1 = none
var s1 = none
var r2 = none
var s2 = none
var r3 = none
var s3 = none

// On the first bar of a new period, the levels from the period that
// has just ended, where H, L and C are its high, low and last close:
//   P = (H + L + C) / 3
//   R1 = 2P - L          S1 = 2P - H
//   R2 = P + (H - L)     S2 = P - (H - L)
//   R3 = H + 2(P - L)    S3 = L - 2(H - P)
// Then the new period's high and low start from this bar.
if newPeriod:
    if not none(periodHigh):
        pivot = (periodHigh + periodLow + lastClose) / 3
        r1 = 2 * pivot - periodLow
        s1 = 2 * pivot - periodHigh
        r2 = pivot + (periodHigh - periodLow)
        s2 = pivot - (periodHigh - periodLow)
        r3 = periodHigh + 2 * (pivot - periodLow)
        s3 = periodLow - 2 * (periodHigh - pivot)
    periodHigh = p.high
    periodLow = p.low
elif not none(periodHigh):
    periodHigh = math.max(periodHigh, p.high)
    periodLow = math.min(periodLow, p.low)
lastClose = p.close

// ---- 3. Drawing ----------------------------------------------------
// Each level is a line through its period, with a gap where a new
// period starts.
plot.line(newPeriod ? none : r3, "R3", color = resistanceColor)
plot.line(newPeriod ? none : r2, "R2", color = resistanceColor)
plot.line(newPeriod ? none : r1, "R1", color = resistanceColor)
plot.line(newPeriod ? none : pivot, "P", color = pivotColor, linewidth = 2)
plot.line(newPeriod ? none : s1, "S1", color = supportColor)
plot.line(newPeriod ? none : s2, "S2", color = supportColor)
plot.line(newPeriod ? none : s3, "S3", color = supportColor)

// A label for each level, to the right of the newest bar, with its
// name and price. Each is made once, with no background, then moved
// and rewritten on every update of the newest bar.
noFill = color.hex(#000000, 100)

newLevelLabel(textColor) =>
    return plot.label(bars.count, none, "", color = noFill, style = style.labelleft, textcolor = textColor)

placeLabel(lbl, level, levelName) =>
    lbl.xy(bars.count + 3, level)
    lbl.text(levelName + " " + format(level, "tick"))

var r3Label = newLevelLabel(resistanceColor)
var r2Label = newLevelLabel(resistanceColor)
var r1Label = newLevelLabel(resistanceColor)
var pivotLabel = newLevelLabel(pivotColor)
var s1Label = newLevelLabel(supportColor)
var s2Label = newLevelLabel(supportColor)
var s3Label = newLevelLabel(supportColor)

if bar.isLast:
    placeLabel(r3Label, r3, "R3")
    placeLabel(r2Label, r2, "R2")
    placeLabel(r1Label, r1, "R1")
    placeLabel(pivotLabel, pivot, "P")
    placeLabel(s1Label, s1, "S1")
    placeLabel(s2Label, s2, "S2")
    placeLabel(s3Label, s3, "S3")
The Pine it came from
//@version=6
indicator("Floor pivots", shorttitle = "Pivots", overlay = true)

// ====================================================================
// FLOOR PIVOTS
// The classic floor traders' levels, worked out from the high, low and
// close of the period before and held through the whole of the next.
// The pivot is the average of the three; three resistance levels sit
// above it and three support levels below. Traders watch them as
// places where the price may pause or turn.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
pivotPeriod = input.timeframe("1D", "Pivot period", tooltip = "Each period's levels come from the one before it")
pivotColor = input.color(#fbbf24, "Pivot colour")
resistanceColor = input.color(#ff5252, "Resistance colour")
supportColor = input.color(#00d79e, "Support colour")

// ---- 2. Calculation ------------------------------------------------
// Whether this bar starts a new period.
newPeriod = timeframe.change(pivotPeriod)

// The period's high and low so far, and the last close, kept from one
// bar to the next. The tracking starts with the first whole period.
var float periodHigh = na
var float periodLow = na
var float lastClose = na

// The levels, kept from one bar to the next until the next period.
var float pivot = na
var float r1 = na
var float s1 = na
var float r2 = na
var float s2 = na
var float r3 = na
var float s3 = na

// On the first bar of a new period, the levels from the period that
// has just ended, where H, L and C are its high, low and last close:
//   P = (H + L + C) / 3
//   R1 = 2P - L          S1 = 2P - H
//   R2 = P + (H - L)     S2 = P - (H - L)
//   R3 = H + 2(P - L)    S3 = L - 2(H - P)
// Then the new period's high and low start from this bar.
if newPeriod
    if not na(periodHigh)
        pivot := (periodHigh + periodLow + lastClose) / 3
        r1 := 2 * pivot - periodLow
        s1 := 2 * pivot - periodHigh
        r2 := pivot + (periodHigh - periodLow)
        s2 := pivot - (periodHigh - periodLow)
        r3 := periodHigh + 2 * (pivot - periodLow)
        s3 := periodLow - 2 * (periodHigh - pivot)
    periodHigh := high
    periodLow := low
else if not na(periodHigh)
    periodHigh := math.max(periodHigh, high)
    periodLow := math.min(periodLow, low)
lastClose := close

// ---- 3. Drawing ----------------------------------------------------
// Each level is a line through its period, with a gap where a new
// period starts.
plot(newPeriod ? na : r3, "R3", color = resistanceColor, style = plot.style_linebr)
plot(newPeriod ? na : r2, "R2", color = resistanceColor, style = plot.style_linebr)
plot(newPeriod ? na : r1, "R1", color = resistanceColor, style = plot.style_linebr)
plot(newPeriod ? na : pivot, "P", color = pivotColor, style = plot.style_linebr, linewidth = 2)
plot(newPeriod ? na : s1, "S1", color = supportColor, style = plot.style_linebr)
plot(newPeriod ? na : s2, "S2", color = supportColor, style = plot.style_linebr)
plot(newPeriod ? na : s3, "S3", color = supportColor, style = plot.style_linebr)

// A label for each level, to the right of the newest bar, with its
// name and price. Each is made once, with no background, then moved
// and rewritten on every update of the newest bar.
noFill = color.new(#000000, 100)

newLevelLabel(textColor) =>
    label.new(bar_index, na, "", style = label.style_label_left, color = noFill, textcolor = textColor)

placeLabel(lbl, level, levelName) =>
    label.set_xy(lbl, bar_index + 3, level)
    label.set_text(lbl, levelName + " " + str.tostring(level, format.mintick))

var label r3Label = newLevelLabel(resistanceColor)
var label r2Label = newLevelLabel(resistanceColor)
var label r1Label = newLevelLabel(resistanceColor)
var label pivotLabel = newLevelLabel(pivotColor)
var label s1Label = newLevelLabel(supportColor)
var label s2Label = newLevelLabel(supportColor)
var label s3Label = newLevelLabel(supportColor)

if barstate.islast
    placeLabel(r3Label, r3, "R3")
    placeLabel(r2Label, r2, "R2")
    placeLabel(r1Label, r1, "R1")
    placeLabel(pivotLabel, pivot, "P")
    placeLabel(s1Label, s1, "S1")
    placeLabel(s2Label, s2, "S2")
    placeLabel(s3Label, s3, "S3")

Auto Fibonacci retracement

Finds the biggest move of the lookback, from its lowest low to its highest high or the other way round, whichever came first, and draws its Fibonacci levels.

CharmScript 1.0
script("Auto Fibonacci retracement", tool = indicator, chart = main, legendtitle = "Auto Fib")

// ====================================================================
// AUTO FIBONACCI RETRACEMENT
// Finds the biggest move of the lookback, from its lowest low to its
// highest high or the other way round, whichever came first, and
// draws its Fibonacci levels. Level 0 is where the move ended and 1 is
// where it began: at 0.618 the price has given back 61.8% of the move.
// Traders watch the levels as places where a pullback may stop. They
// are drawn again on each update of the last bar.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
lookback = input.int(100, "Lookback", min = 2, max = 1000, tooltip = "How many bars back to look for the move")

// ---- 2. Calculation ------------------------------------------------
// The highest high and the lowest low of the lookback, and how many
// bars back each one was.
highestHigh = math.highest(p.high, lookback)
lowestLow = math.lowest(p.low, lookback)
highBarsBack = -(math.highestbars(p.high, lookback) + 1)
lowBarsBack = -(math.lowestbars(p.low, lookback) + 1)

// The move runs from whichever came first to the other: up when the
// low is the older of the two, down when the high is.
movesUp = lowBarsBack > highBarsBack
moveStart = movesUp ? lowestLow : highestHigh
moveEnd = movesUp ? highestHigh : lowestLow
startBarsBack = movesUp ? lowBarsBack : highBarsBack

// The levels, as shares of the move given back from its end, and the
// colour of each.
var levels = array(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
var levelColors = array(#787b86, #ff5252, #fbbf24, #00d79e, #2196f3, #a396ff, #787b86)

// ---- 3. Drawing ----------------------------------------------------
// The lines and labels of the last update, kept so that each update
// can take them away before it draws its own.
var levelLines = array()
var levelLabels = array()

if bar.isLast:
    for oldLine in levelLines:
        oldLine.delete()
    for oldLabel in levelLabels:
        oldLabel.delete()
    levelLines.clear()
    levelLabels.clear()

    // Each level's price, a line at it from the start of the move that
    // runs on to the right, and a label just left of the start with the
    // level and its price, its text alone in the level's colour.
    fromBar = bars.count - startBarsBack
    for i in range(levels.size()):
        level = levels[i]
        price = moveEnd - level * (moveEnd - moveStart)
        levelColor = levelColors[i]
        caption = format(level) + " (" + format(price, "tick") + ")"
        levelLines.push(plot.segment(fromBar, price, bars.count, price, extend = "right", color = levelColor))
        tag = plot.label(fromBar, price, caption, color = none, style = style.labelright, textcolor = levelColor)
        levelLabels.push(tag)
The Pine it came from
//@version=6
indicator("Auto Fibonacci retracement", shorttitle = "Auto Fib", overlay = true)

// ====================================================================
// AUTO FIBONACCI RETRACEMENT
// Finds the biggest move of the lookback, from its lowest low to its
// highest high or the other way round, whichever came first, and
// draws its Fibonacci levels. Level 0 is where the move ended and 1 is
// where it began: at 0.618 the price has given back 61.8% of the move.
// Traders watch the levels as places where a pullback may stop. They
// are drawn again on each update of the last bar.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
lookback = input.int(100, "Lookback", minval = 2, maxval = 1000, tooltip = "How many bars back to look for the move")

// ---- 2. Calculation ------------------------------------------------
// The highest high and the lowest low of the lookback, and how many
// bars back each one was.
highestHigh = ta.highest(high, lookback)
lowestLow = ta.lowest(low, lookback)
highBarsBack = -ta.highestbars(high, lookback)
lowBarsBack = -ta.lowestbars(low, lookback)

// The move runs from whichever came first to the other: up when the
// low is the older of the two, down when the high is.
movesUp = lowBarsBack > highBarsBack
moveStart = movesUp ? lowestLow : highestHigh
moveEnd = movesUp ? highestHigh : lowestLow
startBarsBack = movesUp ? lowBarsBack : highBarsBack

// The levels, as shares of the move given back from its end, and the
// colour of each.
var array<float> levels = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0)
var array<color> levelColors = array.from(#787b86, #ff5252, #fbbf24, #00d79e, #2196f3, #a396ff, #787b86)

// ---- 3. Drawing ----------------------------------------------------
// The lines and labels of the last update, kept so that each update
// can take them away before it draws its own.
var array<line> levelLines = array.new<line>()
var array<label> levelLabels = array.new<label>()

if barstate.islast
    for oldLine in levelLines
        line.delete(oldLine)
    for oldLabel in levelLabels
        label.delete(oldLabel)
    array.clear(levelLines)
    array.clear(levelLabels)

    // Each level's price, a line at it from the start of the move that
    // runs on to the right, and a label just left of the start with the
    // level and its price, its text alone in the level's colour.
    fromBar = bar_index - startBarsBack
    for [i, level] in levels
        price = moveEnd - level * (moveEnd - moveStart)
        levelColor = array.get(levelColors, i)
        caption = str.tostring(level) + " (" + str.tostring(price, format.mintick) + ")"
        array.push(levelLines, line.new(fromBar, price, bar_index, price, color = levelColor, extend = extend.right))
        tag = label.new(fromBar, price, caption, color = na, textcolor = levelColor, style = label.style_label_right)
        array.push(levelLabels, tag)

ZigZag

Joins the swing highs and lows and leaves out every move smaller than the deviation.

CharmScript 1.0
script("ZigZag", tool = indicator, chart = main)

// ====================================================================
// ZIGZAG
// Joins the swing highs and lows and leaves out every move smaller
// than the deviation. A swing ends when the price turns that many per
// cent away from the swing's extreme, measured on the bars' highs and
// lows: the extreme becomes a pivot, labelled with the move of the leg
// that ended there, and a new leg starts from it. The newest leg is
// still open: its end follows the price while it keeps going its way,
// and becomes a pivot only once the price turns.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
deviation = input.float(5.0, "Deviation (%)", min = 0.1, step = 0.1, tooltip = "How far the price must turn back")
upColor = input.color(#00d79e, "Up leg colour")
downColor = input.color(#ff5252, "Down leg colour")

// ---- 2. Calculation ------------------------------------------------
// The way the swing is going (1 up, -1 down, 0 until the first swing),
// its extreme so far and that extreme's bar, and the price its leg
// started from, all kept from one bar to the next.
var direction = 0
var extremePrice = none
var extremeBar = none
var legStart = none

// What this bar did: took the swing further, or turned it. A turn
// leaves a pivot at the old extreme, which ends the leg before it.
extended = false
turned = false
pivotBar = none
pivotPrice = none
pivotLegStart = none

// To turn the swing, the price must climb to this multiple of its low,
// or fall to this multiple of its high.
riseToTurn = 1 + deviation / 100
fallToTurn = 1 - deviation / 100

if bar.isFirst:
    // The first close is where the first leg starts.
    extremePrice = p.close
    extremeBar = bars.count
elif direction == 1 and p.high > extremePrice:
    extremePrice = p.high
    extremeBar = bars.count
    extended = true
elif direction == -1 and p.low < extremePrice:
    extremePrice = p.low
    extremeBar = bars.count
    extended = true
else:
    // Before the first swing either way can start one; after that, a
    // swing can only turn against itself.
    turnsUp = direction <= 0 and p.high >= extremePrice * riseToTurn
    turnsDown = not turnsUp and direction >= 0 and p.low <= extremePrice * fallToTurn
    if turnsUp or turnsDown:
        pivotBar = extremeBar
        pivotPrice = extremePrice
        pivotLegStart = legStart
        legStart = extremePrice
        direction = turnsUp ? 1 : -1
        extremePrice = turnsUp ? p.high : p.low
        extremeBar = bars.count
        turned = true

// ---- 3. Drawing ----------------------------------------------------
// The move of a leg from its start to its end, in per cent, as text.
moveText(fromPrice, toPrice) =>
    move = (toPrice - fromPrice) / fromPrice * 100
    return (move > 0 ? "+" : "") + format(move, "#.##") + "%"

// The newest leg's line, kept from one bar to the next so that its end
// can follow the swing.
var legLine = none

if turned:
    // The pivot's label gives the move of the leg that ended there. The
    // first leg starts from the first close, which is no pivot.
    if not none(pivotLegStart):
        endedUp = direction == -1
        labelColor = endedUp ? upColor : downColor
        labelStyle = endedUp ? style.labeldown : style.labelup
        pivotText = moveText(pivotLegStart, pivotPrice)
        plot.label(pivotBar, pivotPrice, pivotText, color = labelColor, style = labelStyle, textcolor = #000000)
    legColor = direction == 1 ? upColor : downColor
    legLine = plot.segment(pivotBar, pivotPrice, bars.count, extremePrice, color = legColor, width = 2)
elif extended:
    legLine.xy2(bars.count, extremePrice)
The Pine it came from
//@version=6
indicator("ZigZag", overlay = true, max_lines_count = 500, max_labels_count = 500)

// ====================================================================
// ZIGZAG
// Joins the swing highs and lows and leaves out every move smaller
// than the deviation. A swing ends when the price turns that many per
// cent away from the swing's extreme, measured on the bars' highs and
// lows: the extreme becomes a pivot, labelled with the move of the leg
// that ended there, and a new leg starts from it. The newest leg is
// still open: its end follows the price while it keeps going its way,
// and becomes a pivot only once the price turns.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
deviation = input.float(5.0, "Deviation (%)", minval = 0.1, step = 0.1, tooltip = "How far the price must turn back")
upColor = input.color(#00d79e, "Up leg colour")
downColor = input.color(#ff5252, "Down leg colour")

// ---- 2. Calculation ------------------------------------------------
// The way the swing is going (1 up, -1 down, 0 until the first swing),
// its extreme so far and that extreme's bar, and the price its leg
// started from, all kept from one bar to the next.
var int direction = 0
var float extremePrice = na
var int extremeBar = na
var float legStart = na

// What this bar did: took the swing further, or turned it. A turn
// leaves a pivot at the old extreme, which ends the leg before it.
bool extended = false
bool turned = false
int pivotBar = na
float pivotPrice = na
float pivotLegStart = na

// To turn the swing, the price must climb to this multiple of its low,
// or fall to this multiple of its high.
riseToTurn = 1 + deviation / 100
fallToTurn = 1 - deviation / 100

if barstate.isfirst
    // The first close is where the first leg starts.
    extremePrice := close
    extremeBar := bar_index
else if direction == 1 and high > extremePrice
    extremePrice := high
    extremeBar := bar_index
    extended := true
else if direction == -1 and low < extremePrice
    extremePrice := low
    extremeBar := bar_index
    extended := true
else
    // Before the first swing either way can start one; after that, a
    // swing can only turn against itself.
    turnsUp = direction <= 0 and high >= extremePrice * riseToTurn
    turnsDown = not turnsUp and direction >= 0 and low <= extremePrice * fallToTurn
    if turnsUp or turnsDown
        pivotBar := extremeBar
        pivotPrice := extremePrice
        pivotLegStart := legStart
        legStart := extremePrice
        direction := turnsUp ? 1 : -1
        extremePrice := turnsUp ? high : low
        extremeBar := bar_index
        turned := true

// ---- 3. Drawing ----------------------------------------------------
// The move of a leg from its start to its end, in per cent, as text.
moveText(fromPrice, toPrice) =>
    move = (toPrice - fromPrice) / fromPrice * 100
    (move > 0 ? "+" : "") + str.tostring(move, "#.##") + "%"

// The newest leg's line, kept from one bar to the next so that its end
// can follow the swing.
var line legLine = na

if turned
    // The pivot's label gives the move of the leg that ended there. The
    // first leg starts from the first close, which is no pivot.
    if not na(pivotLegStart)
        endedUp = direction == -1
        labelColor = endedUp ? upColor : downColor
        labelStyle = endedUp ? label.style_label_down : label.style_label_up
        pivotText = moveText(pivotLegStart, pivotPrice)
        label.new(pivotBar, pivotPrice, pivotText, color = labelColor, style = labelStyle, textcolor = #000000)
    legColor = direction == 1 ? upColor : downColor
    legLine := line.new(pivotBar, pivotPrice, bar_index, extremePrice, color = legColor, width = 2)
else if extended
    line.set_xy2(legLine, bar_index, extremePrice)

Candlestick patterns

Marks five classic candle shapes, read from the sizes of the bar's body and wicks against its whole range, from high to low: - Bullish engulfing: a rising bar whose body covers, and is bigger than, the body of the falling bar before it.

CharmScript 1.0
script("Candlestick patterns", tool = indicator, chart = main, legendtitle = "Patterns")

// ====================================================================
// CANDLESTICK PATTERNS
// Marks five classic candle shapes, read from the sizes of the bar's
// body and wicks against its whole range, from high to low:
// - Bullish engulfing: a rising bar whose body covers, and is bigger
//   than, the body of the falling bar before it.
// - Bearish engulfing: the same, the other way round.
// - Hammer: a small body at the top of the bar over a long lower wick.
// - Shooting star: a small body at the bottom under a long upper wick.
// - Doji: a body so small that the bar closed about where it opened.
//   A bar with a body that small is only ever a doji.
// These are shapes only: the trend before one, which traders read as
// well, is left to you. A table counts how often each has been seen.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
showBullEngulf = input.bool(true, "Bullish engulfing", group = "Patterns")
showBearEngulf = input.bool(true, "Bearish engulfing", group = "Patterns")
showHammer = input.bool(true, "Hammer", group = "Patterns")
showStar = input.bool(true, "Shooting star", group = "Patterns")
showDoji = input.bool(true, "Doji", group = "Patterns")
dojiBody = input.float(10.0, "Doji: largest body (% of range)", min = 0, max = 50, group = "Sizes")
wickRatio = input.float(2.0, "Hammer and star: smallest wick to body", min = 1, step = 0.1, group = "Sizes")
bullColor = input.color(#00d79e, "Bullish colour", group = "Colours")
bearColor = input.color(#ff5252, "Bearish colour", group = "Colours")
dojiColor = input.color(#787b86, "Doji colour", group = "Colours")

// ---- 2. Calculation ------------------------------------------------
// The parts of the bar: its body from open to close, its wicks above
// and below the body, and its whole range.
body = math.abs(p.close - p.open)
upperWick = p.high - math.max(p.open, p.close)
lowerWick = math.min(p.open, p.close) - p.low
barRange = p.high - p.low

// A doji's body is at most the set share of the range; only a bigger
// body can make one of the other four patterns.
isDoji = barRange > 0 and body <= barRange * dojiBody / 100
hasBody = barRange > 0 and not isDoji

// Engulfing: a body that covers the whole body of the bar before,
// which went the other way, and is bigger than it.
coversUp = p.close > p.open and p.close[-2] < p.open[-2] and p.open <= p.close[-2] and p.close >= p.open[-2]
coversDown = p.close < p.open and p.close[-2] > p.open[-2] and p.open >= p.close[-2] and p.close <= p.open[-2]
biggerBody = body > body[-2]

// Each pattern is looked for only while it is switched on. A hammer's
// lower wick is at least the set number of bodies long, and its upper
// wick no longer than its body; a shooting star is a hammer upside
// down.
bullEngulf = showBullEngulf and hasBody and coversUp and biggerBody
bearEngulf = showBearEngulf and hasBody and coversDown and biggerBody
hammer = showHammer and hasBody and lowerWick >= wickRatio * body and upperWick <= body
star = showStar and hasBody and upperWick >= wickRatio * body and lowerWick <= body
doji = showDoji and isDoji

// How many times each has been seen, kept from one bar to the next.
var bullEngulfCount = 0
var bearEngulfCount = 0
var hammerCount = 0
var starCount = 0
var dojiCount = 0
bullEngulfCount += bullEngulf ? 1 : 0
bearEngulfCount += bearEngulf ? 1 : 0
hammerCount += hammer ? 1 : 0
starCount += star ? 1 : 0
dojiCount += doji ? 1 : 0

// ---- 3. Drawing ----------------------------------------------------
// Bullish patterns on a label under the bar, bearish ones on a label
// over it, and a doji as a small cross over it.
plot.shape(bullEngulf, "Bull engulfing", style = style.labelup, y = y.belowbar, color = bullColor, text = "BE", textcolor = #000000)
plot.shape(bearEngulf, "Bear engulfing", style = style.labeldown, y = y.abovebar, color = bearColor, text = "BE", textcolor = #000000)
plot.shape(hammer, "Hammer", style = style.labelup, y = y.belowbar, color = bullColor, text = "H", textcolor = #000000)
plot.shape(star, "Shooting star", style = style.labeldown, y = y.abovebar, color = bearColor, text = "SS", textcolor = #000000)
plot.shape(doji, "Doji", style = style.cross, y = y.abovebar, color = dojiColor, text = "D", textcolor = dojiColor, size = "tiny")

// The table of counts in the top right, filled in on the last bar. A
// pattern that is switched off shows "Off" in place of its count.
var countTable = plot.table("top_right", 2, 6, bgcolor = color.hex(#787b86, 85), border_width = 1)

countRow(row, name, count, isOn, rowColor) =>
    countTable.cell(0, row, name, text_color = rowColor, text_halign = "left")
    countTable.cell(1, row, isOn ? format(count) : "Off", text_color = rowColor)

if bar.isLast:
    countTable.cell(0, 0, "Pattern", text_color = #787b86, text_halign = "left")
    countTable.cell(1, 0, "Seen", text_color = #787b86)
    countRow(1, "Bullish engulfing", bullEngulfCount, showBullEngulf, bullColor)
    countRow(2, "Bearish engulfing", bearEngulfCount, showBearEngulf, bearColor)
    countRow(3, "Hammer", hammerCount, showHammer, bullColor)
    countRow(4, "Shooting star", starCount, showStar, bearColor)
    countRow(5, "Doji", dojiCount, showDoji, dojiColor)

// ---- 4. Alerts -----------------------------------------------------
// One alert when a bar closes on any pattern that is switched on,
// naming every pattern the bar made.
if bar.isConfirmed:
    found = array()
    if bullEngulf:
        found.push("bullish engulfing")
    if bearEngulf:
        found.push("bearish engulfing")
    if hammer:
        found.push("hammer")
    if star:
        found.push("shooting star")
    if doji:
        found.push("doji")
    if found.size() > 0:
        message = "Candlestick patterns: " + found.join(", ") + " on " + chart.symbol
        alert(true, "Candlestick patterns", message)
The Pine it came from
//@version=6
indicator("Candlestick patterns", shorttitle = "Patterns", overlay = true)

// ====================================================================
// CANDLESTICK PATTERNS
// Marks five classic candle shapes, read from the sizes of the bar's
// body and wicks against its whole range, from high to low:
// - Bullish engulfing: a rising bar whose body covers, and is bigger
//   than, the body of the falling bar before it.
// - Bearish engulfing: the same, the other way round.
// - Hammer: a small body at the top of the bar over a long lower wick.
// - Shooting star: a small body at the bottom under a long upper wick.
// - Doji: a body so small that the bar closed about where it opened.
//   A bar with a body that small is only ever a doji.
// These are shapes only: the trend before one, which traders read as
// well, is left to you. A table counts how often each has been seen.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
showBullEngulf = input.bool(true, "Bullish engulfing", group = "Patterns")
showBearEngulf = input.bool(true, "Bearish engulfing", group = "Patterns")
showHammer = input.bool(true, "Hammer", group = "Patterns")
showStar = input.bool(true, "Shooting star", group = "Patterns")
showDoji = input.bool(true, "Doji", group = "Patterns")
dojiBody = input.float(10.0, "Doji: largest body (% of range)", minval = 0, maxval = 50, group = "Sizes")
wickRatio = input.float(2.0, "Hammer and star: smallest wick to body", minval = 1, step = 0.1, group = "Sizes")
bullColor = input.color(#00d79e, "Bullish colour", group = "Colours")
bearColor = input.color(#ff5252, "Bearish colour", group = "Colours")
dojiColor = input.color(#787b86, "Doji colour", group = "Colours")

// ---- 2. Calculation ------------------------------------------------
// The parts of the bar: its body from open to close, its wicks above
// and below the body, and its whole range.
body = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
barRange = high - low

// A doji's body is at most the set share of the range; only a bigger
// body can make one of the other four patterns.
isDoji = barRange > 0 and body <= barRange * dojiBody / 100
hasBody = barRange > 0 and not isDoji

// Engulfing: a body that covers the whole body of the bar before,
// which went the other way, and is bigger than it.
coversUp = close > open and close[1] < open[1] and open <= close[1] and close >= open[1]
coversDown = close < open and close[1] > open[1] and open >= close[1] and close <= open[1]
biggerBody = body > body[1]

// Each pattern is looked for only while it is switched on. A hammer's
// lower wick is at least the set number of bodies long, and its upper
// wick no longer than its body; a shooting star is a hammer upside
// down.
bullEngulf = showBullEngulf and hasBody and coversUp and biggerBody
bearEngulf = showBearEngulf and hasBody and coversDown and biggerBody
hammer = showHammer and hasBody and lowerWick >= wickRatio * body and upperWick <= body
star = showStar and hasBody and upperWick >= wickRatio * body and lowerWick <= body
doji = showDoji and isDoji

// How many times each has been seen, kept from one bar to the next.
var int bullEngulfCount = 0
var int bearEngulfCount = 0
var int hammerCount = 0
var int starCount = 0
var int dojiCount = 0
bullEngulfCount += bullEngulf ? 1 : 0
bearEngulfCount += bearEngulf ? 1 : 0
hammerCount += hammer ? 1 : 0
starCount += star ? 1 : 0
dojiCount += doji ? 1 : 0

// ---- 3. Drawing ----------------------------------------------------
// Bullish patterns on a label under the bar, bearish ones on a label
// over it, and a doji as a small cross over it.
plotshape(bullEngulf, "Bull engulfing", shape.labelup, location.belowbar, bullColor, text = "BE", textcolor = #000000)
plotshape(bearEngulf, "Bear engulfing", shape.labeldown, location.abovebar, bearColor, text = "BE", textcolor = #000000)
plotshape(hammer, "Hammer", shape.labelup, location.belowbar, bullColor, text = "H", textcolor = #000000)
plotshape(star, "Shooting star", shape.labeldown, location.abovebar, bearColor, text = "SS", textcolor = #000000)
plotshape(doji, "Doji", shape.cross, location.abovebar, dojiColor, text = "D", textcolor = dojiColor, size = size.tiny)

// The table of counts in the top right, filled in on the last bar. A
// pattern that is switched off shows "Off" in place of its count.
var table countTable = table.new(position.top_right, 2, 6, bgcolor = color.new(#787b86, 85), border_width = 1)

countRow(row, name, count, isOn, rowColor) =>
    table.cell(countTable, 0, row, name, text_color = rowColor, text_halign = text.align_left)
    table.cell(countTable, 1, row, isOn ? str.tostring(count) : "Off", text_color = rowColor)

if barstate.islast
    table.cell(countTable, 0, 0, "Pattern", text_color = #787b86, text_halign = text.align_left)
    table.cell(countTable, 1, 0, "Seen", text_color = #787b86)
    countRow(1, "Bullish engulfing", bullEngulfCount, showBullEngulf, bullColor)
    countRow(2, "Bearish engulfing", bearEngulfCount, showBearEngulf, bearColor)
    countRow(3, "Hammer", hammerCount, showHammer, bullColor)
    countRow(4, "Shooting star", starCount, showStar, bearColor)
    countRow(5, "Doji", dojiCount, showDoji, dojiColor)

// ---- 4. Alerts -----------------------------------------------------
// One alert when a bar closes on any pattern that is switched on,
// naming every pattern the bar made.
if barstate.isconfirmed
    found = array.new<string>()
    if bullEngulf
        array.push(found, "bullish engulfing")
    if bearEngulf
        array.push(found, "bearish engulfing")
    if hammer
        array.push(found, "hammer")
    if star
        array.push(found, "shooting star")
    if doji
        array.push(found, "doji")
    if array.size(found) > 0
        message = "Candlestick patterns: " + array.join(found, ", ") + " on " + syminfo.ticker
        alert(message, alert.freq_once_per_bar_close)

Trading sessions

Shades the hours of the three main trading sessions, Asia, London and New York, and draws a box around each session's high and low.

CharmScript 1.0
script("Trading sessions", tool = indicator, chart = main, legendtitle = "Sessions")

// ====================================================================
// TRADING SESSIONS
// Shades the hours of the three main trading sessions, Asia, London
// and New York, and draws a box around each session's high and low.
// A box starts on its session's first bar and grows with it, so the
// open session's box shows its range so far. The hours are in UTC and
// can be changed; London and New York overlap in the early afternoon.
// Made for intraday charts.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
showAsia = input.bool(true, "Show", group = "Asia")
asiaHours = input.session("0000-0900", "Hours (UTC)", group = "Asia")
asiaColor = input.color(#fbbf24, "Colour", group = "Asia")
showLondon = input.bool(true, "Show", group = "London")
londonHours = input.session("0700-1600", "Hours (UTC)", group = "London")
londonColor = input.color(#2196f3, "Colour", group = "London")
showNewYork = input.bool(true, "Show", group = "New York")
newYorkHours = input.session("1300-2200", "Hours (UTC)", group = "New York")
newYorkColor = input.color(#a396ff, "Colour", group = "New York")

// ---- 2. Calculation ------------------------------------------------
// A bar is in a session when its time falls within the session's hours
// in UTC; outside them, its time in that session is missing.
inAsia = bar.inSession(asiaHours, "UTC")
inLondon = bar.inSession(londonHours, "UTC")
inNewYork = bar.inSession(newYorkHours, "UTC")

// ---- 3. Drawing ----------------------------------------------------
// A light shade behind each session's bars.
paint.background(showAsia and inAsia ? color.hex(asiaColor, 94) : none, title = "Asia")
paint.background(showLondon and inLondon ? color.hex(londonColor, 94) : none, title = "London")
paint.background(showNewYork and inNewYork ? color.hex(newYorkColor, 94) : none, title = "New York")

// A box around a session's high and low, made on the session's first
// bar and stretched over each bar after it to take in its new highs
// and lows. Each session keeps its own box, high and low from one bar
// to the next.
sessionBox(inSession, shown, boxColor) =>
    var current = none
    var sessionHigh = none
    var sessionLow = none
    boxFill = color.hex(boxColor, 88)
    if inSession and not inSession[-2]:
        sessionHigh = p.high
        sessionLow = p.low
        if shown:
            current = plot.box(bars.count, p.high, bars.count, p.low, border_color = boxColor, bgcolor = boxFill)
    elif inSession:
        sessionHigh = math.max(sessionHigh, p.high)
        sessionLow = math.min(sessionLow, p.low)
        if shown:
            current.right(bars.count)
            current.top(sessionHigh)
            current.bottom(sessionLow)
    return current

sessionBox(inAsia, showAsia, asiaColor)
sessionBox(inLondon, showLondon, londonColor)
sessionBox(inNewYork, showNewYork, newYorkColor)
The Pine it came from
//@version=6
indicator("Trading sessions", shorttitle = "Sessions", overlay = true, max_boxes_count = 500)

// ====================================================================
// TRADING SESSIONS
// Shades the hours of the three main trading sessions, Asia, London
// and New York, and draws a box around each session's high and low.
// A box starts on its session's first bar and grows with it, so the
// open session's box shows its range so far. The hours are in UTC and
// can be changed; London and New York overlap in the early afternoon.
// Made for intraday charts.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
showAsia = input.bool(true, "Show", group = "Asia")
asiaHours = input.session("0000-0900", "Hours (UTC)", group = "Asia")
asiaColor = input.color(#fbbf24, "Colour", group = "Asia")
showLondon = input.bool(true, "Show", group = "London")
londonHours = input.session("0700-1600", "Hours (UTC)", group = "London")
londonColor = input.color(#2196f3, "Colour", group = "London")
showNewYork = input.bool(true, "Show", group = "New York")
newYorkHours = input.session("1300-2200", "Hours (UTC)", group = "New York")
newYorkColor = input.color(#a396ff, "Colour", group = "New York")

// ---- 2. Calculation ------------------------------------------------
// A bar is in a session when its time falls within the session's hours
// in UTC; outside them, its time in that session is missing.
inAsia = not na(time(timeframe.period, asiaHours, timezone = "UTC"))
inLondon = not na(time(timeframe.period, londonHours, timezone = "UTC"))
inNewYork = not na(time(timeframe.period, newYorkHours, timezone = "UTC"))

// ---- 3. Drawing ----------------------------------------------------
// A light shade behind each session's bars.
bgcolor(showAsia and inAsia ? color.new(asiaColor, 94) : na, title = "Asia")
bgcolor(showLondon and inLondon ? color.new(londonColor, 94) : na, title = "London")
bgcolor(showNewYork and inNewYork ? color.new(newYorkColor, 94) : na, title = "New York")

// A box around a session's high and low, made on the session's first
// bar and stretched over each bar after it to take in its new highs
// and lows. Each session keeps its own box, high and low from one bar
// to the next.
sessionBox(inSession, shown, boxColor) =>
    var box current = na
    var float sessionHigh = na
    var float sessionLow = na
    boxFill = color.new(boxColor, 88)
    if inSession and not inSession[1]
        sessionHigh := high
        sessionLow := low
        if shown
            current := box.new(bar_index, high, bar_index, low, border_color = boxColor, bgcolor = boxFill)
    else if inSession
        sessionHigh := math.max(sessionHigh, high)
        sessionLow := math.min(sessionLow, low)
        if shown
            box.set_right(current, bar_index)
            box.set_top(current, sessionHigh)
            box.set_bottom(current, sessionLow)
    current

sessionBox(inAsia, showAsia, asiaColor)
sessionBox(inLondon, showLondon, londonColor)
sessionBox(inNewYork, showNewYork, newYorkColor)

Oscillators

Momentum first, then trend strength, then volatility: each in a pane of its own.

Stochastic

Where the close sits between the lowest low and the highest high of the lookback, from 0 at the low to 100 at the high.

CharmScript 1.0
script("Stochastic", tool = indicator, chart = oscillator, legendtitle = "Stoch", precision = 2, format = "price")

// ====================================================================
// STOCHASTIC
// Where the close sits between the lowest low and the highest high of
// the lookback, from 0 at the low to 100 at the high. This is the slow
// stochastic: that reading smoothed into K, with D an average of K as
// the signal line. Above the upper band the close is near the top of
// its recent range; below the lower band, near the bottom.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
kLength = input.int(14, "K length", min = 1)
smoothK = input.int(3, "K smoothing", min = 1)
smoothD = input.int(3, "D smoothing", min = 1)
upperBand = input.int(80, "Upper band", min = 50, max = 100)
lowerBand = input.int(20, "Lower band", min = 0, max = 50)
kColor = input.color(#2196f3, "K colour")
dColor = input.color(#fbbf24, "D colour")

// ---- 2. Calculation ------------------------------------------------
// Where the close sits between the lowest low and the highest high of
// the last K length bars: 0 at the low, 100 at the high. On its own
// this is the fast stochastic.
fastK = ind.stoch(p.close, p.high, p.low, kLength)

// K is the fast reading smoothed by a simple average, which makes this
// the slow stochastic; D is K smoothed again, the signal line.
k = ind.sma(fastK, smoothK)
d = ind.sma(k, smoothD)

// ---- 3. Drawing ----------------------------------------------------
plot.line(k, "K", color = kColor, linewidth = 2)
plot.line(d, "D", color = dColor)
upperLine = plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
lowerLine = plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
// K crossing up through D below the lower band, and down through it
// above the upper band.
crossUpLow = math.crossover(k, d) and k < lowerBand
crossDownHigh = math.crossunder(k, d) and k > upperBand
alert(crossUpLow, "K up through D, low", "Stochastic: K crossed above D below the lower band")
alert(crossDownHigh, "K down through D, high", "Stochastic: K crossed below D above the upper band")
The Pine it came from
//@version=6
indicator("Stochastic", shorttitle = "Stoch", overlay = false, format = format.price, precision = 2)

// ====================================================================
// STOCHASTIC
// Where the close sits between the lowest low and the highest high of
// the lookback, from 0 at the low to 100 at the high. This is the slow
// stochastic: that reading smoothed into K, with D an average of K as
// the signal line. Above the upper band the close is near the top of
// its recent range; below the lower band, near the bottom.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
kLength = input.int(14, "K length", minval = 1)
smoothK = input.int(3, "K smoothing", minval = 1)
smoothD = input.int(3, "D smoothing", minval = 1)
upperBand = input.int(80, "Upper band", minval = 50, maxval = 100)
lowerBand = input.int(20, "Lower band", minval = 0, maxval = 50)
kColor = input.color(#2196f3, "K colour")
dColor = input.color(#fbbf24, "D colour")

// ---- 2. Calculation ------------------------------------------------
// Where the close sits between the lowest low and the highest high of
// the last K length bars: 0 at the low, 100 at the high. On its own
// this is the fast stochastic.
fastK = ta.stoch(close, high, low, kLength)

// K is the fast reading smoothed by a simple average, which makes this
// the slow stochastic; D is K smoothed again, the signal line.
k = ta.sma(fastK, smoothK)
d = ta.sma(k, smoothD)

// ---- 3. Drawing ----------------------------------------------------
plot(k, "K", color = kColor, linewidth = 2)
plot(d, "D", color = dColor)
upperLine = hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(50, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
lowerLine = hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
// K crossing up through D below the lower band, and down through it
// above the upper band.
crossUpLow = ta.crossover(k, d) and k < lowerBand
crossDownHigh = ta.crossunder(k, d) and k > upperBand
alertcondition(crossUpLow, "K up through D, low", "Stochastic: K crossed above D below the lower band")
alertcondition(crossDownHigh, "K down through D, high", "Stochastic: K crossed below D above the upper band")

Stochastic RSI

The stochastic of the RSI: where the RSI sits between its own lowest and highest over the lookback, from 0 to 100.

CharmScript 1.0
script("Stochastic RSI", tool = indicator, chart = oscillator, legendtitle = "Stoch RSI", precision = 2, format = "price")

// ====================================================================
// STOCHASTIC RSI
// The stochastic of the RSI: where the RSI sits between its own lowest
// and highest over the lookback, from 0 to 100. It turns sooner than
// the RSI does. Above the upper band the RSI is at the top of its
// recent range; below the lower band, at the bottom.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
rsiLength = input.int(14, "RSI length", min = 1)
stochLength = input.int(14, "Stochastic length", min = 1)
smoothK = input.int(3, "K smoothing", min = 1)
smoothD = input.int(3, "D smoothing", min = 1)
upperBand = input.int(80, "Upper band", min = 50, max = 100)
lowerBand = input.int(20, "Lower band", min = 0, max = 50)
kColor = input.color(#00d79e, "K colour")
dColor = input.color(#ff5252, "D colour")

// ---- 2. Calculation ------------------------------------------------
// The RSI, then where it sits between its lowest and highest over the
// stochastic length: 0 at its low, 100 at its high.
rsiValue = ind.rsi(source, rsiLength)
rawK = ind.stoch(rsiValue, rsiValue, rsiValue, stochLength)

// K is that, smoothed; D is K smoothed again, the signal line.
k = ind.sma(rawK, smoothK)
d = ind.sma(k, smoothD)

// ---- 3. Drawing ----------------------------------------------------
plot.line(k, "K", color = kColor, linewidth = 2)
plot.line(d, "D", color = dColor)
upperLine = plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
lowerLine = plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
// K crossing D counts only near the ends: up through it below the
// lower band, down through it above the upper band.
crossUpLow = math.crossover(k, d) and k < lowerBand
crossDownHigh = math.crossunder(k, d) and k > upperBand
alert(crossUpLow, "K up through D, low", "Stochastic RSI: K crossed above D below the lower band")
alert(crossDownHigh, "K down through D, high", "Stochastic RSI: K crossed below D above the upper band")
The Pine it came from
//@version=6
indicator("Stochastic RSI", shorttitle = "Stoch RSI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// STOCHASTIC RSI
// The stochastic of the RSI: where the RSI sits between its own lowest
// and highest over the lookback, from 0 to 100. It turns sooner than
// the RSI does. Above the upper band the RSI is at the top of its
// recent range; below the lower band, at the bottom.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
rsiLength = input.int(14, "RSI length", minval = 1)
stochLength = input.int(14, "Stochastic length", minval = 1)
smoothK = input.int(3, "K smoothing", minval = 1)
smoothD = input.int(3, "D smoothing", minval = 1)
upperBand = input.int(80, "Upper band", minval = 50, maxval = 100)
lowerBand = input.int(20, "Lower band", minval = 0, maxval = 50)
kColor = input.color(#00d79e, "K colour")
dColor = input.color(#ff5252, "D colour")

// ---- 2. Calculation ------------------------------------------------
// The RSI, then where it sits between its lowest and highest over the
// stochastic length: 0 at its low, 100 at its high.
rsiValue = ta.rsi(source, rsiLength)
rawK = ta.stoch(rsiValue, rsiValue, rsiValue, stochLength)

// K is that, smoothed; D is K smoothed again, the signal line.
k = ta.sma(rawK, smoothK)
d = ta.sma(k, smoothD)

// ---- 3. Drawing ----------------------------------------------------
plot(k, "K", color = kColor, linewidth = 2)
plot(d, "D", color = dColor)
upperLine = hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(50, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
lowerLine = hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
// K crossing D counts only near the ends: up through it below the
// lower band, down through it above the upper band.
crossUpLow = ta.crossover(k, d) and k < lowerBand
crossDownHigh = ta.crossunder(k, d) and k > upperBand
alertcondition(crossUpLow, "K up through D, low", "Stochastic RSI: K crossed above D below the lower band")
alertcondition(crossDownHigh, "K down through D, high", "Stochastic RSI: K crossed below D above the upper band")

MACD

Moving average convergence divergence: a fast moving average of the price minus a slow one.

CharmScript 1.0
script("MACD", tool = indicator, chart = oscillator)

// ====================================================================
// MACD
// Moving average convergence divergence: a fast moving average of the
// price minus a slow one. It is above zero while the fast average is
// above the slow, and moves away from zero as the two spread apart.
// The signal line is an average of the MACD. The columns are the gap
// between the two lines, so they change sign where the lines cross.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
fastLength = input.int(12, "Fast length", min = 1)
slowLength = input.int(26, "Slow length", min = 1)
signalLength = input.int(9, "Signal length", min = 1)
oscillatorType = input.string("EMA", "Oscillator average", options = ["EMA", "SMA"])
signalType = input.string("EMA", "Signal average", options = ["EMA", "SMA"])
macdColor = input.color(#2196f3, "MACD colour")
signalColor = input.color(#fbbf24, "Signal colour")
aboveRising = input.color(#00d79e, "Above zero, rising", group = "Histogram")
aboveFalling = input.color(#00d79e80, "Above zero, falling", group = "Histogram")
belowFalling = input.color(#ff5252, "Below zero, falling", group = "Histogram")
belowRising = input.color(#ff525280, "Below zero, rising", group = "Histogram")

// ---- 2. Calculation ------------------------------------------------
// A moving average of the chosen kind: simple, which weighs every bar
// the same, or exponential, which weighs the latest bars the most.
movingAverage(value, len, kind) =>
    return match kind:
        "SMA": ind.sma(value, len)
        else: ind.ema(value, len)

// The MACD is the fast average of the source minus the slow one. The
// signal line is an average of the MACD, and the histogram is the gap
// between the two.
fastAverage = movingAverage(source, fastLength, oscillatorType)
slowAverage = movingAverage(source, slowLength, oscillatorType)
macdLine = fastAverage - slowAverage
signalLine = movingAverage(macdLine, signalLength, signalType)
histogram = macdLine - signalLine

// Each column takes one of four colours: above or below zero, and
// higher or lower than on the bar before. By default it is green above
// zero and red below, full while moving away from zero and pale while
// moving back towards it.
isHigher = histogram > histogram[-2]
aboveColor = isHigher ? aboveRising : aboveFalling
belowColor = isHigher ? belowRising : belowFalling
histogramColor = histogram >= 0 ? aboveColor : belowColor

// ---- 3. Drawing ----------------------------------------------------
// The histogram as columns behind the two lines, and the zero line.
plot.column(histogram, "Histogram", color = histogramColor)
plot.line(macdLine, "MACD", color = macdColor, linewidth = 2)
plot.line(signalLine, "Signal", color = signalColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)

// ---- 4. Alerts -----------------------------------------------------
alert(math.crossover(histogram, 0), "Histogram turns positive", "MACD: the histogram turned positive")
alert(math.crossunder(histogram, 0), "Histogram turns negative", "MACD: the histogram turned negative")
The Pine it came from
//@version=6
indicator("MACD", overlay = false)

// ====================================================================
// MACD
// Moving average convergence divergence: a fast moving average of the
// price minus a slow one. It is above zero while the fast average is
// above the slow, and moves away from zero as the two spread apart.
// The signal line is an average of the MACD. The columns are the gap
// between the two lines, so they change sign where the lines cross.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
fastLength = input.int(12, "Fast length", minval = 1)
slowLength = input.int(26, "Slow length", minval = 1)
signalLength = input.int(9, "Signal length", minval = 1)
oscillatorType = input.string("EMA", "Oscillator average", options = ["EMA", "SMA"])
signalType = input.string("EMA", "Signal average", options = ["EMA", "SMA"])
macdColor = input.color(#2196f3, "MACD colour")
signalColor = input.color(#fbbf24, "Signal colour")
aboveRising = input.color(#00d79e, "Above zero, rising", group = "Histogram")
aboveFalling = input.color(color.new(#00d79e, 50), "Above zero, falling", group = "Histogram")
belowFalling = input.color(#ff5252, "Below zero, falling", group = "Histogram")
belowRising = input.color(color.new(#ff5252, 50), "Below zero, rising", group = "Histogram")

// ---- 2. Calculation ------------------------------------------------
// A moving average of the chosen kind: simple, which weighs every bar
// the same, or exponential, which weighs the latest bars the most.
movingAverage(value, len, kind) =>
    switch kind
        "SMA" => ta.sma(value, len)
        => ta.ema(value, len)

// The MACD is the fast average of the source minus the slow one. The
// signal line is an average of the MACD, and the histogram is the gap
// between the two.
fastAverage = movingAverage(source, fastLength, oscillatorType)
slowAverage = movingAverage(source, slowLength, oscillatorType)
macdLine = fastAverage - slowAverage
signalLine = movingAverage(macdLine, signalLength, signalType)
histogram = macdLine - signalLine

// Each column takes one of four colours: above or below zero, and
// higher or lower than on the bar before. By default it is green above
// zero and red below, full while moving away from zero and pale while
// moving back towards it.
isHigher = histogram > histogram[1]
aboveColor = isHigher ? aboveRising : aboveFalling
belowColor = isHigher ? belowRising : belowFalling
histogramColor = histogram >= 0 ? aboveColor : belowColor

// ---- 3. Drawing ----------------------------------------------------
// The histogram as columns behind the two lines, and the zero line.
plot(histogram, "Histogram", color = histogramColor, style = plot.style_columns)
plot(macdLine, "MACD", color = macdColor, linewidth = 2)
plot(signalLine, "Signal", color = signalColor)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)

// ---- 4. Alerts -----------------------------------------------------
alertcondition(ta.crossover(histogram, 0), "Histogram turns positive", "MACD: the histogram turned positive")
alertcondition(ta.crossunder(histogram, 0), "Histogram turns negative", "MACD: the histogram turned negative")

Commodity channel index

How far the price is from its average, measured against how far it usually strays from it.

CharmScript 1.0
script("Commodity channel index", tool = indicator, chart = oscillator, legendtitle = "CCI", precision = 2, format = "price")

// ====================================================================
// COMMODITY CHANNEL INDEX
// How far the price is from its average, measured against how far it
// usually strays from it. At +100 it is one and a half times its usual
// distance above the average; at -100, the same below. Past either
// band the price is unusually far from its recent norm. A smoothed
// copy of the line can be drawn over it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.hlc3, "Source")
length = input.int(20, "Length", min = 1)
cciColor = input.color(#a396ff, "CCI colour")
smoothingType = input.string("None", "Smoothing", options = ["None", "SMA", "EMA"], group = "Smoothing line")
smoothingLength = input.int(14, "Smoothing length", min = 1, group = "Smoothing line")
smoothingColor = input.color(#fbbf24, "Smoothing colour", group = "Smoothing line")

// ---- 2. Calculation ------------------------------------------------
// The source's distance from its simple average over the length, over
// 0.015 times its mean deviation: the average distance of the source
// from that same average. The 0.015 puts a reading of 100 at one and a
// half mean deviations above the average.
cciValue = ind.cci(source, length)

// The smoothed copy: a simple or an exponential average of the line,
// or missing when smoothing is off, so that nothing is drawn.
smoothed(value, kind, len) =>
    return match kind:
        "SMA": ind.sma(value, len)
        "EMA": ind.ema(value, len)
        else: none

smoothingLine = smoothed(cciValue, smoothingType, smoothingLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(cciValue, "CCI", color = cciColor, linewidth = 2)
plot.line(smoothingLine, "Smoothing line", color = smoothingColor)
upperLine = plot.level(100, "Upper band", color = #787b86, style = line.dashed)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)
lowerLine = plot.level(-100, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
alert(math.crossover(cciValue, 100), "Crosses above +100", "CCI: crossed above +100")
alert(math.crossunder(cciValue, -100), "Crosses below -100", "CCI: crossed below -100")
The Pine it came from
//@version=6
indicator("Commodity channel index", shorttitle = "CCI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// COMMODITY CHANNEL INDEX
// How far the price is from its average, measured against how far it
// usually strays from it. At +100 it is one and a half times its usual
// distance above the average; at -100, the same below. Past either
// band the price is unusually far from its recent norm. A smoothed
// copy of the line can be drawn over it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(hlc3, "Source")
length = input.int(20, "Length", minval = 1)
cciColor = input.color(#a396ff, "CCI colour")
smoothingType = input.string("None", "Smoothing", options = ["None", "SMA", "EMA"], group = "Smoothing line")
smoothingLength = input.int(14, "Smoothing length", minval = 1, group = "Smoothing line")
smoothingColor = input.color(#fbbf24, "Smoothing colour", group = "Smoothing line")

// ---- 2. Calculation ------------------------------------------------
// The source's distance from its simple average over the length, over
// 0.015 times its mean deviation: the average distance of the source
// from that same average. The 0.015 puts a reading of 100 at one and a
// half mean deviations above the average.
cciValue = ta.cci(source, length)

// The smoothed copy: a simple or an exponential average of the line,
// or missing when smoothing is off, so that nothing is drawn.
smoothed(value, kind, len) =>
    switch kind
        "SMA" => ta.sma(value, len)
        "EMA" => ta.ema(value, len)
        => na

smoothingLine = smoothed(cciValue, smoothingType, smoothingLength)

// ---- 3. Drawing ----------------------------------------------------
plot(cciValue, "CCI", color = cciColor, linewidth = 2)
plot(smoothingLine, "Smoothing line", color = smoothingColor)
upperLine = hline(100, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
lowerLine = hline(-100, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

// ---- 4. Alerts -----------------------------------------------------
alertcondition(ta.crossover(cciValue, 100), "Crosses above +100", "CCI: crossed above +100")
alertcondition(ta.crossunder(cciValue, -100), "Crosses below -100", "CCI: crossed below -100")

Williams %R

Where the close sits between the highest high and the lowest low of the lookback, from 0 at the high down to -100 at the low: the fast stochastic, moved down by 100.

CharmScript 1.0
script("Williams %R", tool = indicator, chart = oscillator, legendtitle = "%R", precision = 2, format = "price")

// ====================================================================
// WILLIAMS %R
// Where the close sits between the highest high and the lowest low of
// the lookback, from 0 at the high down to -100 at the low: the fast
// stochastic, moved down by 100. Above -20 the close is near the top
// of its recent range; below -80, near the bottom. The line is amber
// above -20, purple below -80 and grey between.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", min = 1)
highColor = input.color(#fbbf24, "Above -20 colour")
lowColor = input.color(#a396ff, "Below -80 colour")
middleColor = input.color(#787b86, "Between the bands colour")

// ---- 2. Calculation ------------------------------------------------
// The highest high minus the close, as a share of the range from the
// lowest low to the highest high of the last length bars, times -100:
// 0 with the close at the high, -100 with it at the low.
percentR = ind.wpr(length)

// The line's colour by the zone it is in.
lineColor = percentR > -20 ? highColor : percentR < -80 ? lowColor : middleColor

// ---- 3. Drawing ----------------------------------------------------
plot.line(percentR, "%R", color = lineColor, linewidth = 2)
upperLine = plot.level(-20, "Upper band", color = #787b86, style = line.dashed)
plot.level(-50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
lowerLine = plot.level(-80, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")
The Pine it came from
//@version=6
indicator("Williams %R", shorttitle = "%R", overlay = false, format = format.price, precision = 2)

// ====================================================================
// WILLIAMS %R
// Where the close sits between the highest high and the lowest low of
// the lookback, from 0 at the high down to -100 at the low: the fast
// stochastic, moved down by 100. Above -20 the close is near the top
// of its recent range; below -80, near the bottom. The line is amber
// above -20, purple below -80 and grey between.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", minval = 1)
highColor = input.color(#fbbf24, "Above -20 colour")
lowColor = input.color(#a396ff, "Below -80 colour")
middleColor = input.color(#787b86, "Between the bands colour")

// ---- 2. Calculation ------------------------------------------------
// The highest high minus the close, as a share of the range from the
// lowest low to the highest high of the last length bars, times -100:
// 0 with the close at the high, -100 with it at the low.
percentR = ta.wpr(length)

// The line's colour by the zone it is in.
lineColor = percentR > -20 ? highColor : percentR < -80 ? lowColor : middleColor

// ---- 3. Drawing ----------------------------------------------------
plot(percentR, "%R", color = lineColor, linewidth = 2)
upperLine = hline(-20, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(-50, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
lowerLine = hline(-80, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

Money flow index

An RSI weighted by volume: the money that flowed in on rising bars, as a share of all that flowed in or out over the lookback, from 0 to 100.

CharmScript 1.0
script("Money flow index", tool = indicator, chart = oscillator, legendtitle = "MFI", precision = 2, format = "price")

// ====================================================================
// MONEY FLOW INDEX
// An RSI weighted by volume: the money that flowed in on rising bars,
// as a share of all that flowed in or out over the lookback, from 0
// to 100. Above the upper band the buyers have been in charge and a
// red shade shows; below the lower band the sellers have, and a green
// one shows. The further past its band, the stronger the shade.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.hlc3, "Source")
length = input.int(14, "Length", min = 1)
upperBand = input.int(80, "Upper band", min = 50, max = 100)
lowerBand = input.int(20, "Lower band", min = 0, max = 50)
mfiColor = input.color(#a396ff, "MFI colour")
highColor = input.color(#ff5252, "Above the upper band colour")
lowColor = input.color(#00d79e, "Below the lower band colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's money flow is its source price times its volume. It
// counts as flowing in when the price rose from the bar before, and as
// flowing out when it fell. The index is the money that flowed in over
// the length, as a share of all that flowed in or out, times 100.
mfiValue = ind.mfi(source, length)

// ---- 3. Drawing ----------------------------------------------------
// The bands and the middle as hidden lines, never drawn, there only to
// be shaded between.
upperPlot = plot.line(upperBand, "Upper band edge", display = "none")
middlePlot = plot.line(50, "Middle edge", display = "none")
lowerPlot = plot.line(lowerBand, "Lower band edge", display = "none")
mfiPlot = plot.line(mfiValue, "MFI", color = mfiColor, linewidth = 2)

// A faint shade between the bands. Then two shades between the line
// and the middle, each fading from its full colour at the end of the
// scale to clear at its band: red from 100 down to the upper band, and
// green from 0 up to the lower band. Each shows only where the line is
// past its band, and grows stronger the further past it goes.
highClear = color.hex(highColor, 100)
lowClear = color.hex(lowColor, 100)
paint.fill(upperPlot, lowerPlot, color = color.hex(mfiColor, 92), title = "Background")
paint.fill(mfiPlot, middlePlot, top = 100, bottom = upperBand, top_color = highColor, bottom_color = highClear, title = "Upper band shade")
paint.fill(mfiPlot, middlePlot, top = lowerBand, bottom = 0, top_color = lowClear, bottom_color = lowColor, title = "Lower band shade")

// The bands and the middle, drawn for the eye.
plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("Money flow index", shorttitle = "MFI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// MONEY FLOW INDEX
// An RSI weighted by volume: the money that flowed in on rising bars,
// as a share of all that flowed in or out over the lookback, from 0
// to 100. Above the upper band the buyers have been in charge and a
// red shade shows; below the lower band the sellers have, and a green
// one shows. The further past its band, the stronger the shade.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(hlc3, "Source")
length = input.int(14, "Length", minval = 1)
upperBand = input.int(80, "Upper band", minval = 50, maxval = 100)
lowerBand = input.int(20, "Lower band", minval = 0, maxval = 50)
mfiColor = input.color(#a396ff, "MFI colour")
highColor = input.color(#ff5252, "Above the upper band colour")
lowColor = input.color(#00d79e, "Below the lower band colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's money flow is its source price times its volume. It
// counts as flowing in when the price rose from the bar before, and as
// flowing out when it fell. The index is the money that flowed in over
// the length, as a share of all that flowed in or out, times 100.
mfiValue = ta.mfi(source, length)

// ---- 3. Drawing ----------------------------------------------------
// The bands and the middle as hidden lines, never drawn, there only to
// be shaded between.
upperPlot = plot(upperBand, "Upper band edge", editable = false, display = display.none)
middlePlot = plot(50, "Middle edge", editable = false, display = display.none)
lowerPlot = plot(lowerBand, "Lower band edge", editable = false, display = display.none)
mfiPlot = plot(mfiValue, "MFI", color = mfiColor, linewidth = 2)

// A faint shade between the bands. Then two shades between the line
// and the middle, each fading from its full colour at the end of the
// scale to clear at its band: red from 100 down to the upper band, and
// green from 0 up to the lower band. Each shows only where the line is
// past its band, and grows stronger the further past it goes.
highClear = color.new(highColor, 100)
lowClear = color.new(lowColor, 100)
fill(upperPlot, lowerPlot, color = color.new(mfiColor, 92), title = "Background")
fill(mfiPlot, middlePlot, 100, upperBand, top_color = highColor, bottom_color = highClear, title = "Upper band shade")
fill(mfiPlot, middlePlot, lowerBand, 0, top_color = lowClear, bottom_color = lowColor, title = "Lower band shade")

// The bands and the middle, drawn for the eye.
hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(50, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)

Awesome oscillator

A fast simple average of each bar's midpoint, halfway between its high and low, minus a slow one.

CharmScript 1.0
script("Awesome oscillator", tool = indicator, chart = oscillator, legendtitle = "AO")

// ====================================================================
// AWESOME OSCILLATOR
// A fast simple average of each bar's midpoint, halfway between its
// high and low, minus a slow one. Above zero the last few bars have
// sat higher than the longer run; below zero, lower. A column is green
// while the oscillator is higher than on the bar before and red while
// it is lower, so a change of colour shows momentum turning.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(5, "Fast length", min = 1)
slowLength = input.int(34, "Slow length", min = 1)
risingColor = input.color(#00d79e, "Rising colour")
fallingColor = input.color(#ff5252, "Falling colour")

// ---- 2. Calculation ------------------------------------------------
// The fast average of the bar's midpoint minus the slow one.
oscillator_ = ind.sma(p.hl2, fastLength) - ind.sma(p.hl2, slowLength)

// Each column takes the rising colour while the oscillator is higher
// than on the bar before, and the falling colour otherwise.
columnColor = oscillator_ > oscillator_[-2] ? risingColor : fallingColor

// ---- 3. Drawing ----------------------------------------------------
plot.column(oscillator_, "AO", color = columnColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)

// ---- 4. Alerts -----------------------------------------------------
alert(math.crossover(oscillator_, 0), "Crosses above zero", "Awesome oscillator: crossed above zero")
alert(math.crossunder(oscillator_, 0), "Crosses below zero", "Awesome oscillator: crossed below zero")
The Pine it came from
//@version=6
indicator("Awesome oscillator", shorttitle = "AO", overlay = false)

// ====================================================================
// AWESOME OSCILLATOR
// A fast simple average of each bar's midpoint, halfway between its
// high and low, minus a slow one. Above zero the last few bars have
// sat higher than the longer run; below zero, lower. A column is green
// while the oscillator is higher than on the bar before and red while
// it is lower, so a change of colour shows momentum turning.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(5, "Fast length", minval = 1)
slowLength = input.int(34, "Slow length", minval = 1)
risingColor = input.color(#00d79e, "Rising colour")
fallingColor = input.color(#ff5252, "Falling colour")

// ---- 2. Calculation ------------------------------------------------
// The fast average of the bar's midpoint minus the slow one.
oscillator = ta.sma(hl2, fastLength) - ta.sma(hl2, slowLength)

// Each column takes the rising colour while the oscillator is higher
// than on the bar before, and the falling colour otherwise.
columnColor = oscillator > oscillator[1] ? risingColor : fallingColor

// ---- 3. Drawing ----------------------------------------------------
plot(oscillator, "AO", color = columnColor, style = plot.style_columns)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)

// ---- 4. Alerts -----------------------------------------------------
alertcondition(ta.crossover(oscillator, 0), "Crosses above zero", "Awesome oscillator: crossed above zero")
alertcondition(ta.crossunder(oscillator, 0), "Crosses below zero", "Awesome oscillator: crossed below zero")

TRIX

The close smoothed by an exponential average three times over, then its percent change from the bar before.

CharmScript 1.0
script("TRIX", tool = indicator, chart = oscillator, precision = 4, format = "price")

// ====================================================================
// TRIX
// The close smoothed by an exponential average three times over, then
// its percent change from the bar before. This is Hutson's definition:
// 100 times the change, over the smoothed value on the bar before. The
// triple smoothing strips out the small swings, so it crosses zero
// only on the larger turns. The signal line is an average of it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(18, "Length", min = 1)
signalLength = input.int(9, "Signal length", min = 1)
trixColor = input.color(#2196f3, "TRIX colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The close smoothed three times, each pass an exponential average of
// the pass before it over the same length.
firstPass = ind.ema(p.close, length)
secondPass = ind.ema(firstPass, length)
thirdPass = ind.ema(secondPass, length)

// TRIX is the third pass's change from the bar before, as a percentage
// of its value on the bar before. The signal line is an exponential
// average of TRIX.
trixValue = 100 * (thirdPass - thirdPass[-2]) / thirdPass[-2]
signalLine = ind.ema(trixValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(trixValue, "TRIX", color = trixColor, linewidth = 2)
plot.line(signalLine, "Signal", color = signalColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)
The Pine it came from
//@version=6
indicator("TRIX", overlay = false, format = format.price, precision = 4)

// ====================================================================
// TRIX
// The close smoothed by an exponential average three times over, then
// its percent change from the bar before. This is Hutson's definition:
// 100 times the change, over the smoothed value on the bar before. The
// triple smoothing strips out the small swings, so it crosses zero
// only on the larger turns. The signal line is an average of it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(18, "Length", minval = 1)
signalLength = input.int(9, "Signal length", minval = 1)
trixColor = input.color(#2196f3, "TRIX colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The close smoothed three times, each pass an exponential average of
// the pass before it over the same length.
firstPass = ta.ema(close, length)
secondPass = ta.ema(firstPass, length)
thirdPass = ta.ema(secondPass, length)

// TRIX is the third pass's change from the bar before, as a percentage
// of its value on the bar before. The signal line is an exponential
// average of TRIX.
trixValue = 100 * (thirdPass - thirdPass[1]) / thirdPass[1]
signalLine = ta.ema(trixValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot(trixValue, "TRIX", color = trixColor, linewidth = 2)
plot(signalLine, "Signal", color = signalColor)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)

True strength index

The close's change from one bar to the next, smoothed twice, as a share of the size of those changes smoothed the same way: from -100 to +100.

CharmScript 1.0
script("True strength index", tool = indicator, chart = oscillator, legendtitle = "TSI", precision = 2, format = "price")

// ====================================================================
// TRUE STRENGTH INDEX
// The close's change from one bar to the next, smoothed twice, as a
// share of the size of those changes smoothed the same way: from -100
// to +100. Above zero the rises have outweighed the falls, and the
// further from zero, the more one-sided the run has been. The signal
// line is an average of it; the bands mark readings far from zero.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
longLength = input.int(25, "Long length", min = 1)
shortLength = input.int(13, "Short length", min = 1)
signalLength = input.int(13, "Signal length", min = 1)
upperBand = input.int(25, "Upper band", min = 0, max = 100)
lowerBand = input.int(-25, "Lower band", min = -100, max = 0)
tsiColor = input.color(#2196f3, "TSI colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// Smooths values twice: an exponential average over the long length,
// then an exponential average of that over the short length.
doubleSmooth(value, longLen, shortLen) =>
    return ind.ema(ind.ema(value, longLen), shortLen)

// The close's change from the bar before, and the size of that change
// whichever way it went, each smoothed twice. The index is the first
// over the second, times 100. The signal line is an exponential
// average of the index.
priceChange = p.close - p.close[-2]
smoothedChange = doubleSmooth(priceChange, longLength, shortLength)
smoothedSize = doubleSmooth(math.abs(priceChange), longLength, shortLength)
tsiValue = 100 * smoothedChange / smoothedSize
signalLine = ind.ema(tsiValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(tsiValue, "TSI", color = tsiColor, linewidth = 2)
plot.line(signalLine, "Signal", color = signalColor)
plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("True strength index", shorttitle = "TSI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// TRUE STRENGTH INDEX
// The close's change from one bar to the next, smoothed twice, as a
// share of the size of those changes smoothed the same way: from -100
// to +100. Above zero the rises have outweighed the falls, and the
// further from zero, the more one-sided the run has been. The signal
// line is an average of it; the bands mark readings far from zero.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
longLength = input.int(25, "Long length", minval = 1)
shortLength = input.int(13, "Short length", minval = 1)
signalLength = input.int(13, "Signal length", minval = 1)
upperBand = input.int(25, "Upper band", minval = 0, maxval = 100)
lowerBand = input.int(-25, "Lower band", minval = -100, maxval = 0)
tsiColor = input.color(#2196f3, "TSI colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// Smooths values twice: an exponential average over the long length,
// then an exponential average of that over the short length.
doubleSmooth(value, longLen, shortLen) =>
    ta.ema(ta.ema(value, longLen), shortLen)

// The close's change from the bar before, and the size of that change
// whichever way it went, each smoothed twice. The index is the first
// over the second, times 100. The signal line is an exponential
// average of the index.
priceChange = close - close[1]
smoothedChange = doubleSmooth(priceChange, longLength, shortLength)
smoothedSize = doubleSmooth(math.abs(priceChange), longLength, shortLength)
tsiValue = 100 * smoothedChange / smoothedSize
signalLine = ta.ema(tsiValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot(tsiValue, "TSI", color = tsiColor, linewidth = 2)
plot(signalLine, "Signal", color = signalColor)
hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)

Ultimate oscillator

How much of each bar's true range the close took, the buying pressure, added up over a short, a middle and a long lookback and blended with the most weight on the short one: from 0 to 100.

CharmScript 1.0
script("Ultimate oscillator", tool = indicator, chart = oscillator, legendtitle = "UO", precision = 2, format = "price")

// ====================================================================
// ULTIMATE OSCILLATOR
// How much of each bar's true range the close took, the buying
// pressure, added up over a short, a middle and a long lookback and
// blended with the most weight on the short one: from 0 to 100.
// Three lookbacks at once keep one short swing from turning it. Above
// 70 the buyers have had the upper hand; below 30, the sellers.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
shortLength = input.int(7, "Short length", min = 1)
middleLength = input.int(14, "Middle length", min = 1)
longLength = input.int(28, "Long length", min = 1)
uoColor = input.color(#a396ff, "UO colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's true range runs from the lower of its low and the close
// of the bar before, up to the higher of its high and that close. The
// buying pressure is how far the close is above the bottom of it.
rangeLow = math.min(p.low, p.close[-2])
rangeHigh = math.max(p.high, p.close[-2])
buyingPressure = p.close - rangeLow
trueRange = rangeHigh - rangeLow

// For each lookback, the buying pressure added up over it, as a share
// of the true range added up over it: from 0 to 1.
shortShare = math.sum(buyingPressure, shortLength) / math.sum(trueRange, shortLength)
middleShare = math.sum(buyingPressure, middleLength) / math.sum(trueRange, middleLength)
longShare = math.sum(buyingPressure, longLength) / math.sum(trueRange, longLength)

// The three blended with weights 4, 2 and 1, so the short lookback
// counts the most, then scaled to run from 0 to 100.
uoValue = 100 * (4 * shortShare + 2 * middleShare + longShare) / 7

// ---- 3. Drawing ----------------------------------------------------
plot.line(uoValue, "UO", color = uoColor, linewidth = 2)
plot.level(70, "Upper band", color = #787b86, style = line.dashed)
plot.level(50, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(30, "Lower band", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("Ultimate oscillator", shorttitle = "UO", overlay = false, format = format.price, precision = 2)

// ====================================================================
// ULTIMATE OSCILLATOR
// How much of each bar's true range the close took, the buying
// pressure, added up over a short, a middle and a long lookback and
// blended with the most weight on the short one: from 0 to 100.
// Three lookbacks at once keep one short swing from turning it. Above
// 70 the buyers have had the upper hand; below 30, the sellers.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
shortLength = input.int(7, "Short length", minval = 1)
middleLength = input.int(14, "Middle length", minval = 1)
longLength = input.int(28, "Long length", minval = 1)
uoColor = input.color(#a396ff, "UO colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's true range runs from the lower of its low and the close
// of the bar before, up to the higher of its high and that close. The
// buying pressure is how far the close is above the bottom of it.
rangeLow = math.min(low, close[1])
rangeHigh = math.max(high, close[1])
buyingPressure = close - rangeLow
trueRange = rangeHigh - rangeLow

// For each lookback, the buying pressure added up over it, as a share
// of the true range added up over it: from 0 to 1.
shortShare = math.sum(buyingPressure, shortLength) / math.sum(trueRange, shortLength)
middleShare = math.sum(buyingPressure, middleLength) / math.sum(trueRange, middleLength)
longShare = math.sum(buyingPressure, longLength) / math.sum(trueRange, longLength)

// The three blended with weights 4, 2 and 1, so the short lookback
// counts the most, then scaled to run from 0 to 100.
uoValue = 100 * (4 * shortShare + 2 * middleShare + longShare) / 7

// ---- 3. Drawing ----------------------------------------------------
plot(uoValue, "UO", color = uoColor, linewidth = 2)
hline(70, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(50, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(30, "Lower band", color = #787b86, linestyle = hline.style_dashed)

Fisher transform

Where the bar's midpoint sits in the range of the lookback, smoothed and then stretched so that readings near the edges of the range grow large: turns show as sharp peaks and troughs.

CharmScript 1.0
script("Fisher transform", tool = indicator, chart = oscillator, legendtitle = "Fisher", precision = 2, format = "price")

// ====================================================================
// FISHER TRANSFORM
// Where the bar's midpoint sits in the range of the lookback, smoothed
// and then stretched so that readings near the edges of the range grow
// large: turns show as sharp peaks and troughs. The trigger line is
// the Fisher line one bar late, so the two cross at each turn. The
// smoothing and the stretch follow Ehlers' formula, with the range
// from the lowest low to the highest high.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(9, "Length", min = 1)
fisherColor = input.color(#2196f3, "Fisher colour")
triggerColor = input.color(#fbbf24, "Trigger colour")

// ---- 2. Calculation ------------------------------------------------
// Where the bar's midpoint, halfway between its high and low, sits
// between the lowest low and the highest high of the last length bars:
// -0.5 at the low, +0.5 at the high. Missing until the lookback is
// full, and when the range has no width.
highestHigh = math.highest(p.high, length)
lowestLow = math.lowest(p.low, length)
span = highestHigh - lowestLow
place = span > 0 ? (p.hl2 - lowestLow) / span - 0.5 : none

// The place smoothed: 0.66 times this bar's place plus 0.67 times the
// smoothed value of the bar before, which starts at 0. A steady place
// settles at twice itself, from -1 to +1, so the value is held between
// -0.999 and +0.999 to keep the stretch finite. Then the stretch: half
// the natural log of (1 + value) / (1 - value), plus half the Fisher
// line's value on the bar before (0 at the start). Both are kept from
// one bar to the next, and stay as they were on a bar with no place.
var smoothed = 0.0
var fisher = none
if not none(place):
    smoothed = math.max(-0.999, math.min(0.999, 0.66 * place + 0.67 * smoothed))
    fisher = 0.5 * math.log((1 + smoothed) / (1 - smoothed)) + 0.5 * replace(fisher)

// The trigger line is the Fisher line's value on the bar before.
trigger = fisher[-2]

// ---- 3. Drawing ----------------------------------------------------
plot.line(fisher, "Fisher", color = fisherColor, linewidth = 2)
plot.line(trigger, "Trigger", color = triggerColor)
plot.level(1.5, "+1.5", color = #787b86, style = line.dashed)
plot.level(0.75, "+0.75", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(-0.75, "-0.75", color = color.hex(#787b86, 50), style = line.dotted)
plot.level(-1.5, "-1.5", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("Fisher transform", shorttitle = "Fisher", overlay = false, format = format.price, precision = 2)

// ====================================================================
// FISHER TRANSFORM
// Where the bar's midpoint sits in the range of the lookback, smoothed
// and then stretched so that readings near the edges of the range grow
// large: turns show as sharp peaks and troughs. The trigger line is
// the Fisher line one bar late, so the two cross at each turn. The
// smoothing and the stretch follow Ehlers' formula, with the range
// from the lowest low to the highest high.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(9, "Length", minval = 1)
fisherColor = input.color(#2196f3, "Fisher colour")
triggerColor = input.color(#fbbf24, "Trigger colour")

// ---- 2. Calculation ------------------------------------------------
// Where the bar's midpoint, halfway between its high and low, sits
// between the lowest low and the highest high of the last length bars:
// -0.5 at the low, +0.5 at the high. Missing until the lookback is
// full, and when the range has no width.
highestHigh = ta.highest(high, length)
lowestLow = ta.lowest(low, length)
span = highestHigh - lowestLow
place = span > 0 ? (hl2 - lowestLow) / span - 0.5 : na

// The place smoothed: 0.66 times this bar's place plus 0.67 times the
// smoothed value of the bar before, which starts at 0. A steady place
// settles at twice itself, from -1 to +1, so the value is held between
// -0.999 and +0.999 to keep the stretch finite. Then the stretch: half
// the natural log of (1 + value) / (1 - value), plus half the Fisher
// line's value on the bar before (0 at the start). Both are kept from
// one bar to the next, and stay as they were on a bar with no place.
var float smoothed = 0.0
var float fisher = na
if not na(place)
    smoothed := math.max(-0.999, math.min(0.999, 0.66 * place + 0.67 * smoothed))
    fisher := 0.5 * math.log((1 + smoothed) / (1 - smoothed)) + 0.5 * nz(fisher)

// The trigger line is the Fisher line's value on the bar before.
trigger = fisher[1]

// ---- 3. Drawing ----------------------------------------------------
plot(fisher, "Fisher", color = fisherColor, linewidth = 2)
plot(trigger, "Trigger", color = triggerColor)
hline(1.5, "+1.5", color = #787b86, linestyle = hline.style_dashed)
hline(0.75, "+0.75", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(-0.75, "-0.75", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
hline(-1.5, "-1.5", color = #787b86, linestyle = hline.style_dashed)

Know sure thing

Four rates of change of the close, from a short lookback to a long one, each smoothed by a simple average and then added up with the most weight on the longest.

CharmScript 1.0
script("Know sure thing", tool = indicator, chart = oscillator, legendtitle = "KST", precision = 2, format = "price")

// ====================================================================
// KNOW SURE THING
// Four rates of change of the close, from a short lookback to a long
// one, each smoothed by a simple average and then added up with the
// most weight on the longest. Blending the four gives one steady line
// of momentum: above zero the close has been rising across them, below
// zero falling. The signal line is a simple average of it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
kstColor = input.color(#00d79e, "KST colour")
signalColor = input.color(#ff5252, "Signal colour")
rocLength1 = input.int(10, "Length 1", min = 1, group = "Rates of change")
rocLength2 = input.int(15, "Length 2", min = 1, group = "Rates of change")
rocLength3 = input.int(20, "Length 3", min = 1, group = "Rates of change")
rocLength4 = input.int(30, "Length 4", min = 1, group = "Rates of change")
smoothLength1 = input.int(10, "Smoothing 1", min = 1, group = "Smoothing")
smoothLength2 = input.int(10, "Smoothing 2", min = 1, group = "Smoothing")
smoothLength3 = input.int(10, "Smoothing 3", min = 1, group = "Smoothing")
smoothLength4 = input.int(15, "Smoothing 4", min = 1, group = "Smoothing")
signalLength = input.int(9, "Signal length", min = 1, group = "Signal")

// ---- 2. Calculation ------------------------------------------------
// Each rate of change is the close's percent change over its length,
// then smoothed by a simple average over its smoothing length.
smoothedRoc1 = ind.sma(ind.roc(p.close, rocLength1), smoothLength1)
smoothedRoc2 = ind.sma(ind.roc(p.close, rocLength2), smoothLength2)
smoothedRoc3 = ind.sma(ind.roc(p.close, rocLength3), smoothLength3)
smoothedRoc4 = ind.sma(ind.roc(p.close, rocLength4), smoothLength4)

// The four added with weights 1, 2, 3 and 4, so the longest counts the
// most. The signal line is a simple average of the result.
kstValue = smoothedRoc1 + 2 * smoothedRoc2 + 3 * smoothedRoc3 + 4 * smoothedRoc4
signalLine = ind.sma(kstValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(kstValue, "KST", color = kstColor, linewidth = 2)
plot.line(signalLine, "Signal", color = signalColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.dotted)
The Pine it came from
//@version=6
indicator("Know sure thing", shorttitle = "KST", overlay = false, format = format.price, precision = 2)

// ====================================================================
// KNOW SURE THING
// Four rates of change of the close, from a short lookback to a long
// one, each smoothed by a simple average and then added up with the
// most weight on the longest. Blending the four gives one steady line
// of momentum: above zero the close has been rising across them, below
// zero falling. The signal line is a simple average of it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
kstColor = input.color(#00d79e, "KST colour")
signalColor = input.color(#ff5252, "Signal colour")
rocLength1 = input.int(10, "Length 1", minval = 1, group = "Rates of change")
rocLength2 = input.int(15, "Length 2", minval = 1, group = "Rates of change")
rocLength3 = input.int(20, "Length 3", minval = 1, group = "Rates of change")
rocLength4 = input.int(30, "Length 4", minval = 1, group = "Rates of change")
smoothLength1 = input.int(10, "Smoothing 1", minval = 1, group = "Smoothing")
smoothLength2 = input.int(10, "Smoothing 2", minval = 1, group = "Smoothing")
smoothLength3 = input.int(10, "Smoothing 3", minval = 1, group = "Smoothing")
smoothLength4 = input.int(15, "Smoothing 4", minval = 1, group = "Smoothing")
signalLength = input.int(9, "Signal length", minval = 1, group = "Signal")

// ---- 2. Calculation ------------------------------------------------
// Each rate of change is the close's percent change over its length,
// then smoothed by a simple average over its smoothing length.
smoothedRoc1 = ta.sma(ta.roc(close, rocLength1), smoothLength1)
smoothedRoc2 = ta.sma(ta.roc(close, rocLength2), smoothLength2)
smoothedRoc3 = ta.sma(ta.roc(close, rocLength3), smoothLength3)
smoothedRoc4 = ta.sma(ta.roc(close, rocLength4), smoothLength4)

// The four added with weights 1, 2, 3 and 4, so the longest counts the
// most. The signal line is a simple average of the result.
kstValue = smoothedRoc1 + 2 * smoothedRoc2 + 3 * smoothedRoc3 + 4 * smoothedRoc4
signalLine = ta.sma(kstValue, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot(kstValue, "KST", color = kstColor, linewidth = 2)
plot(signalLine, "Signal", color = signalColor)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_dotted)

Connors RSI

The average of three readings, each from 0 to 100: a short RSI of the close, an RSI of the streak (how many closes in a row have been up, or down), and the percent rank of this bar's change, the share of the earlier bars' one-bar changes that were no bigger.

CharmScript 1.0
script("Connors RSI", tool = indicator, chart = oscillator, legendtitle = "CRSI", precision = 2, format = "price")

// ====================================================================
// CONNORS RSI
// The average of three readings, each from 0 to 100: a short RSI of
// the close, an RSI of the streak (how many closes in a row have been
// up, or down), and the percent rank of this bar's change, the share
// of the earlier bars' one-bar changes that were no bigger. It is made
// for short swings: above 90 the market is stretched up, below 10 it
// is stretched down.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
rsiLength = input.int(3, "RSI length", min = 1)
streakLength = input.int(2, "Streak RSI length", min = 1)
rankLength = input.int(100, "Percent rank length", min = 1)
lineColor = input.color(#2196f3, "Line colour")

// ---- 2. Calculation ------------------------------------------------
// The streak, kept from one bar to the next: how many closes in a row
// were higher than the one before (counted up from 1) or lower
// (counted down from -1). A close no different from the one before
// sets it back to 0.
var streak = 0
if p.close > p.close[-2]:
    streak = streak > 0 ? streak + 1 : 1
elif p.close < p.close[-2]:
    streak = streak < 0 ? streak - 1 : -1
else:
    streak = 0

// The three readings, and their average.
closeRsi = ind.rsi(p.close, rsiLength)
streakRsi = ind.rsi(streak, streakLength)
changeRank = math.percentrank(ind.roc(p.close, 1), rankLength)
crsi = (closeRsi + streakRsi + changeRank) / 3

// ---- 3. Drawing ----------------------------------------------------
plot.line(crsi, "CRSI", color = lineColor, linewidth = 2)
upperLine = plot.level(90, "Upper band", color = #787b86, style = line.dashed)
lowerLine = plot.level(10, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")
The Pine it came from
//@version=6
indicator("Connors RSI", shorttitle = "CRSI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// CONNORS RSI
// The average of three readings, each from 0 to 100: a short RSI of
// the close, an RSI of the streak (how many closes in a row have been
// up, or down), and the percent rank of this bar's change, the share
// of the earlier bars' one-bar changes that were no bigger. It is made
// for short swings: above 90 the market is stretched up, below 10 it
// is stretched down.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
rsiLength = input.int(3, "RSI length", minval = 1)
streakLength = input.int(2, "Streak RSI length", minval = 1)
rankLength = input.int(100, "Percent rank length", minval = 1)
lineColor = input.color(#2196f3, "Line colour")

// ---- 2. Calculation ------------------------------------------------
// The streak, kept from one bar to the next: how many closes in a row
// were higher than the one before (counted up from 1) or lower
// (counted down from -1). A close no different from the one before
// sets it back to 0.
var int streak = 0
if close > close[1]
    streak := streak > 0 ? streak + 1 : 1
else if close < close[1]
    streak := streak < 0 ? streak - 1 : -1
else
    streak := 0

// The three readings, and their average.
closeRsi = ta.rsi(close, rsiLength)
streakRsi = ta.rsi(streak, streakLength)
changeRank = ta.percentrank(ta.roc(close, 1), rankLength)
crsi = (closeRsi + streakRsi + changeRank) / 3

// ---- 3. Drawing ----------------------------------------------------
plot(crsi, "CRSI", color = lineColor, linewidth = 2)
upperLine = hline(90, "Upper band", color = #787b86, linestyle = hline.style_dashed)
lowerLine = hline(10, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

RSI divergences

The RSI, marked where it and the price disagree.

CharmScript 1.0
script("RSI divergences", tool = indicator, chart = oscillator, legendtitle = "RSI Div")

// ====================================================================
// RSI DIVERGENCES
// The RSI, marked where it and the price disagree. A regular bullish
// divergence is a lower low in the price while the RSI makes a higher
// low: the selling is losing its strength. A regular bearish one is a
// higher high in the price with a lower high in the RSI. The hidden
// ones are the other way round and hint that the trend will go on.
// The swings are the RSI's own pivots, each found only once the set
// number of bars after it have closed.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
rsiLength = input.int(14, "RSI length", min = 1)
leftBars = input.int(5, "Pivot bars to the left", min = 1)
rightBars = input.int(5, "Pivot bars to the right", min = 1)
minGap = input.int(5, "Fewest bars between pivots", min = 1)
maxGap = input.int(60, "Most bars between pivots", min = 1)
showHidden = input.bool(false, "Show hidden divergences")
rsiColor = input.color(#a396ff, "RSI colour")
bullColor = input.color(#00d79e, "Bullish colour")
bearColor = input.color(#ff5252, "Bearish colour")

// ---- 2. Calculation ------------------------------------------------
rsiValue = ind.rsi(p.close, rsiLength)

// A pivot low of the RSI is a bar whose RSI is lower than that of the
// bars either side of it. It is known once the bars to its right have
// closed, so it lies that many bars back. A pivot high is the same the
// other way up.
lowFound = not none(ind.pivotlow(rsiValue, leftBars, rightBars))
highFound = not none(ind.pivothigh(rsiValue, leftBars, rightBars))
pivotBar = bars.count - rightBars
pivotRsi = rsiValue[-rightBars - 1]

// The RSI, the price and the bar at the pivot before the newest one,
// and how many bars apart the two pivots are.
prevLowRsi = math.valuewhen(lowFound, rsiValue[-rightBars - 1], 1)
prevLowPrice = math.valuewhen(lowFound, p.low[-rightBars - 1], 1)
prevLowBar = math.valuewhen(lowFound, pivotBar, 1)
lowGap = math.barssince(lowFound[-2]) + 1
prevHighRsi = math.valuewhen(highFound, rsiValue[-rightBars - 1], 1)
prevHighPrice = math.valuewhen(highFound, p.high[-rightBars - 1], 1)
prevHighBar = math.valuewhen(highFound, pivotBar, 1)
highGap = math.barssince(highFound[-2]) + 1

// Two pivots count only when they are the set number of bars apart.
lowsApart = lowFound and lowGap >= minGap and lowGap <= maxGap
highsApart = highFound and highGap >= minGap and highGap <= maxGap

// Regular: the price makes the new extreme (a lower low, a higher
// high) and the RSI does not. Hidden: the RSI makes it and the price
// does not.
bullish = lowsApart and p.low[-rightBars - 1] < prevLowPrice and pivotRsi > prevLowRsi
bearish = highsApart and p.high[-rightBars - 1] > prevHighPrice and pivotRsi < prevHighRsi
hiddenBullish = showHidden and lowsApart and p.low[-rightBars - 1] > prevLowPrice and pivotRsi < prevLowRsi
hiddenBearish = showHidden and highsApart and p.high[-rightBars - 1] < prevHighPrice and pivotRsi > prevHighRsi

// ---- 3. Drawing ----------------------------------------------------
// The RSI, with its bands at 70 and 30 and a shade between them.
plot.line(rsiValue, "RSI", color = rsiColor, linewidth = 2)
upperLine = plot.level(70, "Upper band", color = #787b86, style = line.dashed)
lowerLine = plot.level(30, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")

// A divergence is marked with a line between the two RSI pivots and a
// label at the newer one; a hidden one's line is dashed.
markDivergence(fromBar, fromRsi, toBar, toRsi, name, markColor, atLow, hidden) =>
    lineStyle = hidden ? line.dashed : line.solid
    labelStyle = atLow ? style.labelup : style.labeldown
    plot.segment(fromBar, fromRsi, toBar, toRsi, color = markColor, style = lineStyle, width = 2)
    return plot.label(toBar, toRsi, name, color = markColor, style = labelStyle, textcolor = #000000, size = "small")

if bullish:
    markDivergence(prevLowBar, prevLowRsi, pivotBar, pivotRsi, "Bull", bullColor, true, false)
if bearish:
    markDivergence(prevHighBar, prevHighRsi, pivotBar, pivotRsi, "Bear", bearColor, false, false)
if hiddenBullish:
    markDivergence(prevLowBar, prevLowRsi, pivotBar, pivotRsi, "Hidden bull", bullColor, true, true)
if hiddenBearish:
    markDivergence(prevHighBar, prevHighRsi, pivotBar, pivotRsi, "Hidden bear", bearColor, false, true)

// ---- 4. Alerts -----------------------------------------------------
// Hidden divergences raise an alert only while they are switched on.
anyBullish = bullish or hiddenBullish
anyBearish = bearish or hiddenBearish
alert(anyBullish, "Bullish divergence", "RSI divergences: a bullish divergence was found")
alert(anyBearish, "Bearish divergence", "RSI divergences: a bearish divergence was found")
The Pine it came from
//@version=6
indicator("RSI divergences", shorttitle = "RSI Div", overlay = false, max_lines_count = 200, max_labels_count = 200)

// ====================================================================
// RSI DIVERGENCES
// The RSI, marked where it and the price disagree. A regular bullish
// divergence is a lower low in the price while the RSI makes a higher
// low: the selling is losing its strength. A regular bearish one is a
// higher high in the price with a lower high in the RSI. The hidden
// ones are the other way round and hint that the trend will go on.
// The swings are the RSI's own pivots, each found only once the set
// number of bars after it have closed.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
rsiLength = input.int(14, "RSI length", minval = 1)
leftBars = input.int(5, "Pivot bars to the left", minval = 1)
rightBars = input.int(5, "Pivot bars to the right", minval = 1)
minGap = input.int(5, "Fewest bars between pivots", minval = 1)
maxGap = input.int(60, "Most bars between pivots", minval = 1)
showHidden = input.bool(false, "Show hidden divergences")
rsiColor = input.color(#a396ff, "RSI colour")
bullColor = input.color(#00d79e, "Bullish colour")
bearColor = input.color(#ff5252, "Bearish colour")

// ---- 2. Calculation ------------------------------------------------
rsiValue = ta.rsi(close, rsiLength)

// A pivot low of the RSI is a bar whose RSI is lower than that of the
// bars either side of it. It is known once the bars to its right have
// closed, so it lies that many bars back. A pivot high is the same the
// other way up.
lowFound = not na(ta.pivotlow(rsiValue, leftBars, rightBars))
highFound = not na(ta.pivothigh(rsiValue, leftBars, rightBars))
pivotBar = bar_index - rightBars
pivotRsi = rsiValue[rightBars]

// The RSI, the price and the bar at the pivot before the newest one,
// and how many bars apart the two pivots are.
prevLowRsi = ta.valuewhen(lowFound, rsiValue[rightBars], 1)
prevLowPrice = ta.valuewhen(lowFound, low[rightBars], 1)
prevLowBar = ta.valuewhen(lowFound, pivotBar, 1)
lowGap = ta.barssince(lowFound[1]) + 1
prevHighRsi = ta.valuewhen(highFound, rsiValue[rightBars], 1)
prevHighPrice = ta.valuewhen(highFound, high[rightBars], 1)
prevHighBar = ta.valuewhen(highFound, pivotBar, 1)
highGap = ta.barssince(highFound[1]) + 1

// Two pivots count only when they are the set number of bars apart.
lowsApart = lowFound and lowGap >= minGap and lowGap <= maxGap
highsApart = highFound and highGap >= minGap and highGap <= maxGap

// Regular: the price makes the new extreme (a lower low, a higher
// high) and the RSI does not. Hidden: the RSI makes it and the price
// does not.
bullish = lowsApart and low[rightBars] < prevLowPrice and pivotRsi > prevLowRsi
bearish = highsApart and high[rightBars] > prevHighPrice and pivotRsi < prevHighRsi
hiddenBullish = showHidden and lowsApart and low[rightBars] > prevLowPrice and pivotRsi < prevLowRsi
hiddenBearish = showHidden and highsApart and high[rightBars] < prevHighPrice and pivotRsi > prevHighRsi

// ---- 3. Drawing ----------------------------------------------------
// The RSI, with its bands at 70 and 30 and a shade between them.
plot(rsiValue, "RSI", color = rsiColor, linewidth = 2)
upperLine = hline(70, "Upper band", color = #787b86, linestyle = hline.style_dashed)
lowerLine = hline(30, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")

// A divergence is marked with a line between the two RSI pivots and a
// label at the newer one; a hidden one's line is dashed.
markDivergence(fromBar, fromRsi, toBar, toRsi, name, markColor, atLow, hidden) =>
    lineStyle = hidden ? line.style_dashed : line.style_solid
    labelStyle = atLow ? label.style_label_up : label.style_label_down
    line.new(fromBar, fromRsi, toBar, toRsi, color = markColor, style = lineStyle, width = 2)
    label.new(toBar, toRsi, name, color = markColor, style = labelStyle, textcolor = #000000, size = size.small)

if bullish
    markDivergence(prevLowBar, prevLowRsi, pivotBar, pivotRsi, "Bull", bullColor, true, false)
if bearish
    markDivergence(prevHighBar, prevHighRsi, pivotBar, pivotRsi, "Bear", bearColor, false, false)
if hiddenBullish
    markDivergence(prevLowBar, prevLowRsi, pivotBar, pivotRsi, "Hidden bull", bullColor, true, true)
if hiddenBearish
    markDivergence(prevHighBar, prevHighRsi, pivotBar, pivotRsi, "Hidden bear", bearColor, false, true)

// ---- 4. Alerts -----------------------------------------------------
// Hidden divergences raise an alert only while they are switched on.
anyBullish = bullish or hiddenBullish
anyBearish = bearish or hiddenBearish
alertcondition(anyBullish, "Bullish divergence", "RSI divergences: a bullish divergence was found")
alertcondition(anyBearish, "Bearish divergence", "RSI divergences: a bearish divergence was found")

Aroon

How recently the highest high and the lowest low of the lookback were made, from 100 if on this bar down to 0 if a full length of bars ago.

CharmScript 1.0
script("Aroon", tool = indicator, chart = oscillator, precision = 2, format = "price")

// ====================================================================
// AROON
// How recently the highest high and the lowest low of the lookback
// were made, from 100 if on this bar down to 0 if a full length of
// bars ago. Aroon up near 100 means new highs keep coming; Aroon down
// near 100, new lows. The shade between the two lines is green while
// up is above down, and red while it is not.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", min = 1)
upColor = input.color(#00d79e, "Aroon up colour")
downColor = input.color(#ff5252, "Aroon down colour")

// ---- 2. Calculation ------------------------------------------------
// How many bars ago the highest high and the lowest low were made,
// looking at this bar and the length of bars before it: 0 for this
// bar, up to the length for the oldest.
barsSinceHigh = -(math.highestbars(p.high, length + 1) + 1)
barsSinceLow = -(math.lowestbars(p.low, length + 1) + 1)

// Each line is the length minus those bars, as a percentage of the
// length: 100 when the extreme is on this bar, 0 when it is the oldest.
aroonUp = 100 * (length - barsSinceHigh) / length
aroonDown = 100 * (length - barsSinceLow) / length

// ---- 3. Drawing ----------------------------------------------------
// The two lines, and the shade between them in Aroon up's colour while
// it is above Aroon down, and in Aroon down's colour otherwise.
upPlot = plot.line(aroonUp, "Aroon up", color = upColor, linewidth = 2)
downPlot = plot.line(aroonDown, "Aroon down", color = downColor, linewidth = 2)
shadeColor = aroonUp > aroonDown ? color.hex(upColor, 85) : color.hex(downColor, 85)
paint.fill(upPlot, downPlot, color = shadeColor, title = "Shade")

// ---- 4. Alerts -----------------------------------------------------
alert(math.crossover(aroonUp, aroonDown), "Up crosses above down", "Aroon: Aroon up crossed above Aroon down")
alert(math.crossunder(aroonUp, aroonDown), "Up crosses below down", "Aroon: Aroon up crossed below Aroon down")
The Pine it came from
//@version=6
indicator("Aroon", overlay = false, format = format.price, precision = 2)

// ====================================================================
// AROON
// How recently the highest high and the lowest low of the lookback
// were made, from 100 if on this bar down to 0 if a full length of
// bars ago. Aroon up near 100 means new highs keep coming; Aroon down
// near 100, new lows. The shade between the two lines is green while
// up is above down, and red while it is not.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", minval = 1)
upColor = input.color(#00d79e, "Aroon up colour")
downColor = input.color(#ff5252, "Aroon down colour")

// ---- 2. Calculation ------------------------------------------------
// How many bars ago the highest high and the lowest low were made,
// looking at this bar and the length of bars before it: 0 for this
// bar, up to the length for the oldest.
barsSinceHigh = -ta.highestbars(high, length + 1)
barsSinceLow = -ta.lowestbars(low, length + 1)

// Each line is the length minus those bars, as a percentage of the
// length: 100 when the extreme is on this bar, 0 when it is the oldest.
aroonUp = 100 * (length - barsSinceHigh) / length
aroonDown = 100 * (length - barsSinceLow) / length

// ---- 3. Drawing ----------------------------------------------------
// The two lines, and the shade between them in Aroon up's colour while
// it is above Aroon down, and in Aroon down's colour otherwise.
upPlot = plot(aroonUp, "Aroon up", color = upColor, linewidth = 2)
downPlot = plot(aroonDown, "Aroon down", color = downColor, linewidth = 2)
shadeColor = aroonUp > aroonDown ? color.new(upColor, 85) : color.new(downColor, 85)
fill(upPlot, downPlot, color = shadeColor, title = "Shade")

// ---- 4. Alerts -----------------------------------------------------
alertcondition(ta.crossover(aroonUp, aroonDown), "Up crosses above down", "Aroon: Aroon up crossed above Aroon down")
alertcondition(ta.crossunder(aroonUp, aroonDown), "Up crosses below down", "Aroon: Aroon up crossed below Aroon down")

ADX and DMI

The directional movement index in three lines: +DI, how hard the price has been pushing up; -DI, how hard it has been pushing down; and the ADX, how strong the trend is, whichever way it points.

CharmScript 1.0
script("ADX and DMI", tool = indicator, chart = oscillator, legendtitle = "DMI", precision = 2, format = "price")

// ====================================================================
// ADX AND DMI
// The directional movement index in three lines: +DI, how hard the
// price has been pushing up; -DI, how hard it has been pushing down;
// and the ADX, how strong the trend is, whichever way it points. +DI
// above -DI is an uptrend and below it a downtrend; an ADX above the
// key level is a trend strong enough to follow. All three use the
// original smoothing, an average in which each new bar counts for one
// part in the length.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
diLength = input.int(14, "DI length", min = 1, tooltip = "Bars each direction's moves are averaged over")
adxSmoothing = input.int(14, "ADX smoothing", min = 1, tooltip = "Bars the ADX is averaged over")
keyLevel = input.int(25, "Key level", min = 0, max = 100, tooltip = "An ADX above it is a strong trend")
plusColor = input.color(#00d79e, "+DI colour")
minusColor = input.color(#ff5252, "-DI colour")
adxColor = input.color(#a396ff, "ADX colour")

// ---- 2. Calculation ------------------------------------------------
// A bar's move up is how far its high rose above the high of the bar
// before, and its move down how far its low fell below the low of the
// bar before. Only the larger of the two counts, and only when it is
// above zero. Each is averaged over the DI length and divided by the
// average true range over the same bars: +DI and -DI, in percent. The
// gap between them as a percentage of their sum, averaged over the
// ADX smoothing, is the ADX.
[plusDI, minusDI, adx] = ind.dmi(diLength, adxSmoothing)

// ---- 3. Drawing ----------------------------------------------------
// The two direction lines, the ADX over them, and the key level.
plot.line(plusDI, "+DI", color = plusColor)
plot.line(minusDI, "-DI", color = minusColor)
plot.line(adx, "ADX", color = adxColor, linewidth = 2)
plot.level(keyLevel, "Key level", color = #787b86, style = line.dashed)

// ---- 4. Alerts -----------------------------------------------------
// +DI crossing -DI: the trend changing sides.
plusCrossUp = math.crossover(plusDI, minusDI)
plusCrossDown = math.crossunder(plusDI, minusDI)
alert(plusCrossUp, "+DI above -DI", "ADX and DMI: +DI crossed above -DI")
alert(plusCrossDown, "+DI below -DI", "ADX and DMI: +DI crossed below -DI")
The Pine it came from
//@version=6
indicator("ADX and DMI", shorttitle = "DMI", overlay = false, format = format.price, precision = 2)

// ====================================================================
// ADX AND DMI
// The directional movement index in three lines: +DI, how hard the
// price has been pushing up; -DI, how hard it has been pushing down;
// and the ADX, how strong the trend is, whichever way it points. +DI
// above -DI is an uptrend and below it a downtrend; an ADX above the
// key level is a trend strong enough to follow. All three use the
// original smoothing, an average in which each new bar counts for one
// part in the length.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
diLength = input.int(14, "DI length", minval = 1, tooltip = "Bars each direction's moves are averaged over")
adxSmoothing = input.int(14, "ADX smoothing", minval = 1, tooltip = "Bars the ADX is averaged over")
keyLevel = input.int(25, "Key level", minval = 0, maxval = 100, tooltip = "An ADX above it is a strong trend")
plusColor = input.color(#00d79e, "+DI colour")
minusColor = input.color(#ff5252, "-DI colour")
adxColor = input.color(#a396ff, "ADX colour")

// ---- 2. Calculation ------------------------------------------------
// A bar's move up is how far its high rose above the high of the bar
// before, and its move down how far its low fell below the low of the
// bar before. Only the larger of the two counts, and only when it is
// above zero. Each is averaged over the DI length and divided by the
// average true range over the same bars: +DI and -DI, in percent. The
// gap between them as a percentage of their sum, averaged over the
// ADX smoothing, is the ADX.
[plusDI, minusDI, adx] = ta.dmi(diLength, adxSmoothing)

// ---- 3. Drawing ----------------------------------------------------
// The two direction lines, the ADX over them, and the key level.
plot(plusDI, "+DI", color = plusColor)
plot(minusDI, "-DI", color = minusColor)
plot(adx, "ADX", color = adxColor, linewidth = 2)
hline(keyLevel, "Key level", color = #787b86, linestyle = hline.style_dashed)

// ---- 4. Alerts -----------------------------------------------------
// +DI crossing -DI: the trend changing sides.
plusCrossUp = ta.crossover(plusDI, minusDI)
plusCrossDown = ta.crossunder(plusDI, minusDI)
alertcondition(plusCrossUp, "+DI above -DI", "ADX and DMI: +DI crossed above -DI")
alertcondition(plusCrossDown, "+DI below -DI", "ADX and DMI: +DI crossed below -DI")

Vortex indicator

Two lines that weigh the market's up moves against its down moves.

CharmScript 1.0
script("Vortex indicator", tool = indicator, chart = oscillator, legendtitle = "VI", precision = 3, format = "price")

// ====================================================================
// VORTEX INDICATOR
// Two lines that weigh the market's up moves against its down moves.
// VI+ adds up how far each bar's high reached above the low of the bar
// before, VI- how far each bar's low reached below the high of the
// bar before, each as a share of the true range over the same bars.
// VI+ above VI- is an uptrend and below it a downtrend; a cross of the
// two is the trend changing sides.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", min = 1, tooltip = "Bars the moves are added up over")
plusColor = input.color(#00d79e, "VI+ colour")
minusColor = input.color(#ff5252, "VI- colour")

// ---- 2. Calculation ------------------------------------------------
// The upward movement is the distance from the low of the bar before
// to this bar's high; the downward movement, the distance from the
// high of the bar before to this bar's low.
upMove = math.abs(p.high - p.low[-2])
downMove = math.abs(p.low - p.high[-2])

// The true range is the bar's high to its low, stretched to the close
// of the bar before when that is further out. Each movement is added
// up over the length and divided by the true range added up over the
// same bars.
rangeSum = math.sum(ind.tr(true), length)
viPlus = math.sum(upMove, length) / rangeSum
viMinus = math.sum(downMove, length) / rangeSum

// ---- 3. Drawing ----------------------------------------------------
// The two lines, and the level of one that they move around.
plot.line(viPlus, "VI+", color = plusColor)
plot.line(viMinus, "VI-", color = minusColor)
plot.level(1, "One", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("Vortex indicator", shorttitle = "VI", overlay = false, format = format.price, precision = 3)

// ====================================================================
// VORTEX INDICATOR
// Two lines that weigh the market's up moves against its down moves.
// VI+ adds up how far each bar's high reached above the low of the bar
// before, VI- how far each bar's low reached below the high of the
// bar before, each as a share of the true range over the same bars.
// VI+ above VI- is an uptrend and below it a downtrend; a cross of the
// two is the trend changing sides.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", minval = 1, tooltip = "Bars the moves are added up over")
plusColor = input.color(#00d79e, "VI+ colour")
minusColor = input.color(#ff5252, "VI- colour")

// ---- 2. Calculation ------------------------------------------------
// The upward movement is the distance from the low of the bar before
// to this bar's high; the downward movement, the distance from the
// high of the bar before to this bar's low.
upMove = math.abs(high - low[1])
downMove = math.abs(low - high[1])

// The true range is the bar's high to its low, stretched to the close
// of the bar before when that is further out. Each movement is added
// up over the length and divided by the true range added up over the
// same bars.
rangeSum = math.sum(ta.tr(true), length)
viPlus = math.sum(upMove, length) / rangeSum
viMinus = math.sum(downMove, length) / rangeSum

// ---- 3. Drawing ----------------------------------------------------
// The two lines, and the level of one that they move around.
plot(viPlus, "VI+", color = plusColor)
plot(viMinus, "VI-", color = minusColor)
hline(1, "One", color = #787b86, linestyle = hline.style_dashed)

Choppiness index

Whether the market is trending or going sideways, from 0 to 100.

CharmScript 1.0
script("Choppiness index", tool = indicator, chart = oscillator, legendtitle = "CHOP", precision = 2, format = "price")

// ====================================================================
// CHOPPINESS INDEX
// Whether the market is trending or going sideways, from 0 to 100. It
// sets the distance the price travelled bar by bar (the true ranges
// added up) against the ground it covered (the highest high to the
// lowest low). A steady trend covers nearly all of the distance it
// travels and reads low; a choppy market travels far, covers little
// and reads high. Above the upper band the market is choppy, below
// the lower band it is trending. It says nothing of which way.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", min = 2)
upperBand = input.float(61.8, "Upper band", min = 50, max = 100, step = 0.1)
lowerBand = input.float(38.2, "Lower band", min = 0, max = 50, step = 0.1)
shadeChoppy = input.bool(true, "Shade when choppy", tooltip = "Shades the background above the upper band")
trendColor = input.color(#2196f3, "Trending colour")
chopColor = input.color(#fbbf24, "Choppy colour")

// ---- 2. Calculation ------------------------------------------------
// The true ranges of the last bars added up, against the highest high
// minus the lowest low over the same bars. The logarithm of the ratio
// is divided by the logarithm of the length, so the index runs from 0
// to 100.
travelled = math.sum(ind.atr(1), length)
covered = math.highest(p.high, length) - math.lowest(p.low, length)
chop = covered > 0 ? 100 * math.log10(travelled / covered) / math.log10(length) : none

// ---- 3. Drawing ----------------------------------------------------
// The line moves from the trending colour at the lower band to the
// choppy colour at the upper band.
lineColor = color.gradient(chop, lowerBand, upperBand, trendColor, chopColor)
plot.line(chop, "CHOP", color = lineColor, linewidth = 2)
upperLine = plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
lowerLine = plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
paint.fill(upperLine, lowerLine, color = color.hex(#a396ff, 92), title = "Background")
paint.background(shadeChoppy and chop > upperBand ? color.hex(chopColor, 90) : none, title = "Choppy")
The Pine it came from
//@version=6
indicator("Choppiness index", shorttitle = "CHOP", overlay = false, format = format.price, precision = 2)

// ====================================================================
// CHOPPINESS INDEX
// Whether the market is trending or going sideways, from 0 to 100. It
// sets the distance the price travelled bar by bar (the true ranges
// added up) against the ground it covered (the highest high to the
// lowest low). A steady trend covers nearly all of the distance it
// travels and reads low; a choppy market travels far, covers little
// and reads high. Above the upper band the market is choppy, below
// the lower band it is trending. It says nothing of which way.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(14, "Length", minval = 2)
upperBand = input.float(61.8, "Upper band", minval = 50, maxval = 100, step = 0.1)
lowerBand = input.float(38.2, "Lower band", minval = 0, maxval = 50, step = 0.1)
shadeChoppy = input.bool(true, "Shade when choppy", tooltip = "Shades the background above the upper band")
trendColor = input.color(#2196f3, "Trending colour")
chopColor = input.color(#fbbf24, "Choppy colour")

// ---- 2. Calculation ------------------------------------------------
// The true ranges of the last bars added up, against the highest high
// minus the lowest low over the same bars. The logarithm of the ratio
// is divided by the logarithm of the length, so the index runs from 0
// to 100.
travelled = math.sum(ta.atr(1), length)
covered = ta.highest(high, length) - ta.lowest(low, length)
chop = covered > 0 ? 100 * math.log10(travelled / covered) / math.log10(length) : na

// ---- 3. Drawing ----------------------------------------------------
// The line moves from the trending colour at the lower band to the
// choppy colour at the upper band.
lineColor = color.from_gradient(chop, lowerBand, upperBand, trendColor, chopColor)
plot(chop, "CHOP", color = lineColor, linewidth = 2)
upperLine = hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
lowerLine = hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(upperLine, lowerLine, color = color.new(#a396ff, 92), title = "Background")
bgcolor(shadeChoppy and chop > upperBand ? color.new(chopColor, 90) : na, title = "Choppy")

Bollinger %B

Where the price sits within its Bollinger Bands: 1 at the upper band, 0 at the lower one, 0.5 on the middle line.

CharmScript 1.0
script("Bollinger %B", tool = indicator, chart = oscillator, legendtitle = "%B", precision = 2, format = "price")

// ====================================================================
// BOLLINGER %B
// Where the price sits within its Bollinger Bands: 1 at the upper
// band, 0 at the lower one, 0.5 on the middle line. Above 1 the price
// is outside the upper band, below 0 outside the lower one. The bands
// are a simple moving average with a band either side a set number of
// standard deviations away.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(p.close, "Source")
length = input.int(20, "Length", min = 1)
mult = input.float(2.0, "Deviations", min = 0.1, step = 0.1, tooltip = "From the middle line to each band")
aboveColor = input.color(#00d79e, "Above 1 colour")
insideColor = input.color(#a396ff, "Between colour")
belowColor = input.color(#ff5252, "Below 0 colour")

// ---- 2. Calculation ------------------------------------------------
// The bands, then where the source sits between them: its distance
// above the lower band as a share of the gap between the bands.
[middle, upper, lower] = ind.bb(source, length, mult)
bandGap = upper - lower
percentB = bandGap > 0 ? (source - lower) / bandGap : none

// ---- 3. Drawing ----------------------------------------------------
// Green above 1, red below 0, purple in between.
lineColor = percentB > 1 ? aboveColor : percentB < 0 ? belowColor : insideColor
plot.line(percentB, "%B", color = lineColor, linewidth = 2)
topLine = plot.level(1, "Upper band", color = #787b86, style = line.dashed)
plot.level(0.5, "Middle", color = color.hex(#787b86, 50), style = line.dotted)
bottomLine = plot.level(0, "Lower band", color = #787b86, style = line.dashed)
paint.fill(topLine, bottomLine, color = color.hex(#a396ff, 92), title = "Background")
The Pine it came from
//@version=6
indicator("Bollinger %B", shorttitle = "%B", overlay = false, format = format.price, precision = 2)

// ====================================================================
// BOLLINGER %B
// Where the price sits within its Bollinger Bands: 1 at the upper
// band, 0 at the lower one, 0.5 on the middle line. Above 1 the price
// is outside the upper band, below 0 outside the lower one. The bands
// are a simple moving average with a band either side a set number of
// standard deviations away.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
source = input.source(close, "Source")
length = input.int(20, "Length", minval = 1)
mult = input.float(2.0, "Deviations", minval = 0.1, step = 0.1, tooltip = "From the middle line to each band")
aboveColor = input.color(#00d79e, "Above 1 colour")
insideColor = input.color(#a396ff, "Between colour")
belowColor = input.color(#ff5252, "Below 0 colour")

// ---- 2. Calculation ------------------------------------------------
// The bands, then where the source sits between them: its distance
// above the lower band as a share of the gap between the bands.
[middle, upper, lower] = ta.bb(source, length, mult)
bandGap = upper - lower
percentB = bandGap > 0 ? (source - lower) / bandGap : na

// ---- 3. Drawing ----------------------------------------------------
// Green above 1, red below 0, purple in between.
lineColor = percentB > 1 ? aboveColor : percentB < 0 ? belowColor : insideColor
plot(percentB, "%B", color = lineColor, linewidth = 2)
topLine = hline(1, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(0.5, "Middle", color = color.new(#787b86, 50), linestyle = hline.style_dotted)
bottomLine = hline(0, "Lower band", color = #787b86, linestyle = hline.style_dashed)
fill(topLine, bottomLine, color = color.new(#a396ff, 92), title = "Background")

Average true range

How far the price moves in a bar, on average.

CharmScript 1.0
script("Average true range", tool = indicator, chart = oscillator, legendtitle = "ATR")

// ====================================================================
// AVERAGE TRUE RANGE
// How far the price moves in a bar, on average. A bar's true range is
// its high minus its low, stretched to take in any gap from the close
// before it; the first bar, with no close before it, counts its high
// minus its low. The average is Wilder's smoothing, the usual choice,
// or a simple, exponential or weighted moving average. As a percentage
// of the close it can be compared across markets and price levels.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
atrLength = input.int(14, "Length", min = 1)
averageType = input.string("RMA", "Smoothing", options = ["RMA", "SMA", "EMA", "WMA"])
asPercent = input.bool(false, "As a percentage of the close")
lineColor = input.color(#a396ff, "Line colour")

// ---- 2. Calculation ------------------------------------------------
// The chosen kind of average of the values over the length.
averageOf(values, length, kind) =>
    return match kind:
        "SMA": ind.sma(values, length)
        "EMA": ind.ema(values, length)
        "WMA": ind.wma(values, length)
        else: ind.rma(values, length)

// The average of the true range, the first bar included, then the same
// as a percentage of the close when that is chosen.
atr = averageOf(ind.tr(true), atrLength, averageType)
shown = asPercent ? 100 * atr / p.close : atr

// ---- 3. Drawing ----------------------------------------------------
plot.line(shown, "ATR", color = lineColor, linewidth = 2)
The Pine it came from
//@version=6
indicator("Average true range", shorttitle = "ATR", overlay = false)

// ====================================================================
// AVERAGE TRUE RANGE
// How far the price moves in a bar, on average. A bar's true range is
// its high minus its low, stretched to take in any gap from the close
// before it; the first bar, with no close before it, counts its high
// minus its low. The average is Wilder's smoothing, the usual choice,
// or a simple, exponential or weighted moving average. As a percentage
// of the close it can be compared across markets and price levels.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
atrLength = input.int(14, "Length", minval = 1)
averageType = input.string("RMA", "Smoothing", options = ["RMA", "SMA", "EMA", "WMA"])
asPercent = input.bool(false, "As a percentage of the close")
lineColor = input.color(#a396ff, "Line colour")

// ---- 2. Calculation ------------------------------------------------
// The chosen kind of average of the values over the length.
averageOf(values, length, kind) =>
    switch kind
        "SMA" => ta.sma(values, length)
        "EMA" => ta.ema(values, length)
        "WMA" => ta.wma(values, length)
        => ta.rma(values, length)

// The average of the true range, the first bar included, then the same
// as a percentage of the close when that is chosen.
atr = averageOf(ta.tr(true), atrLength, averageType)
shown = asPercent ? 100 * atr / close : atr

// ---- 3. Drawing ----------------------------------------------------
plot(shown, "ATR", color = lineColor, linewidth = 2)

Volume

What the volume says, each in a pane of its own.

On-balance volume

A running total of volume: a bar that closes above the close of the bar before adds its volume, one that closes below it takes its volume away, and an unchanged close leaves the total as it is.

CharmScript 1.0
script("On-balance volume", tool = indicator, chart = oscillator, legendtitle = "OBV", format = "volume")

// ====================================================================
// ON-BALANCE VOLUME
// A running total of volume: a bar that closes above the close of the
// bar before adds its volume, one that closes below it takes its
// volume away, and an unchanged close leaves the total as it is. A
// rising total says the volume is with the buyers, a falling one with
// the sellers. A signal line, an average of the total, can be drawn
// over it to show its trend.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
signalType = input.string("None", "Signal line", options = ["None", "SMA", "EMA"], tooltip = "An average of the total")
signalLength = input.int(20, "Signal length", min = 1)
obvColor = input.color(#2196f3, "OBV colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The running total of volume, added or taken away by each close.
obvTotal = ind.obv

// The signal line: a simple or an exponential moving average of the
// total over the signal length. With "None" there is no signal line:
// its value is missing on every bar, so nothing is drawn.
signalOf(source, kind, len) =>
    return match kind:
        "SMA": ind.sma(source, len)
        "EMA": ind.ema(source, len)
        else: none

signal = signalOf(obvTotal, signalType, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(obvTotal, "OBV", color = obvColor, linewidth = 2)
plot.line(signal, "Signal", color = signalColor)
The Pine it came from
//@version=6
indicator("On-balance volume", shorttitle = "OBV", overlay = false, format = format.volume)

// ====================================================================
// ON-BALANCE VOLUME
// A running total of volume: a bar that closes above the close of the
// bar before adds its volume, one that closes below it takes its
// volume away, and an unchanged close leaves the total as it is. A
// rising total says the volume is with the buyers, a falling one with
// the sellers. A signal line, an average of the total, can be drawn
// over it to show its trend.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
signalType = input.string("None", "Signal line", options = ["None", "SMA", "EMA"], tooltip = "An average of the total")
signalLength = input.int(20, "Signal length", minval = 1)
obvColor = input.color(#2196f3, "OBV colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The running total of volume, added or taken away by each close.
obvTotal = ta.obv

// The signal line: a simple or an exponential moving average of the
// total over the signal length. With "None" there is no signal line:
// its value is missing on every bar, so nothing is drawn.
signalOf(source, kind, len) =>
    switch kind
        "SMA" => ta.sma(source, len)
        "EMA" => ta.ema(source, len)
        => na

signal = signalOf(obvTotal, signalType, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot(obvTotal, "OBV", color = obvColor, linewidth = 2)
plot(signal, "Signal", color = signalColor)

Chaikin money flow

Where the bars closed in their ranges, weighted by their volume and taken over the length: from -1, every bar closing on its low, to +1, every bar closing on its high.

CharmScript 1.0
script("Chaikin money flow", tool = indicator, chart = oscillator, legendtitle = "CMF", precision = 3, format = "price")

// ====================================================================
// CHAIKIN MONEY FLOW
// Where the bars closed in their ranges, weighted by their volume and
// taken over the length: from -1, every bar closing on its low, to +1,
// every bar closing on its high. Above zero the buyers have had the
// better of it and below zero the sellers; beyond a band, by a clear
// margin.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", min = 1, tooltip = "Bars the money flow is added up over")
upperBand = input.float(0.05, "Upper band", min = 0.0, max = 1.0, step = 0.01)
lowerBand = input.float(-0.05, "Lower band", min = -1.0, max = 0.0, step = 0.01)
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The money flow multiplier: where the close sits in the bar's range,
// +1 on the high, -1 on the low and 0 halfway, or 0 when the bar has
// no range at all.
barRange = p.high - p.low
multiplier = barRange == 0 ? 0.0 : ((p.close - p.low) - (p.high - p.close)) / barRange

// A bar's money flow volume is its volume times the multiplier. The
// money flow is that added up over the length, divided by the volume
// added up over the same bars.
cmf = math.sum(multiplier * p.volume, length) / math.sum(p.volume, length)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, the zero line and the two
// bands.
plot.column(cmf, "CMF", color = cmf >= 0 ? upColor : downColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.solid)
plot.level(upperBand, "Upper band", color = #787b86, style = line.dashed)
plot.level(lowerBand, "Lower band", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
indicator("Chaikin money flow", shorttitle = "CMF", overlay = false, format = format.price, precision = 3)

// ====================================================================
// CHAIKIN MONEY FLOW
// Where the bars closed in their ranges, weighted by their volume and
// taken over the length: from -1, every bar closing on its low, to +1,
// every bar closing on its high. Above zero the buyers have had the
// better of it and below zero the sellers; beyond a band, by a clear
// margin.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", minval = 1, tooltip = "Bars the money flow is added up over")
upperBand = input.float(0.05, "Upper band", minval = 0.0, maxval = 1.0, step = 0.01)
lowerBand = input.float(-0.05, "Lower band", minval = -1.0, maxval = 0.0, step = 0.01)
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The money flow multiplier: where the close sits in the bar's range,
// +1 on the high, -1 on the low and 0 halfway, or 0 when the bar has
// no range at all.
barRange = high - low
multiplier = barRange == 0 ? 0.0 : ((close - low) - (high - close)) / barRange

// A bar's money flow volume is its volume times the multiplier. The
// money flow is that added up over the length, divided by the volume
// added up over the same bars.
cmf = math.sum(multiplier * volume, length) / math.sum(volume, length)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, the zero line and the two
// bands.
plot(cmf, "CMF", color = cmf >= 0 ? upColor : downColor, style = plot.style_columns)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_solid)
hline(upperBand, "Upper band", color = #787b86, linestyle = hline.style_dashed)
hline(lowerBand, "Lower band", color = #787b86, linestyle = hline.style_dashed)

Chaikin oscillator

The momentum of the accumulation/distribution line, a running total of each bar's volume weighted by where the bar closed in its range: a fast exponential moving average of the line minus a slow one.

CharmScript 1.0
script("Chaikin oscillator", tool = indicator, chart = oscillator, legendtitle = "Chaikin Osc", format = "volume")

// ====================================================================
// CHAIKIN OSCILLATOR
// The momentum of the accumulation/distribution line, a running total
// of each bar's volume weighted by where the bar closed in its range:
// a fast exponential moving average of the line minus a slow one.
// Above zero the line has been rising, money flowing in; below zero it
// has been falling, money flowing out.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(3, "Fast length", min = 1)
slowLength = input.int(10, "Slow length", min = 1)
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The accumulation/distribution line: each bar adds its volume times
// where it closed in its range, from +1 on its high to -1 on its low,
// or nothing when the bar has no range.
adLine = ind.accdist

// The oscillator: the fast exponential moving average of the line
// minus the slow one.
osc = ind.ema(adLine, fastLength) - ind.ema(adLine, slowLength)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, and the zero line.
plot.column(osc, "Oscillator", color = osc >= 0 ? upColor : downColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.solid)
The Pine it came from
//@version=6
indicator("Chaikin oscillator", shorttitle = "Chaikin Osc", overlay = false, format = format.volume)

// ====================================================================
// CHAIKIN OSCILLATOR
// The momentum of the accumulation/distribution line, a running total
// of each bar's volume weighted by where the bar closed in its range:
// a fast exponential moving average of the line minus a slow one.
// Above zero the line has been rising, money flowing in; below zero it
// has been falling, money flowing out.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(3, "Fast length", minval = 1)
slowLength = input.int(10, "Slow length", minval = 1)
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The accumulation/distribution line: each bar adds its volume times
// where it closed in its range, from +1 on its high to -1 on its low,
// or nothing when the bar has no range.
adLine = ta.accdist

// The oscillator: the fast exponential moving average of the line
// minus the slow one.
osc = ta.ema(adLine, fastLength) - ta.ema(adLine, slowLength)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, and the zero line.
plot(osc, "Oscillator", color = osc >= 0 ? upColor : downColor, style = plot.style_columns)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_solid)

Price volume trend

A running total of volume weighted by how far the close moved: each bar adds its volume times its close's change from the close of the bar before, as a fraction of that close (a 2% rise adds 0.02 of the bar's volume, a 2% fall takes as much away).

CharmScript 1.0
script("Price volume trend", tool = indicator, chart = oscillator, legendtitle = "PVT", format = "volume")

// ====================================================================
// PRICE VOLUME TREND
// A running total of volume weighted by how far the close moved: each
// bar adds its volume times its close's change from the close of the
// bar before, as a fraction of that close (a 2% rise adds 0.02 of the
// bar's volume, a 2% fall takes as much away). A rising total says
// the volume is with the buyers. The signal line, an exponential
// moving average of the total, shows its trend.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
signalLength = input.int(21, "Signal length", min = 1, tooltip = "Bars the signal line averages over")
pvtColor = input.color(#2196f3, "PVT colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The running total, and the signal line: its exponential moving
// average over the signal length.
pvtTotal = ind.pvt
signal = ind.ema(pvtTotal, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot.line(pvtTotal, "PVT", color = pvtColor, linewidth = 2)
plot.line(signal, "Signal", color = signalColor)
The Pine it came from
//@version=6
indicator("Price volume trend", shorttitle = "PVT", overlay = false, format = format.volume)

// ====================================================================
// PRICE VOLUME TREND
// A running total of volume weighted by how far the close moved: each
// bar adds its volume times its close's change from the close of the
// bar before, as a fraction of that close (a 2% rise adds 0.02 of the
// bar's volume, a 2% fall takes as much away). A rising total says
// the volume is with the buyers. The signal line, an exponential
// moving average of the total, shows its trend.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
signalLength = input.int(21, "Signal length", minval = 1, tooltip = "Bars the signal line averages over")
pvtColor = input.color(#2196f3, "PVT colour")
signalColor = input.color(#fbbf24, "Signal colour")

// ---- 2. Calculation ------------------------------------------------
// The running total, and the signal line: its exponential moving
// average over the signal length.
pvtTotal = ta.pvt
signal = ta.ema(pvtTotal, signalLength)

// ---- 3. Drawing ----------------------------------------------------
plot(pvtTotal, "PVT", color = pvtColor, linewidth = 2)
plot(signal, "Signal", color = signalColor)

Elder's force index

The force behind the price's moves: each bar's change in the close times its volume, so a big move on heavy volume counts for a lot, smoothed with an exponential moving average.

CharmScript 1.0
script("Elder's force index", tool = indicator, chart = oscillator, legendtitle = "EFI", format = "volume")

// ====================================================================
// ELDER'S FORCE INDEX
// The force behind the price's moves: each bar's change in the close
// times its volume, so a big move on heavy volume counts for a lot,
// smoothed with an exponential moving average. Above zero the buyers
// are in control and below zero the sellers; the further from zero,
// the harder they are pushing.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(13, "Length", min = 1, tooltip = "Bars the force is averaged over")
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's raw force: how far the close moved from the close of the
// bar before, times the bar's volume. The index is its exponential
// moving average over the length.
force = math.change(p.close) * p.volume
efi = ind.ema(force, length)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, and the zero line.
plot.column(efi, "EFI", color = efi >= 0 ? upColor : downColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.solid)
The Pine it came from
//@version=6
indicator("Elder's force index", shorttitle = "EFI", overlay = false, format = format.volume)

// ====================================================================
// ELDER'S FORCE INDEX
// The force behind the price's moves: each bar's change in the close
// times its volume, so a big move on heavy volume counts for a lot,
// smoothed with an exponential moving average. Above zero the buyers
// are in control and below zero the sellers; the further from zero,
// the harder they are pushing.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(13, "Length", minval = 1, tooltip = "Bars the force is averaged over")
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// Each bar's raw force: how far the close moved from the close of the
// bar before, times the bar's volume. The index is its exponential
// moving average over the length.
force = ta.change(close) * volume
efi = ta.ema(force, length)

// ---- 3. Drawing ----------------------------------------------------
// Columns green above zero and red below, and the zero line.
plot(efi, "EFI", color = efi >= 0 ? upColor : downColor, style = plot.style_columns)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_solid)

Volume profile

How much volume traded at each price over the latest bars, drawn as rows reaching left from the last bar.

CharmScript 1.0
script("Volume profile", tool = indicator, chart = main, legendtitle = "VP")

// ====================================================================
// VOLUME PROFILE
// How much volume traded at each price over the latest bars, drawn as
// rows reaching left from the last bar. Each bar's volume goes to the
// row its typical price (the average of its high, low and close) is
// in. The row with the most volume is the point of control. The value
// area is the band of rows around it that holds the set share of all
// the volume, grown from it one row at a time towards the side with
// more volume. Prices are often drawn back to the point of control,
// and often stall at the edges of the value area.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
barsBack = input.int(200, "Bars", min = 10, max = 500, tooltip = "How many of the latest bars the profile counts")
rowCount = input.int(24, "Rows", min = 2, max = 100)
valueAreaShare = input.int(70, "Value area (%)", min = 1, max = 100)
maxWidth = input.int(50, "Width (bars)", min = 5, max = 500, tooltip = "How many bars long the biggest row is")
pocColor = input.color(#fbbf24, "Point of control colour")
areaColor = input.color(#a396ff, "Value area colour")
restColor = input.color(#787b86, "Other rows colour")

// ---- 2. Calculation ------------------------------------------------
// The volume of each row, from the bottom row up, and the rows and
// sizes found below, all worked out on the last bar only.
var rowVolumes = array(size = rowCount, fill = 0.0)
bottom = none
rowHeight = none
pocRow = none
areaLow = none
areaHigh = none

if bar.isLast:
    // The bars counted: the setting, or all of them on a short chart.
    count = math.min(barsBack, bars.count + 1)

    // The range of those bars, from the lowest low to the highest high,
    // cut into rows of the same height.
    top = p.high
    bottom = p.low
    for i in range(count):
        top = math.max(top, p.high[-i - 1])
        bottom = math.min(bottom, p.low[-i - 1])
    rowHeight = (top - bottom) / rowCount

    // Each bar's volume goes to the row its typical price is in.
    rowVolumes.fill(0.0)
    for i in range(count):
        row = rowHeight > 0 ? math.min(math.floor((p.hlc3[-i - 1] - bottom) / rowHeight), rowCount - 1) : 0
        rowVolumes[row] = rowVolumes[row] + replace(p.volume[-i - 1])

    // The point of control: the row with the most volume.
    pocRow = rowVolumes.indexof(rowVolumes.max())

    // The value area grows from the point of control one row at a time,
    // to whichever side has more volume in its next row, until it holds
    // the set share of all the volume.
    target = rowVolumes.sum() * valueAreaShare / 100
    areaVolume = rowVolumes[pocRow]
    areaLow = pocRow
    areaHigh = pocRow
    while areaVolume < target and (areaLow > 0 or areaHigh < rowCount - 1):
        below = areaLow > 0 ? rowVolumes[areaLow - 1] : -1.0
        above = areaHigh < rowCount - 1 ? rowVolumes[areaHigh + 1] : -1.0
        if above >= below:
            areaHigh += 1
            areaVolume += above
        else:
            areaLow -= 1
            areaVolume += below

// ---- 3. Drawing ----------------------------------------------------
// The boxes of the last update, kept so that each update can take them
// away before it draws its own.
var rowBoxes = array()

if bar.isLast:
    for oldBox in rowBoxes:
        oldBox.delete()
    rowBoxes.clear()

    // A box for each row, reaching left from the last bar. Its length
    // is in proportion to its volume, so that the biggest row is the
    // width setting long.
    biggest = rowVolumes.max()
    for row in range(rowCount):
        rowLength = biggest > 0 ? math.round(rowVolumes[row] / biggest * maxWidth) : 0
        if rowLength > 0:
            inArea = row >= areaLow and row <= areaHigh
            rowColor = row == pocRow ? pocColor : inArea ? areaColor : restColor
            rowLeft = bars.count - rowLength
            rowTop = bottom + (row + 1) * rowHeight
            rowBottom = bottom + row * rowHeight
            fillColor = color.hex(rowColor, 60)
            newBox = plot.box(rowLeft, rowTop, bars.count, rowBottom, border_color = rowColor, bgcolor = fillColor)
            rowBoxes.push(newBox)
The Pine it came from
//@version=6
indicator("Volume profile", shorttitle = "VP", overlay = true, max_bars_back = 500, max_boxes_count = 500)

// ====================================================================
// VOLUME PROFILE
// How much volume traded at each price over the latest bars, drawn as
// rows reaching left from the last bar. Each bar's volume goes to the
// row its typical price (the average of its high, low and close) is
// in. The row with the most volume is the point of control. The value
// area is the band of rows around it that holds the set share of all
// the volume, grown from it one row at a time towards the side with
// more volume. Prices are often drawn back to the point of control,
// and often stall at the edges of the value area.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
barsBack = input.int(200, "Bars", minval = 10, maxval = 500, tooltip = "How many of the latest bars the profile counts")
rowCount = input.int(24, "Rows", minval = 2, maxval = 100)
valueAreaShare = input.int(70, "Value area (%)", minval = 1, maxval = 100)
maxWidth = input.int(50, "Width (bars)", minval = 5, maxval = 500, tooltip = "How many bars long the biggest row is")
pocColor = input.color(#fbbf24, "Point of control colour")
areaColor = input.color(#a396ff, "Value area colour")
restColor = input.color(#787b86, "Other rows colour")

// ---- 2. Calculation ------------------------------------------------
// The volume of each row, from the bottom row up, and the rows and
// sizes found below, all worked out on the last bar only.
var array<float> rowVolumes = array.new<float>(rowCount, 0.0)
float bottom = na
float rowHeight = na
int pocRow = na
int areaLow = na
int areaHigh = na

if barstate.islast
    // The bars counted: the setting, or all of them on a short chart.
    count = math.min(barsBack, bar_index + 1)

    // The range of those bars, from the lowest low to the highest high,
    // cut into rows of the same height.
    top = high
    bottom := low
    for i = 0 to count - 1
        top := math.max(top, high[i])
        bottom := math.min(bottom, low[i])
    rowHeight := (top - bottom) / rowCount

    // Each bar's volume goes to the row its typical price is in.
    array.fill(rowVolumes, 0.0)
    for i = 0 to count - 1
        row = rowHeight > 0 ? math.min(math.floor((hlc3[i] - bottom) / rowHeight), rowCount - 1) : 0
        array.set(rowVolumes, row, array.get(rowVolumes, row) + nz(volume[i]))

    // The point of control: the row with the most volume.
    pocRow := array.indexof(rowVolumes, array.max(rowVolumes))

    // The value area grows from the point of control one row at a time,
    // to whichever side has more volume in its next row, until it holds
    // the set share of all the volume.
    target = array.sum(rowVolumes) * valueAreaShare / 100
    areaVolume = array.get(rowVolumes, pocRow)
    areaLow := pocRow
    areaHigh := pocRow
    while areaVolume < target and (areaLow > 0 or areaHigh < rowCount - 1)
        below = areaLow > 0 ? array.get(rowVolumes, areaLow - 1) : -1.0
        above = areaHigh < rowCount - 1 ? array.get(rowVolumes, areaHigh + 1) : -1.0
        if above >= below
            areaHigh += 1
            areaVolume += above
        else
            areaLow -= 1
            areaVolume += below

// ---- 3. Drawing ----------------------------------------------------
// The boxes of the last update, kept so that each update can take them
// away before it draws its own.
var array<box> rowBoxes = array.new<box>()

if barstate.islast
    for oldBox in rowBoxes
        box.delete(oldBox)
    array.clear(rowBoxes)

    // A box for each row, reaching left from the last bar. Its length
    // is in proportion to its volume, so that the biggest row is the
    // width setting long.
    biggest = array.max(rowVolumes)
    for row = 0 to rowCount - 1
        rowLength = biggest > 0 ? math.round(array.get(rowVolumes, row) / biggest * maxWidth) : 0
        if rowLength > 0
            inArea = row >= areaLow and row <= areaHigh
            rowColor = row == pocRow ? pocColor : inArea ? areaColor : restColor
            rowLeft = bar_index - rowLength
            rowTop = bottom + (row + 1) * rowHeight
            rowBottom = bottom + row * rowHeight
            fillColor = color.new(rowColor, 60)
            newBox = box.new(rowLeft, rowTop, bar_index, rowBottom, border_color = rowColor, bgcolor = fillColor)
            array.push(rowBoxes, newBox)

Strategies

Entries and exits marked on the chart, and backtested in the Backtests panel.

MACD crossover strategy

Trades the MACD's crosses of its signal line: long when the MACD crosses above it, short when it crosses below.

CharmScript 1.0
script("MACD crossover strategy", tool = strategy, chart = oscillator, legendtitle = "MACD strat", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// MACD CROSSOVER STRATEGY
// Trades the MACD's crosses of its signal line: long when the MACD
// crosses above it, short when it crosses below. The MACD is a fast
// EMA of the close minus a slow one, and the signal line an EMA of the
// MACD, so a cross is the momentum turning. Either side can be
// switched off, and trades can be kept to crosses on the far side of
// zero: a long only from a cross below zero, a short only from one
// above it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(12, "Fast length", min = 1)
slowLength = input.int(26, "Slow length", min = 1)
signalLength = input.int(9, "Signal length", min = 1)
direction = input.string("Long and short", "Trade direction", options = ["Long and short", "Long only", "Short only"])
farSideOnly = input.bool(false, "Only crosses on the far side of zero", tooltip = "Longs below zero, shorts above")
macdColor = input.color(#2196f3, "MACD colour")
signalColor = input.color(#fbbf24, "Signal colour")
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The MACD is the fast EMA of the close minus the slow one; the signal
// line is an EMA of the MACD, and the histogram the gap between them.
[macdLine, signalLine, histogram] = ind.macd(p.close, fastLength, slowLength, signalLength)
crossUp = math.crossover(macdLine, signalLine)
crossDown = math.crossunder(macdLine, signalLine)

// Whether a cross may open a trade: its side must be on and, when only
// crosses on the far side of zero count, a cross up must come below
// zero and a cross down above it.
longsOn = direction != "Short only"
shortsOn = direction != "Long only"
longOk = longsOn and (not farSideOnly or macdLine < 0)
shortOk = shortsOn and (not farSideOnly or macdLine > 0)

// ---- 3. Trades -----------------------------------------------------
// Every cross ends the trade against it. A cross up that may open a
// long does so, turning a short into it; any other cross up only
// closes the short. A cross down is the mirror image.
strategy.enter.long(crossUp and longOk, "Long", chart = main)
strategy.exit.short(crossUp and not longOk, chart = main)
strategy.enter.short(crossDown and shortOk, "Short", chart = main)
strategy.exit.long(crossDown and not shortOk, chart = main)

// ---- 4. Drawing ----------------------------------------------------
// The histogram as columns, green above zero and red below, behind the
// MACD and its signal line, with the zero line.
histColor = histogram >= 0 ? color.hex(upColor, 40) : color.hex(downColor, 40)
plot.column(histogram, "Histogram", color = histColor)
plot.line(macdLine, "MACD", color = macdColor, linewidth = 2)
plot.line(signalLine, "Signal", color = signalColor)
plot.level(0, "Zero", color = color.hex(#787b86, 50), style = line.solid)
The Pine it came from
//@version=6
strategy("MACD crossover strategy", shorttitle = "MACD strat", overlay = false, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// MACD CROSSOVER STRATEGY
// Trades the MACD's crosses of its signal line: long when the MACD
// crosses above it, short when it crosses below. The MACD is a fast
// EMA of the close minus a slow one, and the signal line an EMA of the
// MACD, so a cross is the momentum turning. Either side can be
// switched off, and trades can be kept to crosses on the far side of
// zero: a long only from a cross below zero, a short only from one
// above it.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(12, "Fast length", minval = 1)
slowLength = input.int(26, "Slow length", minval = 1)
signalLength = input.int(9, "Signal length", minval = 1)
direction = input.string("Long and short", "Trade direction", options = ["Long and short", "Long only", "Short only"])
farSideOnly = input.bool(false, "Only crosses on the far side of zero", tooltip = "Longs below zero, shorts above")
macdColor = input.color(#2196f3, "MACD colour")
signalColor = input.color(#fbbf24, "Signal colour")
upColor = input.color(#00d79e, "Above zero colour")
downColor = input.color(#ff5252, "Below zero colour")

// ---- 2. Calculation ------------------------------------------------
// The MACD is the fast EMA of the close minus the slow one; the signal
// line is an EMA of the MACD, and the histogram the gap between them.
[macdLine, signalLine, histogram] = ta.macd(close, fastLength, slowLength, signalLength)
crossUp = ta.crossover(macdLine, signalLine)
crossDown = ta.crossunder(macdLine, signalLine)

// Whether a cross may open a trade: its side must be on and, when only
// crosses on the far side of zero count, a cross up must come below
// zero and a cross down above it.
longsOn = direction != "Short only"
shortsOn = direction != "Long only"
longOk = longsOn and (not farSideOnly or macdLine < 0)
shortOk = shortsOn and (not farSideOnly or macdLine > 0)

// ---- 3. Trades -----------------------------------------------------
// Every cross ends the trade against it. A cross up that may open a
// long does so, turning a short into it; any other cross up only
// closes the short. A cross down is the mirror image.
if crossUp
    if longOk
        strategy.entry("Long", strategy.long)
    else
        strategy.close("Short")
if crossDown
    if shortOk
        strategy.entry("Short", strategy.short)
    else
        strategy.close("Long")

// ---- 4. Drawing ----------------------------------------------------
// The histogram as columns, green above zero and red below, behind the
// MACD and its signal line, with the zero line.
histColor = histogram >= 0 ? color.new(upColor, 40) : color.new(downColor, 40)
plot(histogram, "Histogram", color = histColor, style = plot.style_columns)
plot(macdLine, "MACD", color = macdColor, linewidth = 2)
plot(signalLine, "Signal", color = signalColor)
hline(0, "Zero", color = color.new(#787b86, 50), linestyle = hline.style_solid)

Bollinger reversion strategy

Bets on the price coming back to its average after a stretch outside the Bollinger bands, which sit a few standard deviations either side of a simple moving average.

CharmScript 1.0
script("Bollinger reversion strategy", tool = strategy, chart = main, legendtitle = "BB revert", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// BOLLINGER REVERSION STRATEGY
// Bets on the price coming back to its average after a stretch outside
// the Bollinger bands, which sit a few standard deviations either side
// of a simple moving average. A close back above the lower band goes
// long and a close back below the upper band goes short. A trade is
// closed when the close crosses the middle line, or stopped out a set
// percent from the price it was entered at.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", min = 1, tooltip = "Bars the average and the deviation look back over")
mult = input.float(2.0, "Standard deviations", min = 0.1, step = 0.1, tooltip = "From the average to each band")
stopPercent = input.float(3.0, "Stop (%)", min = 0.1, step = 0.1, tooltip = "From the entry price to the stop")
allowShorts = input.bool(true, "Take short trades")
bandColor = input.color(#2196f3, "Band colour")
middleColor = input.color(#fbbf24, "Middle line colour")

// ---- 2. Calculation ------------------------------------------------
// The middle line is a simple moving average of the close, and each
// band sits the set number of standard deviations of the close over
// the same bars from it.
[middle, upper, lower] = ind.bb(p.close, length, mult)
backAboveLower = math.crossover(p.close, lower)
backBelowUpper = math.crossunder(p.close, upper)
crossMiddle = math.cross(p.close, middle)

// ---- 3. Trades -----------------------------------------------------
// A close back above the lower band opens a long, and a close back
// below the upper band a short, when shorts are on.
strategy.enter.long(backAboveLower, "Long")
strategy.enter.short(allowShorts and backBelowUpper, "Short")

// While a trade is open, it is closed when the close crosses the
// middle line, and its stop sits the set percent from the price it was
// entered at, on the losing side. The stop is set once the trade is
// open, so it guards the trade from the bar after the one it opens on.
if strategy.isLong:
    strategy.exit.long(crossMiddle)
    strategy.exit.long(name = "Long stop", sl = strategy.entryPrice * (1 - stopPercent / 100), type = price)
if strategy.isShort:
    strategy.exit.short(crossMiddle)
    strategy.exit.short(name = "Short stop", sl = strategy.entryPrice * (1 + stopPercent / 100), type = price)

// ---- 4. Drawing ----------------------------------------------------
// The two bands with a shade between them, and the middle line.
upperPlot = plot.line(upper, "Upper", color = bandColor)
plot.line(middle, "Middle", color = middleColor)
lowerPlot = plot.line(lower, "Lower", color = bandColor)
paint.fill(upperPlot, lowerPlot, color = color.hex(bandColor, 92), title = "Background")
The Pine it came from
//@version=6
strategy("Bollinger reversion strategy", shorttitle = "BB revert", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// BOLLINGER REVERSION STRATEGY
// Bets on the price coming back to its average after a stretch outside
// the Bollinger bands, which sit a few standard deviations either side
// of a simple moving average. A close back above the lower band goes
// long and a close back below the upper band goes short. A trade is
// closed when the close crosses the middle line, or stopped out a set
// percent from the price it was entered at.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
length = input.int(20, "Length", minval = 1, tooltip = "Bars the average and the deviation look back over")
mult = input.float(2.0, "Standard deviations", minval = 0.1, step = 0.1, tooltip = "From the average to each band")
stopPercent = input.float(3.0, "Stop (%)", minval = 0.1, step = 0.1, tooltip = "From the entry price to the stop")
allowShorts = input.bool(true, "Take short trades")
bandColor = input.color(#2196f3, "Band colour")
middleColor = input.color(#fbbf24, "Middle line colour")

// ---- 2. Calculation ------------------------------------------------
// The middle line is a simple moving average of the close, and each
// band sits the set number of standard deviations of the close over
// the same bars from it.
[middle, upper, lower] = ta.bb(close, length, mult)
backAboveLower = ta.crossover(close, lower)
backBelowUpper = ta.crossunder(close, upper)
crossMiddle = ta.cross(close, middle)

// ---- 3. Trades -----------------------------------------------------
// A close back above the lower band opens a long, and a close back
// below the upper band a short, when shorts are on.
if backAboveLower
    strategy.entry("Long", strategy.long)
if allowShorts and backBelowUpper
    strategy.entry("Short", strategy.short)

// While a trade is open, it is closed when the close crosses the
// middle line, and its stop sits the set percent from the price it was
// entered at, on the losing side. The stop is set once the trade is
// open, so it guards the trade from the bar after the one it opens on.
if strategy.position_size > 0
    if crossMiddle
        strategy.close("Long")
    strategy.exit("Long stop", "Long", stop = strategy.position_avg_price * (1 - stopPercent / 100))
if strategy.position_size < 0
    if crossMiddle
        strategy.close("Short")
    strategy.exit("Short stop", "Short", stop = strategy.position_avg_price * (1 + stopPercent / 100))

// ---- 4. Drawing ----------------------------------------------------
// The two bands with a shade between them, and the middle line.
upperPlot = plot(upper, "Upper", color = bandColor)
plot(middle, "Middle", color = middleColor)
lowerPlot = plot(lower, "Lower", color = bandColor)
fill(upperPlot, lowerPlot, color = color.new(bandColor, 92), title = "Background")

Donchian breakout strategy

Rides breakouts of the Donchian channel, the highest high and lowest low of a run of bars.

CharmScript 1.0
script("Donchian breakout strategy", tool = strategy, chart = main, legendtitle = "DC breakout", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// DONCHIAN BREAKOUT STRATEGY
// Rides breakouts of the Donchian channel, the highest high and lowest
// low of a run of bars. A close above the highest high of the bars
// before goes long, and the long is closed by a close below the lowest
// low of a shorter run of bars before, so a trend is held until the
// price makes a smaller breakout the other way. Shorts are the mirror
// image.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
entryLength = input.int(20, "Entry length", min = 1, tooltip = "Bars the breakout is measured over")
exitLength = input.int(10, "Exit length", min = 1, tooltip = "Bars the exit is measured over")
allowShorts = input.bool(true, "Take short trades")
entryColor = input.color(#2196f3, "Entry channel colour")
exitColor = input.color(#fbbf24, "Exit channel colour")

// ---- 2. Calculation ------------------------------------------------
// Each channel as it stood on the bar before: the highest high and the
// lowest low of its length of bars before this one, so this bar's own
// high and low are left out and its close can break through. The
// entry channel looks back over the entry length, the exit channel
// over the shorter exit length.
entryHigh = math.highest(p.high, entryLength)[-2]
entryLow = math.lowest(p.low, entryLength)[-2]
exitHigh = math.highest(p.high, exitLength)[-2]
exitLow = math.lowest(p.low, exitLength)[-2]

// ---- 3. Trades -----------------------------------------------------
// A close above the entry channel opens a long, turning a short into
// it; otherwise a close above the exit channel only closes the short.
// A close below the entry channel opens a short when shorts are on,
// turning a long into it; otherwise a close below the exit channel
// only closes the long.
if p.close > entryHigh:
    strategy.enter.long(true, "Long")
elif p.close > exitHigh:
    strategy.exit.short(true)
if allowShorts and p.close < entryLow:
    strategy.enter.short(true, "Short")
elif p.close < exitLow:
    strategy.exit.long(true)

// ---- 4. Drawing ----------------------------------------------------
// Both channels as they stood on the bar before, the levels each close
// is measured against, stepping where they change.
plot.step(entryHigh, "Entry high", color = entryColor)
plot.step(entryLow, "Entry low", color = entryColor)
plot.step(exitHigh, "Exit high", color = exitColor)
plot.step(exitLow, "Exit low", color = exitColor)
The Pine it came from
//@version=6
strategy("Donchian breakout strategy", shorttitle = "DC breakout", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// DONCHIAN BREAKOUT STRATEGY
// Rides breakouts of the Donchian channel, the highest high and lowest
// low of a run of bars. A close above the highest high of the bars
// before goes long, and the long is closed by a close below the lowest
// low of a shorter run of bars before, so a trend is held until the
// price makes a smaller breakout the other way. Shorts are the mirror
// image.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
entryLength = input.int(20, "Entry length", minval = 1, tooltip = "Bars the breakout is measured over")
exitLength = input.int(10, "Exit length", minval = 1, tooltip = "Bars the exit is measured over")
allowShorts = input.bool(true, "Take short trades")
entryColor = input.color(#2196f3, "Entry channel colour")
exitColor = input.color(#fbbf24, "Exit channel colour")

// ---- 2. Calculation ------------------------------------------------
// Each channel as it stood on the bar before: the highest high and the
// lowest low of its length of bars before this one, so this bar's own
// high and low are left out and its close can break through. The
// entry channel looks back over the entry length, the exit channel
// over the shorter exit length.
entryHigh = ta.highest(high, entryLength)[1]
entryLow = ta.lowest(low, entryLength)[1]
exitHigh = ta.highest(high, exitLength)[1]
exitLow = ta.lowest(low, exitLength)[1]

// ---- 3. Trades -----------------------------------------------------
// A close above the entry channel opens a long, turning a short into
// it; otherwise a close above the exit channel only closes the short.
// A close below the entry channel opens a short when shorts are on,
// turning a long into it; otherwise a close below the exit channel
// only closes the long.
if close > entryHigh
    strategy.entry("Long", strategy.long)
else if close > exitHigh
    strategy.close("Short")
if allowShorts and close < entryLow
    strategy.entry("Short", strategy.short)
else if close < exitLow
    strategy.close("Long")

// ---- 4. Drawing ----------------------------------------------------
// Both channels as they stood on the bar before, the levels each close
// is measured against, stepping where they change.
plot(entryHigh, "Entry high", color = entryColor, style = plot.style_stepline)
plot(entryLow, "Entry low", color = entryColor, style = plot.style_stepline)
plot(exitHigh, "Exit high", color = exitColor, style = plot.style_stepline)
plot(exitLow, "Exit low", color = exitColor, style = plot.style_stepline)

Parabolic SAR strategy

Follows the parabolic stop and reverse (SAR), a trailing level that sits below the price in an uptrend and above it in a downtrend, and closes in faster each time the trend makes a new extreme.

CharmScript 1.0
script("Parabolic SAR strategy", tool = strategy, chart = main, legendtitle = "SAR strat", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// PARABOLIC SAR STRATEGY
// Follows the parabolic stop and reverse (SAR), a trailing level that
// sits below the price in an uptrend and above it in a downtrend, and
// closes in faster each time the trend makes a new extreme. A close
// above it goes long and a close below it goes short, so the strategy
// is always in the market; with longs only, a close below it just
// ends the long.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
start = input.float(0.02, "Start", min = 0.001, step = 0.01, tooltip = "The acceleration a trend starts with")
increment = input.float(0.02, "Increment", min = 0.001, step = 0.01, tooltip = "Added at each new extreme")
maximum = input.float(0.2, "Maximum", min = 0.01, step = 0.01, tooltip = "The most the acceleration can reach")
longOnly = input.bool(false, "Long only", tooltip = "A close below the SAR only closes the long")
upColor = input.color(#00d79e, "Uptrend colour")
downColor = input.color(#ff5252, "Downtrend colour")

// ---- 2. Calculation ------------------------------------------------
// The SAR starts each trend at the extreme of the trend before. Each
// bar it moves towards the trend's own extreme by the acceleration
// times the distance between them. The acceleration starts at the
// start value and grows by the increment with each new extreme, up to
// the maximum. When the price reaches the SAR, the trend flips.
sar = ind.sar(start, increment, maximum)
crossUp = math.crossover(p.close, sar)
crossDown = math.crossunder(p.close, sar)

// ---- 3. Trades -----------------------------------------------------
// A close above the SAR opens a long, turning a short into it; a close
// below it turns the long into a short, or only closes the long with
// longs only.
strategy.enter.long(crossUp, "Long")
strategy.exit.long(crossDown and longOnly)
strategy.enter.short(crossDown and not longOnly, "Short")

// ---- 4. Drawing ----------------------------------------------------
// The SAR as dots, green below the price and red above it.
plot.circles(sar, "SAR", color = p.close > sar ? upColor : downColor, linewidth = 2)
The Pine it came from
//@version=6
strategy("Parabolic SAR strategy", shorttitle = "SAR strat", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// PARABOLIC SAR STRATEGY
// Follows the parabolic stop and reverse (SAR), a trailing level that
// sits below the price in an uptrend and above it in a downtrend, and
// closes in faster each time the trend makes a new extreme. A close
// above it goes long and a close below it goes short, so the strategy
// is always in the market; with longs only, a close below it just
// ends the long.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
start = input.float(0.02, "Start", minval = 0.001, step = 0.01, tooltip = "The acceleration a trend starts with")
increment = input.float(0.02, "Increment", minval = 0.001, step = 0.01, tooltip = "Added at each new extreme")
maximum = input.float(0.2, "Maximum", minval = 0.01, step = 0.01, tooltip = "The most the acceleration can reach")
longOnly = input.bool(false, "Long only", tooltip = "A close below the SAR only closes the long")
upColor = input.color(#00d79e, "Uptrend colour")
downColor = input.color(#ff5252, "Downtrend colour")

// ---- 2. Calculation ------------------------------------------------
// The SAR starts each trend at the extreme of the trend before. Each
// bar it moves towards the trend's own extreme by the acceleration
// times the distance between them. The acceleration starts at the
// start value and grows by the increment with each new extreme, up to
// the maximum. When the price reaches the SAR, the trend flips.
sar = ta.sar(start, increment, maximum)
crossUp = ta.crossover(close, sar)
crossDown = ta.crossunder(close, sar)

// ---- 3. Trades -----------------------------------------------------
// A close above the SAR opens a long, turning a short into it; a close
// below it turns the long into a short, or only closes the long with
// longs only.
if crossUp
    strategy.entry("Long", strategy.long)
if crossDown
    if longOnly
        strategy.close("Long")
    else
        strategy.entry("Short", strategy.short)

// ---- 4. Drawing ----------------------------------------------------
// The SAR as dots, green below the price and red above it.
plot(sar, "SAR", color = close > sar ? upColor : downColor, style = plot.style_circles, linewidth = 2)

ADX trend strategy

Trades the crosses of the two direction lines, +DI and -DI, but only opens a trade when the ADX says the market is trending.

CharmScript 1.0
script("ADX trend strategy", tool = strategy, chart = oscillator, legendtitle = "ADX strat", precision = 2, format = "price", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// ADX TREND STRATEGY
// Trades the crosses of the two direction lines, +DI and -DI, but only
// opens a trade when the ADX says the market is trending. Long when
// +DI crosses above -DI with the ADX above the threshold, closed when
// -DI crosses back above +DI; shorts are the mirror image. The lines
// use the original smoothing, an average in which each new bar counts
// for one part in the length.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
diLength = input.int(14, "DI length", min = 1, tooltip = "Bars each direction's moves are averaged over")
adxSmoothing = input.int(14, "ADX smoothing", min = 1, tooltip = "Bars the ADX is averaged over")
threshold = input.int(25, "ADX threshold", min = 0, max = 100, tooltip = "Trades need the ADX above it")
allowShorts = input.bool(true, "Take short trades")
plusColor = input.color(#00d79e, "+DI colour")
minusColor = input.color(#ff5252, "-DI colour")
adxColor = input.color(#a396ff, "ADX colour")

// ---- 2. Calculation ------------------------------------------------
// +DI and -DI: how hard the price has pushed up and down, each as a
// percentage of the average true range. The ADX: the gap between them
// as a percentage of their sum, averaged, so how strong the trend is,
// whichever way it points.
[plusDI, minusDI, adx] = ind.dmi(diLength, adxSmoothing)
plusCross = math.crossover(plusDI, minusDI)
minusCross = math.crossover(minusDI, plusDI)
trending = adx > threshold

// ---- 3. Trades -----------------------------------------------------
// +DI crossing above -DI opens a long while the market is trending,
// turning a short into it; otherwise it only closes the short. -DI
// crossing above +DI is the mirror image, and only closes the long
// when shorts are off.
strategy.enter.long(plusCross and trending, "Long", chart = main)
strategy.exit.short(plusCross and not trending, chart = main)
if minusCross:
    if trending and allowShorts:
        strategy.enter.short(true, "Short", chart = main)
    else:
        strategy.exit.long(true, chart = main)

// ---- 4. Drawing ----------------------------------------------------
// The two direction lines, the ADX over them, and the threshold.
plot.line(plusDI, "+DI", color = plusColor)
plot.line(minusDI, "-DI", color = minusColor)
plot.line(adx, "ADX", color = adxColor, linewidth = 2)
plot.level(threshold, "ADX threshold", color = #787b86, style = line.dashed)
The Pine it came from
//@version=6
strategy("ADX trend strategy", shorttitle = "ADX strat", overlay = false, format = format.price, precision = 2, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// ADX TREND STRATEGY
// Trades the crosses of the two direction lines, +DI and -DI, but only
// opens a trade when the ADX says the market is trending. Long when
// +DI crosses above -DI with the ADX above the threshold, closed when
// -DI crosses back above +DI; shorts are the mirror image. The lines
// use the original smoothing, an average in which each new bar counts
// for one part in the length.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
diLength = input.int(14, "DI length", minval = 1, tooltip = "Bars each direction's moves are averaged over")
adxSmoothing = input.int(14, "ADX smoothing", minval = 1, tooltip = "Bars the ADX is averaged over")
threshold = input.int(25, "ADX threshold", minval = 0, maxval = 100, tooltip = "Trades need the ADX above it")
allowShorts = input.bool(true, "Take short trades")
plusColor = input.color(#00d79e, "+DI colour")
minusColor = input.color(#ff5252, "-DI colour")
adxColor = input.color(#a396ff, "ADX colour")

// ---- 2. Calculation ------------------------------------------------
// +DI and -DI: how hard the price has pushed up and down, each as a
// percentage of the average true range. The ADX: the gap between them
// as a percentage of their sum, averaged, so how strong the trend is,
// whichever way it points.
[plusDI, minusDI, adx] = ta.dmi(diLength, adxSmoothing)
plusCross = ta.crossover(plusDI, minusDI)
minusCross = ta.crossover(minusDI, plusDI)
trending = adx > threshold

// ---- 3. Trades -----------------------------------------------------
// +DI crossing above -DI opens a long while the market is trending,
// turning a short into it; otherwise it only closes the short. -DI
// crossing above +DI is the mirror image, and only closes the long
// when shorts are off.
if plusCross
    if trending
        strategy.entry("Long", strategy.long)
    else
        strategy.close("Short")
if minusCross
    if trending and allowShorts
        strategy.entry("Short", strategy.short)
    else
        strategy.close("Long")

// ---- 4. Drawing ----------------------------------------------------
// The two direction lines, the ADX over them, and the threshold.
plot(plusDI, "+DI", color = plusColor)
plot(minusDI, "-DI", color = minusColor)
plot(adx, "ADX", color = adxColor, linewidth = 2)
hline(threshold, "ADX threshold", color = #787b86, linestyle = hline.style_dashed)

EMA cross with ATR exits

Goes long when a fast EMA crosses above a slow one, and short when it crosses back below.

CharmScript 1.0
script("EMA cross with ATR exits", tool = strategy, chart = main, legendtitle = "EMA ATR", capital = 10000, compounding = 100, fee = 0.05, slippage = 0)

// ====================================================================
// EMA CROSS WITH ATR EXITS
// Goes long when a fast EMA crosses above a slow one, and short when
// it crosses back below. Each trade has a stop and a target a set
// number of ATRs (average true ranges) from where it was signalled,
// so both sit further away when the market moves more.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(9, "Fast EMA", min = 1)
slowLength = input.int(21, "Slow EMA", min = 1)
atrLength = input.int(14, "ATR length", min = 1)
stopAtr = input.float(1.5, "Stop (ATRs)", min = 0.1, step = 0.1, tooltip = "From the signal's close, in ATRs")
targetAtr = input.float(3.0, "Target (ATRs)", min = 0.1, step = 0.1, tooltip = "From the signal's close, in ATRs")
allowShorts = input.bool(true, "Take short trades")

// ---- 2. Calculation ------------------------------------------------
fast = ind.ema(p.close, fastLength)
slow = ind.ema(p.close, slowLength)
atr = ind.atr(atrLength)
crossUp = math.crossover(fast, slow)
crossDown = math.crossunder(fast, slow)

// Each side's stop and target, set from the close on the bar its trade
// is signalled and kept from one bar to the next until the next signal.
var longStop = none
var longTarget = none
var shortStop = none
var shortTarget = none
if crossUp:
    longStop = p.close - stopAtr * atr
    longTarget = p.close + targetAtr * atr
if crossDown:
    shortStop = p.close + stopAtr * atr
    shortTarget = p.close - targetAtr * atr

// ---- 3. Trades -----------------------------------------------------
// A cross down turns a long into a short, or only closes the long when
// shorts are off.
strategy.enter.long(crossUp, "Long")
strategy.enter.short(crossDown and allowShorts, "Short")
strategy.exit.long(crossDown and not allowShorts)

// Each exit waits for its own side's trade and guards it from the bar
// the trade opens on.
strategy.exit.long(name = "Long exit", sl = longStop, tp = longTarget, type = price)
strategy.exit.short(name = "Short exit", sl = shortStop, tp = shortTarget, type = price)

// ---- 4. Drawing ----------------------------------------------------
// The two EMAs, and while a trade is open its entry price, stop and
// target, each with a gap where no trade is open.
inLong = strategy.isLong
inShort = strategy.isShort
plot.line(fast, "Fast EMA", color = #00d79e, linewidth = 2)
plot.line(slow, "Slow EMA", color = color.hex(#787b86, 30))
plot.line(inLong or inShort ? strategy.entryPrice : none, "Entry price", color = #787b86)
plot.line(inLong ? longStop : inShort ? shortStop : none, "Stop", color = #ff5252)
plot.line(inLong ? longTarget : inShort ? shortTarget : none, "Target", color = #00d79e)
The Pine it came from
//@version=6
strategy("EMA cross with ATR exits", shorttitle = "EMA ATR", overlay = true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.05)

// ====================================================================
// EMA CROSS WITH ATR EXITS
// Goes long when a fast EMA crosses above a slow one, and short when
// it crosses back below. Each trade has a stop and a target a set
// number of ATRs (average true ranges) from where it was signalled,
// so both sit further away when the market moves more.
// ====================================================================

// ---- 1. Settings ---------------------------------------------------
fastLength = input.int(9, "Fast EMA", minval = 1)
slowLength = input.int(21, "Slow EMA", minval = 1)
atrLength = input.int(14, "ATR length", minval = 1)
stopAtr = input.float(1.5, "Stop (ATRs)", minval = 0.1, step = 0.1, tooltip = "From the signal's close, in ATRs")
targetAtr = input.float(3.0, "Target (ATRs)", minval = 0.1, step = 0.1, tooltip = "From the signal's close, in ATRs")
allowShorts = input.bool(true, "Take short trades")

// ---- 2. Calculation ------------------------------------------------
fast = ta.ema(close, fastLength)
slow = ta.ema(close, slowLength)
atr = ta.atr(atrLength)
crossUp = ta.crossover(fast, slow)
crossDown = ta.crossunder(fast, slow)

// Each side's stop and target, set from the close on the bar its trade
// is signalled and kept from one bar to the next until the next signal.
var float longStop = na
var float longTarget = na
var float shortStop = na
var float shortTarget = na
if crossUp
    longStop := close - stopAtr * atr
    longTarget := close + targetAtr * atr
if crossDown
    shortStop := close + stopAtr * atr
    shortTarget := close - targetAtr * atr

// ---- 3. Trades -----------------------------------------------------
// A cross down turns a long into a short, or only closes the long when
// shorts are off.
if crossUp
    strategy.entry("Long", strategy.long)
if crossDown
    if allowShorts
        strategy.entry("Short", strategy.short)
    else
        strategy.close("Long")

// Each exit waits for its own side's trade and guards it from the bar
// the trade opens on.
strategy.exit("Long exit", "Long", stop = longStop, limit = longTarget)
strategy.exit("Short exit", "Short", stop = shortStop, limit = shortTarget)

// ---- 4. Drawing ----------------------------------------------------
// The two EMAs, and while a trade is open its entry price, stop and
// target, each with a gap where no trade is open.
inLong = strategy.position_size > 0
inShort = strategy.position_size < 0
plot(fast, "Fast EMA", color = #00d79e, linewidth = 2)
plot(slow, "Slow EMA", color = color.new(#787b86, 30))
plot(inLong or inShort ? strategy.position_avg_price : na, "Entry price", color = #787b86, style = plot.style_linebr)
plot(inLong ? longStop : inShort ? shortStop : na, "Stop", color = #ff5252, style = plot.style_linebr)
plot(inLong ? longTarget : inShort ? shortTarget : na, "Target", color = #00d79e, style = plot.style_linebr)

Reference

Every built-in function and value, as the editor's Reference lists them. A method is also its namespace's function: lbl.text("Buy") is label.text(lbl, "Buy").

Script 2

script(title, tool = indicator, chart = oscillator, legendtitle, tooltip, history, compounding, capital, fee, slippage, leverage, pyramiding, feetype = percent, labels = simple)
Names the script. tool is indicator or strategy (a strategy can use strategy.enter and strategy.exit). chart = main draws it over the candles; chart = oscillator (the default) gives it a pane of its own below them. A drawing can pick for itself with its own chart =. legendtitle is the name the chart shows for it (its Tools row and its pane), when that should be shorter than the title. tooltip is what the script says about itself: the card shown when its name is hovered in the Tools list, and from the "i" beside its name in its settings. A line of it that starts with "- " is a bullet under the rest (\n starts a new line). history = all runs it from the first candle of the whole history on every chart (for a script whose values never settle, like a count of every bar); history = window from 2,000 candles before the drawn ones. Without it, saving checks which the script needs. compounding = 50 (a strategy's, a plain number from 0 to 100) is how much of its profit the strategy reinvests: its Compounding % on the Strategy tab of its settings, which starts there and can still be changed (99 without it). capital = 10000, fee = 0.05, slippage = 0.02 and leverage = 2 (a strategy's, plain numbers) are its Initial Capital, Fee % and Slippage % on each entry and exit, and Leverage, on the same tab, where they start and can still be changed; a fee or a slippage switches Execution on. feetype = coin makes the fee money for each coin bought or sold (fee = 1.25 is $1.25 a coin), and feetype = order money for each order filled; percent (the default) a percent of each trade. pyramiding = 3 (a strategy's, a whole number up to 100) lets three entries be open on one side at once, Pine's pyramiding: each its own trade, an exit closing the oldest first, and one stop and target for the whole position, counted from strategy.entryPrice, the average entry price. labels = detailed (a strategy's) adds each trade's number beside the word of its Long, Short and Close labels: an entry's size, an exit's return in green or red; labels = simple (the default) draws the words alone. It is the Labels row on the Strategy tab of its settings, which starts there and can still be changed.
alert(when, title, message)
An alert the script offers: it fires on a bar where when is true, when that bar closes. title names it, in quotes (at most 32 characters): what the alert is called in the script's settings (Alerts tab), on its card and in the notification. message is what the notification says, worked out on the bar that fired, so it can carry values ("RSI " + rsi). Switched on in the script's settings, Alerts tab, for the chart's coin and timeframe; it runs the saved script, on the chart and on the server, so it reaches the phone with no chart open.

Inputs 11

input(default, title)
A setting shown in the script's settings. Its type follows the default value. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.int(default, title, min, max, step)
A whole-number setting. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.float(default, title, min, max, step)
A decimal-number setting. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.bool(default, title)
An on/off setting. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.string(default, title, options = ["A", "B"])
A text setting, or a dropdown when options is given. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.enum(Trend.up, title, options = [Trend.up, Trend.down])
A dropdown of an enum's choices (Pine's input.enum): it shows their titles and gives the choice picked, so pick = input.enum(Trend.up, "Trend") under enum Trend: is compared as pick == Trend.up, and format(pick) is its title. options offers only some of them. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.color(default, title)
A colour setting. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.source(p.close, title)
Which price to use: p.open, high, low, close, volume, hl2, hlc3, ohlc4 or hlcc4. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.timeframe("1D", title)
A timeframe setting, a dropdown of timeframes: written as the chart writes them ("60" is an hour, "240" four, "D" or "1D" a day, "W" a week) or a month ("1M", as in Pine; one minute is "1"). input.timeframe(chart.timeframe, "Period") starts at the chart's own timeframe ("" too). Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.session("0700-1600", title)
Session hours, written as Pine writes them: "0700-1600" (the end not included), several as "0800-0900,1230-1630", the days after a colon ("0930-1600:23456", 1 is Sunday), "2000-0400" past midnight, "24x7" all of it. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).
input.time("2024-01-15 09:30", title)
A date and time setting (Pine's input.time): the time it holds in milliseconds since 1970, what bar.time is compared with (bar.time >= start). Its default is a date in quotes, "2024-01-15" or "2024-01-15 09:30" in UTC ("2024-01-15 09:30 +0200" in another zone), or a time in milliseconds; the settings box writes it in UTC. Every setting takes tooltip = "…" (its ? help), group = "…" (a heading over it) and badge = true (its value in a box beside the script's name on its pane, as an order-flow pane shows Aggregate; off unless written; a colour has no value to show).

Price 10

data.fetch(asset, timeframe, value, forming = false, gaps = false, all = false, candles = standard)
value worked out on another timeframe's candles, of the chart's coin or another: data.fetch(chart.asset, "1D", ind.ema(p.close, 50)) on an hourly chart is the 50-day average, run on the daily candles with their own history, and data.fetch("BINANCE:ETHUSDT", "1D", p.close) ETH's daily close. The asset is chart.asset (or "") for the chart's own coin, a coin written as the chart writes it, or a text setting. A variable made above it is worked out again there, as Pine does, and [p.open, p.close] gives several values at once. Each bar reads the newest of those candles that has closed by the bar's close: an hour reads yesterday's day until the day's last hour. forming = true reads the candle the bar is in, as it stood at the bar's close (today's high so far), built from the chart's own bars, so of its own coin on a longer timeframe; p.high[-2] in it is yesterday's high all day. gaps = true gives a value only on the bar where a new one arrives. On a smaller timeframe it is the bar's last such candle, and all = true an array of every one inside the bar, oldest first (Pine's request.security_lower_tf). Another coin's candles, and a smaller timeframe's, come in live. The timeframe is in quotes, as the chart writes it ("240", "1D", "1W", or "1M" for a month), chart.timeframe for the chart's own (Pine's timeframe.period; "" too), or a setting made with input.timeframe. It goes at the top level of the script, not inside an if, a loop or a function. A script can use at most 40 different timeframes and coins.
p.open
Opening price of the bar.
p.high
Highest price of the bar.
p.low
Lowest price of the bar.
p.close
Closing price of the bar (the latest price on the forming bar).
p.volume
Volume of the bar.
p.hl2
(high + low) / 2
p.hlc3
(high + low + close) / 3
p.ohlc4
(open + high + low + close) / 4
p.hlcc4
(high + low + close + close) / 4

Order flow 6

data.funding(asset)
The funding rate of the coin's perpetual future on each candle, in percent (0.01 is 0.01%), as the chart's Funding pane shows it: on Binance and HyperLiquid's perpetuals, none on a spot pair. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.
data.openInterest(asset, value = close)
The open interest of the coin's perpetual future at each candle's close, in coins, as the chart's Open Interest pane draws it: on Binance and HyperLiquid's perpetuals, none on a spot pair. value = open, high or low gives its open, its highest and its lowest during the candle instead. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.
data.longLiquidations(asset)
How much of the coin's longs were liquidated during each candle, in dollars, as the chart's Liquidations pane draws it (0 on a candle with none): on Binance and HyperLiquid's perpetuals. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.
data.shortLiquidations(asset)
How much of the coin's shorts were liquidated during each candle, in dollars, as the chart's Liquidations pane draws it (0 on a candle with none): on Binance and HyperLiquid's perpetuals. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.
data.buyVolume(asset)
What buyers bought at the market during each candle (the taker buys), in coins: the buying side of the chart's CVD pane. ta.cum(data.buyVolume() - data.sellVolume()) is the cumulative volume delta. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.
data.sellVolume(asset)
What sellers sold at the market during each candle (the taker sells), in coins: the selling side of the chart's CVD pane. With data.buyVolume() it makes the candle's volume. asset is another coin's, as data.fetch() takes one ("BINANCE:ETHUSDT", or a text setting); the chart's own without it. Inside a data.fetch() value it is that request's coin and timeframe: data.fetch(chart.asset, "1D", data.openInterest()) is the daily one. None where the market has none, before its data begins, and on Renko, Range and Line Break bricks. A value a bar back, [-2], is the bar before's own.

Bars 25

bar.isFirstOf("1D")
True on the first bar of each new period of a timeframe, in UTC: "1D" a day, "W" a week from Monday, "1M" a month, "240" four hours (Pine's timeframe.change). False on the chart's first bar, which follows none. bar.isFirstOf(chart.timeframe) is the chart's own timeframe ("" too): every bar after the first.
bar.inSession("0700-1600", zone = "UTC")
True while the bar opens inside the session hours, written as Pine writes them: "0700-1600" (the end not included), several as "0800-0900,1230-1630", the days after a colon ("0930-1600:23456", 1 is Sunday), "2000-0400" past midnight, "24x7". In UTC, or the time zone given: an offset ("UTC+2") or a place ("America/New_York", its summer time too).
bar.openTimeOf("1D")
When the period of a timeframe the bar is in began, in milliseconds since 1970 (Pine's time("1D")): 00:00 UTC of the bar's day for "1D", Monday 00:00 for "W", the 1st for "1M". bar.time for the chart's own timeframe (""). None for text that isn't a timeframe.
bar.closeTimeOf("1D")
When the period of a timeframe the bar is in ends, in milliseconds since 1970 (Pine's time_close("1D")): the next day's 00:00 UTC for "1D". bar.closeTime for the chart's own timeframe (""). None for text that isn't a timeframe.
bars.count
How many bars come before this one: 0 on the oldest bar.
bars.last
bars.count of the newest bar.
bar.time
Bar open time, in milliseconds since 1970 (UTC).
bar.year
Year of the bar (UTC).
bar.month
Month of the bar, 1–12 (UTC).
bar.day
Day of the month, 1–31 (UTC).
bar.weekday
Day of the week: 1 = Sunday … 7 = Saturday (UTC).
bar.week
The ISO week of the year, 1 to 53: weeks start on Monday, and week 1 holds the year's first Thursday (UTC).
bar.hour
Hour, 0–23 (UTC).
bar.minute
Minute, 0–59.
bar.second
Second, 0–59.
bar.isFirst
True on the oldest bar.
bar.isLast
True on the newest bar.
bar.isConfirmed
True once the bar has closed (every bar but the newest).
bar.isRealtime
True on the newest, still-forming bar.
bar.isHistory
True on every bar but the newest.
bar.isLastClosed
True on the newest closed bar, the one before the forming bar, when the script runs from the start (Pine's barstate.islastconfirmedhistory): a bar that closes later never is.
bar.closeTime
When the bar closes, in milliseconds since 1970 (UTC): bar.time and one bar of the chart's timeframe (Pine's time_close). On the forming bar, when it will close.
bars.lastTime
bar.time of the newest bar (Pine's last_bar_time).
bars.firstTime
bar.time of the oldest bar loaded: on the chart, the first candle of the history it holds (older ones load as you scroll back, and the script runs again).
bar.isNew
True on a bar's first run: on every closed bar, and on the forming bar the first time it runs, not on the updates after (Pine's barstate.isnew). What a bar changes on its first run is undone when it runs again, as in Pine.

Chart 28

chart.secondsOf("1D")
How many seconds a bar of a timeframe lasts: 86400 for "1D", 14400 for "240", chart.seconds for "" (Pine's timeframe.in_seconds). A month counts as 2,628,003 seconds, as Pine counts one. None for text that isn't a timeframe.
chart.timeframeOf(14400)
The shortest timeframe at least that many seconds long, as chart.timeframe spells one: "240" for 14400, "D" for 86400, "7D" for 604799, "5S" for 3 (Pine's timeframe.from_seconds). None for no seconds.
chart.symbol
The chart's ticker, like "BTCUSDT".
chart.asset
The chart's asset as the chart writes it, like "BINANCE:BTCUSDT" (Pine's syminfo.tickerid): what data.fetch() takes for the chart's own coin.
chart.timeframe
The chart's timeframe as the chart spells it ("60", "240", "1D" …).
chart.seconds
Bar length in seconds.
chart.isIntraday
True below one day.
chart.isDaily
True on a daily chart.
chart.isWeekly
True on a weekly chart.
chart.isMonthly
True on a monthly chart.
chart.minQty
The step a quantity of this coin is counted in: the largest power of ten worth at most a dollar at its newest price, and at most 1 (BTC 0.00001, ETH 0.0001, DOGE 1), as exchanges' steps run. Pine's syminfo.mincontract.
chart.tick
The step the chart writes this coin's prices to: 0.01 where it shows two decimals (from the newest price, as the chart's scale does). math.round(x / chart.tick) * chart.tick rounds to it; format(x, "tick") writes a price so. It can be finer than the exchange's own tick (Pine's syminfo.mintick).
chart.fgColor
The chart's own text colour: light on a dark chart, dark on a light one (Pine's chart.fg_color). A script that reads it runs again when the theme changes.
chart.bgColor
The chart's background colour (Pine's chart.bg_color). A script that reads it runs again when the theme changes.
chart.isStandard
True while the chart draws the coin's own candles; false under Heikin Ashi, Renko, Range, Line Break, nOHLC and nHA (Pine's chart.is_standard). On those the script runs on the bars drawn, and a strategy decides on them but fills every order on the real candles.
chart.isHeikinAshi
True while the chart draws Heikin Ashi candles (Pine's chart.is_heikinashi): the script then runs on them, and a strategy fills on the real candles.
chart.isRenko
True while the chart draws Renko bricks (Pine's chart.is_renko).
chart.isRange
True while the chart draws Range bars (Pine's chart.is_range).
chart.isLineBreak
True while the chart draws Line Break bars (Pine's chart.is_linebreak).
chart.isNohlc
True while the chart draws nOHLC's neural candles: the script then runs on them, and a strategy fills on the real candles.
chart.isNha
True while the chart draws nHA's neural candles: the script then runs on them, and a strategy fills on the real candles.
chart.exchange
Where the chart's asset comes from: the part of chart.asset before its colon, like "BINANCE" or "HYPERLIQUID" (Pine's syminfo.prefix).
chart.currency
The currency the chart's prices are in: "USDT" for BINANCE:BTCUSDT, "USD" on HyperLiquid, its stocks and metals and for an index (Pine's syminfo.currency).
chart.base
What the chart prices: "BTC" for BINANCE:BTCUSDT and on HyperLiquid's BTC (Pine's syminfo.basecurrency).
chart.timezone
The market's time zone: "UTC" (every market here trades around the clock, its candles in UTC; Pine's syminfo.timezone).
chart.assetType
What the chart's asset is: "index" for a market index (TOTAL, BTC.D), else "crypto" (Pine's syminfo.type).
chart.multiplier
The number in the chart's timeframe: 240 for "240", 3 for "3D", 1 for "W", 15 for "15S" (Pine's timeframe.multiplier).
chart.pointValue
What a move of 1 in the price is worth for one unit of the asset: 1 (Pine's syminfo.pointvalue).

Time 11

time.of(2024, 1, 15, 9, 30, zone = "UTC") time.of("2024-01-15 09:30")
A date and a clock time as a time in milliseconds since 1970, what bar.time is compared with (Pine's timestamp()). In UTC, or the zone given: an offset ("UTC+2") or a place ("America/New_York", its summer time too). A month or a day past its end rolls on: month 13 is the next January. Or one text: "2024-01-15", "2024-01-15T09:30:00+02:00" or "15 Jan 2024 09:30 +0200", in UTC where it names no zone. None for one that isn't a date, or a zone that isn't one.
time.year(bar.time, zone = "UTC")
The year of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's year(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.year is the same.
time.month(bar.time, zone = "UTC")
The month, 1 to 12, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's month(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.month is the same.
time.day(bar.time, zone = "UTC")
The day of the month, 1 to 31, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's dayofmonth(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.day is the same.
time.weekday(bar.time, zone = "UTC")
The day of the week, 1 Sunday to 7 Saturday, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's dayofweek(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.weekday is the same.
time.week(bar.time, zone = "UTC")
The ISO week of the year, 1 to 53 (weeks start on Monday), of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's weekofyear(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.week is the same.
time.hour(bar.time, zone = "UTC")
The hour, 0 to 23, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's hour(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.hour is the same.
time.minute(bar.time, zone = "UTC")
The minute, 0 to 59, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's minute(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.minute is the same.
time.second(bar.time, zone = "UTC")
The second, 0 to 59, of a time (ms since 1970), in UTC or the zone given ("UTC+2", "America/New_York"): Pine's second(time, timezone). None for a time or a zone that isn't one. On the bar's own time in UTC, bar.second is the same.
time.format(bar.time, "yyyy-MM-dd HH:mm", zone = "UTC")
A time written as text by a pattern (Pine's str.format_time): yyyy the year, MM the month (MMM Jan, MMMM January), dd the day, EEE Mon (EEEE Monday), HH the hour (hh 1 to 12, with a for AM or PM), mm the minute, ss the second, Z the zone's offset (+0200); words in 'single quotes' stay as they are. In UTC, or the zone given. "" for a time or a zone that isn't one.
time.now
The time now, in milliseconds since 1970 (UTC), the same on every bar (Pine's timenow): it moves on each time the script runs.

Indicators 34

ind.sma(source, length)
Simple moving average: the mean of the last length values.
ind.ema(source, length)
Exponential moving average (alpha = 2 / (length + 1)).
ind.rma(source, length)
Wilder's moving average (alpha = 1 / length), the smoothing RSI and ATR use.
ind.wma(source, length)
Weighted moving average: newer values weigh more.
ind.hma(source, length)
Hull moving average: wma(2·wma(src, n/2) − wma(src, n), √n).
ind.vwma(source, length)
Volume-weighted moving average.
ind.alma(source, length, offset = 0.85, sigma = 6)
Arnaud Legoux moving average (a Gaussian-weighted average).
ind.swma(source)
Symmetrically weighted average of the last 4 values (weights 1, 2, 2, 1).
ind.linreg(source, length, offset = 0)
Least-squares line through the last length values, read offset bars back.
ind.rsi(source, length)
Relative strength index, 0 to 100.
[macd, signal, hist] = ind.macd(source, fastlen, slowlen, siglen)
MACD line, its signal line and the histogram, as three values.
ind.stoch(source, high, low, length)
Stochastic %K: where source sits between the lowest low and highest high, 0 to 100.
ind.cci(source, length)
Commodity channel index.
ind.wpr(length)
Williams %R, −100 to 0.
ind.mfi(source, length)
Money flow index, 0 to 100 (usually on p.hlc3).
ind.cmo(source, length)
Chande momentum oscillator, −100 to 100.
ind.tr(handleNone = false)
True range. With handleNone = true, the first bar uses high − low instead of none.
ind.atr(length)
Average true range (RMA of the true range).
ind.mom(source, length)
Momentum: the value now minus the value length bars ago.
ind.roc(source, length)
Rate of change in percent over length bars.
[middle, upper, lower] = ind.bb(source, length, mult)
Bollinger Bands: the SMA and mult standard deviations either side.
[middle, upper, lower] = ind.kc(source, length, mult, useTrueRange = true)
Keltner Channels: an EMA with a band of mult average ranges.
[supertrend, direction] = ind.supertrend(factor, atrPeriod)
Supertrend line and direction (−1 = up trend, 1 = down trend).
[plus, minus, adx] = ind.dmi(diLength, adxSmoothing)
Directional movement: +DI, −DI and ADX.
ind.sar(start, inc, max)
Parabolic SAR.
ind.vwap(source, anchor?) [vwap, upper, lower] = ind.vwap(source, anchor, mult)
Volume-weighted average price, restarting each UTC day (or whenever anchor is true). Given mult, its bands too: mult volume-weighted standard deviations either side, since the same restart (Pine's ta.vwap with stdev_mult).
ind.pivotPointLevels(type, anchor, developing = false)
Pivot point levels, as an array of 11: [P, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5] (none where type has no such level). type is "Traditional", "Fibonacci", "Woodie", "Classic", "DM" or "Camarilla" (the formulas of Pine's ta.pivot_point_levels). A period starts on each bar anchor is true (bar.isFirstOf("D") for daily pivots); the levels are worked out from the high, low and close of the period that ended there (Woodie takes the new period's open, DM the old one's) and kept until the next. None before the first period has ended. developing = true works them out on the period so far, on every bar (not for Woodie).
ind.pivothigh(source, leftbars, rightbars) ind.pivothigh(leftbars, rightbars)
The pivot high rightbars bars ago (a value no lower than the leftbars before it and higher than the rightbars after it: of two equal highs, the later), else none.
ind.pivotlow(source, leftbars, rightbars) ind.pivotlow(leftbars, rightbars)
The pivot low rightbars bars ago (a value no higher than the leftbars before it and lower than the rightbars after it: of two equal lows, the later), else none.
ind.tr
True range (none on the first bar).
ind.obv
On-balance volume.
ind.pvt
Price volume trend: a running total of each bar's volume times its close's change, as a share of the close before (0 on the first bar).
ind.accdist
Accumulation/distribution.
ind.vwap
VWAP of p.hlc3, restarting each UTC day.

Math 47

math.abs(number)
Absolute value.
math.ceil(number)
Rounds up.
math.floor(number)
Rounds down.
math.random(min = 0, max = 1, seed)
A number picked at random from min up to max (Pine's math.random). With a seed (a whole number), the same numbers in the same order every time the script runs; without one, others each time.
math.trunc(number)
The whole number part, toward 0: 2.7 is 2, -2.7 is -2 (Pine's int()).
math.sign(number)
1, 0 or −1.
math.sqrt(number)
Square root.
math.exp(number)
e to the power of x.
math.log(number)
Natural logarithm.
math.log10(number)
Base-10 logarithm.
math.sin(number)
Sine (radians).
math.cos(number)
Cosine (radians).
math.tan(number)
Tangent (radians).
math.asin(number)
Arcsine.
math.acos(number)
Arccosine.
math.atan(number)
Arctangent.
math.todegrees(number)
Radians to degrees.
math.toradians(number)
Degrees to radians.
math.round(number, precision)
Rounds to the nearest whole number, or to precision decimals.
math.pow(base, exponent)
base to the power of exponent.
math.max(a, b, …)
The largest of the values (none if any value is none).
math.min(a, b, …)
The smallest of the values (none if any value is none).
math.avg(a, b, …)
The average of the values.
math.stdev(source, length, biased = true)
Standard deviation of the last length values.
math.variance(source, length, biased = true)
Variance of the last length values.
math.dev(source, length)
Mean absolute deviation from the average of the last length values.
math.highest(source, length) math.highest(length)
Highest value of the last length bars (of p.high when no source is given).
math.lowest(source, length) math.lowest(length)
Lowest value of the last length bars (of p.low when no source is given).
math.highestbars(source, length)
Where the highest value was, as an index for [ ]: -1 is this bar, -2 the bar before.
math.lowestbars(source, length)
Where the lowest value was, as an index for [ ]: -1 is this bar, -2 the bar before.
math.range(source, length)
Highest minus lowest of the last length values.
math.change(source, length = 1)
Difference between the value now and length bars ago.
math.crossover(a, b)
True on the bar a goes from at-or-below b to above it. A bar where either is none is passed over: the cross counts from the last bar both had values, as in Pine.
math.crossunder(a, b)
True on the bar a goes from at-or-above b to below it. A bar where either is none is passed over: the cross counts from the last bar both had values, as in Pine.
math.cross(a, b)
True on the bar a and b cross, either way. A bar where either is none is passed over: the cross counts from the last bar both had values, as in Pine.
math.cum(source)
Running total of every value so far (none counts as 0).
math.barssince(condition)
Bars since condition was last true (0 on the bar it is true).
math.valuewhen(condition, source, occurrence = 0)
source on the most recent bar condition was true (occurrence 1 = the time before, …).
math.rising(source, length)
True when source has risen on each of the last length bars: every value above the one before it (Pine's ta.rising).
math.falling(source, length)
True when source has fallen on each of the last length bars: every value below the one before it (Pine's ta.falling).
math.median(source, length)
Median of the last length values.
math.percentile(source, length, percent, nearest = false)
The value percent % of the way up the last length values in order, between two of them where it falls between them (Pine's ta.percentile_linear_interpolation): 50 is the median. With nearest = true, always one of the values: the one at that rank, rounded up (Pine's ta.percentile_nearest_rank). None until the window is full. A value in it that is none counts as the lowest, as in Pine: the window keeps its length, and where the rank falls on one of them the answer is none.
math.cummax(source)
The highest value so far, from the chart's first bar (Pine's ta.max). None until the first value.
math.cummin(source)
The lowest value so far, from the chart's first bar (Pine's ta.min). None until the first value.
math.percentrank(source, length)
Percent of the previous length values at or below the current one.
math.correlation(source1, source2, length)
Pearson correlation of two series over length bars, −1 to 1.
math.sum(source, length)
Sum of the last length values.

Drawing 54

plot.line(value, title, color, linewidth = 1, linestyle = "solid", chart, tooltip, pricelabel = true)
Draws a line through a value on every bar. Gives back a handle for paint.fill(). linestyle is solid (the default), dashed or dotted. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.step(value, title, color, linewidth = 1, linestyle = "solid", chart, tooltip, pricelabel = true)
Draws a value as steps: flat across each bar, straight up or down between them. linestyle is solid (the default), dashed or dotted. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.area(value, title, color, linewidth = 1, linestyle = "solid", chart, tooltip, pricelabel = true)
Draws a line with the area under it shaded. linestyle is solid (the default), dashed or dotted. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.histogram(value, title, color, linewidth = 1, chart, tooltip, pricelabel = true)
Draws a value as thin bars growing from base (0 unless given). tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.column(value, title, color, linewidth = 1, chart, tooltip, pricelabel = true)
Draws a value as columns a bar wide, growing from base (0 unless given). tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.circles(value, title, color, linewidth = 1, chart, tooltip, pricelabel = true)
Draws a dot at the value on every bar. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.cross(value, title, color, linewidth = 1, chart, tooltip, pricelabel = true)
Draws a small cross at the value on every bar. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.shape(when, title, style = "triangleup", y = y.abovebar, color, text, textcolor, size = 2, chart, tooltip)
Draws a shape on bars where when is true. y is where: y.abovebar, y.belowbar (a little gap from the candle), y.high, y.low (on the high or the low itself), y.top, y.bottom (the pane's edges), or a value to draw at, like y = emaLine or y = p.low (also written as text: y = "belowbar"; y = "absolute" makes when the price). style is triangleup (the default), triangledown, circle, square, diamond, cross, xcross, arrowup, arrowdown, labelup, labeldown, box, pill (the box with fully rounded ends), text, flag or corners (four focus corners framing the point, as Residual Nodes draws). text goes inside a labelup / labeldown / box / pill, is all a text shape draws, and sits beside any other shape, in textcolor (left out: black or white inside a label, the shape's colour otherwise; none: no text). size is 1 to 4 (or tiny, small, normal, large, huge). tooltip is the text behind the ? on its row in the settings (Appearance).
plot.char(when, char = "•", title, y = y.abovebar, color, size = 2, chart, tooltip)
Draws a character (or emoji) on bars where when is true. y is where, as plot.shape's: y.abovebar, y.belowbar, y.high, y.low, y.top, y.bottom or a value to draw at. size is 1 to 4. tooltip is the text behind the ? on its row in the settings (Appearance).
plot.arrow(value, title, colorup, colordown, size = 2, chart, tooltip)
An arrow on each bar where value isn't 0 (Pine's plotarrow), drawn as plot.shape draws its arrowup and arrowdown: pointing up under the bar where value is above 0, in colorup (left out: the chart's green), and down over the bar where it is below 0, in colordown (the chart's red). Every arrow is one size: size is 1 to 4 (or tiny, small, normal, large, huge). plot.arrow(p.close - p.open) marks each up candle and each down candle. tooltip is the text behind the ? on its row in the settings (Appearance).
plot.level(price, title, color, style = "dashed", linewidth = 1, chart, tooltip)
A horizontal line at a fixed level. style (or linestyle, as on plot.line) is solid, dashed or dotted. Gives back a handle for paint.fill(). tooltip is the text behind the ? on its row in the settings (Appearance).
paint.fill(a, b, color, title, tooltip) paint.fill(a, b, top = 100, bottom = 80, top_color = c1, bottom_color = c2)
Shades the area between two lines or two levels (what plot.line() or plot.level() gave back). It goes where its two lines are. title names its row in the settings. A shade that fades (Pine's gradient fill): top and bottom are two values on the scale, top_color the colour at top and bottom_color at bottom, the shade going from one to the other between them and keeping the end colour past them (one fully clear colour shows only the part past the other value). tooltip is the text behind the ? on its row in the settings (Appearance).
plot.candles(open, high, low, close, title, color, wickcolor, bordercolor, chart, tooltip, pricelabel = true)
Draws candles from four values, the way the chart draws its own (Open Interest's Candles): in a pane of their own, or over the chart's candles (chart = main, a Heikin Ashi). color colours each candle; left out, or none on a bar, a candle takes the chart's up or down colour. wickcolor and bordercolor give its wick and the edge of its body colours of their own (the candle's colour where left out). tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
plot.bars(open, high, low, close, title, color, chart, tooltip, pricelabel = true)
Draws OHLC bars from four values (Pine's plotbar), as the chart's OHLC type draws its own: a line from the low to the high, the open's tick on its left and the close's on its right. In a pane of their own, or over the chart's candles with chart = main. color colours each bar; left out, or none on a bar, a bar takes the chart's up or down colour. tooltip is the text behind the ? on its row in the settings (Appearance). pricelabel = false leaves its newest value off the price scale (no value pill on the axis); the drawing stays.
paint.candles(color, title, tooltip)
Colours the chart's own candles, bar by bar, as Trend Oracle's and Bayesian Trend's Candle Coloring do. A bar given none keeps the chart's up or down colour. Always on the candles. title names its row in the settings. tooltip is the text behind the ? on its row in the settings (Appearance).
paint.background(when, color, title, chart, tooltip)
Tints the background behind bars where when is true. A solid colour is drawn 90% transparent, so the candles show through; give a colour its own transparency (color.hex(c, 70)) to choose. title names its row in the settings. tooltip is the text behind the ? on its row in the settings (Appearance).
y.abovebar
Above the candle's high, a little gap from it. For plot.shape, plot.char and plot.label: y = y.abovebar.
y.belowbar
Below the candle's low, a little gap from it. For plot.shape, plot.char and plot.label: y = y.belowbar.
y.high
On the candle's high itself, with no gap: a labeldown's point touches it. For plot.shape, plot.char and plot.label: y = y.high.
y.low
On the candle's low itself, with no gap: a labelup's point touches it. For plot.shape, plot.char and plot.label: y = y.low.
y.top
Pinned to the top edge of the pane. For plot.shape, plot.char and plot.label: y = y.top.
y.bottom
Pinned to the bottom edge of the pane. For plot.shape, plot.char and plot.label: y = y.bottom.
y.absolute
At a price: plot.shape's first value (when) is the price to draw at, as Pine's location.absolute. For a label, the same as y.price. For plot.shape, plot.char and plot.label: y = y.absolute.
y.price
At a price: a label's own y (yloc = y.price, its default), as Pine's yloc.price. For plot.shape, the same as y.absolute. For plot.shape, plot.char and plot.label: y = y.price.
style.triangleup
The style "triangleup", for plot.shape, plot.label: style = style.triangleup.
style.triangledown
The style "triangledown", for plot.shape, plot.label: style = style.triangledown.
style.circle
The style "circle", for plot.shape, plot.label: style = style.circle.
style.square
The style "square", for plot.shape, plot.label: style = style.square.
style.diamond
The style "diamond", for plot.shape, plot.label: style = style.diamond.
style.cross
The style "cross", for plot.shape, plot.label, a plot (plot.line(…, style = …)): style = style.cross.
style.xcross
The style "xcross", for plot.shape, plot.label: style = style.xcross.
style.arrowup
The style "arrowup", for plot.shape, plot.label: style = style.arrowup.
style.arrowdown
The style "arrowdown", for plot.shape, plot.label: style = style.arrowdown.
style.labelup
The style "labelup", for plot.shape, plot.label: style = style.labelup.
style.labeldown
The style "labeldown", for plot.shape, plot.label: style = style.labeldown.
style.flag
The style "flag", for plot.shape, plot.label: style = style.flag.
style.box
The style "box", for plot.shape, plot.label: style = style.box.
style.text
The style "text", for plot.shape, plot.label: style = style.text.
style.pill
The style "pill", for plot.shape, plot.label: style = style.pill.
style.corners
The style "corners", for plot.shape, plot.label: style = style.corners.
style.labelleft
The style "labelleft", for plot.label: style = style.labelleft.
style.labelright
The style "labelright", for plot.label: style = style.labelright.
style.line
The style "line", for a plot (plot.line(…, style = …)): style = style.line.
style.step
The style "step", for a plot (plot.line(…, style = …)): style = style.step.
style.area
The style "area", for a plot (plot.line(…, style = …)): style = style.area.
style.histogram
The style "histogram", for a plot (plot.line(…, style = …)): style = style.histogram.
style.column
The style "column", for a plot (plot.line(…, style = …)): style = style.column.
style.circles
The style "circles", for a plot (plot.line(…, style = …)): style = style.circles.
line.solid
A line drawn "solid", for a plot's linestyle and plot.level's style, a box's border_style, plot.segment and plot.polyline: linestyle = line.solid (style = line.solid on plot.level, plot.segment and plot.polyline).
line.dashed
A line drawn "dashed", for a plot's linestyle and plot.level's style, a box's border_style, plot.segment and plot.polyline: linestyle = line.dashed (style = line.dashed on plot.level, plot.segment and plot.polyline).
line.dotted
A line drawn "dotted", for a plot's linestyle and plot.level's style, a box's border_style, plot.segment and plot.polyline: linestyle = line.dotted (style = line.dotted on plot.level, plot.segment and plot.polyline).
line.arrowleft
A line drawn "arrowleft", for plot.segment and plot.polyline: linestyle = line.arrowleft (style = line.arrowleft on plot.level, plot.segment and plot.polyline).
line.arrowright
A line drawn "arrowright", for plot.segment and plot.polyline: linestyle = line.arrowright (style = line.arrowright on plot.level, plot.segment and plot.polyline).
line.arrowboth
A line drawn "arrowboth", for plot.segment and plot.polyline: linestyle = line.arrowboth (style = line.arrowboth on plot.level, plot.segment and plot.polyline).

Labels 14

plot.label(x, y, text, xloc = "bar", yloc = "price", color, style = "labeldown", textcolor, size = 2, chart)
ONE label, made where the code says, with text in it, and gives it back (keep it in a var to move or change it on a later bar). plot.shape is the other kind: a mark on every bar where a condition holds. x is a bar number, as bars.count counts it (bars.count + 5 is five bars to come), or with xloc = "time" a time in milliseconds, as bar.time is. y is a price, or a place as plot.shape's: y.high, y.low (on the bar's high or low itself), y.abovebar, y.belowbar (a little gap from it), y.top, y.bottom (the pane's edges). yloc takes the same places (and y.price, at y), as Pine's yloc; given, it wins over a place in y. style is labeldown (the default: over the point, pointing down at it), labelup, labelleft, labelright, box, pill (the box with fully rounded ends), text (the words alone), triangleup, triangledown, arrowup, arrowdown, circle, square, diamond, cross, xcross, flag or corners (four focus corners framing the point). color = none leaves only the words; textcolor left out is black or white to suit the label. size is 1 to 4 (or tiny, small, normal, large, huge). chart = main puts it over the candles and chart = oscillator in the script's pane (left out: where the script draws). The chart keeps a script's newest 500 labels.
label.x(lbl, x) lbl.x(x) lbl.x()
Its bar (or its time, with xloc = "time").
label.y(lbl, y) lbl.y(y) lbl.y()
Its price; or a place (lbl.y(y.low) puts it on its bar's low), which sets its yloc.
label.xy(lbl, x, y) lbl.xy(x, y) lbl.xy()
Its bar and price (or a place, y.low …): lbl.xy(bars.count, p.close) moves it there, and [x, y] = lbl.xy() reads both.
label.xloc(lbl, x, xloc) lbl.xloc(x, xloc) lbl.xloc()
Whether its x is a bar number ("bar") or a time ("time"): lbl.xloc(bar.time, "time") moves it to a time.
label.yloc(lbl, yloc) lbl.yloc(yloc) lbl.yloc()
Where it sits: at its price (y.price), on its bar's high or low itself (y.high, y.low), over the high or under the low with a little gap (y.abovebar, y.belowbar), or at the pane's top or bottom (y.top, y.bottom).
label.text(lbl, text) lbl.text(text) lbl.text()
Its words.
label.color(lbl, color) lbl.color(color) lbl.color()
Its colour (none: only its words).
label.textcolor(lbl, textcolor) lbl.textcolor(textcolor) lbl.textcolor()
Its words' colour (none: no words).
label.style(lbl, style) lbl.style(style) lbl.style()
Its shape: labeldown, labelup, labelleft, labelright, box, pill, text, triangleup … (as plot.label).
label.size(lbl, size) lbl.size(size) lbl.size()
Its size: 1 to 4 (or tiny, small, normal, large, huge).
label.copy(lbl) lbl.copy()
A new label, the same as this one.
label.delete(lbl) lbl.delete()
Takes the label off the chart. It still reads its values; changing it does nothing.
label.all
A new array of the script's labels on the chart now, oldest first.

Lines 26

plot.segment(x1, y1, x2, y2, xloc = "bar", extend = "none", color, style = "solid", width = 1, chart)
ONE straight line from (x1, y1) to (x2, y2), and gives it back (the chart's Segment tool). plot.line is the other kind: a value on every bar, joined up. Each x is a bar number, as bars.count counts it (bars.count + 5 is five bars to come), or with xloc = "time" a time in milliseconds, as bar.time is. extend carries it on past its ends: "left", "right" or "both". style is solid, dashed, dotted, arrowleft, arrowright or arrowboth (an arrowhead on that end). chart = main puts it over the candles and chart = oscillator in the script's pane (left out: where the script draws). The chart keeps a script's newest 500 lines.
line.x1(ln, x) ln.x1(x) ln.x1()
Its first end's bar (or time).
line.y1(ln, y) ln.y1(y) ln.y1()
Its first end's price.
line.x2(ln, x) ln.x2(x) ln.x2()
Its second end's bar (or time).
line.y2(ln, y) ln.y2(y) ln.y2()
Its second end's price.
line.xy1(ln, x, y) ln.xy1(x, y) ln.xy1()
Its first end: ln.xy1(bars.count, p.low) moves it there, and [x, y] = ln.xy1() reads it.
line.xy2(ln, x, y) ln.xy2(x, y) ln.xy2()
Its second end: ln.xy2(bars.count, p.close) moves it there, and [x, y] = ln.xy2() reads it.
line.xloc(ln, x1, x2, xloc) ln.xloc(x1, x2, xloc) ln.xloc()
Whether its ends' x are bar numbers ("bar") or times ("time"): ln.xloc(x1, x2, "time") moves both ends to times.
line.extend(ln, extend) ln.extend(extend) ln.extend()
Carries it on past its ends: "none", "left", "right" or "both".
line.color(ln, color) ln.color(color) ln.color()
Its colour.
line.style(ln, style) ln.style(style) ln.style()
solid, dashed, dotted, arrowleft, arrowright or arrowboth.
line.width(ln, width) ln.width(width) ln.width()
Its thickness in pixels.
line.price_at(ln, x) ln.price_at(x)
Its price at bar x (or time, as its xloc), on the line through its two ends.
line.copy(ln) ln.copy()
A new line, the same as this one.
line.delete(ln) ln.delete()
Takes the line off the chart. It still reads its values; changing it does nothing.
plot.linefill(line1, line2, color)
ONE shade between two segments (what plot.segment gave back), and gives it back: as far as both reach, their extensions too, so it moves when they do. It goes where its segments are, and goes when either is deleted. color is its colour (left out: the default colour, faint). The chart keeps a script's newest 500 line fills.
linefill.color(lf, color) lf.color(color) lf.color()
Its colour (none: no shade).
linefill.line1(lf) lf.line1()
The first segment it shades from.
linefill.line2(lf) lf.line2()
The second segment it shades to.
linefill.delete(lf) lf.delete()
Takes the line fill off the chart. It still reads its values; changing it does nothing.
plot.polyline(points, curved = false, closed = false, xloc = "bar", color, fill, style = "solid", width = 1, chart)
ONE line through many points, and gives it back (Pine's polyline.new). points is an array of [x, y] pairs: pts.push([bars.count, p.high]) adds this bar's high. Each x is a bar number, as bars.count counts it (bars.count + 5 is five bars to come), or with xloc = "time" a time in milliseconds, as bar.time is. curved = true bends it smoothly through the points, closed = true joins the last point back to the first, and fill shades what it encloses (left out: no shade). style is solid, dashed, dotted, arrowleft, arrowright or arrowboth (an arrowhead on that end). Its points are taken when it is made: changing the array afterwards does not move it. A point with no value (none) is left out. At most 10,000 points. chart = main puts it over the candles and chart = oscillator in the script's pane (left out: where the script draws). The chart keeps a script's newest 100 polylines.
polyline.points(pl) pl.points()
A new array of its points, each an [x, y] pair.
polyline.delete(pl) pl.delete()
Takes the polyline off the chart. It still reads its values; changing it does nothing.
line.all
A new array of the script's lines on the chart now, oldest first.
linefill.all
A new array of the script's line fills on the chart now, oldest first.
polyline.all
A new array of the script's polylines on the chart now, oldest first.

Boxes 22

plot.box(left, top, right, bottom, border_color, border_width = 1, border_style = "solid", extend = "none", xloc = "bar", bgcolor, text, text_size, text_color, text_halign = "center", text_valign = "center", radius = 0, chart)
ONE box from bar left to bar right and price top to price bottom, and gives it back (keep it in a var to move or change it later). Its bars are numbers as bars.count counts them (or times, with xloc = "time"). bgcolor fills it (left out: the default colour, faint; none: no fill), border_style is solid, dashed or dotted, and extend carries it to the chart's edge: "left", "right" or "both". text is written inside it, placed by text_halign (left, center, right) and text_valign (top, center, bottom). radius rounds its corners, in pixels (0, the default: square; a big number rounds them as far as fully round ends, never past half its shorter side); a side carried to the chart's edge stays square. chart = main puts it over the candles and chart = oscillator in the script's pane (left out: where the script draws). The chart keeps a script's newest 500 boxes.
box.left(bx, left) bx.left(left) bx.left()
Its left side's bar (or time).
box.right(bx, right) bx.right(right) bx.right()
Its right side's bar (or time).
box.top(bx, top) bx.top(top) bx.top()
Its top's price.
box.bottom(bx, bottom) bx.bottom(bottom) bx.bottom()
Its bottom's price.
box.lefttop(bx, left, top) bx.lefttop(left, top) bx.lefttop()
Its top-left corner: bx.lefttop(bars.count - 5, p.high) moves it there.
box.rightbottom(bx, right, bottom) bx.rightbottom(right, bottom) bx.rightbottom()
Its bottom-right corner: bx.rightbottom(bars.count, p.low) moves it there.
box.xloc(bx, left, right, xloc) bx.xloc(left, right, xloc) bx.xloc()
Whether its sides are bar numbers ("bar") or times ("time"): bx.xloc(left, right, "time") moves them to times.
box.extend(bx, extend) bx.extend(extend) bx.extend()
Carries it to the chart's edge: "none", "left", "right" or "both".
box.border_color(bx, color) bx.border_color(color) bx.border_color()
Its border's colour (none: no border).
box.border_width(bx, width) bx.border_width(width) bx.border_width()
Its border's thickness in pixels (0: none).
box.border_style(bx, style) bx.border_style(style) bx.border_style()
solid, dashed or dotted.
box.bgcolor(bx, color) bx.bgcolor(color) bx.bgcolor()
Its fill (none: no fill).
box.text(bx, text) bx.text(text) bx.text()
The words inside it.
box.text_color(bx, color) bx.text_color(color) bx.text_color()
Its words' colour.
box.text_size(bx, size) bx.text_size(size) bx.text_size()
Its words' size: 1 to 4 (or tiny, small, normal, large, huge, auto).
box.text_halign(bx, align) bx.text_halign(align) bx.text_halign()
left, center or right.
box.text_valign(bx, align) bx.text_valign(align) bx.text_valign()
top, center or bottom.
box.radius(bx, radius) bx.radius(radius) bx.radius()
How round its corners are, in pixels: 0 is square, a big number rounds them as far as fully round ends.
box.copy(bx) bx.copy()
A new box, the same as this one.
box.delete(bx) bx.delete()
Takes the box off the chart. It still reads its values; changing it does nothing.
box.all
A new array of the script's boxes on the chart now, oldest first.

Tables 21

plot.table(position, columns, rows, bgcolor, frame_color, frame_width = 0, border_color, border_width = 0, radius = 0, chart)
A table of columns × rows cells in one place on its pane, over everything else, and gives it back: fill its cells with t.cell(…) (make it once, in a var, and fill it on the last bar: if bar.isLast). position is top_left, top_center, top_right, middle_left, middle_center, middle_right, bottom_left, bottom_center or bottom_right. bgcolor fills it, frame_* draws its outer edge and border_* the lines between its cells (all none unless given). radius rounds its outer corners, in pixels (0, the default: square; a big number rounds them as far as fully round ends, never past half its shorter side): its corner cells follow the rounding. chart = main puts it over the candles and chart = oscillator in the script's pane (left out: where the script draws). The chart keeps a script's newest 20 tables.
table.cell(tbl, column, row, text, width = 0, height = 0, text_color, text_halign = "center", text_valign = "center", text_size = "normal", bgcolor) tbl.cell(column, row, text, width = 0, height = 0, text_color, text_halign = "center", text_valign = "center", text_size = "normal", bgcolor)
Sets a cell (column and row from 0; -1 the last): its text, its width and height as % of the pane (0 fits the text), its words' colour (left out: the chart's text colour), where they sit and their size (1 to 4, or tiny, small, normal, large, huge), and its fill.
table.cell_text(tbl, column, row, text) tbl.cell_text(column, row, text) tbl.cell_text(column, row)
A cell's words.
table.cell_bgcolor(tbl, column, row, color) tbl.cell_bgcolor(column, row, color) tbl.cell_bgcolor(column, row)
A cell's fill.
table.cell_text_color(tbl, column, row, color) tbl.cell_text_color(column, row, color) tbl.cell_text_color(column, row)
A cell's words' colour.
table.cell_text_size(tbl, column, row, size) tbl.cell_text_size(column, row, size) tbl.cell_text_size(column, row)
A cell's words' size.
table.cell_text_halign(tbl, column, row, align) tbl.cell_text_halign(column, row, align) tbl.cell_text_halign(column, row)
Where a cell's words sit across it: left, center or right.
table.cell_text_valign(tbl, column, row, align) tbl.cell_text_valign(column, row, align) tbl.cell_text_valign(column, row)
Where a cell's words sit up and down it: top, center or bottom.
table.cell_width(tbl, column, row, width) tbl.cell_width(column, row, width) tbl.cell_width(column, row)
A cell's width, % of the pane (0 fits the text).
table.cell_height(tbl, column, row, height) tbl.cell_height(column, row, height) tbl.cell_height(column, row)
A cell's height, % of the pane (0 fits the text).
table.merge_cells(tbl, start_column, start_row, end_column, end_row) tbl.merge_cells(start_column, start_row, end_column, end_row)
Joins the cells from (start_column, start_row) to (end_column, end_row) into one, which shows the first cell's text and look. Joining the same cells again does nothing.
table.clear(tbl, start_column, start_row, end_column, end_row) tbl.clear(start_column, start_row, end_column, end_row)
Empties the cells from (start_column, start_row) to (end_column, end_row) (left out: just the first), and undoes merges among them.
table.position(tbl, position) tbl.position(position) tbl.position()
Where it sits: top_left, top_center, top_right, middle_left … bottom_right.
table.bgcolor(tbl, color) tbl.bgcolor(color) tbl.bgcolor()
Its fill.
table.frame_color(tbl, color) tbl.frame_color(color) tbl.frame_color()
Its outer edge's colour.
table.frame_width(tbl, width) tbl.frame_width(width) tbl.frame_width()
Its outer edge's thickness in pixels.
table.border_color(tbl, color) tbl.border_color(color) tbl.border_color()
The colour of the lines between its cells.
table.border_width(tbl, width) tbl.border_width(width) tbl.border_width()
The thickness of the lines between its cells.
table.radius(tbl, radius) tbl.radius(radius) tbl.radius()
How round its outer corners are, in pixels: 0 is square, a big number rounds them as far as fully round ends.
table.delete(tbl) tbl.delete()
Takes the table off the chart. It still reads its values; changing it does nothing.
table.all
A new array of the script's tables on the chart now, oldest first.

Strategy 39

strategy.enter.long(when, name = "Long", color, percent, cash, qty, limit, stop, oca, chart, tooltip)
Goes long on bars where when is true (turning a short around), and marks the entry. Nothing happens while already long. percent = 25 puts 25% of the account in (counted as the Compounding % setting counts it), or cash = 100 an amount of money (the Execution section's Initial Capital is what it is counted against); left out, the whole account goes in. With Enigma on, every entry is sized by volatility instead. qty = 0.5 buys that much of the coin (no more than the account can, with its leverage). limit = p waits for the price to fall to p (a short's, to rise to it), stop = p for it to rise to p (a short's, fall), both a stop-limit: an order that stands from the next bar until it fills, at its price or at the open of a bar that opens past it, strategy.cancel(name) takes it back, or the call runs again with new prices. It cannot fill while its side is already open. oca = "range" puts it in a group (Pine's one-cancels-all): when one entry of the group fills, the group's other orders are taken back at once, in the same bar too. Needs script(…, tool = strategy). Its trades are backtested in the Backtests panel the way the Eclipse strategies are. tooltip is the text behind the ? on its row in the settings (Appearance).
strategy.enter.short(when, name = "Short", color, percent, cash, qty, limit, stop, oca, chart, tooltip)
Goes short on bars where when is true (turning a long around), and marks the entry. Nothing happens while already short. percent = 25 puts 25% of the account in (counted as the Compounding % setting counts it), or cash = 100 an amount of money (the Execution section's Initial Capital is what it is counted against); left out, the whole account goes in. With Enigma on, every entry is sized by volatility instead. qty = 0.5 buys that much of the coin (no more than the account can, with its leverage). limit = p waits for the price to fall to p (a short's, to rise to it), stop = p for it to rise to p (a short's, fall), both a stop-limit: an order that stands from the next bar until it fills, at its price or at the open of a bar that opens past it, strategy.cancel(name) takes it back, or the call runs again with new prices. It cannot fill while its side is already open. oca = "range" puts it in a group (Pine's one-cancels-all): when one entry of the group fills, the group's other orders are taken back at once, in the same bar too. Needs script(…, tool = strategy). Its trades are backtested in the Backtests panel the way the Eclipse strategies are. tooltip is the text behind the ? on its row in the settings (Appearance).
strategy.exit.long(when, name = "Close", color, percent = 100, sl, tp, type = percent, trail, trailstart, qty, entry, chart, tooltip)
Closes a long on bars where when is true, and marks the exit. Nothing happens unless long. percent = 50 closes half of what the trade entered (never more than is still open), as Pine's qty_percent: three exits of 33% close a third of the entry each; left out, all that is open. sl = 2 and tp = 4 are a stop and a target 2% and 4% from the entry price; with type = price they are prices (sl = 60000, tp = 70000, type = price). They are orders that stand from the next bar until they fill, at their price inside a bar, or at the open where a bar opens past one. Set every bar, a level that moves trails. When one of a call's two fills, the other stands down for the rest of the trade. when may be left out when the call only sets a stop or a target. qty = 0.5 closes that much of the coin in place of a percent (Pine's qty), never more than is open. trail = 2 is a stop 2% behind the best price since the entry (a long's highest, a short's lowest), which never moves back; trailstart = 1 starts it once the trade is 1% up. With type = price, trail is a distance and trailstart a price. entry = "Long 1" ties it to the entry of that name (Pine's from_entry): it closes only the trades that entry opened, its percent a share of what that entry entered, its stop and target counted from that entry's price and standing only while it is open. Needs script(…, tool = strategy). Its trades are backtested in the Backtests panel the way the Eclipse strategies are. tooltip is the text behind the ? on its row in the settings (Appearance).
strategy.exit.short(when, name = "Close", color, percent = 100, sl, tp, type = percent, trail, trailstart, qty, entry, chart, tooltip)
Closes a short on bars where when is true, and marks the exit. Nothing happens unless short. percent = 50 closes half of what the trade entered (never more than is still open), as Pine's qty_percent: three exits of 33% close a third of the entry each; left out, all that is open. sl = 2 and tp = 4 are a stop and a target 2% and 4% from the entry price; with type = price they are prices (sl = 60000, tp = 70000, type = price). They are orders that stand from the next bar until they fill, at their price inside a bar, or at the open where a bar opens past one. Set every bar, a level that moves trails. When one of a call's two fills, the other stands down for the rest of the trade. when may be left out when the call only sets a stop or a target. qty = 0.5 closes that much of the coin in place of a percent (Pine's qty), never more than is open. trail = 2 is a stop 2% behind the best price since the entry (a long's highest, a short's lowest), which never moves back; trailstart = 1 starts it once the trade is 1% up. With type = price, trail is a distance and trailstart a price. entry = "Long 1" ties it to the entry of that name (Pine's from_entry): it closes only the trades that entry opened, its percent a share of what that entry entered, its stop and target counted from that entry's price and standing only while it is open. Needs script(…, tool = strategy). Its trades are backtested in the Backtests panel the way the Eclipse strategies are. tooltip is the text behind the ? on its row in the settings (Appearance).
strategy.closed(index)
A trade the strategy has closed, as this bar's code starts: strategy.closed(-1) the latest, strategy.closed(0) the first (a partial exit is a trade of its own, as in strategy.totalTrades). Its numbers: .profit (money, after its fees), .entryPrice, .exitPrice, .entryTime, .exitTime (as bar.time), .entryBar, .exitBar (bars.count then), .size (coins, below 0 for a short), .fee (its fees and slippage, in money), .exitName, and the most it was up and down while open: .maxRunupCash and .maxDrawdownCash in money, .maxRunup and .maxDrawdown as a percent of what it cost (from its entry to its exit, along the path the strategy fills on through each bar). None where there is no such trade.
strategy.open(index)
A trade still open, as this bar's code starts: strategy.open(0) the oldest entry, strategy.open(-1) the newest (more than one with pyramiding). Its numbers as strategy.closed's, .profit at this bar's close before the costs of closing it, its run-up and drawdown through this bar; its exit ones are none. None where there is no such trade.
strategy.cancel(name)
Takes back the orders at a price (limit, stop) of the enter calls with that name, where they have not filled: strategy.enter.long(setup, "Breakout", stop = level), then strategy.cancel("Breakout").
strategy.cancelAll()
Takes back every order at a price not yet filled.
strategy.risk.maxDayLoss(percent = 2) strategy.risk.maxDayLoss(cash = 500)
The most the strategy may lose in a day (Pine's strategy.risk.max_intraday_loss). percent = 2 is 2% of the day's highest equity, cash = 500 an amount of money (counted against the Initial Capital). The account is checked at each bar's open, high, low and close, and each time an order fills; once it is down that much from the day's highest, orders at a price are taken back, the open trade is closed at that price (marked "Day loss" on its side's exit call, whose alert it fires), and no enter call does anything until the next day (a UTC day; the next bar on a chart of a day or more). Write it once: the last value it ran with holds. Needs script(…, tool = strategy).
strategy.isLong
True while a long trade is open, as this bar's code starts (on the bar a long is signalled, still false).
strategy.isShort
True while a short trade is open, as this bar's code starts.
strategy.isFlat
True while no trade is open, as this bar's code starts.
strategy.entryPrice
The open trade's entry price (the close of the bar that entered it; on a chart of other bars, the real candle's close, as every fill is), none while flat, as this bar's code starts. With pyramiding, the average price of the entries open, each counted by its size.
strategy.openTrades
How many entries are open (Pine's strategy.opentrades): 0 while flat, 1 for a trade, up to the script's pyramiding, as this bar's code starts.
strategy.initialCapital
The money the strategy started with: its Initial Capital (the Strategy tab of its settings; 10,000 until changed, or its own capital = …). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.equity
The money the strategy has now: its Initial Capital, plus what its closed trades made, plus the open trade valued at this bar's close. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.netProfit
The money its closed trades made, after costs (a loss is below 0). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.openProfit
The open trade's profit at this bar's close, in money, before the costs of closing it; 0 while flat. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.grossProfit
The money its winning trades made, after costs. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.grossLoss
The money its losing trades lost, after costs, as a number above 0. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.roi
Net Return: what its closed trades made, as a percent of the Initial Capital (12.5 is 12.5%). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.profitFactor
Profit Factor: the money its winning trades made over what its losing ones lost (99.99 with wins and no loss; 0 with no win). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.maxDrawdown
Max Drawdown: the deepest fall of the account from a high, in percent (4.89 is 4.89%), counted at each trade's close. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.maxDrawdownCash
Max Drawdown in money: the deepest fall of the account from a high, counted at each trade's close (strategy.maxDrawdown is it in percent). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.maxRunupCash
Max Run-up in money: the highest rise of the account from a low, counted at each trade's close (Pine's strategy.max_runup). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.size
The position in coins: above 0 while long, below 0 while short, 0 while flat (Pine's strategy.position_size). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.recoveryFactor
Recovery Factor: Net Return over Max Drawdown. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.hitRate
Hit Rate: the share of its closed trades that made money, in percent. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.totalTrades
Total Trades: how many trades it closed (a partial exit is a trade of its own). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.wins
How many of its closed trades made money. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.losses
How many of its closed trades lost money. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.bestTrade
Best Trade: its best closed trade, as a percent of the account it was opened with. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.worstTrade
Worst Trade: its worst closed trade, as a percent of the account it was opened with. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.meanTrade
Mean Trade: its closed trades' average, as a percent of the account each was opened with. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.cagr
CAGR: its Net Return as a yearly rate, over the bars it has run (or its Custom Date Range), in percent. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.sharpe
Sharpe Ratio: its trades' mean return over their spread, scaled to a year. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.expectancy
Expectancy: what a trade makes on average, in R (its average loss): 0.5 is half an average loss won a trade. As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.kurtosis
Kurtosis: how heavy the tails of its trades' returns are (3 is a normal spread's). As this bar's code starts: a trade signalled on it counts from the next bar.
strategy.skewness
Skewness: which way its trades' returns lean (above 0, big wins; below 0, big losses). As this bar's code starts: a trade signalled on it counts from the next bar.

Arrays 41

array(a, b, …) array(size = n, fill = value)
A new array: array() is empty, array(1, 2, 3) holds those values, and array(size = 10, fill = 0) holds ten zeros (fill left out: none). It holds any kind of value: numbers, text, colours, true / false, and arrays, maps, labels and the rest. Kept in a var, it lasts from bar to bar. a[0] is its first item and a[-1] its last, as in Python.
array.copy(a) a.copy()
A new array with the same items (the items themselves are not copied: an array inside is the same array).
array.size(a) a.size()
How many items it holds.
array.get(a, index) a.get(index)
The item at index (0 the first, -1 the last), or none outside the items. a[index] does the same.
array.set(a, index, value) a.set(index, value)
Puts value at index (0 the first, -1 the last). a[index] = value does the same. An index outside the items is an error: add items with push().
array.push(a, value) a.push(value)
Adds value at the end.
array.pop(a) a.pop()
Takes the last item off and gives it back (none when there is none).
array.unshift(a, value) a.unshift(value)
Adds value at the start.
array.shift(a) a.shift()
Takes the first item off and gives it back (none when there is none).
array.insert(a, index, value) a.insert(index, value)
Puts value in before the item at index (as Python's insert: past the end adds it at the end, -1 before the last).
array.remove(a, index) a.remove(index)
Takes the item at index out and gives it back. An index outside the items is an error.
array.clear(a) a.clear()
Takes every item out.
array.concat(a, other) a.concat(other)
Adds the items of other (an array) at the end, and gives back the array.
array.slice(a, from, to) a.slice(from, to)
A new array of the items from from up to (not including) to, counted as Python counts (negative from the end; to left out: to the end).
array.reverse(a) a.reverse()
Turns the order of the items around.
array.sort(a, order = "ascending", field) a.sort(order = "ascending", field)
Sorts the items: numbers, then text, then true / false, none last. order is "ascending" or "descending". Objects of a type of the script's sort by one of their fields: field = "score" (Pine's sort_field).
array.sort_indices(a, order = "ascending") a.sort_indices(order = "ascending")
A new array of the indexes the items would have sorted (the array itself is left as it is).
array.includes(a, value) a.includes(value)
True when one of the items is value.
array.indexof(a, value) a.indexof(value)
The index of the first item that is value, or -1.
array.lastindexof(a, value) a.lastindexof(value)
The index of the last item that is value, or -1.
array.first(a) a.first()
The first item (none when there is none).
array.last(a) a.last()
The last item (none when there is none).
array.fill(a, value, from = 0, to) a.fill(value, from = 0, to)
Sets the items from from up to (not including) to to value (left out: every item).
array.join(a, separator = ",") a.join(separator = ",")
The items as one text, with separator between them.
array.sum(a) a.sum()
The sum of its numbers (none and anything that is not a number left out; 0 when there are none).
array.avg(a) a.avg()
The average of its numbers (none when there are none).
array.min(a, nth = 0) a.min(nth = 0)
The smallest of its numbers; with nth, the nth smallest (0 the smallest).
array.max(a, nth = 0) a.max(nth = 0)
The largest of its numbers; with nth, the nth largest (0 the largest).
array.median(a) a.median()
The middle of its numbers (the average of the two middle ones when there is an even count).
array.mode(a) a.mode()
Its most frequent number (of several as frequent, the smallest).
array.stdev(a, biased = true) a.stdev(biased = true)
The standard deviation of its numbers: over all of them (biased, the default), or as a sample (biased = false).
array.variance(a, biased = true) a.variance(biased = true)
The variance of its numbers: over all of them (biased, the default), or as a sample (biased = false).
array.range(a) a.range()
Its largest number less its smallest.
array.abs(a) a.abs()
A new array of each number's absolute value.
array.standardize(a) a.standardize()
A new array of each number less the average, divided by the standard deviation.
array.covariance(a, other, biased = true) a.covariance(other, biased = true)
The covariance of its numbers with other's, item by item (pairs where either is none left out).
array.percentile(a, percentage, nearest = false) a.percentile(percentage, nearest = false)
The value percentage % of the way up its sorted numbers, between two of them where it falls between (Pine's percentile_linear_interpolation): 50 is the median. With nearest = true, always one of them: the one at that rank, rounded up (Pine's percentile_nearest_rank).
array.percentrank(a, index) a.percentrank(index)
How many of the other numbers are at or below the item at index, as a percentage of them.
array.every(a) a.every()
True when every item is true (an empty array too).
array.some(a) a.some()
True when at least one item is true.

Matrices 36

matrix(rows, columns, fill = none)
A new matrix of rows × columns items, each fill (none when left out): matrix(2, 3, 0) is two rows of three zeros. m[row, column] reads and sets one item (0 the first, -1 the last).
matrix.get(m, row, column) m.get(row, column)
The item at (row, column), or none outside the matrix. m[row, column] does the same.
matrix.set(m, row, column, value) m.set(row, column, value)
Puts value at (row, column). m[row, column] = value does the same.
matrix.rows(m) m.rows()
How many rows it has.
matrix.columns(m) m.columns()
How many columns it has.
matrix.elements_count(m) m.elements_count()
How many items it holds (rows × columns).
matrix.row(m, row) m.row(row)
A new array of the items in a row.
matrix.col(m, column) m.col(column)
A new array of the items in a column.
matrix.add_row(m, row = rows, values) m.add_row(row = rows, values)
Adds a row before row (left out: at the bottom), of values (an array as long as a row; left out: none). The first row of an empty matrix sets its columns.
matrix.add_col(m, column = columns, values) m.add_col(column = columns, values)
Adds a column before column (left out: at the right), of values (an array as long as a column; left out: none). The first column of an empty matrix sets its rows.
matrix.remove_row(m, row = -1) m.remove_row(row = -1)
Takes a row out (left out: the last) and gives back its items as an array.
matrix.remove_col(m, column = -1) m.remove_col(column = -1)
Takes a column out (left out: the last) and gives back its items as an array.
matrix.swap_rows(m, row1, row2) m.swap_rows(row1, row2)
Swaps two rows.
matrix.swap_columns(m, column1, column2) m.swap_columns(column1, column2)
Swaps two columns.
matrix.fill(m, value, from_row, to_row, from_column, to_column) m.fill(value, from_row, to_row, from_column, to_column)
Sets the items in the rows from from_row up to (not including) to_row and the columns likewise to value (left out: all of them).
matrix.copy(m) m.copy()
A new matrix with the same items.
matrix.submatrix(m, from_row, to_row, from_column, to_column) m.submatrix(from_row, to_row, from_column, to_column)
A new matrix of the rows from from_row up to (not including) to_row and the columns likewise (left out: all of them).
matrix.reshape(m, rows, columns) m.reshape(rows, columns)
Lays its items out again as rows × columns (which must hold as many items), row after row.
matrix.reverse(m) m.reverse()
Turns the order of its items around: the last row first, each read right to left.
matrix.transpose(m) m.transpose()
A new matrix with its rows as columns.
matrix.sort(m, column = 0, order = "ascending") m.sort(column = 0, order = "ascending")
Sorts its rows by the items in column.
matrix.concat(m, other) m.concat(other)
Adds the rows of other (a matrix with as many columns) at the bottom, and gives back the matrix.
matrix.sum(m, other) m.sum(other)
A new matrix: item by item, it plus other (a matrix of its size, or a number).
matrix.diff(m, other) m.diff(other)
A new matrix: item by item, it less other (a matrix of its size, or a number).
matrix.mult(m, other) m.mult(other)
It times other: a matrix (the matrix product, a new matrix), a number (each item, a new matrix) or an array (a vector as long as a row: a new array).
matrix.pow(m, power) m.pow(power)
A new matrix: it multiplied by itself power times (a square matrix; 0 gives the identity).
matrix.det(m) m.det()
Its determinant (a square matrix).
matrix.inv(m) m.inv()
A new matrix, its inverse (a square matrix), or none when it has none.
matrix.trace(m) m.trace()
The sum of its diagonal (a square matrix).
matrix.rank(m) m.rank()
How many of its rows are independent of each other.
matrix.avg(m) m.avg()
The average of its numbers.
matrix.min(m) m.min()
The smallest of its numbers.
matrix.max(m) m.max()
The largest of its numbers.
matrix.median(m) m.median()
The middle of its numbers.
matrix.mode(m) m.mode()
Its most frequent number (of several as frequent, the smallest).
matrix.is_square(m) m.is_square()
True when it has as many rows as columns.

Maps 11

map()
A new, empty map: values kept under keys (a number, text or true / false), in the order they were first put, like a Python dict. mp[key] reads one (none when it is not there) and mp[key] = value puts one.
map.put(mp, key, value) mp.put(key, value)
Puts value under key, and gives back what was there before (none if nothing). mp[key] = value does the same.
map.get(mp, key) mp.get(key)
The value under key, or none. mp[key] does the same.
map.contains(mp, key) mp.contains(key)
True when there is a value under key.
map.remove(mp, key) mp.remove(key)
Takes key and its value out, and gives back the value (none if it was not there).
map.clear(mp) mp.clear()
Takes every key out.
map.size(mp) mp.size()
How many keys it holds.
map.keys(mp) mp.keys()
A new array of its keys, in the order they were first put.
map.values(mp) mp.values()
A new array of its values, in its keys' order.
map.copy(mp) mp.copy()
A new map with the same keys and values.
map.put_all(mp, other) mp.put_all(other)
Puts every key and value of other (a map) into this one.

Colour 26

color.hex(color, transparency = 0)
The colour with a transparency: 0 is solid, 100 is invisible.
color.rgb(red, green, blue, transparency = 0)
A colour from red, green and blue (0–255).
color.gradient(value, low, high, lowColor, highColor)
A colour between two colours, by where value sits between low and high.
color.r(color)
Red part, 0–255.
color.g(color)
Green part, 0–255.
color.b(color)
Blue part, 0–255.
color.t(color)
Transparency, 0–100.
color.aqua
#00bcd4
color.black
#363a45
color.blue
#2196f3
color.fuchsia
#e040fb
color.gray
#787b86
color.green
#4caf50
color.lime
#00e676
color.maroon
#880e4f
color.navy
#311b92
color.olive
#808000
color.orange
#ff9800
color.purple
#9c27b0
color.red
#ff5252
color.silver
#b2b5be
color.teal
#00897b
color.white
#ffffff
color.yellow
#ffeb3b
color.eclipse_green
#00d79e
color.eclipse_purple
#6a5ebc

Text 16

format(value, pattern)
Text for a value, as Python's format(). pattern is a number of decimals (format(p.close, 2) always shows two) or a pattern: "#.##" up to two decimals (# a digit that can be left off), "#.00" always two (0 a digit always shown), "#,###.##" with commas, or Python's ".2f" and ",.2f". "tick" writes a price as the chart writes this coin's prices, to its step (chart.tick), as Pine's format.mintick. Left out, a number shows the decimals that suit its size.
str.tonumber(text)
The number in the text, or none.
str.format("{0} is {1}", a, b)
Fills {0}, {1} … with the values.
str.length(text)
Number of characters.
str.upper(text)
Upper case.
str.lower(text)
Lower case.
str.contains(text, part)
True if text contains part.
str.startswith(text, part)
True if text starts with part.
str.endswith(text, part)
True if text ends with part.
str.replace_all(text, target, replacement)
Replaces every target with replacement.
str.substring(text, begin, end)
Part of the text, from begin up to (not including) end.
str.trim(text)
The text without the spaces, tabs and line breaks at its start and end.
str.split(text, separator)
The parts of the text between each separator, as an array of texts: str.split("a,b", ",") is ["a", "b"]. "" as the separator splits it into its characters.
str.pos(text, part)
Where part first starts in the text (0 the first character), or none when it isn't in it.
str.repeat(text, times, separator = "")
The text times times over, with separator between (at most 10,000 characters).
str.replace(text, target, replacement, occurrence = 0)
Replaces one target with replacement: the first, or the one occurrence counts to (0 the first, 1 the second).

Utility 5

none(x)
True when x is none (missing). On its own, none is the missing value.
replace(value, replacement = 0)
The value, or replacement when it is none.
debug(value, …)
Writes the values to the Output tab, with the bar they came from.
stop(message)
Stops the script with this message (it shows in the console).
fixnone(source)
Replaces none with the last value that was not none.

Constants 4

math.pi
π
math.e
Euler's number.
math.phi
The golden ratio.
math.rphi
1 / the golden ratio.
CharmScript docs