DocsSlangLanguage Reference

Language Reference

Complete syntax rules, namespace prefixes, all 300+ commands, argument types, and annotated examples.

Syntax

Every non-blank, non-comment line in a Slang script is one of two forms:

Assignment (creates / updates a node)

varName = [ns.]FUNC(arg1, arg2, …)

Standalone call (config / action — no node)

[ns.]FUNC(arg1, arg2, …)
Variable names

Must match [A-Za-z_]\w* — letters, digits, and underscores. The name becomes the node label inside the graph editor.

Namespace prefix

Optional two-letter prefix followed by a dot (e.g. ta., dm.). The compiler validates that the function belongs to the declared namespace and throws a descriptive error if not.

String arguments

Enclosed in single or double quotes. Quotes are stripped by the tokeniser. Example: "AAPL", 'day'.

Numeric arguments

Any numeric literal (integer or float). Coerced to a JavaScript number; a type error is thrown if the parameter expects a number but receives a non-numeric string.

Input references

Variable names used as arguments refer to previously declared nodes. The compiler resolves them to node IDs. If the variable is not yet declared on a prior line, compilation fails.

Placeholder ?

A ? in an input position leaves that edge unconnected. Useful when a node's optional input should remain unwired.

Comments

Lines starting with // or # are skipped entirely. Inline comments are not supported.

Blank lines

Silently ignored. Use them freely for readability.

Namespaces

Every Slang command belongs to exactly one namespace. Using the prefix is optional but strongly recommended — the compiler validates the pairing and provides clear error messages when a command is used under the wrong namespace.

PrefixFull nameDescriptionCommands
scSourceData feed inputs — market OHLCV nodesSTOCK, CRYPTO, FOREX
taTechnical Analysis200+ technical indicators, pattern recognition, core math, and statisticsSMA, EMA, RSI, MACD, BOLLINGER_BANDS, VWAP, ATR, ADX, STOCHASTIC, … (200+)
dmDecision / LogicComparison, boolean logic, crossover detection, wait gatesCOMPARE, BOOLEAN, CROSSOVER, NOT, WAIT
rmRisk ManagementPosition sizing, take-profit, stop-loss, Kelly criterionTAKEPROFIT, STOPLOSS, KELLY, RISK_PER_TRADE
exExecution / ActionOrder nodes that open and close positionsOPENPOSITION, CLOSEPOSITION
chChartChart display and pane assignment — no node createdAddToChart, MoveToPane, PlotRoid
cgConfigurationGlobal script settings — no node createdSetWindowSize, PlotRoid

Namespace Validation

The compiler calls validateNamespace(ns, funcName) from SlangNamespaces.ts. It returns null on success or a human-readable error string. Two checks are performed:

Unknown namespace

xx.SMA(s, 20)
// Error: Unknown namespace "xx". Valid namespaces: sc, ta, dm, rm, ex, ch, cg

Wrong namespace

sc.SMA(s, 20)
// Error: "SMA" belongs to namespace "ta", not "sc"

sc — Source Commands

Source commands create data-feed nodes. They have zero input edges and output a full OHLCV channel set (t, o, h, l, c, v).

CommandNode TypeSignatureOutput Channels
STOCKstockNodeSTOCK(symbol: string, timespan: string, multiplier: number)t, o, h, l, c, v
CRYPTOcryptoMarketNodeCRYPTO(symbol: string, timespan: string, multiplier: number)t, o, h, l, c, v
FOREXforexNodeFOREX(symbol: string, timespan: string, multiplier: number)t, o, h, l, c, v

Valid timespan values

minutehourdayweekmonth

ta — Technical Analysis Commands

The ta namespace is the largest, covering over 200 indicators plus core math and statistics. Most indicator commands follow one of two patterns:

Standard — one input, optional period

result = ta.SMA(source, period)
result = ta.RSI(source, 14)
result = ta.ATR(source, 14)

Multi-output — use GETVALUE to extract channel

bb   = ta.BOLLINGER_BANDS(s, 20)
upper = ta.GETVALUE(bb, "upper", 0)
lower = ta.GETVALUE(bb, "lower", 0)

Moving Averages

SMAEMAWMAHMADEMATEMAALMAVWMAJMAKAMAT3TRIMALSMAFRAMAGMAMCGINLEY_DYNAMICVIDYAVMARAINBOW_MASUPER_SMOOTHERGAUSSIAN_MALAGUERRE_FILTER

Oscillators & Momentum

RSIMACDSTOCHASTICSTOCHASTIC_RSICCIWILLIAMS_RMFICMOROCMOMENTUM_RAWTSIKSTPMOTRIXDPOAROONAROON_OSCILLATORCONNORS_RSILAGUERRE_RSIRMIDYNAMIC_MOMENTUM_INDEX

Volatility

ATRBOLLINGER_BANDSKELTNER_CHANNELSDONCHIAN_CHANNELSATR_BANDSHVNATRGARMAN_KLASS_VOLATILITYPARKINSON_VOLATILITYYANG_ZHANG_VOLATILITYROGERS_SATCHELL_VOLATILITYRANGE_VOLATILITYRVI_VOLATILITYCHAIKIN_VOLATILITY

Volume

OBVVWAPANCHORED_VWAPCHAIKIN_MONEY_FLOWMFIMFI_OSCILLATORFORCE_INDEXEMVKLINGER_OSCILLATORVOLUME_OSCILLATORVOLUME_PROFILEVOLUME_TRENDVROCPVINVIPVTTSVTWIGGS_MONEY_FLOWVSAVPCICVD

Trend & Direction

ADXDMISUPER_TRENDPARABOLIC_SARICHIMOKUELDER_RAYELDER_IMPULSEVORTEXTREND_DIRECTIONDIRECTIONAL_MOMENTUMLINEAR_REGRESSIONLINEAR_REGRESSION_CHANNELGANN_HIGH_LOW

Statistical & Advanced

ZSCOREZSCORE_ROBUSTROLLING_SHARPEROLLING_KURTOSISROLLING_SKEWNESSHURST_EXPONENTFRACTAL_DIMENSIONKALMAN_FILTERKALMAN_SMOOTHERWAVELET_TRANSFORMHMM_REGIMEBAYESIAN_TREND_FILTERCOINTEGRATIONAUTOCORRELATIONDFAHALF_LIFE_MEAN_REVERSIONROLLING_PCA

Math (Unary)

ABSCEILFLOORROUNDSIGNSQRTLOGPOWCLAMP

Math (Binary)

ADDSUBTRACTMULTDIVIDEMODULO

Statistics (Windowed)

SUMAVERAGEMINMAXVARIANCESTD_DEVMEDIANMOMENTUMCUMSUMSHARPESORTINOSLOPESKEWNESSKURTOSISR_SQUAREDENTROPYGAINLOSSVOLATILITYNORMALIZESCALERANK

dm — Decision / Logic Commands

CommandInputsParametersDescription
COMPAREinput1, input2operator: string, threshold: numberCompares two signals element-wise. operator: >, <, >=, <=, ==, !=, crossAbove, crossBelow. Emits 1 when true, 0 otherwise.
BOOLEANinput1, input2operation: stringCombines two boolean signals with AND, OR, XOR, NAND, NOR.
CROSSOVERinput1, input2(none)Fires 1 on the exact candle where input1 crosses above input2.
NOTinput(none)Inverts a boolean signal (0 → 1, 1 → 0).
WAITinput1, input2maxCandles: numberHolds a 1 signal active for up to maxCandles bars after input1 fires, or until input2 fires.

COMPARE operator values

">""<"">=""<=""==""!=""crossAbove""crossBelow"

rm — Risk Management Commands

TAKEPROFIT and STOPLOSS use paramGroups — the first parameter is a discriminator string that selects which subsequent parameters are required.

CommandTypeAdditional paramsExample
TAKEPROFIT"percentage"takeProfitPercent: numberrm.TAKEPROFIT(s, "percentage", 2.5)
TAKEPROFIT"fixed"fixedAmount: numberrm.TAKEPROFIT(s, "fixed", 5.0)
TAKEPROFIT"pips"pips: number, pipSize: numberrm.TAKEPROFIT(s, "pips", 50, 0.0001)
TAKEPROFIT"money"moneyTarget: number, positionSize: numberrm.TAKEPROFIT(s, "money", 200, 100)
STOPLOSS"percentage"stopLossPercent: numberrm.STOPLOSS(s, "percentage", 1.0)
STOPLOSS"fixed"fixedAmount: numberrm.STOPLOSS(s, "fixed", 2.0)
STOPLOSS"pips"pips: number, pipSize: numberrm.STOPLOSS(s, "pips", 20, 0.0001)
STOPLOSS"money"moneyRisk: number, positionSize: numberrm.STOPLOSS(s, "money", 100, 100)
KELLYkellyFraction: number (0–1)k = rm.KELLY(posResult, 0.5)
RISK_PER_TRADEriskPercentage: numberr = rm.RISK_PER_TRADE(equity, 2)

ex — Execution Commands

CommandInput channelsParametersOutput channels
OPENPOSITIONinput1 (ohlc) input2 (take profit) input3 (stop loss) signal (0/1)positionType: string initialCapital: number quantity: number commission: number slippage: numbervalues, timestamps, positionType, entryPrice, stopLossPrice, takeProfitPrice, signalTriggered
CLOSEPOSITIONsignal (0/1)triggered, lastSignalValue

positionType values

"market_long""market_short""limit_long""limit_short""stop_long""stop_short""stop_limit_long""stop_limit_short"

ch & cg — Config Commands

Config commands are standalone calls — they do not create nodes and do not require a variable assignment. They are executed as side-effects during compilation and also emitted at the end of a decompiled script.

CommandNamespaceParametersEffect
SetWindowSizecgsize: numberSets the visible candle window to size bars. Calls setSlangWindowRange() and stores the value as a global.
AddToChartchchartIndex: number, …nodeRefsAssigns one or more nodes to a chart pane. chartIndex is 0-based. Calls addNodeToChart() for each resolved node ID.
MoveToPanech…nodeRefsSets stacked: true on each referenced node so the chart renders it in a separate sub-pane.
PlotRoidch/cg…nodeRefsSets plotRoid: true on each referenced node, enabling the Roid runner overlay display.
// Display two indicators on chart 0, move RSI to a sub-pane
ch.AddToChart(0, sma, ema)
ch.MoveToPane(rsi)
cg.SetWindowSize(300)

Candlestick Pattern Commands

Pattern commands live under the ta namespace (they are registered by SlangPatternParser.ts). Each takes an OHLC input and outputs a signal (0/1) channel and a confidence channel.

Single-candle

DOJIDRAGONFLY_DOJIGRAVESTONE_DOJIHAMMERHANGING_MANINVERTED_HAMMERLONG_LEGGED_DOJIMARUBOZUSHOOTING_STARSPINNING_TOP

Two-candle

BULLISH_ENGULFINGBEARISH_ENGULFINGTWEEZER_TOPTWEEZER_BOTTOMPIERCING_LINEDARK_CLOUD_COVERHARAMIHARAMI_CROSS

Three-candle & More

MORNING_STAREVENING_STARTHREE_WHITE_SOLDIERSTHREE_BLACK_CROWSABANDONED_BABYRISING_THREEFALLING_THREE