Standard Library
Math, array manipulation, string utilities, logging, type conversion, and indicator orchestration — all built into the language with no imports required.
Math.*
All Math functions take and return double; ints are accepted and converted. Always write the Math. prefix — there are no bare sqrt() / abs() shorthands.
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
Math.Abs(x) | double x | double | Absolute value. |
Math.Sqrt(x) | double x | double | Square root (NaN for x < 0). |
Math.Pow(base,exp) | double base, exp | double | base raised to the power of exp. |
Math.Log(x) | double x | double | Natural logarithm. |
Math.Exp(x) | double x | double | e raised to the power x. |
Math.Sin(x) | double x | double | Sine (radians). |
Math.Cos(x) | double x | double | Cosine (radians). |
Math.Tan(x) | double x | double | Tangent (radians). |
Math.Asin(x) / Math.Acos(x) / Math.Atan(x) | double x | double | Inverse trigonometric functions (radians). |
Math.Floor(x) | double x | double | Largest integer ≤ x. |
Math.Ceil(x) | double x | double | Smallest integer ≥ x. |
Math.Round(x) | double x | double | Round to nearest integer (halves away from zero). |
To pick the larger / smaller of two values use an if or a ternary: double hi = a > b ? a : b;. The min / max helpers below reduce a whole array, they do not take two scalars. To divide two ints as doubles, copy one into a double first (double pd = period;), as the examples do.
// DOCS stdlib — Math.*: realised volatility of log returns and a volatility-scaled lot. NO TRADING.
// Uses: Math.Log, Math.Sqrt, Math.Pow, Math.Abs, Math.Floor, Math.Round, Symbol.LotStep / LotMin / LotMax.
// Expect (Journal), once per new bar after period + 2 bars:
// [VOL] stdev=.. (per bar, e.g. 0.0002 .. 0.002) abs_last=.. lot=..
// lot is a multiple of the symbol's lot step, between its min and max lot; it gets smaller
// when the market is more volatile.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: Math functions";
}
parameters {
int period = 20; // Bars
double target_vol = 0.001; // Volatility for base_lot
double base_lot = 0.10; // Lot at target_vol
}
Init() {
Print("[INIT] volatility lot on " + Symbol() + " period=" + ToString(period));
}
Tick() {
if (!Time.IsNewBar()) { return; }
if (bars() < period + 2) { return; }
// log returns of the last period closed bars
double s = 0.0;
double sq = 0.0;
for (int k = 1; k <= period; k = k + 1) {
double r = Math.Log(close(k) / close(k + 1));
s = s + r;
sq = sq + Math.Pow(r, 2.0);
}
double pd = period;
double mean = s / pd;
double stdev = Math.Sqrt(sq / pd - mean * mean);
double abs_last = Math.Abs(Math.Log(close(1) / close(2)));
// lot scaled by target / actual volatility, rounded DOWN to the lot step
double lot = base_lot;
if (stdev > 0.0) { lot = base_lot * target_vol / stdev; }
double step = Symbol.LotStep();
if (step > 0.0) { lot = Math.Floor(lot / step) * step; }
if (lot < Symbol.LotMin()) { lot = Symbol.LotMin(); }
if (lot > Symbol.LotMax()) { lot = Symbol.LotMax(); }
Print("[VOL] stdev=" + ToString(stdev) + " abs_last=" + ToString(abs_last)
+ " lot=" + ToString(lot) + " lot_x100=" + ToString(Math.Round(lot * 100.0)));
}Array Functions
All array helpers work on double[] and return a new array or a value — the input is never changed. Index 0 is the oldest element; arr(0) reads the newest one (counting back), arr[i] the absolute index.
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
create_array(n) | int n | double[] | A fresh array of exactly n elements, all NaN. Temporary (not persisted between calls) unless assigned to a series buffer. |
Array.Create(n) | int n | double[] | Same as create_array(n). |
length(arr) / len(arr) / Array.Length(arr) | double[] arr | int | Number of elements. |
sum(arr) / Array.Sum(arr) | double[] arr | double | Sum of the whole array (no period argument). |
avg(arr) / Array.Avg(arr) | double[] arr | double | Average of the whole array. |
min(arr) / Array.Min(arr) | double[] arr | double | Smallest element of the whole array. |
max(arr) / Array.Max(arr) | double[] arr | double | Largest element of the whole array. |
highest(arr,n) | double[] arr, int n | double[] | Rolling maximum: element i = max of the n elements ending at i (the first n-1 elements are not set). |
lowest(arr,n) | double[] arr, int n | double[] | Rolling minimum: element i = min of the n elements ending at i (the first n-1 elements are not set). |
find(arr,v) / index_of(arr,v) | double[] arr, double v | double | Index of the first element equal to v (-1 if missing). |
contains(arr,v) | double[] arr, double v | double | 1.0 if arr contains v, else 0.0. |
fill(arr,val) | double[] arr, double | double[] | A new array of the same length filled with val (arr is not changed). |
concat(a,b) | double[] a, b | double[] | a followed by b. |
slice(arr,s,e) | double[] arr, int s,e | double[] | Elements s … e-1 (e is exclusive); empty when the range is out of bounds. |
reverse(arr) | double[] arr | double[] | Reversed copy. |
sort(arr) | double[] arr | double[] | Sorted ascending copy. |
// DOCS stdlib — Array helpers on a window of closes. NO TRADING.
// Uses: bars, slice, avg, sum, min, max, highest, lowest, sort, reverse, find, contains, fill,
// concat, length, series access arr(0) on a local array.
// Expect (Journal), once per new bar after 20 bars:
// [ARRAY] mean=.. range=.. hh=.. ll=.. (hh >= every close of the window, ll <= every one)
// [ARRAY] median=.. newest=.. oldest=.. at_max=<0..19> has_newest=1.00000
// [ARRAY] joined=40 fives=5.00000 total=.. (total = mean x 20)
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: array helpers";
}
Init() {
Print("[INIT] array helpers on " + Symbol());
}
Tick() {
if (!Time.IsNewBar()) { return; }
int n = bars();
if (n < 20) { return; }
double win[] = slice(close(), n - 20, n); // last 20 closes, oldest first
double mean = avg(win);
double range_w = max(win) - min(win);
double hh[] = highest(close(), 20); // rolling 20-bar high
double ll[] = lowest(close(), 20); // rolling 20-bar low
Print("[ARRAY] mean=" + ToString(mean) + " range=" + ToString(range_w)
+ " hh=" + ToString(hh(0)) + " ll=" + ToString(ll(0)));
double sorted[] = sort(win); // ascending copy
double rev[] = reverse(win); // newest first
double at_max = find(win, max(win)); // index of the highest close (-1 if missing)
double has_newest = contains(win, close(0)); // 1.0 / 0.0
Print("[ARRAY] median=" + ToString(sorted[10]) + " newest=" + ToString(rev[0])
+ " oldest=" + ToString(win[0]) + " at_max=" + ToString(at_max)
+ " has_newest=" + ToString(has_newest));
double fives[] = fill(win, 5.0); // same length, every element 5.0
double joined[] = concat(win, rev);
Print("[ARRAY] joined=" + ToString(length(joined)) + " fives=" + ToString(fives[0])
+ " total=" + ToString(sum(win)));
}Example: Donchian channel with highest() / lowest()
The rolling helpers return a whole array in one call, so an indicator can compute them once per calculate() and then read hh[i - 1] inside the usual Chart.resume_index loop.
// DOCS stdlib — Donchian channel from highest() / lowest(), breakout arrows, fill (price chart)
// Uses: highest(arr, n), lowest(arr, n), Chart.resume_index, series buffers, arrows, fill.
// Expect: red upper line = highest high of the previous period bars, green lower line =
// lowest low of the previous period bars, grey dashed middle, light blue fill between
// upper and lower; green up-arrow under a bar that closes above the upper line, red
// down-arrow over a bar that closes below the lower line.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: Donchian channel with highest / lowest";
}
struct Donchian {
double upper;
double middle;
double lower;
double buy_arrow;
double sell_arrow;
}
display {
outputs: 5
Donchian.upper { type: "line"; color: "#dc2626"; name: "Upper"; width: 1; };
Donchian.middle { type: "line"; color: "#9ca3af"; name: "Middle"; width: 1; style: "dashed"; };
Donchian.lower { type: "line"; color: "#16a34a"; name: "Lower"; width: 1; };
Donchian.buy_arrow { type: "arrow"; color: "#16a34a"; name: "Break Up"; width: 1; arrow_code: 233; };
Donchian.sell_arrow { type: "arrow"; color: "#dc2626"; name: "Break Down"; width: 1; arrow_code: 234; };
fill { buffer_a: 0; buffer_b: 2; color: "rgba(59,130,246,0.10)"; };
}
parameters {
int period = 20; // Channel Period
double arrow_gap = 50; // Arrow distance (points)
}
series double dc_up[];
series double dc_mid[];
series double dc_lo[];
series double dc_buy[];
series double dc_sell[];
calculate() {
double closes[] = close();
double highs[] = high();
double lows[] = low();
int len = length(closes);
dc_up[] = create_array(len);
dc_mid[] = create_array(len);
dc_lo[] = create_array(len);
dc_buy[] = create_array(len);
dc_sell[] = create_array(len);
// rolling extremes: hh[i] = highest high of bars i-period+1 .. i
double hh[] = highest(highs, period);
double ll[] = lowest(lows, period);
int start = Chart.resume_index;
if (start > 0) {
start = start - 1;
} else {
start = period; // reads hh[i - 1], valid from period - 1
}
double pt = Symbol.Point();
for (int i = start; i < len; i = i + 1) {
// channel of the PREVIOUS period bars, so the current bar can break it
dc_up[i] = hh[i - 1];
dc_lo[i] = ll[i - 1];
dc_mid[i] = (dc_up[i] + dc_lo[i]) / 2.0;
dc_buy[i] = 0.0;
dc_sell[i] = 0.0;
if (closes[i] > dc_up[i]) { dc_buy[i] = lows[i] - (arrow_gap * pt); }
if (closes[i] < dc_lo[i]) { dc_sell[i] = highs[i] + (arrow_gap * pt); }
}
return Donchian { upper: dc_up, middle: dc_mid, lower: dc_lo, buy_arrow: dc_buy, sell_arrow: dc_sell };
}String Functions
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
String.Length(text) | string text | int | Length of the text in bytes (= characters for plain ASCII text such as symbols and comments). |
String.Contains(text,sub) | string text, sub | bool | True if text contains sub (case-sensitive). |
String.StartsWith(text,prefix) | string text, prefix | bool | True if text starts with prefix (case-sensitive). Handy for draw.* name filters. |
String.EndsWith(text,suffix) | string text, suffix | bool | True if text ends with suffix (case-sensitive). |
String.Find(text,sub) | string text, sub | int | Position of the first sub in text (-1 if not found). |
String.Substring(text,start,len) | string text, int start, len | string | len characters starting at start (shorter if the text ends first). |
a + b | string a, b | string | Concatenation; use ToString(x) for numbers. |
a == b / a != b | string a, b | bool | Comparison, e.g. Position.Symbol() != Symbol(). |
// DOCS stdlib — String functions: reading a grid level out of a position comment. NO TRADING.
// Uses: String.Contains, String.Find, String.Length, String.Substring, ToInteger, ToString.
// Expect (Journal):
// - at start: [PARSE] [Grid L3] -> level 3 (a fixed demo comment, so you always see a line)
// - once per new bar, for every open position whose comment contains "Grid" (e.g. the
// positions of the grid basket example): [PARSE] #ticket [Grid L2] -> level 2
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: parsing a comment";
}
// Grid level from a comment like "Grid L3" (0 when there is none)
int GridLevel(string c) {
if (!String.Contains(c, "Grid")) { return 0; }
int at = String.Find(c, "L");
if (at < 0) { return 0; }
return ToInteger(String.Substring(c, at + 1, String.Length(c) - at - 1));
}
Init() {
string demo = "Grid L3";
Print("[PARSE] [" + demo + "] -> level " + ToString(GridLevel(demo)));
}
Tick() {
if (!Time.IsNewBar()) { return; }
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
string c = Position.Comment();
int level = GridLevel(c);
if (level > 0) {
Print("[PARSE] #" + ToString(Position.Ticket()) + " [" + c + "] -> level " + ToString(level));
}
}
}Logging & Alerts
Print and the Log.Info / Log.Warn / Log.Error calls all write one line to the strategy Journal — use your own tags ([ENTRY], [RISK] …) to tell them apart.
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
Print(msg) / Log.Print(msg) | string msg | void | Write to the strategy Journal. |
Log.Info(msg) | string msg | void | Journal line (info). |
Log.Warn(msg) | string msg | void | Journal line (warning). |
Log.Error(msg) | string msg | void | Journal line (error). |
Alert(msg) / Log.Alert(msg) | string msg | void | Alert in the terminal. |
Notify(msg) / Log.Notify(msg) | string msg | void | Push notification to the mobile app. |
Sound(file) / Log.Sound(file) | string file | void | Play a sound file. |
if (!Time.IsNewBar()) { return; }, a Timer() block, or only when something changes.// DOCS stdlib — Logging: Print / Log.Info / Log.Warn / Log.Error and a live-only Notify. NO TRADING.
// Uses: Print, Log.Info, Log.Warn, Log.Error, Notify, Env.IsLive, Account.Balance / Equity.
// Expect (Journal):
// - [INIT] once, then once per new bar: "[DD] drawdown=..%" (0.00000 with no open trades).
// - "Drawdown: ..%" warning lines only while floating drawdown is above warn_pct;
// a push notification only live and above alert_pct.
// - [EXIT] when you remove the strategy.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: logging";
}
parameters {
double warn_pct = 5.0; // Warn above (% drawdown)
double alert_pct = 10.0; // Notify above (% drawdown, live only)
}
Init() {
Print("[INIT] Strategy started on " + Symbol());
Log.Info("balance " + ToString(Account.Balance()) + " " + Account.Currency());
}
Tick() {
if (!Time.IsNewBar()) { return; }
double bal = Account.Balance();
if (bal <= 0.0) { Log.Error("no balance"); return; }
double dd = (bal - Account.Equity()) / bal * 100.0;
Print("[DD] drawdown=" + ToString(dd) + "%");
if (dd > warn_pct) { Log.Warn("Drawdown: " + ToString(dd) + "%"); }
if (Env.IsLive() && dd > alert_pct) { Notify("Drawdown alert: " + ToString(dd) + "%"); }
}
Exit() {
Print("[EXIT] stopped on " + Symbol());
}Type Conversions
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
ToString(val) | any val | string | Plain conversion, no rounding: double → as it is and always with a decimal point (1.2345 → "1.2345", 2.0 → "2.0"), int / enum → plain number, bool → "true"/"false", datetime → "HH:MM:SS" (UTC time of day), string → unchanged. |
ToDouble(text) | string text | double | Parse a string to double (0 on failure). |
ToDouble(x, digits) | double x, int digits | double | Round x to digits decimals (0..10): ToDouble(1234.5678, 2) = 1234.57 (never -0). ToString(ToDouble(x, 2)) shows exactly 2 decimals: 1234.1 → "1234.10", 0 → "0.00". Stored in a variable first, the value prints as a plain double ("1234.1"). |
ToInteger(text) | string text | int | Parse a whole number (0 on failure, also for "1.5"). |
ToTime(text) | string text | datetime | Parse a number of milliseconds written as text, e.g. "1700000000000" (0 on failure). |
double d = i; | — | double | An int assigned to a double converts; datetimes are numbers of ms and mix with ints in arithmetic. |
// DOCS stdlib — Type conversions. NO TRADING.
// Uses: ToString (double / int / bool / datetime), ToDouble (parse + round), ToInteger, ToTime,
// datetime maths.
// Expect (Journal) once at start:
// [CONV] lot=Lot=0.1 bt=false (true in the tester) now=HH:MM:SS later=HH:MM:SS (+1 min)
// [CONV] v=1.2345 r=1.23 n=42 bad=0 t=00:00:00 (ToTime("0"))
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs stdlib: conversions";
}
Init() {
string s = "Lot=" + ToString(0.1); // "Lot=0.1" (plain: no rounding, no padding)
string b = ToString(Env.IsBacktest()); // "true" / "false"
string t = ToString(Time.Now()); // e.g. "14:05:31" (UTC)
datetime later = Time.Now() + 60 * 1000; // datetimes are milliseconds
Print("[CONV] lot=" + s + " bt=" + b + " now=" + t + " later=" + ToString(later));
double v = ToDouble("1.2345"); // 1.2345 (parse)
double r = ToDouble(v, 2); // 1.23 (round to 2 decimals)
int n = ToInteger("42"); // 42
int bad = ToInteger("abc"); // 0
datetime t0 = ToTime("0"); // milliseconds as text -> 0 = 00:00:00
Print("[CONV] v=" + ToString(v) + " r=" + ToString(r) + " n=" + ToString(n) + " bad=" + ToString(bad) + " t=" + ToString(t0));
}
Tick() {
}Orchestration Functions
These wire up sub-indicators inside Init(). Proxies work only in strategies (files with a Tick() function), not in indicator files. Each proxy has a Name.calculate() block that declares its buffers, fills or fetches them and returns a struct; Tick() reads Name.field(0) (current bar), Name.field(1) (previous bar) …. In proxy blocks, fetch targets and returned buffers are series double (they keep history between ticks) with a unique name, sized with create_array(len) — int len = candle_count(); series double rsi_val[]; rsi_val[] = create_array(len); Native.Fetch(0, rsi_val);. Full scripts are on the Native Indicators page.
| Function / Property | Parameters | Returns | Description |
|---|---|---|---|
Load(proxyName) | identifier | void | Activate a proxy computed by its own Name.calculate() block (your maths, no engine). |
Native.Source(i.Name) | indicator alias | void | Select a native indicator engine (see Native Indicators). |
Native.Init(sym, tf) | string sym, timeframe tf | void | Symbol and timeframe for the engine: Native.Init(Symbol(), Timeframe) = the chart; Native.Init(Symbol(), Timeframe.H4) another timeframe; Native.Init("EURUSD.r", Timeframe.H1) another symbol. A string timeframe is a compile error. |
Native.Parameter(…) | variadic | void | Pass positional parameters to the native engine. |
Native.Bind(proxyName) | identifier | void | Bind the configured native engine to a proxy name. |
Native.Fetch(index, buf) | int idx, double[] | void | Copy native output buffer at index into buf (a series double buffer: full history on the first run, then only the newest value). |
Custom.Source("file") | string path | void | Load an external compiled indicator (.tbc) as a source. |
Custom.Init(sym, tf) | sym, tf | void | Context for the external script — chart symbol only for now (another symbol is not supported yet). |
Custom.Parameter(…) | positional | void | Pass positional parameters to the external script. |
Custom.Bind(proxyName) | identifier | void | Bind external script output to a proxy name. |
Custom.Fetch(index, buf) | int idx, double[] | void | Copy external script output buffer into buf (a series double buffer: full history on the first run, then only the newest value). |
Chart.resume_index | — | int | Index of first bar needing recalculation. 0 on first run. |