Docs / Language Syntax

Language Syntax

TDSL is statically typed: every name, member, argument count and type is checked at compile time. It has structs, enums, typed timeframes, history-backed series buffers, and compiles to high-performance Rust.


Script Structure

A script is an indicator when it has a calculate() block and no Tick(), and a strategy when it has a Tick(). Everything is written at file level; the old indicator "Name" { } / strategy "Name" { } wrappers are rejected with an error. The parentheses of the lifecycle blocks are optional.

Function / PropertyDescription
Init() / init()Runs once when the script loads (and again when parameters change). Bind proxies, set timers.
calculate()Indicators: fills and returns the output buffers. Called on load and on every update. Lower case only.
Tick() / tick()Strategies: called on every price tick.
Timer()Strategies: every Timer.Set(seconds), on the broker clock (also between ticks).
Trade()Strategies: once per trade event. Read the event with Event.*.
Exit() / exit() / Shutdown()Runs once when the script is removed or stopped.
Name.calculate()Strategies: fills the buffers of a proxy bound in Init() (Load / Native / Custom).

The skeleton below uses every top-level part of an indicator: an enum, a result struct, the display block, parameters with a section header and a dropdown, persistent globals, series buffers, a helper function and the three lifecycle blocks.

Skeleton.tdsl — every part of an indicatorTDSL
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs syntax: script skeleton";
}

enum Source {
    Close = 0,      // Close
    Median = 1,     // (High + Low) / 2
    Typical = 2     // (High + Low + Close) / 3
}

struct AvgResult {
    double value;
}

display {
    outputs: 1
    AvgResult.value { type: "line"; color: "#14b8a6"; name: "Source Avg"; width: 2; };
}

parameters {
    string _Main_ = "====== Average ======";
    int    period = 14;               // Average Period
    Source src    = Source.Close;     // Price Source
}

state {
    int bars_seen = 0;
}
static datetime last_bar_time = 0;

series double sk_price[];
series double sk_avg[];

// helper: price of bar i for the chosen source
double SourcePrice(int i) {
    double closes[] = close();
    double highs[]  = high();
    double lows[]   = low();
    double p = closes[i];
    if (src == Source.Median)  { p = (highs[i] + lows[i]) / 2.0; }
    if (src == Source.Typical) { p = (highs[i] + lows[i] + closes[i]) / 3.0; }
    return p;
}

Init() {
    bars_seen = 0;
    Print("[INIT] skeleton on " + Symbol() + " period=" + ToString(period));
}

calculate() {
    double closes[] = close();
    int len = length(closes);
    sk_price[] = create_array(len);
    sk_avg[]   = create_array(len);

    int start = Chart.resume_index;
    if (start > 0) { start = start - 1; } else { start = 0; }

    double pd = period;
    for (int i = start; i < len; i = i + 1) {
        sk_price[i] = SourcePrice(i);
        if (i >= period - 1) {
            double s = 0.0;
            for (int j = 0; j < period; j = j + 1) { s = s + sk_price[i - j]; }
            sk_avg[i] = s / pd;
        }
    }

    datetime bar_time = time(0);
    if (bar_time != last_bar_time) {
        last_bar_time = bar_time;
        bars_seen = bars_seen + 1;
        Print("[BAR] #" + ToString(bars_seen) + " value=" + ToString(sk_avg[len - 1]));
    }

    return AvgResult { value: sk_avg };
}

Exit() {
    Print("[EXIT] skeleton saw " + ToString(bars_seen) + " new bars");
}

About Block

Optional metadata shown in the script library. Recognised keys are author, version, about and link, all string literals. Any other key is ignored.

about { }TDSL
about {
  author: "TBC Trading Team";
  version: "1.2.0";
  about: "A multi-indicator scalp bot with internal RSI and bands.";
  link: "https://corextrader.com";
}

Primitive Types

Function / PropertyDescription
intInteger number.
doubleDouble-precision float. Default for prices and calculations.
boolBoolean: true or false.
stringText string. Concatenate with +.
datetimePoint in time in milliseconds since the Unix epoch (UTC).
timeframeA bar period: Timeframe.M1 … Timeframe.MO6, the bare form (H1), or bare Timeframe = the chart's. Strings are not accepted.
enumUser-defined enumeration — shown as a dropdown in the UI.
double x[]Array of doubles (create with create_array(n)). datetime x[] holds times (time()).
series double x[]History-backed buffer, kept between calls (see Series vs Arrays).

An int becomes a double by assigning it (double pd = period;) — the usual way to keep a division in doubles.

Variable declarations (inside a block)TDSL
int      count   = 50;
double   price   = 1.23456;
bool     is_long = true;
string   label   = "Upper Band";
datetime now     = Time.Now();
datetime in_1h   = now + 3600000;          // datetimes are milliseconds

int    three = 3;
double td    = three;                      // int -> double by assignment
double ratio = 1.0 / td;

string side = is_long ? "BUY" : "SELL";

System Data

Function / PropertyTypeDescription
candle_count() / bars()intNumber of bars on the chart (= length(close())).
Chart.resume_indexintFirst bar that needs calculation: 0 on the first run, > 0 on updates. The only Chart member.
Symbol()stringChart symbol. Call it as Symbol() when passing it as a value (bare Symbol is the namespace, e.g. Symbol.Bid()).
TimeframetimeframeChart timeframe, e.g. Native.Init(Symbol(), Timeframe). Timeframe.H1 etc. name a fixed one.
Point / Symbol.Point()doublePoint size of the chart symbol.
DigitsintPrice digits of the chart symbol.

The standard incremental loop: on the first run start at the lookback, afterwards start one bar before Chart.resume_index so the bar that was still forming last time is finished too.

The resume patternTDSL
int start = Chart.resume_index;
if (start > 0) {
    start = start - 1;          // recalculate the previous bar too
} else {
    start = period;             // first run: enough bars behind for [i - period]
}
for (int i = start; i < len; i = i + 1) {
    // ... fill buf[i] ...
}

Series vs Arrays

Price data can be read two ways. Shift syntax close(n) counts back from the newest bar (0 = current, 1 = previous); the same form reads proxy fields in strategies (Bands.upper(0)). Index syntax x[i] is an absolute index: 0 = oldest bar, len - 1 = newest. close(), open(), high(), low(), volume() and time() without an argument return the whole array, oldest first.

Indicator output buffers are declared once at file level as series double name[]; and sized at the top of calculate() with name[] = create_array(len);. The engine keeps their values between calls, so on updates you fill only the bars from the resume index on and can read your own earlier values (avg[i - 1]) for recursive formulas. A fresh create_array(n) is n × NaN. Series buffers are allocated by name across the whole script — give each a unique name (the verified scripts use a short prefix such as t1_).

In proxy blocks (Name.calculate() in a strategy) the fetch targets and returned buffers are series double declared inside the block, then sized with create_array(len) before Native.Fetch / Custom.Fetch.

Index vs shift access (indicator)TDSL
struct Offsets {
    double upper;
    double lower;
}

display {
    outputs: 2
    Offsets.upper { type: "line"; color: "#16a34a"; name: "Close + 10 pts"; width: 1; };
    Offsets.lower { type: "line"; color: "#dc2626"; name: "Close - 10 pts"; width: 1; };
}

static datetime last_bar_time = 0;

series double sa_up[];
series double sa_lo[];

calculate() {
    double closes[] = close();
    int len = length(closes);
    sa_up[] = create_array(len);
    sa_lo[] = create_array(len);

    double pt = Symbol.Point();
    int start = Chart.resume_index;
    if (start > 0) { start = start - 1; } else { start = 0; }

    for (int i = start; i < len; i = i + 1) {
        sa_up[i] = closes[i] + (10.0 * pt);      // index: 0 = oldest, len - 1 = newest
        sa_lo[i] = closes[i] - (10.0 * pt);
    }

    datetime bar_time = time(0);
    if (bar_time != last_bar_time && len > 1) {
        last_bar_time = bar_time;
        double last = closes[len - 1];
        double prev = closes[len - 2];
        Print("[ACCESS] last=" + ToString(last) + " close0=" + ToString(close(0))
            + " prev=" + ToString(prev) + " close1=" + ToString(close(1))
            + " same=" + ToString(last == close(0)) + " same_prev=" + ToString(prev == close(1)));
    }

    return Offsets { upper: sa_up, lower: sa_lo };
}
Note
close(0) reads relative to the most recent bar. arr[i] reads by absolute bar index — never below 0 or at/after len, so differences like closes[i] - closes[i - 1] need the loop to start at i >= 1 (the lookback).

Structs & Returns

Struct fields are declared as type name; (no default values); fields may be written on one line (struct OscLines { double a; double b; }). Build a value with a named literal; a trailing comma is allowed. An indicator returns its buffers either as a named struct (recommended) or as an anonymous tuple.

Option 1: Named Structs

Each field maps to a Struct.field entry in the display block; field order is buffer order (used by fill).

Named struct returnTDSL
struct BandSignal {
    double upper;
    double middle;
    double lower;
}

display {
    outputs: 3
    BandSignal.upper  { type: "line"; color: "#c42626ff"; name: "Upper";  width: 1; };
    BandSignal.middle { type: "line"; color: "#b0aaaaff"; name: "Middle"; width: 0.5; };
    BandSignal.lower  { type: "line"; color: "#50c426ff"; name: "Lower";  width: 1; };
}

// ... in calculate():
return BandSignal {
    upper: t1_upper,
    middle: t1_middle,
    lower: t1_lower,
};

Option 2: Anonymous Tuples (Buffer Arrays)

Return the buffers with return [a, b];. They map to buffer[index] in the display block.

TupleBands.tdsl — tuple returnTDSL
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs syntax: tuple return";
}

display {
    outputs: 3
    buffer[0] { type: "line"; color: "#10b981"; name: "Upper";  width: 1; };
    buffer[1] { type: "line"; color: "#9ca3af"; name: "Middle"; width: 1; style: "dashed"; };
    buffer[2] { type: "line"; color: "#ef4444"; name: "Lower";  width: 1; };
}

series double tr_up[];
series double tr_mid[];
series double tr_lo[];

calculate() {
    double closes[] = close();
    int len = length(closes);
    tr_up[]  = create_array(len);
    tr_mid[] = create_array(len);
    tr_lo[]  = create_array(len);

    double pt = Symbol.Point();
    int start = Chart.resume_index;
    if (start > 0) { start = start - 1; } else { start = 0; }

    for (int i = start; i < len; i = i + 1) {
        tr_mid[i] = closes[i];
        tr_up[i]  = closes[i] + (100.0 * pt);
        tr_lo[i]  = closes[i] - (100.0 * pt);
    }

    return [tr_up, tr_mid, tr_lo];
}
Caution
Compatibility Note: Anonymous tuple returns ([ ]) are only supported in standalone indicators. Strategy proxy blocks (Name.calculate()) must return a named struct.

Enums

Members take explicit integer values; a same-line // comment becomes the label shown in the dropdown. Access members with the scoped form Source.Close; enum values compare with ==.A misspelled member is a compile error with a suggestion (see Compile Errors).

Enum definition and usageTDSL
enum Source {
    Close = 0,      // Close
    Median = 1,     // (High + Low) / 2
    Typical = 2     // (High + Low + Close) / 3
}

parameters {
    Source src = Source.Close;    // Price Source
}

// ... inside the bar loop:
t5_price[i] = closes[i];
if (src == Source.Median)  { t5_price[i] = (highs[i] + lows[i]) / 2.0; }
if (src == Source.Typical) { t5_price[i] = (highs[i] + lows[i] + closes[i]) / 3.0; }
Warning
An array variable can't be re-pointed at another price array (src_data = highs;). Pick the source bar by bar into your own buffer, as above.

Parameters Block

Each parameter is type name = default; with type int, double, bool, string, datetime or one of your enums. Optional features:

  • A trailing same-line // comment becomes the UI label.
  • A string parameter whose value is a banner such as "====== Grid ======" acts as a section header.
  • Enum-typed parameters (Source src = Source.Close;) show their members as a dropdown.

There are no min/max ranges; validate inputs in Init() if needed. A parameter may not use a reserved name (see Reserved Names).

Parameters with UI labels, headers and dropdownsTDSL
enum AvgType {
    SMA = 0,        // Simple
    EMA = 1         // Exponential
}

parameters {
    string  _MA_      = "====== Averages ======";
    int     fast_len  = 10;              // Fast Length
    int     slow_len  = 30;              // Slow Length
    Source  src       = Source.Close;    // Price Source
    AvgType avg_type  = AvgType.EMA;     // Average Type

    string  _Risk_    = "====== Risk ======";
    double  lot_size  = 0.1;             // Fixed Lot Size
    bool    use_sl    = true;            // Enable Stop Loss
}

Globals & Persistence

A global keeps its value between ticks / calls and across helper-function calls. Declare it inside state { } or with static at file level — both behave the same. Persisted types are numbers, bool, string and datetime; buffers that must keep history are series arrays.

state { }Script lifetimePersistent globals, one declaration per line.
staticScript lifetimeSame as state { }. Initial value optional; several names in one line: static double a = 0.0, b = 0.0;
create_array(n)One callFresh local array (n × NaN). Assign it to a series buffer to size that buffer.
series double x[];Script lifetimeHistory-backed buffer, allocated by name; each name must be unique across the script.
Persistence formsTDSL
state {
    int bar_counter = 0;
}
static datetime last_bar;
static double last_avg = 0.0, last_range = 0.0;

bool BarStarted() {
    datetime cur = time(0);
    if (cur != last_bar) {
        last_bar = cur;
        return true;
    }
    return false;
}

Helper Functions

Write helpers as returnType Name(type a, type b) { … } at file level (void for none). They can read parameters, globals and price data, and are callable from every block. Calls are checked: a call needs all parameters of the function and no more (`Name` takes N arguments (a, b), M given.). A helper may not be named like a built-in — names match built-ins case-insensitively, so Open collides with open.

Helper with a while loop (from the verified tuple-return indicator)TDSL
// average of (high + low) / 2 over n bars ending at index i
double HLAverage(int i, int n) {
    double highs[] = high();
    double lows[]  = low();
    double s = 0.0;
    int j = 0;
    while (j < n) {
        s = s + (highs[i - j] + lows[i - j]) / 2.0;
        j = j + 1;
    }
    double dn = n;
    return s / dn;
}

Operators

Function / PropertyParametersReturnsDescription
== != > < >= <=—voidComparison.
&& || !—voidLogical and / or / not.
+ - * / %—voidArithmetic (% = remainder); + also concatenates strings. Parentheses are kept exactly as written: 100.0 * (c - l) / (h - l).
c ? a : b—voidTernary: only the chosen side is used. Mixing int and double gives a double.
x = x + 1—voidAssignment. Write loop steps as i = i + 1.

Control Flow

if / else if / else, for, while, break, continue and return. continue in a for loop still runs the step (i = i + 1).

FlowDemo.tdsl — globals, operators and loops (strategy, no trading)TDSL
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs syntax: globals, operators, control flow";
}

state {
    int bar_counter = 0;
}
static datetime last_bar;
static double last_avg = 0.0, last_range = 0.0;

bool BarStarted() {
    datetime cur = time(0);
    if (cur != last_bar) {
        last_bar = cur;
        return true;
    }
    return false;
}

Tick() {
    if (!BarStarted()) { return; }
    bar_counter = bar_counter + 1;

    // for + continue + break: count up-bars among the last 20, stop if data runs out
    int up = 0;
    for (int k = 1; k <= 20; k = k + 1) {
        if (close(k) <= 0.0) { break; }            // no more history
        if (close(k) <= open(k)) { continue; }     // only up-bars count
        up = up + 1;
    }

    // 20-bar average of closes
    double s = 0.0;
    for (int k = 1; k <= 20; k = k + 1) { s = s + close(k); }
    last_avg = s / 20.0;

    // while: streak of closes above that average
    int streak = 0;
    while (streak < 50 && close(streak + 1) > last_avg) {
        streak = streak + 1;
    }

    // if / else if / else
    int bias = 0;
    if (up >= 14) { bias = 1; }
    else if (up <= 6) { bias = -1; }
    else { bias = 0; }

    // parentheses are kept: (c - l) / (h - l)
    double h = high(1);
    double l = low(1);
    last_range = h - l > 0.0 ? 100.0 * (close(1) - l) / (h - l) : 50.0;

    bool even = bar_counter % 2 == 0;

    Print("[FLOW] bar #" + ToString(bar_counter) + " up=" + ToString(up) + " streak=" + ToString(streak)
        + " bias=" + ToString(bias) + " even=" + ToString(even) + " range_pct=" + ToString(last_range));
}

ToString & Datetimes

Function / PropertyDescription
doubleAs it is, no rounding, always with a decimal point: ToString(1.2) → "1.2", ToString(2.0) → "2.0". Fixed decimals: ToString(ToDouble(x, 2)) → "1234.10".
int / enumPlain number: ToString(42) → "42".
bool"true" or "false".
datetimeUTC time of day "HH:MM:SS".

Datetimes are milliseconds, so one minute from now is Time.Now() + 60 * 1000 and one hour is 3600000. time(0) is the open time of the current chart bar — comparing it with a stored value is the usual once-per-bar check in indicators (strategies can also use Time.IsNewBar()).


Timeframes & Other Symbols

Timeframe values: M1 M2 M3 M4 M5 M6 M8 M10 M12 M15 M20 M30, H1 H2 H3 H4 H6 H8 H12, D1 … D5, W1 W2 W3, MN MO2 MO3 MO4 MO6 — each as Timeframe.H1 or bare H1. Bare Timeframe is the chart's timeframe. A string ("H1") where a timeframe is expected is a compile error (Native.Init, Bars.*, price accessors).

Function / PropertyTypeDescription
close(symbol, timeframe, shift)doubleClose of that series' bar; shift 0 = its newest bar. Siblings: open, high, low, volume, time (ms).
Bars.Shift(symbol, timeframe, time)intShift of the series' bar that contains time (ms); -1 = none (before its history / still loading). Maps a chart bar onto the other series.
Bars.Count(symbol, timeframe)intBars in that series (0 = none yet / still loading).
Symbol.Bid(symbol)doubleLive bid of another symbol.

Another symbol is added to Market Watch while the script runs and its history is loaded in the background. Bars follow the shared bucket rule (M1 … D1 fixed UTC buckets, W1 from Sunday 00:00 UTC, MN = calendar month). Live-verified in strategies; indicator files use the same host functions (see the higher-timeframe overlay on Indicators). Full reference on the market-data page.

Timeframes.tdsl — typed timeframes and other symbols (strategy, no trading)TDSL
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs syntax: timeframes and other symbols";
}

parameters {
    string other = "EURUSD.r";   // Other Symbol
}

Tick() {
    if (!Time.IsNewBar()) { return; }
    string sym = Symbol();

    int    h1_bars   = Bars.Count(sym, Timeframe.H1);
    double h1_close1 = close(sym, Timeframe.H1, 1);
    double h4_high1  = high(sym, H4, 1);                       // bare H4 = Timeframe.H4
    double d1_close1 = close(sym, Timeframe.D1, 1);
    double chart_c1  = close(sym, Timeframe, 1);               // bare Timeframe = chart's timeframe

    // Which H1 bar holds the previous chart bar?
    double bar1_time = time(sym, Timeframe, 1);               // bar open time in ms
    int h1_shift = Bars.Shift(sym, Timeframe.H1, bar1_time);

    double eur_bid = Symbol.Bid(other);
    double eur_h1  = close(other, Timeframe.H1, 0);

    Print("[TF] h1_bars=" + ToString(h1_bars) + " h1_close1=" + ToString(h1_close1)
        + " h4_high1=" + ToString(h4_high1) + " d1_close1=" + ToString(d1_close1)
        + " chart_close1=" + ToString(chart_c1) + " h1_shift_of_bar1=" + ToString(h1_shift)
        + " eur_bid=" + ToString(eur_bid) + " eur_h1_close0=" + ToString(eur_h1));
}

Reserved Names

Built-in names can't be reused — before these checks a variable called Point silently read the symbol's point instead of its own value.

Function / PropertyDescription
Point, Digits, close, Close, high, High, low, Low, open, Open, volume, Volume, time, TimeNot allowed as a variable or parameter name in these spellings (point in lower case is a normal name).
symbol, timeframe, trade, position, order, account, history, deal, env, log, array, _symbolNot allowed as a variable or parameter name in any spelling (Trade, TRADE, …).
Function namesA user function may not share a built-in function's name in any spelling (Open = open, Close = close).

Compile Errors

The checker stops at the first error and reports its line. Typical messages:

Function / PropertyDescription
Misspelled member`Position` has no member `Profitt` - did you mean `Profit`?
Misspelled enum memberEnum `Mode` has no member `Agresive` - did you mean `Aggressive`?
Function named like a built-in`Open` is a built-in (open(symbol, timeframe, offset)) and cannot be redefined. Give your function another name.
Variable named like a built-in`Point` is a built-in name and cannot be used for a variable or parameter. Give it another name.
Too many / too few arguments`OpenLeg` takes 2 arguments (side, lot), 3 given. — built-ins: `open` takes at most 3 arguments (symbol, timeframe, offset), 4 given.
Member on a plain valueA double value has no member `value`
Each of these must NOT compileTDSL
// 1. did you mean
Tick() {
    double p = Position.Profitt();      // `Position` has no member `Profitt` - did you mean `Profit`?
}

// 2. built-in function name (case-insensitive)
void Open(int side, double lot) { Print("never"); }

// 3. argument count
void OpenLeg(int side, double lot) { Print("leg"); }
Tick() {
    OpenLeg(1, 0.1, 99);                // `OpenLeg` takes 2 arguments (side, lot), 3 given.
    double x = open(1, 2, 3, 4);        // `open` takes at most 3 arguments ..., 4 given.
}

// 4. reserved variable names
Tick() {
    double Point = 10;                  // `Point` is a built-in name ...
    int trade = 1;                      // `trade` is a built-in name ... (any spelling)
}

// 5. member on a number
Tick() {
    double price = close(0);
    double v = price.value;             // A double value has no member `value`
}

// 6. enum member typo
enum Mode { Safe = 0, Aggressive = 1 }
parameters { Mode mode = Mode.Safe; }
Tick() {
    if (mode == Mode.Agresive) { Print("x"); }   // did you mean `Aggressive`?
}

Display Configuration

The display block controls how buffers are drawn. The full reference with examples is on Display & Visuals.

Display block with buffer indicesTDSL
display {
    separate_window: false;
    outputs: 3
    buffer[0] { type: "line"; color: "#c42626ff"; name: "Upper Band";  width: 1; };
    buffer[1] { type: "line"; color: "#b0aaaaff"; name: "Middle Band"; width: 1; style: "dashed"; };
    buffer[2] { type: "line"; color: "#50c426ff"; name: "Lower Band";  width: 1; };
    fill { buffer_a: 0; buffer_b: 1; color: "rgba(220,38,38,0.05)"; };
}
"line"Continuous line connecting bar values.
"histogram"Vertical bar from zero to the value.
"arrow"Arrow glyph at each bar with a value (arrow_code: 233 up, 234 down); 0.0 = no arrow.
"dots"Single dot at each bar with a value (on the price chart, write 0.0 on bars without a dot).