Docs / Market Data

Market Data

Direct access to price history (of the chart, and of any other symbol and timeframe), symbol specifications, account state, execution environment flags, and time primitives — all through clean namespace APIs.


OHLCVT Price Data

Called without arguments → the chart's full price array (index 0 = oldest bar, length - 1 = latest). Called with an integer → single value n bars ago (0 = current bar, 1 = previous bar). Called with (symbol, timeframe, shift) → one value of another series (see Other Symbols & Timeframes). The same rule holds for your own arrays and proxy fields: arr(0) / Proxy.field(0) count back from the newest bar, while arr[i] is an absolute index (never below 0 or at/after the length). Datetimes are milliseconds.

Function / PropertyParametersReturnsDescription
close()—double[]Full close price array of the chart symbol/timeframe.
close(n)int ndoubleClose n bars ago: 0 = current, 1 = previous bar.
close(sym, tf, n)string sym, timeframe tf, int ndoubleClose of bar n of another series: 0 = that series’ newest bar. NaN when the bar does not exist (yet).
open() / open(n) / open(sym, tf, n)— / int n / sym, tf, ndouble[] / doubleOpen prices.
high() / high(n) / high(sym, tf, n)— / int n / sym, tf, ndouble[] / doubleHigh prices.
low() / low(n) / low(sym, tf, n)— / int n / sym, tf, ndouble[] / doubleLow prices.
volume() / volume(n) / volume(sym, tf, n)— / int n / sym, tf, ndouble[] / doubleTick volume.
time() / time(n)— / int ndatetime[] / datetimeBar open time (ms). Store the array as datetime times[] = time();
open_at(n), high_at(n), low_at(n), close_at(n), volume_at(n), time_at(n)int ndouble / datetimeValue n bars back from the newest bar (0 = current), same as close(n).
hl2()—double[](High + Low) / 2 array.
hlc3()—double[](High + Low + Close) / 3 array.
ohlc4()—double[](Open + High + Low + Close) / 4 array.
tr()—double[]True Range array (bar 0 = high − low).
bars() / candle_count()—intNumber of candles on the chart (= length(close())).
Chart.resume_index—intFirst bar that needs calculation: 0 on the first run, then the first new / changed bar.
Symbol()—stringChart symbol (always called as Symbol()).
TimeframevaluetimeframeThe chart’s own timeframe, e.g. Native.Init(Symbol(), Timeframe). See Timeframes below.
length(arr)double[] arrintNumber of elements in any array.

Point size and digits are read with Symbol.Point() and Symbol.Digits(). Point, Digits, close, high, low, open, volume, time, symbol and timeframe are built-in names: a variable or parameter with one of these names is a compile error.


Timeframes

A timeframe is a typed value, never a string. Write it as Timeframe.H4 or bare H4; bare Timeframe is the chart's own timeframe. Passing a string such as "H4" where a timeframe is expected is a compile error.

Function / PropertyReturnsDescription
TimeframetimeframeThe chart’s timeframe (whatever the script runs on).
Timeframe.M1 · M5 · M15 · M30timeframeMinute series.
Timeframe.H1 · H4timeframeHour series.
Timeframe.D1timeframeDaily series.
Timeframe.W1timeframeWeekly series, the week starts Sunday 00:00 UTC.
Timeframe.MNtimeframeMonthly series = calendar month (UTC).

All bars follow one bucket rule: M1 … D1 are fixed-length buckets counted from the UTC M1 timestamps (an H4 bar opens at 00:00, 04:00, 08:00 … UTC, a D1 bar at 00:00 UTC), W1 starts Sunday 00:00 UTC and MN is the calendar month. The chart, the native engines, close(sym, tf, n) and the tester all build bars with this rule, so a value read from another series lines up with the chart of that series.

Note
The compiler also knows the names M2, M3, M4, M6, M8, M10, M12, M20, H2, H3, H6, H8, H12, D2–D5, W2, W3 and MO2–MO6, but the bar series are built for the timeframes listed in the table above — use those for close(sym, tf, n), Bars.* and Native.Init.

Other Symbols & Timeframes

The array forms (close(), time() …) and close(n) always read the chart. Any other symbol and/or timeframe is read one bar at a time with close(symbol, timeframe, shift) and its siblings, and the Bars.* functions tell you which shift belongs to a given time. Quotes and specifications of another symbol come from Symbol.*(symbol), and a native indicator on another symbol/timeframe is bound with Native.Init(symbol, Timeframe.H1) (see Native Indicators).

Bars.* & close(sym, tf, n)

Function / PropertyParametersReturnsDescription
close / open / high / low / volume(sym, tf, n)string sym, timeframe tf, int ndoubleValue of bar n of that series, 0 = its newest (still forming) bar, 1 = its last closed bar. NaN if there is no such bar.
Bars.Shift(sym, tf, t)string sym, timeframe tf, datetime tintShift of that series’ bar containing time t (ms) — the last bar opening at or before t. -1 when t is before its history or nothing is loaded yet.
Bars.Count(sym, tf)string sym, timeframe tfintNumber of bars the series has (0 while it is still loading).

Typical patterns, with s a symbol and t a chart bar time (e.g. times[i] from datetime times[] = time();):

Function / PropertyDescription
close(s, Timeframe, Bars.Shift(s, Timeframe, t))Symbol s on the chart’s timeframe, at the same time as chart bar t.
close(s, Timeframe.D1, Bars.Shift(s, Timeframe.D1, t) + 1)Previous daily close as of time t (shift + 1 = the bar before the one containing t).
close(s, Timeframe.H4, Bars.Shift(s, Timeframe.H4, t) + 1)Last H4 close that was already final at time t — no look-ahead into the forming H4 bar.
high(Symbol(), Timeframe.D1, 1)Yesterday’s high of the chart symbol (in Tick()).
Symbol.Bid(s)The live price of s (the newest value of its forming bar).
Tip
Always guard the shift: int d = Bars.Shift(s, Timeframe.D1, t); if (d < 0) { return 0.0; } (or continue; inside a loop). On the first run another symbol's history may not have arrived yet, so Bars.Shift returns -1 and Bars.Count returns 0 for a moment.

Loading & Limits

Automatic loading. The first time a script reads another symbol, its history is pulled in the background (about 500 bars of the requested timeframe) and kept updated live. The symbol is added to Market Watch while the script runs and removed again afterwards (unless it was there before). It counts toward your plan's symbol limit.

Native indicators on another symbol work: Native.Init(other, Timeframe.H1). Custom proxies (Custom.Init) on another symbol are not supported yet.

Warning
The backtester replays only the chart symbol. Higher timeframes of the chart symbol work in the tester (e.g. high(Symbol(), Timeframe.D1, 1), built from the simulated bars, no look-ahead), but another symbol has no data in the tester yet: its values read NaN, Bars.Shift -1 and Bars.Count 0.

Example: previous-day levels on any chart

A Load() proxy maps every chart bar to the D1 bar that contains it and draws the day before's high, low and close. Tick() reads the same values directly with shift 1.

Previous-day high / low / close (strategy)TDSL
// DOCS market-data — Previous-day high / low / close drawn on any intraday chart. NO TRADING.
// Uses: high / low / close(symbol, Timeframe.D1, shift), Bars.Shift, Bars.Count.
// Run it on an intraday chart (M5 .. H1).
// Expect:
//   - Three stepped lines on the price chart: red = previous day's high, green = previous
//     day's low, grey dashed = previous day's close. They step once per day (00:00 UTC).
//   - Journal once per new bar: [PREV-DAY] d1_bars=.. high=.. low=.. close=..
//     equal to bar 1 of the same symbol's D1 chart. While the D1 history is still
//     loading: [PREV-DAY] D1 history still loading.
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs market-data: previous-day levels from the D1 series";
}

struct DayLevels { double hi; double lo; double cl; }

display {
    outputs: 3
    Prev.hi { type: "line"; color: "#dc2626"; name: "Prev High";  width: 1; };
    Prev.lo { type: "line"; color: "#16a34a"; name: "Prev Low";   width: 1; };
    Prev.cl { type: "line"; color: "#9ca3af"; name: "Prev Close"; width: 1; style: "dashed"; };
}

Init() {
    Load(Prev);
    Print("[INIT] previous-day levels on " + Symbol());
}

Prev.calculate() {
    datetime times[] = time();
    int len = length(times);
    string s = Symbol();
    series double pd_hi[] = create_array(len);
    series double pd_lo[] = create_array(len);
    series double pd_cl[] = create_array(len);

    // Only the new / changed bars after the first run
    int start = Chart.resume_index;
    if (start > 0) { start = start - 1; }

    for (int i = start; i < len; i = i + 1) {
        int d = Bars.Shift(s, Timeframe.D1, times[i]);   // D1 bar containing chart bar i
        if (d < 0) { continue; }                          // before the D1 history / not loaded yet
        pd_hi[i] = high(s, Timeframe.D1, d + 1);          // d + 1 = the day before
        pd_lo[i] = low(s, Timeframe.D1, d + 1);
        pd_cl[i] = close(s, Timeframe.D1, d + 1);
    }
    return DayLevels { hi: pd_hi, lo: pd_lo, cl: pd_cl };
}

Tick() {
    if (!Time.IsNewBar()) { return; }
    string s = Symbol();
    int n = Bars.Count(s, Timeframe.D1);
    if (n < 2) {
        Print("[PREV-DAY] D1 history still loading");
        return;
    }
    Print("[PREV-DAY] d1_bars=" + ToString(n) + " high=" + ToString(high(s, Timeframe.D1, 1))
        + " low=" + ToString(low(s, Timeframe.D1, 1)) + " close=" + ToString(close(s, Timeframe.D1, 1)));
}

Example: another symbol's H4 close

The same mapping with another symbol and timeframe. Using k + 1 draws the last completed H4 close at each chart bar, so the history shows what was actually known at that time.

Other symbol H4 series on this chart (strategy)TDSL
// DOCS market-data — Another symbol's H4 closes mapped onto this chart. NO TRADING.
// Uses: close(symbol, Timeframe.H4, shift), Bars.Shift, Bars.Count, Symbol.Bid / Spread / Digits(symbol).
// Run it on a chart of a DIFFERENT symbol (e.g. XAUUSD.r M15).
// Expect:
//   - EURUSD.r appears in Market Watch while the strategy runs (if it wasn't there).
//   - A separate window with a stepped blue line: the close of the last COMPLETED EURUSD.r H4
//     bar at every chart bar (it steps every 4 hours, no look-ahead into the forming H4 bar).
//   - Journal once per new chart bar: [OTHER] EURUSD.r h4_bars=.. last_closed=.. forming=..
//     bid=.. spread=.. digits=..  (EURUSD prices, not the chart symbol's; forming moves with the bid).
//   - First run: the line may start empty and fill in once the EURUSD.r history has arrived.
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs market-data: other symbol H4 series on this chart";
}

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

struct OtherLine { double value; }

display {
    separate_window: true;
    outputs: 1
    Other.value { type: "line"; color: "#3b82f6"; name: "Other H4 close"; width: 2; };
}

Init() {
    Load(Other);
    Print("[INIT] " + Symbol() + " following " + other + " H4");
}

Other.calculate() {
    datetime times[] = time();
    int len = length(times);
    series double oh4_val[] = create_array(len);

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

    for (int i = start; i < len; i = i + 1) {
        int k = Bars.Shift(other, Timeframe.H4, times[i]);   // H4 bar containing chart bar i
        if (k < 0) { continue; }                              // no H4 data for that time (yet)
        oh4_val[i] = close(other, Timeframe.H4, k + 1);       // last H4 bar closed before it
    }
    return OtherLine { value: oh4_val };
}

Tick() {
    if (!Time.IsNewBar()) { return; }
    int n = Bars.Count(other, Timeframe.H4);
    if (n == 0) {
        Print("[OTHER] " + other + " H4 still loading");
        return;
    }
    Print("[OTHER] " + other + " h4_bars=" + ToString(n)
        + " last_closed=" + ToString(close(other, Timeframe.H4, 1))
        + " forming=" + ToString(close(other, Timeframe.H4, 0))
        + " bid=" + ToString(Symbol.Bid(other))
        + " spread=" + ToString(Symbol.Spread(other))
        + " digits=" + ToString(Symbol.Digits(other)));
}

Example: previous-day range breakout

Yesterday's high and low as breakout levels, one trade per day, inside the London / New York sessions. Because it only reads a higher timeframe of the chart symbol, it also runs in the tester.

Daily range breakout (strategy)TDSL
// DOCS market-data — Previous-day range breakout: one trade per day, levels from the D1 series.
// Uses: high / low(symbol, Timeframe.D1, 1), Bars.Count, Time.Day, Time.InSession, Symbol.*.
// Run it on an intraday chart (M5 .. M30). Works in the tester too (same symbol, higher timeframe).
// Expect:
//   - At most one position per day, magic 7301: a BUY when the ask breaks above yesterday's
//     high + buffer, a SELL when the bid breaks below yesterday's low - buffer, only inside
//     the London or New York session.
//   - SL in the middle of yesterday's range, TP = rr x the risk. Comment "PDH break" / "PDL break".
//   - Journal: [ENTRY] lines with the levels; "[ENTRY] refused (<code>): <reason>" if refused.
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs market-data: previous-day range breakout";
}

parameters {
    int    Magic      = 7301;   // Magic Number
    double Lot        = 0.1;    // Lot Size
    int    buffer_pts = 20;     // Breakout buffer (points)
    double rr         = 1.5;    // Take profit / risk
}

state {
    int traded_day = 0;
}

Init() {
    Print("[INIT] daily breakout on " + Symbol() + " magic=" + ToString(Magic));
}

Tick() {
    string s = Symbol();
    if (Bars.Count(s, Timeframe.D1) < 2) { return; }          // D1 history not here yet
    if (Time.Day() == traded_day) { return; }                  // one trade per day
    if (!Time.InSession("London") && !Time.InSession("NewYork")) { return; }
    if (Position.Exists(s, Magic)) { return; }

    double pt = Symbol.Point();
    double ph = high(s, Timeframe.D1, 1);                      // yesterday's high
    double pl = low(s, Timeframe.D1, 1);                       // yesterday's low
    if (ph <= 0.0 || pl <= 0.0) { return; }
    double mid = (ph + pl) / 2.0;
    double ask = Symbol.Ask();
    double bid = Symbol.Bid();
    int t = 0;

    if (ask > ph + buffer_pts * pt) {
        double sl = Symbol.NormalizePrice(mid);
        double tp = Symbol.NormalizePrice(ask + (ask - mid) * rr);
        Print("[ENTRY] BUY above " + ToString(ph) + " sl=" + ToString(sl) + " tp=" + ToString(tp));
        t = Trade.Buy(s, Lot, sl, tp, "PDH break", Magic);
        traded_day = Time.Day();
    } else if (bid < pl - buffer_pts * pt) {
        double sl2 = Symbol.NormalizePrice(mid);
        double tp2 = Symbol.NormalizePrice(bid - (mid - bid) * rr);
        Print("[ENTRY] SELL below " + ToString(pl) + " sl=" + ToString(sl2) + " tp=" + ToString(tp2));
        t = Trade.Sell(s, Lot, sl2, tp2, "PDL break", Magic);
        traded_day = Time.Day();
    }
    if (t < 0) { Print("[ENTRY] refused (" + ToString(Trade.LastError()) + "): " + Trade.LastErrorText()); }
}

Symbol.*

sym is optional everywhere and defaults to the chart symbol: Symbol.Bid() is the chart's bid, Symbol.Bid("EURUSD.r") another symbol's. Specification values come from the broker's symbol configuration. Values the broker does not send yet read 0: PipDigits, Status, MarginRate, PriceMin / PriceMax / PriceStep.

Function / PropertyReturnsDescription
Symbol()stringCurrent chart symbol name (e.g. "EURUSD.r").
Symbol.Bid(sym?)doubleCurrent bid price.
Symbol.Ask(sym?)doubleCurrent ask price.
Symbol.Last(sym?)doubleLast traded price.
Symbol.Mid(sym?)double(Bid + Ask) / 2.
Symbol.Spread(sym?)doubleCurrent spread.
Symbol.Point(sym?)doublePoint size (smallest price unit).
Symbol.Digits(sym?)intDecimal places in price.
Symbol.Precision(sym?)intPrice precision.
Symbol.PipDigits(sym?)intDecimal places for pips (reads 0 for now).
Symbol.StopsLevel(sym?)intMinimum SL/TP distance from the price, in points.
Symbol.FreezeLevel(sym?)intFreeze distance in points.
Symbol.TickSize(sym?)doubleMinimum price change.
Symbol.TickValue(sym?)doubleValue of one tick per lot in deposit currency.
Symbol.ContractSize(sym?)doubleUnits per lot.
Symbol.LotMin(sym?)doubleMinimum lot size.
Symbol.LotMax(sym?)doubleMaximum lot size.
Symbol.LotStep(sym?)doubleLot increment step.
Symbol.MarginRate(sym?)doubleMargin rate (reads 0 for now).
Symbol.MarginInitial(sym?)doubleInitial margin.
Symbol.MarginMaintenance(sym?)doubleMaintenance margin.
Symbol.MarginHedged(sym?)doubleHedged margin.
Symbol.SwapLong(sym?) / SwapShort(sym?)doubleSwap for long / short positions.
Symbol.TripleSwapDay(sym?)intDay of the triple swap.
Symbol.PriceMin / PriceMax / PriceStep(sym?)doublePrice limits and step (read 0 for now).
Symbol.ExecutionMode / TradeMode / ExpirationMode(sym?)intExecution, trade and expiration modes.
Symbol.StartSession / EndSession(sym?, day?, index?)intTrade session `index` (default 0) on weekday `day` (0 = Sunday … 6 = Saturday): start / end as seconds since midnight. 0 when the broker sends no session data.
Symbol.Base / Quote / Basis(sym?)stringBase and quote currency, basis.
Symbol.Exchange / Description(sym?)stringExchange and description.
Symbol.Class(sym?)intInstrument class.
Symbol.Status(sym?)intInstrument status (reads 0 for now).
Symbol.TickCount()intNumber of ticks received (chart symbol, no argument).
Symbol.NormalizePrice(px, sym?)doubleRound a price to the symbol’s digits.
Symbol.NormalizeVolume(vol, sym?)doubleRound a lot size to LotStep within LotMin/LotMax.
Symbol.Format(px, sym?)stringPrice as text with the symbol’s digits.
Symbol.ToLots(risk, sl, sym?)doubleLot size for a risk amount and SL distance.
Symbol.ToPips(diff, sym?)doublePrice difference → pips.
Symbol.ToPrice(pips, sym?)doublePips → price difference.
Symbol.ToCurrency(pips, vol, sym?)doubleValue of pips for a volume in deposit currency.
Symbol.CanTrade(vol, sym?)boolTrue if the volume can be traded right now.

Account.*

Function / PropertyReturnsDescription
Account.Balance()doubleAccount balance.
Account.Equity()doubleBalance + floating P&L (live, every tick).
Account.Profit()doubleFloating profit/loss of all open positions at the current prices (live, every tick: the same value as the positions panel).
Account.Margin()doubleUsed margin.
Account.FreeMargin()doubleAvailable free margin.
Account.Level()doubleMargin level percentage.
Account.Credit()doubleCredit.
Account.CallLevel()doubleMargin call level.
Account.StopOutLevel()doubleStop-out level.
Account.Number()intAccount login number.
Account.Leverage()intAccount leverage.
Account.Type()intAccount type.
Account.MaxOrders()intMaximum number of orders.
Account.Name()stringAccount owner name.
Account.Currency()stringDeposit currency (e.g. "USD").
Account.Company()stringBroker company.
Account.Server()stringTrading server name.
Account.SessionID()stringSession id.
Account.Hedging()boolTrue if hedging is allowed.
Account.FIFO()boolTrue if FIFO closing is enforced.
Account.IsConnected()boolNetwork connectivity status.

Env.*

Function / PropertyReturnsDescription
Env.IsBacktest() / Env.IsTesting()boolRunning in the strategy tester.
Env.IsLive()boolRunning against a live broker feed.
Env.IsOptimize() / Env.IsOptimization()boolRunning during parameter optimisation.
Env.IsVisualMode()boolTester running in visual mode.
Env.Connected()boolConnected to the broker.
Env.Latency()intConnection latency.
Env.LastHeartbeat()datetimeTime of the last heartbeat.

Time.*

Times are in milliseconds. Live, the clock is the broker's running clock (not the PC clock); in the tester it is the simulated clock, so the same script behaves the same in both. Time.Now(), Time.Server(), Time.UTC() and Time.Local() all return this same clock. Date and time parts, sessions and InRange use UTC hours. Sessions: Sydney, Tokyo/Asia, London/Europe, NewYork/NY/US.

Function / PropertyReturnsDescription
Time.Now() / Server() / UTC() / Local()datetimeCurrent time (ms): broker clock live, simulated clock in the tester.
Time.Year() / Month() / Day()intCurrent date parts.
Time.Hour() / Minute() / Second()intCurrent time parts (hour 0–23).
Time.DayOfWeek()int0=Sunday … 6=Saturday.
Time.BarOpen()datetimeOpen time of the current bar (ms).
Time.BarClose()datetimeClose time of the current bar (open + chart timeframe).
Time.ToNextBar()intSeconds until the current bar closes.
Time.SinceBarOpen()intSeconds since the current bar opened.
Time.IsNewBar()boolTrue on the first tick of a new chart bar.
Time.InSession(name)boolTrue if the time is inside the named session.
Time.SessionStart(name)datetimeStart of the named session today.
Time.SessionEnd(name)datetimeEnd of the named session today.
Time.InRange(from,to)boolTrue if the time is within the "HH:MM" range.
Session filter (strategy)TDSL
// DOCS market-data — Session / time-window filter with the Time.* clock. NO TRADING.
// Uses: Time.IsNewBar, Time.InSession, Time.InRange, Time.ToNextBar, Time.SinceBarOpen,
//       Time.Hour / Minute / DayOfWeek, Time.Now, Time.BarOpen, Time.BarClose.
// Expect (Journal), once per new bar:
//   - [SESSION] <HH:MM:SS> day=<0..6> london=true/false newyork=true/false
//   - then either "[SESSION] skip: ..." (outside London / New York, inside 16:30-17:00, or
//     less than 10 s to the bar close) or "[SESSION] would trade, bar <open> -> <close>".
//   Times are the broker clock live, the simulated clock in the tester.
about {
    author: "CoreXTrader";
    version: "1.0.0";
    about: "Docs market-data: session filter";
}

Init() {
    Print("[INIT] session filter on " + Symbol() + " broker time " + ToString(Time.Now()));
}

Tick() {
    if (!Time.IsNewBar()) { return; }
    bool london = Time.InSession("London");
    bool newyork = Time.InSession("NewYork");
    Print("[SESSION] " + ToString(Time.Now()) + " day=" + ToString(Time.DayOfWeek())
        + " london=" + ToString(london) + " newyork=" + ToString(newyork));

    if (!london && !newyork) { Print("[SESSION] skip: outside London / New York"); return; }
    if (Time.InRange("16:30", "17:00")) { Print("[SESSION] skip: 16:30-17:00 window"); return; }
    if (Time.ToNextBar() < 10) { Print("[SESSION] skip: bar closes in " + ToString(Time.ToNextBar()) + " s"); return; }

    Print("[SESSION] would trade at " + ToString(Time.Hour()) + ":" + ToString(Time.Minute())
        + ", bar " + ToString(Time.BarOpen()) + " -> " + ToString(Time.BarClose())
        + ", " + ToString(Time.SinceBarOpen()) + " s since open");
}