Strategies
A Strategy script (a file with a Tick() block) runs on every live price tick with full access to the trade execution API, position management, trade events, a timer, other symbols and timeframes, and sub-indicators calculated in real time.
Every complete script on this page is a working file: each one carries a header comment saying what it shows and what to expect on the chart and in the Journal, and its own magic number, so you can run several side by side and tell their positions apart.
How Strategies Work
Global variables (static declarations and the state { } block) keep their values between ticks and across helper-function calls. Proxies (Load(name), Native.*, Custom.*) work only in strategies; read their outputs with Name.field(shift) (0 = current bar, 1 = last closed bar).
Lifecycle Blocks
A strategy is built from up to six blocks, written like Init() { } — no return type, no void. Only Tick() is required.
| Function / Property | Description |
|---|---|
Init() { } | Once when the strategy loads (and again when its parameters change). Bind proxies, reset state, call Timer.Set(). |
Tick() { } | Every price tick of the chart symbol (live) or every simulated tick (tester). Entries, exits, trailing. |
Trade() { } | Once per trade event (open, close, modify, pending placed / filled / cancelled / expired, rejection), before the next Tick(). Read the event with Event.*. |
Timer() { } | Every Timer.Set(seconds). Live it runs on the broker clock in its own loop and fires without ticks (a quiet market still gets its calls). In the tester each due call runs at its own scheduled simulated time, with Time.Now() = that time. |
ChartEvent() { } | Once per chart mouse event (an editable draw.* object dragged or clicked, or a click on empty chart), on the next tick, live only. See Drawing Objects. |
Exit() { } | Once when the strategy is removed or a backtest ends. Kill the timer, print a final report, delete the draw.* objects you don't want left on the chart. |
Timer.Set(seconds) starts or changes the period (called inside Timer() it re-anchors on that call's time); Timer.Kill() stops it. See strategy G below and the Trade Language page for the full Event.* reference.Compiler Rules
The compiler checks strategies before they run. The errors you will meet most often:
| Function / Property | Description |
|---|---|
Reserved built-in names | A user function cannot be named like a built-in — names match case-insensitively, so void Open() is an error (open() is a built-in). The same goes for variables: Point, close, time … cannot be variable names. |
Argument counts | Calls to your own functions are checked: every parameter without a default must be passed, and never more than the function takes ("Name takes N arguments (a, b), M given"). |
Unknown members | A misspelled API member (Position.Proft()) is a compile error with a "did you mean" suggestion. |
Typed timeframes | Timeframes are values, never strings: Timeframe.H4, H4, or bare Timeframe (the chart's). "H4" in quotes is rejected. |
int and double | Convert an int to a double variable before mixing it with a decimal literal: double n = longs; Lot * (1.0 + n). |
Timeframes & Other Symbols
A strategy can read other timeframes and other symbols next to its chart:
| Function / Property | Description |
|---|---|
Native.Init(Symbol(), Timeframe.H4) | Bind a native engine to another timeframe of the chart symbol (strategy E). |
Native.Init(other, Timeframe.H1) | Bind a native engine to another symbol. The symbol is kept in Market Watch while the strategy runs. |
close(sym, tf, shift) | Also open / high / low / volume / time(sym, tf, shift): a bar of another symbol / timeframe. |
Bars.Shift(sym, tf, time) | Shift of the bar of that series containing time (-1 = none yet). Maps a chart bar to the other series. |
Bars.Count(sym, tf) | Number of bars the series has (0 = still loading). |
Symbol.Bid(sym) / Symbol.Ask(sym) | Live quote of another symbol. Every Symbol.* getter takes an optional symbol. |
Custom.Init on another symbol is not supported yet. Buffers from another timeframe are drawn one value per chart bar (stepped drawing comes later — the values are right).Strategy A — Internal Math
All indicator logic written in a proxy .calculate() block activated with Load(). Bollinger Bands mean-reversion grid with progressive lot scaling, per-side exits and a trailing stop that only touches its own magic number.
// DOCS strategies — Strategy A: internal math (Load proxy) + grid scaling + trailing stop
// Shows: Bollinger Bands computed in a Load() proxy, progressive lots, CloseAll by side + magic,
// trailing stop on our own positions only.
// Expect: three bands on the price chart with two fills. A BUY each tick the ask is below the
// lower band (up to MaxEntries legs, lots 0.01, 0.02, 0.03 ...), a SELL above the upper band.
// Longs close when the bid is back above the middle band, shorts when the ask is below it.
// Positions carry magic 7101 and comment "PowerScaler". Refusals: "Buy rejected: ..." in the Journal.
about {
author: "CoreXTrader";
version: "1.2.0";
about: "Docs: Strategy A - internal math grid";
}
parameters {
int Magic = 7101; // Magic Number
int period = 20; // Bands Period
double multiplier = 2.0; // Deviation
double Lot = 0.01; // First Lot
int MaxEntries = 5; // Max Legs per Side
int TrailStart = 200; // Trailing Start (points)
int TrailStep = 50; // Trailing Distance (points)
}
struct BandLines { double upper; double middle; double lower; }
display {
outputs: 3
Bands.upper { type: "line"; color: "#c42626ff"; name: "Upper Band"; width: 1; };
Bands.middle { type: "line"; color: "#b0aaaaff"; name: "Middle Band"; width: 0.5; };
Bands.lower { type: "line"; color: "#50c426ff"; name: "Lower Band"; width: 1; };
fill { buffer_a: 0; buffer_b: 1; color: "rgba(19, 75, 228, 0.25)"; };
fill { buffer_a: 1; buffer_b: 2; color: "rgba(0, 189, 31, 0.25)"; };
}
Init() {
Load(Bands);
Print("[INIT] PowerScaler " + Symbol() + " magic=" + ToString(Magic));
}
Bands.calculate() {
double closes[] = close();
int len = length(closes);
series double ps_up[] = create_array(len); // proxy buffers keep history between ticks
series double ps_mid[] = create_array(len);
series double ps_lo[] = create_array(len);
int start = Chart.resume_index; // only new / changed bars after the first run
if (start == 0) { start = period - 1; }
for (int i = start; i < len; i = i + 1) {
double sum = 0.0;
for (int j = 0; j < period; j = j + 1) { sum = sum + closes[i - j]; }
double mean = sum / period;
ps_mid[i] = mean;
double sq = 0.0;
for (int j = 0; j < period; j = j + 1) {
double d = closes[i - j] - mean;
sq = sq + (d * d);
}
double sd = Math.Sqrt(sq / period);
ps_up[i] = mean + (multiplier * sd);
ps_lo[i] = mean - (multiplier * sd);
}
return BandLines { upper: ps_up, middle: ps_mid, lower: ps_lo };
}
// Our legs of one side on this chart's symbol
int Legs(int side) {
return Position.Count(Symbol(), Magic, side);
}
void Trail() {
string sym = Symbol();
double pt = Symbol.Point();
double bid = Symbol.Bid();
double ask = Symbol.Ask();
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Symbol() != sym || Position.Magic() != Magic) { continue; }
double sl = Position.SL();
if (Position.Direction() == Side.Long) {
if (bid - Position.OpenPrice() > TrailStart * pt) {
double new_sl = Symbol.NormalizePrice(bid - TrailStep * pt);
if (new_sl > sl) { Trade.Modify(Position.Ticket(), sym, new_sl, -1.0); } // -1 = keep TP
}
} else {
if (Position.OpenPrice() - ask > TrailStart * pt) {
double new_sl = Symbol.NormalizePrice(ask + TrailStep * pt);
if (sl == 0.0 || new_sl < sl) { Trade.Modify(Position.Ticket(), sym, new_sl, -1.0); }
}
}
}
}
Tick() {
string sym = Symbol();
double bid = Symbol.Bid();
double ask = Symbol.Ask();
int longs = Legs(Side.Long);
int shorts = Legs(Side.Short);
// 1. Progressive lots: 0.01, 0.02, 0.03 ... (int -> double before mixing with 1.0)
double n_long = longs;
double n_short = shorts;
double lot_long = Symbol.NormalizeVolume(Lot * (1.0 + n_long));
double lot_short = Symbol.NormalizeVolume(Lot * (1.0 + n_short));
if (ask < Bands.lower(0) && longs < MaxEntries) {
int t = Trade.Buy(sym, lot_long, 0, 0, "PowerScaler", Magic);
if (t < 0) { Print("Buy rejected: " + Trade.LastErrorText()); }
}
if (bid > Bands.upper(0) && shorts < MaxEntries) {
int t = Trade.Sell(sym, lot_short, 0, 0, "PowerScaler", Magic);
if (t < 0) { Print("Sell rejected: " + Trade.LastErrorText()); }
}
// 2. Exit at the middle band, per side
if (bid > Bands.middle(0) && longs > 0) { Trade.CloseAll(sym, Side.Long, Magic); }
if (ask < Bands.middle(0) && shorts > 0) { Trade.CloseAll(sym, Side.Short, Magic); }
// 3. Trailing stop
Trail();
}Chart.resume_index is 0 on the first run (whole history) and the first bar to recompute afterwards, so the loop only touches new or changed bars. Proxy buffers must be series double with names unique across the script.Strategy B — Native Engine Indicators
Bind native indicator engines in Init() for maximum performance. Each binding is Native.Source → Native.Init → Native.Parameter → Native.Bind; the proxy's calculate() sizes its buffers with create_array(candle_count()) and fetches into them by output index. RSI + MACD crossover on closed bars.
// DOCS strategies — Strategy B: native engines (RSI + MACD) in one extra window
// Shows: Native.Source -> Init -> Parameter -> Bind, Native.Fetch into series buffers,
// reading proxy values in Tick() with Name.field(shift).
// Expect: one separate window with RSI (blue), MACD line (green), signal (red), histogram (grey).
// A BUY when RSI crosses back above 30 while the MACD histogram turns positive on the same
// bar, a SELL for the mirror case; one position at a time, magic 7102, comment "Trend".
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Strategy B - native RSI + MACD";
}
parameters {
int Magic = 7102; // Magic Number
int rsi_period = 14; // RSI Period
double rsi_oversold = 30.0; // Oversold
double rsi_overbought = 70.0; // Overbought
int macd_fast = 12; // MACD Fast
int macd_slow = 26; // MACD Slow
int macd_signal = 9; // MACD Signal
double Lot = 0.1; // Lot Size
int sl_points = 150; // Stop Loss (points)
int tp_points = 300; // Take Profit (points)
}
struct RSIResult { double value; }
struct MACDResult { double line; double signal; double histogram; }
display {
separate_window: true; // one extra window for all of the strategy's buffers
outputs: 4
NativeRSI.value { type: "line"; color: "#3b82f6"; name: "RSI"; };
NativeMACD.line { type: "line"; color: "#10b981"; name: "MACD Line"; };
NativeMACD.signal { type: "line"; color: "#ef4444"; name: "Signal"; };
NativeMACD.histogram { type: "histogram"; color: "#9ca3af"; name: "Histogram"; };
}
Init() {
Native.Source(i.RSI);
Native.Init(Symbol(), Timeframe);
Native.Parameter(rsi_period, Price.Close);
Native.Bind(NativeRSI);
Native.Source(i.MACD);
Native.Init(Symbol(), Timeframe);
Native.Parameter(macd_fast, macd_slow, macd_signal, Price.Close);
Native.Bind(NativeMACD);
Print("[INIT] Native RSI + MACD on " + Symbol());
}
// Fetch targets are series (they keep their history between ticks), unique names
NativeRSI.calculate() {
int len = candle_count();
series double sb_rsi[];
sb_rsi[] = create_array(len);
Native.Fetch(0, sb_rsi);
return RSIResult { value: sb_rsi };
}
NativeMACD.calculate() {
int len = candle_count();
series double sb_line[]; series double sb_sig[]; series double sb_hist[];
sb_line[] = create_array(len); sb_sig[] = create_array(len); sb_hist[] = create_array(len);
Native.Fetch(0, sb_line);
Native.Fetch(1, sb_sig);
Native.Fetch(2, sb_hist);
return MACDResult { line: sb_line, signal: sb_sig, histogram: sb_hist };
}
Tick() {
if (!Time.IsNewBar()) { return; }
string sym = Symbol();
if (Position.Exists(sym, Magic)) { return; }
// Closed bars: 1 = last closed, 2 = the one before
double rsi_now = NativeRSI.value(1);
double rsi_prev = NativeRSI.value(2);
double hist_now = NativeMACD.histogram(1);
double hist_prev = NativeMACD.histogram(2);
double pt = Symbol.Point();
double ask = Symbol.Ask();
double bid = Symbol.Bid();
if (rsi_prev < rsi_oversold && rsi_now >= rsi_oversold && hist_prev < 0.0 && hist_now >= 0.0) {
int t = Trade.Buy(sym, Lot, Symbol.NormalizePrice(ask - sl_points * pt), Symbol.NormalizePrice(ask + tp_points * pt), "Trend", Magic);
if (t < 0) { Print("Rejected: " + Trade.LastErrorText()); }
}
if (rsi_prev > rsi_overbought && rsi_now <= rsi_overbought && hist_prev > 0.0 && hist_now <= 0.0) {
int t = Trade.Sell(sym, Lot, Symbol.NormalizePrice(bid + sl_points * pt), Symbol.NormalizePrice(bid - tp_points * pt), "Trend", Magic);
if (t < 0) { Print("Rejected: " + Trade.LastErrorText()); }
}
}separate_window: true inside a display line gives that buffer its own window; the block-level separate_window: true used here puts every buffer of the strategy into one extra window.Strategy C — Custom External Source
Use a compiled indicator file (.tbc) from your indicators folder as the source. Custom.Parameter takes the indicator's parameters in their declared order; the fetch index is the position of the buffer in that indicator's display block. This example uses the bundled Bands Arrow.tbc.
// DOCS strategies — Strategy C: a compiled indicator file as the source (Custom.*)
// Needs "Bands Arrow.tbc" in the indicators folder (parameters period, multiplier, atr_period,
// ma_period). Fetch index = position of the buffer in that indicator's display block
// (0 lower, 1 upper, 2 middle, 3 sell arrow, 4 buy arrow).
// Expect: upper / lower lines from the indicator on the price chart. Journal once per new bar:
// "[CUSTOM] up=.. lo=.. buy=.. sell=.." — up / lo close to the price, matching the indicator
// when it is added to the chart on its own. On an arrow bar a BUY STOP above the upper band
// (or SELL STOP below the lower one), magic 7103; the previous pending orders are cancelled first.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Strategy C - custom indicator source";
}
parameters {
int Magic = 7103; // Magic Number
int bands_period = 20; // Bands Period
double bands_mult = 2.0; // Bands Deviation
int atr_len = 14; // ATR Period
int ma_len = 50; // MA Period
double Lot = 0.1; // Lot Size
int sl_points = 100; // Stop Loss (points)
int tp_points = 200; // Take Profit (points)
}
struct BandSignal { double upper; double lower; double buy_signal; double sell_signal; }
display {
outputs: 2
Bands.upper { type: "line"; color: "#dc2626"; name: "Upper Band"; };
Bands.lower { type: "line"; color: "#16a34a"; name: "Lower Band"; };
}
Init() {
Custom.Source("Bands Arrow.tbc");
Custom.Init(Symbol(), Timeframe);
Custom.Parameter(bands_period, bands_mult, atr_len, ma_len);
Custom.Bind(Bands);
Print("[INIT] Custom source on " + Symbol());
}
Bands.calculate() {
int len = candle_count();
series double sc_lo[]; series double sc_up[]; series double sc_sell[]; series double sc_buy[];
sc_lo[] = create_array(len); sc_up[] = create_array(len);
sc_sell[] = create_array(len); sc_buy[] = create_array(len);
Custom.Fetch(0, sc_lo);
Custom.Fetch(1, sc_up);
Custom.Fetch(3, sc_sell);
Custom.Fetch(4, sc_buy);
return BandSignal { upper: sc_up, lower: sc_lo, buy_signal: sc_buy, sell_signal: sc_sell };
}
Tick() {
if (!Time.IsNewBar()) { return; }
string sym = Symbol();
double pt = Symbol.Point();
double up = Bands.upper(1);
double lo = Bands.lower(1);
double buy_sig = Bands.buy_signal(1);
double sell_sig = Bands.sell_signal(1);
Print("[CUSTOM] up=" + ToString(up) + " lo=" + ToString(lo) + " buy=" + ToString(buy_sig) + " sell=" + ToString(sell_sig));
if (buy_sig > 0.0 || sell_sig > 0.0) {
Trade.CancelAll(sym, -1, Magic);
}
if (buy_sig > 0.0) {
double entry = Symbol.NormalizePrice(up + 2.0 * pt);
int t = Trade.BuyStop(sym, Lot, entry, Symbol.NormalizePrice(entry - sl_points * pt), Symbol.NormalizePrice(entry + tp_points * pt), "Custom Buy", Magic);
if (t < 0) { Print("BuyStop rejected: " + Trade.LastErrorText()); }
}
if (sell_sig > 0.0) {
double entry = Symbol.NormalizePrice(lo - 2.0 * pt);
int t = Trade.SellStop(sym, Lot, entry, Symbol.NormalizePrice(entry + sl_points * pt), Symbol.NormalizePrice(entry - tp_points * pt), "Custom Sell", Magic);
if (t < 0) { Print("SellStop rejected: " + Trade.LastErrorText()); }
}
}Custom.Init with another symbol is not supported yet. Compare the [CUSTOM] values with the indicator added to the chart on its own to confirm the buffer order.Strategy D — Hybrid Extension
Fetch a base series from a native engine, then do your own secondary math over its history in the same proxy (here: an envelope around a native EMA at a multiple of the mean distance of price from it).
// DOCS strategies — Strategy D: hybrid (native EMA + own math in the same proxy)
// Shows: Native.Fetch of a base series, then secondary math over its history in calculate().
// Expect: a blue EMA(50) on the price chart with a red upper and green lower envelope at
// multiplier x the mean absolute distance of price from the EMA. A BUY (magic 7104, comment
// "Hybrid") when the ask drops below the lower envelope and no position is open; all our longs
// close when the bid rises above the upper envelope.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Strategy D - hybrid native + own math";
}
parameters {
int Magic = 7104; // Magic Number
int ema_period = 50; // EMA Period
int dev_period = 20; // Distance Average Length
double multiplier = 2.0; // Envelope Multiplier
double Lot = 0.1; // Lot Size
}
struct HybridResult { double upper; double mid; double lower; }
display {
outputs: 3
MySystem.upper { type: "line"; color: "#dc2626"; name: "Upper (Hybrid)"; };
MySystem.mid { type: "line"; color: "#3b82f6"; name: "EMA Base"; };
MySystem.lower { type: "line"; color: "#16a34a"; name: "Lower (Hybrid)"; };
}
Init() {
Native.Source(i.MA);
Native.Init(Symbol(), Timeframe);
Native.Parameter(ema_period, MA.EMA, Price.Close); // period, type, source
Native.Bind(MySystem);
Print("[INIT] Hybrid on " + Symbol());
}
MySystem.calculate() {
double closes[] = close();
int len = length(closes);
series double sd_ema[]; series double sd_up[]; series double sd_lo[];
sd_ema[] = create_array(len); sd_up[] = create_array(len); sd_lo[] = create_array(len);
Native.Fetch(0, sd_ema);
// Secondary math: mean absolute distance of price from the EMA
int start = Chart.resume_index;
if (start == 0) { start = ema_period + dev_period; }
for (int i = start; i < len; i = i + 1) {
double dev = 0.0;
for (int j = 0; j < dev_period; j = j + 1) {
dev = dev + Math.Abs(closes[i - j] - sd_ema[i - j]);
}
dev = dev / dev_period;
sd_up[i] = sd_ema[i] + multiplier * dev;
sd_lo[i] = sd_ema[i] - multiplier * dev;
}
return HybridResult { upper: sd_up, mid: sd_ema, lower: sd_lo };
}
Tick() {
if (Symbol.Ask() < MySystem.lower(0) && !Position.Exists(Symbol(), Magic)) {
int t = Trade.Buy(Symbol(), Lot, 0, 0, "Hybrid", Magic);
if (t < 0) { Print("Rejected: " + Trade.LastErrorText()); }
}
if (Symbol.Bid() > MySystem.upper(0) && Position.Exists(Symbol(), Magic, Side.Long)) {
Trade.CloseAll(Symbol(), Side.Long, Magic);
}
}closes[i] with the fetched value of the same chart bar. For a filter from another timeframe, bind a separate proxy and read only its latest value (strategy E).Trade() & Timer()
Trade() is called once per trade event before the next Tick() — live and in the tester. Timer() is called every Timer.Set(seconds). Filter by Event.Magic() first so manual trades and other strategies don't reach your logic. See Trade Language → Trade() & Timer() for every Event.* field.
// DOCS strategies — Trade() and Timer() lifecycle blocks
// Shows: Trade() once per trade event (Event.*), Timer() every Timer.Set seconds, a loss
// counter kept in state {} that pauses entries.
// Expect (Journal): "Opened #.. @ .." when our position opens; on a close the loss counter
// updates (a stop-out also prints "Stop out!"); "Rejected (code): text" for broker refusals.
// Every 5 minutes (also without ticks, broker clock): "[TIMER] open: N losses in a row: M".
// Entry: one position at a time, in the direction of the last closed bar, magic 7105.
// After 3 losing trades in a row no more entries.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Trade() and Timer() blocks";
}
parameters {
int Magic = 7105; // Magic Number
double Lot = 0.1; // Lot Size
int sl_points = 200; // Stop Loss (points)
int tp_points = 200; // Take Profit (points)
}
state {
int losses = 0;
}
Init() {
losses = 0;
Timer.Set(300); // Timer() every 5 minutes
}
Trade() {
if (Event.Magic() != Magic) { return; }
int kind = Event.Kind();
if (kind == Event.Opened) {
Print("Opened #" + ToString(Event.Ticket()) + " @ " + ToString(Event.Price()));
} else if (kind == Event.Closed) {
if (Event.Profit() < 0.0) { losses = losses + 1; } else { losses = 0; }
if (Event.Reason() == Reason.StopOut) { Print("Stop out!"); }
Print("Closed #" + ToString(Event.Ticket()) + " profit=" + ToString(Event.Profit()) + " losses in a row=" + ToString(losses));
} else if (kind == Event.OrderExpired) {
Print("Pending order expired #" + ToString(Event.Ticket()));
} else if (kind == Event.Rejected) {
Print("Rejected (" + ToString(Event.Error()) + "): " + Event.Comment());
}
}
Timer() {
Print("[TIMER] open: " + ToString(Position.Count(Symbol(), Magic)) + " losses in a row: " + ToString(losses));
}
Tick() {
if (losses >= 3) { return; } // pause after 3 losing trades
if (!Time.IsNewBar()) { return; }
if (Position.Exists(Symbol(), Magic)) { return; }
double pt = Symbol.Point();
int t = 0;
if (close(1) > open(1)) {
double ask = Symbol.Ask();
t = Trade.Buy(Symbol(), Lot, Symbol.NormalizePrice(ask - sl_points * pt), Symbol.NormalizePrice(ask + tp_points * pt), "Events Long", Magic);
} else {
double bid = Symbol.Bid();
t = Trade.Sell(Symbol(), Lot, Symbol.NormalizePrice(bid + sl_points * pt), Symbol.NormalizePrice(bid - tp_points * pt), "Events Short", Magic);
}
if (t < 0) { Print("[ENTRY] refused (" + ToString(Trade.LastError()) + "): " + Trade.LastErrorText()); }
}
Exit() {
Timer.Kill();
}Strategy E — Multi-Timeframe Trend + ATR Stops
A native EMA bound to Timeframe.H4 filters the direction while the chart runs on M15 or H1. A native ATR on the chart timeframe sizes the stop, the target and the trailing distance, and the lot is computed so the stop risks a fixed percentage of the balance.
// DOCS strategies — Multi-timeframe trend filter + ATR stops + ATR trailing + risk-based lots
// Shows: a native EMA on H4 (Native.Init(Symbol(), Timeframe.H4)) as the trend filter on any
// chart timeframe, a native ATR on the chart timeframe for SL / TP / trailing distance,
// i.ema() for the entry trigger, lot size from account risk.
// Run on M15 or H1. Expect:
// - Purple H4 EMA on the price chart (drawn one value per chart bar), orange ATR in its own window.
// - Journal once per new bar: "[MTF] h4_ema=.. ema_fast=.. atr=.. close=.." (real numbers).
// - A BUY when the last closed bar is above the H4 EMA and the fast EMA and breaks the previous
// bar's high (SELL: the mirror case). SL = sl_atr x ATR, TP = tp_atr x ATR, lot sized so the
// SL loses about risk_pct % of the balance. Magic 7106, comment "MTF Long" / "MTF Short".
// - Once a position is in profit by more than trail_atr x ATR, its SL follows price at that
// distance and never moves back ([MOD] style changes visible on the position).
// Other timeframes are verified live; check the tester result separately.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: MTF trend filter with ATR stops";
}
parameters {
int Magic = 7106; // Magic Number
int trend_len = 50; // H4 EMA Length
int fast_len = 20; // Chart EMA Length
int atr_len = 14; // ATR Period
double sl_atr = 2.0; // Stop Loss (x ATR)
double tp_atr = 3.0; // Take Profit (x ATR)
double trail_atr = 1.5; // Trailing Distance (x ATR)
double risk_pct = 1.0; // Risk per Trade (% of balance)
}
struct TrendLine { double value; }
struct AtrLine { double value; }
display {
outputs: 2
TrendH4.value { type: "line"; color: "#8b5cf6"; name: "H4 EMA"; width: 2; };
AtrProxy.value { type: "line"; color: "#f59e0b"; name: "ATR"; width: 1; separate_window: true; };
}
Init() {
Native.Source(i.MA);
Native.Init(Symbol(), Timeframe.H4);
Native.Parameter(trend_len, MA.EMA, Price.Close);
Native.Bind(TrendH4);
Native.Source(i.ATR);
Native.Init(Symbol(), Timeframe);
Native.Parameter(atr_len);
Native.Bind(AtrProxy);
Print("[INIT] MTF trend on " + Symbol() + " magic=" + ToString(Magic));
}
TrendH4.calculate() {
int len = candle_count();
series double mt_trend[];
mt_trend[] = create_array(len);
Native.Fetch(0, mt_trend);
return TrendLine { value: mt_trend };
}
AtrProxy.calculate() {
int len = candle_count();
series double mt_atr[];
mt_atr[] = create_array(len);
Native.Fetch(0, mt_atr);
return AtrLine { value: mt_atr };
}
// Lot size that loses about risk_pct % of the balance at a stop sl_dist (price units) away
double RiskLot(double sl_dist) {
double money = Account.Balance() * risk_pct / 100.0;
double per_lot = sl_dist / Symbol.TickSize() * Symbol.TickValue();
if (per_lot <= 0.0) { return Symbol.LotMin(); }
return Symbol.NormalizeVolume(money / per_lot);
}
// SL follows price at dist once the position is that far in profit; never moves back
void TrailAtr(double dist) {
string sym = Symbol();
double bid = Symbol.Bid();
double ask = Symbol.Ask();
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Magic() != Magic || Position.Symbol() != sym) { continue; }
double sl = Position.SL();
if (Position.Direction() == Side.Long) {
double new_sl = Symbol.NormalizePrice(bid - dist);
if (new_sl > Position.OpenPrice() && new_sl > sl) { Trade.Modify(Position.Ticket(), sym, new_sl, -1.0); }
} else {
double new_sl = Symbol.NormalizePrice(ask + dist);
if (new_sl < Position.OpenPrice() && (sl == 0.0 || new_sl < sl)) { Trade.Modify(Position.Ticket(), sym, new_sl, -1.0); }
}
}
}
Tick() {
double atr_now = AtrProxy.value(1);
bool atr_ok = atr_now > 0.0; // false while the ATR is still NaN / warming up
if (!atr_ok) { return; }
TrailAtr(trail_atr * atr_now);
if (!Time.IsNewBar()) { return; }
double h4_ema = TrendH4.value(0);
double ema_fast = i.ema(fast_len);
Print("[MTF] h4_ema=" + ToString(h4_ema) + " ema_fast=" + ToString(ema_fast)
+ " atr=" + ToString(atr_now) + " close=" + ToString(close(1)));
string sym = Symbol();
if (Position.Exists(sym, Magic)) { return; }
double sl_dist = sl_atr * atr_now;
double tp_dist = tp_atr * atr_now;
double lot = RiskLot(sl_dist);
bool long_ok = close(1) > h4_ema && close(1) > ema_fast && close(1) > high(2);
bool short_ok = close(1) < h4_ema && close(1) < ema_fast && close(1) < low(2);
int t = 0;
if (long_ok) {
double ask = Symbol.Ask();
t = Trade.Buy(sym, lot, Symbol.NormalizePrice(ask - sl_dist), Symbol.NormalizePrice(ask + tp_dist), "MTF Long", Magic);
} else if (short_ok) {
double bid = Symbol.Bid();
t = Trade.Sell(sym, lot, Symbol.NormalizePrice(bid + sl_dist), Symbol.NormalizePrice(bid - tp_dist), "MTF Short", Magic);
}
if (t < 0) { Print("[ENTRY] refused (" + ToString(Trade.LastError()) + "): " + Trade.LastErrorText()); }
}TrendH4.value(0) is the H4 engine's newest value (the forming H4 bar), not the H4 value at chart bar 0's time. Proxies on another timeframe are verified live; check a backtest of this script before relying on it there. i.ema(n) returns the current-bar value of the chart's EMA — call it once per bar, not on every tick.Strategy F — Session Breakout with OCO Pending Orders
On the first bar of the London session each day, bracket the range of the last N bars with a buy stop and a sell stop (both with an expiry). Trade() turns them into a one-cancels-other pair: as soon as one fills, the other is cancelled. From the flat hour on, everything of this magic is closed and cancelled.
// DOCS strategies — Session breakout with pending orders and a Trade()-driven OCO cancel
// Shows: Time.InSession, a range from the last N bars, BuyStop / SellStop with expiry,
// Trade() cancelling the other side on OrderFilled, a flat hour that closes and cancels.
// Expect (Journal / chart):
// - On the first new bar inside the London session each day: "[RANGE] top=.. bottom=.." and a
// BUY STOP above the range + SELL STOP below it (magic 7107), expiring after expiry_min.
// - When one fills: "[FILLED] #.. - cancelling the other side", then "[CANCEL] #.." for the other.
// - Unfilled orders past expiry: "[EXPIRED] #..".
// - From flat_hour (broker clock hour) on: "[FLAT] ..." and our positions / orders are removed.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: session breakout with OCO pending orders";
}
parameters {
int Magic = 7107; // Magic Number
int range_bars = 8; // Range Bars
int gap_points = 20; // Distance beyond the range (points)
double Lot = 0.1; // Lot Size
double rr = 1.5; // TP = range x rr
int expiry_min = 120; // Order Expiry (minutes)
int flat_hour = 20; // Flat from this hour (broker clock)
}
state {
int placed_day = 0; // day of month the orders were placed (0 = not yet)
}
int OurOrders() {
int n = 0;
for (int i = 0; i < Order.Count(); i = i + 1) {
if (!Order.SetIndex(i)) { break; }
if (Order.Magic() == Magic && Order.Symbol() == Symbol()) { n = n + 1; }
}
return n;
}
Init() {
Print("[INIT] Session breakout " + Symbol() + " magic=" + ToString(Magic));
}
Trade() {
if (Event.Magic() != Magic) { return; }
int kind = Event.Kind();
if (kind == Event.OrderFilled) {
Print("[FILLED] #" + ToString(Event.Ticket()) + " @ " + ToString(Event.Price()) + " - cancelling the other side");
Trade.CancelAll(Symbol(), -1, Magic);
}
if (kind == Event.OrderCancelled) { Print("[CANCEL] #" + ToString(Event.Ticket())); }
if (kind == Event.OrderExpired) { Print("[EXPIRED] #" + ToString(Event.Ticket())); }
if (kind == Event.Closed) { Print("[CLOSED] #" + ToString(Event.Ticket()) + " profit=" + ToString(Event.Profit())); }
if (kind == Event.Rejected) { Print("[REJECTED] " + Event.Comment()); }
}
Tick() {
if (!Time.IsNewBar()) { return; }
string sym = Symbol();
if (Time.Hour() >= flat_hour) {
if (Position.Exists(sym, Magic) || OurOrders() > 0) {
Print("[FLAT] closing positions and cancelling orders");
Trade.CloseAll(sym, -1, Magic);
Trade.CancelAll(sym, -1, Magic);
}
return;
}
if (!Time.InSession("London")) { return; }
if (placed_day == Time.Day()) { return; } // once per day
if (Position.Exists(sym, Magic) || OurOrders() > 0) { return; }
// Range of the last range_bars closed bars
double top = high(1);
double bottom = low(1);
for (int k = 2; k <= range_bars; k = k + 1) {
if (high(k) > top) { top = high(k); }
if (low(k) < bottom) { bottom = low(k); }
}
double pt = Symbol.Point();
double size = top - bottom;
double buy_px = Symbol.NormalizePrice(top + gap_points * pt);
double sell_px = Symbol.NormalizePrice(bottom - gap_points * pt);
datetime expiry = Time.Now() + expiry_min * 60000; // ms
Print("[RANGE] top=" + ToString(top) + " bottom=" + ToString(bottom));
// SL at the other side of the range, TP at rr x range
int b = Trade.BuyStop(sym, Lot, buy_px, Symbol.NormalizePrice(bottom), Symbol.NormalizePrice(buy_px + rr * size), "Break Up", Magic, expiry);
if (b < 0) { Print("[BUYSTOP] refused: " + Trade.LastErrorText()); }
int s = Trade.SellStop(sym, Lot, sell_px, Symbol.NormalizePrice(top), Symbol.NormalizePrice(sell_px - rr * size), "Break Down", Magic, expiry);
if (s < 0) { Print("[SELLSTOP] refused: " + Trade.LastErrorText()); }
placed_day = Time.Day();
}datetime in milliseconds: Time.Now() + minutes * 60000. Time.Now() and Time.Hour() follow the broker clock live and the simulated clock in the tester.Strategy G — Timer-Driven Risk Monitor
Timer() keeps running on a quiet market, which makes it the right place for checks that must not wait for a tick: here it reports equity, floating and closed P/L every minute and halts the strategy when the day's drawdown passes a limit.
// DOCS strategies — Timer-driven risk monitor with a daily loss limit
// Shows: Timer() on the broker clock (fires without ticks), History.Deals over the last 24 h,
// floating P/L of our magic, a halt flag in state {} that Tick() respects.
// Expect (Journal):
// - Every every_sec seconds: "[MON] equity=.. floating=.. closed24h=.. (N deals) dd=.. halted=0".
// - When a new day starts (broker clock): "[MON] new day - equity reference .." and halted=0.
// - If equity falls more than daily_loss below the day's starting equity: "[MON] daily loss limit
// hit - closing and halting", our positions (magic 7109) close, no entries until the next day.
// Entry (to have something to watch): one position at a time in the direction of the last bar.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Timer() risk monitor";
}
parameters {
int Magic = 7109; // Magic Number
int every_sec = 60; // Check Every (seconds)
double daily_loss = 200.0; // Daily Loss Limit (account currency)
double Lot = 0.1; // Lot Size
int sl_points = 300; // Stop Loss (points)
int tp_points = 300; // Take Profit (points)
}
state {
int halted = 0;
int cur_day = 0;
double start_equity = 0.0;
}
double Floating() {
double p = 0.0;
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Magic() == Magic) { p = p + Position.Profit(); }
}
return p;
}
Init() {
cur_day = Time.Day();
start_equity = Account.Equity();
halted = 0;
Timer.Set(every_sec);
Print("[INIT] Monitor " + Symbol() + " every " + ToString(every_sec) + " s, equity " + ToString(start_equity));
}
Timer() {
if (Time.Day() != cur_day) {
cur_day = Time.Day();
start_equity = Account.Equity();
halted = 0;
Print("[MON] new day - equity reference " + ToString(start_equity));
}
datetime since = Time.Now() - 86400000; // last 24 hours (ms)
int deals[] = History.Deals(since, 0, Magic, Symbol());
int n = length(deals);
double closed = 0.0;
for (int i = 0; i < n; i = i + 1) { closed = closed + Deal.Profit(deals[i]); }
double equity = Account.Equity();
double dd = start_equity - equity;
Print("[MON] equity=" + ToString(equity) + " floating=" + ToString(Floating())
+ " closed24h=" + ToString(closed) + " (" + ToString(n) + " deals) dd=" + ToString(dd)
+ " halted=" + ToString(halted));
if (halted == 0 && dd > daily_loss) {
halted = 1;
Print("[MON] daily loss limit hit - closing and halting");
Trade.CloseAll(Symbol(), -1, Magic);
Trade.CancelAll(Symbol(), -1, Magic);
}
}
Tick() {
if (halted == 1) { return; }
if (!Time.IsNewBar()) { return; }
if (Position.Exists(Symbol(), Magic)) { return; }
double pt = Symbol.Point();
int t = 0;
if (close(1) > open(1)) {
double ask = Symbol.Ask();
t = Trade.Buy(Symbol(), Lot, Symbol.NormalizePrice(ask - sl_points * pt), Symbol.NormalizePrice(ask + tp_points * pt), "Mon Long", Magic);
} else {
double bid = Symbol.Bid();
t = Trade.Sell(Symbol(), Lot, Symbol.NormalizePrice(bid + sl_points * pt), Symbol.NormalizePrice(bid - tp_points * pt), "Mon Short", Magic);
}
if (t < 0) { Print("[ENTRY] refused: " + Trade.LastErrorText()); }
}
Exit() {
Timer.Kill();
}Strategy H — Two-Symbol Basket Hedge
Compares two symbols' percentage move against their previous daily close (close(sym, Timeframe.D1, 1) and Symbol.Bid(sym)). When they drift apart, it sells the leader and buys the laggard under one magic number, and closes both legs together on a combined profit or loss.
// DOCS strategies — Two-symbol basket hedge (LIVE ONLY: the tester replays the chart symbol only)
// Shows: Symbol.Bid(sym) and close(sym, Timeframe.D1, 1) on other symbols, market orders on
// another symbol, one magic for the whole basket, basket P/L across symbols,
// Trade.CloseAll("", -1, Magic) to close every leg on every symbol.
// Run on any chart (e.g. EURUSD.r M15). Expect:
// - sym_a / sym_b in Market Watch while it runs.
// - Journal once per new bar while flat: "[HEDGE] a=..% b=..% spread=..%" (each symbol's % change
// vs its previous daily close, spread = a - b).
// - spread > entry_pct: SELL sym_a + BUY sym_b; spread < -entry_pct: BUY sym_a + SELL sym_b
// ("Hedge A" / "Hedge B", magic 7110). If one leg is refused the other is closed again.
// - While the basket is open: closes both legs at +take_money or -stop_money combined profit
// ("[HEDGE] basket closed at ..").
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: two-symbol basket hedge";
}
parameters {
int Magic = 7110; // Magic Number
string sym_a = "EURUSD.r"; // Symbol A
string sym_b = "GBPUSD.r"; // Symbol B
double Lot = 0.1; // Lot per Leg
double entry_pct = 0.30; // Entry Spread (%)
double take_money = 50.0; // Basket Take Profit (money)
double stop_money = 100.0; // Basket Stop (money)
}
// % change of s vs its previous daily close, from the live Bid
double ChgVsPrevDay(string s) {
double prev = close(s, Timeframe.D1, 1);
double bid = Symbol.Bid(s);
if (prev <= 0.0 || bid <= 0.0) { return 0.0; }
return (bid / prev - 1.0) * 100.0;
}
// Combined floating profit of every leg with our magic, on any symbol
double BasketProfit() {
double p = 0.0;
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Magic() == Magic) { p = p + Position.Profit(); }
}
return p;
}
// side_a = direction of the sym_a leg; sym_b always takes the other side
void OpenPair(int side_a) {
double lot_a = Symbol.NormalizeVolume(Lot, sym_a);
double lot_b = Symbol.NormalizeVolume(Lot, sym_b);
int ta = -1;
int tb = -1;
if (side_a == Side.Long) {
ta = Trade.Buy(sym_a, lot_a, 0, 0, "Hedge A", Magic);
tb = Trade.Sell(sym_b, lot_b, 0, 0, "Hedge B", Magic);
} else {
ta = Trade.Sell(sym_a, lot_a, 0, 0, "Hedge A", Magic);
tb = Trade.Buy(sym_b, lot_b, 0, 0, "Hedge B", Magic);
}
if (ta < 0 || tb < 0) {
Print("[HEDGE] leg refused: " + Trade.LastErrorText() + " - closing the basket");
Trade.CloseAll("", -1, Magic);
}
}
Init() {
Print("[INIT] Hedge " + sym_a + " / " + sym_b + " magic=" + ToString(Magic));
}
Tick() {
if (Position.Count("", Magic) > 0) {
double p = BasketProfit();
if (p >= take_money || p <= 0.0 - stop_money) {
Print("[HEDGE] basket closed at " + ToString(p));
Trade.CloseAll("", -1, Magic);
}
return;
}
if (!Time.IsNewBar()) { return; }
double a = ChgVsPrevDay(sym_a);
double b = ChgVsPrevDay(sym_b);
double spread_pct = a - b;
Print("[HEDGE] a=" + ToString(a) + "% b=" + ToString(b) + "% spread=" + ToString(spread_pct) + "%");
if (spread_pct > entry_pct) {
OpenPair(Side.Short); // A ran ahead: sell A, buy B
} else if (spread_pct < 0.0 - entry_pct) {
OpenPair(Side.Long); // A fell behind: buy A, sell B
}
}Tick() is driven by the chart symbol's ticks; the other symbol's quote is read on each of them. Write negative thresholds as 0.0 - stop_money.Common Helper Patterns
Filter positions by magic number, exclude specific symbols, or compute risk-based sizes using continue; and logic operators. All of these are in one runnable file, strategies_helpers.tdsl, that manages positions of a magic number you choose.
// 1. Trailing stop that skips one symbol and only touches one magic
void TrailingExcept(string skip_sym, int magic, int pts) {
double pt = Symbol.Point();
double bid = Symbol.Bid();
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Symbol() == skip_sym) { continue; } // skip this symbol
if (Position.Symbol() != Symbol()) { continue; } // prices below are the chart symbol's
if (Position.Magic() != magic) { continue; }
double sl = Position.SL();
if (Position.Direction() == Side.Long && (bid - Position.OpenPrice()) > pts * pt) {
double half = pts; // int -> double before mixing with literals
half = half / 2.0;
double new_sl = Symbol.NormalizePrice(bid - half * pt);
if (new_sl > sl) { Trade.Modify(Position.Ticket(), Position.Symbol(), new_sl, -1.0); }
}
}
}
// 2. Close only positions with a specific magic number
void CloseByMagic(int target_magic) {
Trade.CloseAll("", -1, target_magic); // "" = all symbols, -1 = both sides
}
// 3. Count positions that are NOT ours (manual trades, other strategies)
int CountExternal(int my_magic) {
int count = 0;
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Magic() != my_magic) { count = count + 1; }
}
return count;
}
// 4. Floating profit of one symbol + magic pair
double GetNetProfit(string sym, int magic) {
double total = 0.0;
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Symbol() == sym && Position.Magic() == magic) {
total = total + Position.Profit();
}
}
return total;
}// 5. Inside a trading window (always true in a backtest)
bool TradeAllowed() {
if (Env.IsBacktest()) { return true; }
return Time.InSession("London") || Time.InSession("NewYork");
}
// 6. Lot size that risks risk_pct % of the balance at a stop sl_points away
double GetRiskLot(double risk_pct, int sl_points) {
double risk_val = Account.Balance() * (risk_pct / 100.0);
double per_lot = sl_points * Symbol.Point() / Symbol.TickSize() * Symbol.TickValue();
if (per_lot <= 0.0) { return Symbol.LotMin(); }
return Symbol.NormalizeVolume(risk_val / per_lot);
}
// New-bar gate at the top of Tick()
// if (!Time.IsNewBar()) { return; }TradeAllowed, not Open or Close) — built-in names are reserved case-insensitively.