Trade Language
Direct access to order execution, live position management, pending orders, closed-trade history and trade events. These functions are available in strategies (scripts with a Tick() block) — in Init(), Tick(), Trade(), Timer(), Exit() and helper functions called from them.
Every example on this page is a complete, runnable script with a header comment describing what to expect in the Journal, and its own magic number.
Trade.*
Arguments in ? are optional. sym defaults to the chart symbol (to "" = all symbols for CloseAll / CancelAll), comment to "", magic to 0 when placing and to -1 (any) when filtering, dir to -1 (both sides), exp to 0 (no expiry). A missing volume or price is refused. Arguments are positional: to pass a magic you also pass the SL, TP and comment before it.
| Function / Property | Returns | Description |
|---|---|---|
Trade.Buy(sym?, vol, sl?, tp?, comment?, magic?, dev?) | int | Market buy. Returns the ticket, or -1 when refused. sl / tp 0 = none. |
Trade.Sell(sym?, vol, sl?, tp?, comment?, magic?, dev?) | int | Market sell. Returns the ticket, or -1 when refused. |
Trade.BuyLimit(sym?, vol, px, sl?, tp?, comment?, magic?, exp?) | int | Pending buy limit (px below the ask). Ticket or -1. |
Trade.SellLimit(sym?, vol, px, sl?, tp?, comment?, magic?, exp?) | int | Pending sell limit (px above the bid). Ticket or -1. |
Trade.BuyStop(sym?, vol, px, sl?, tp?, comment?, magic?, exp?) | int | Pending buy stop (px above the ask). Ticket or -1. |
Trade.SellStop(sym?, vol, px, sl?, tp?, comment?, magic?, exp?) | int | Pending sell stop (px below the bid). Ticket or -1. |
Trade.BuyStopLimit(sym?, vol, px, limit, sl?, tp?, comment?, magic?, exp?) | int | Buy stop at px; when triggered it becomes a buy limit at limit. Ticket or -1. Not yet available in the app's order UI. |
Trade.SellStopLimit(sym?, vol, px, limit, sl?, tp?, comment?, magic?, exp?) | int | Sell stop at px; when triggered it becomes a sell limit at limit. Ticket or -1. |
Trade.Close(ticket?, sym?, dir?, magic?, comment?) | bool | Close one position. No ticket = the SetIndex-ed position. |
Trade.CloseAll(sym?, dir?, magic?, comment?) | bool | Close all matching positions ("" = all symbols, -1 = any side / magic). |
Trade.ClosePartial(ticket, vol, sym?, comment?) | bool | Close vol lots of a position; the rest stays open with the same ticket. |
Trade.Modify(ticket?, sym?, sl?, tp?, comment?) | bool | Change SL / TP of a position: > 0 set, 0 remove, negative or omitted keep. No ticket = the SetIndex-ed position. |
Trade.ModifyOrder(ticket, sym?, vol?, px?, sl?, tp?, exp?, comment?) | bool | Change a pending order (volume, price, SL / TP, expiry). Pass every value — read the ones you keep from Order.*. |
Trade.CancelOrder(ticket?, sym?, comment?) | bool | Cancel a pending order. No ticket = the SetIndex / Select-ed order. |
Trade.CancelAll(sym?, dir?, magic?, type?, comment?) | bool | Cancel all matching pending orders (type = OrderType.*, -1 = any). |
Trade.Positions() | int[] | Tickets of all open positions. |
Trade.Orders() | int[] | Tickets of all pending orders. |
// DOCS trade — Order execution: ticket / -1, LastError, Modify (set / keep / remove), CloseAll
// Expect (Journal / Positions), once per run:
// 1. "[EXEC] opened #.. (ticket)" and a BUY 0.1 with SL 150 / TP 300 points, magic 7201,
// comment "Entry". A refusal prints "[EXEC] rejected (code): text" instead.
// 2. When Trade() reports it open: SL moved to 50 points below the bid, TP unchanged ("[EXEC] SL moved").
// 3. Next new bar: TP removed, SL kept ("[EXEC] TP removed").
// 4. hold_bars bars later: all our longs closed ("[EXEC] closed"), Trade() prints the close.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: order execution";
}
parameters {
int Magic = 7201; // Magic Number
int hold_bars = 3; // Bars to hold
}
state {
int step = 0; // 0 send, 1 sent, 2 SL moved, 3 TP removed, 4 done
int bars_held = 0;
}
Init() {
step = 0;
bars_held = 0;
Print("[INIT] Order execution test on " + Symbol());
}
Trade() {
if (Event.Magic() != Magic) { return; }
if (Event.Kind() == Event.Opened && step == 1) {
int ticket = Position.Ticket(Symbol(), Magic);
double pt = Symbol.Point();
// Move the stop, keep the TP (-1 = keep)
if (Trade.Modify(ticket, Symbol(), Symbol.NormalizePrice(Symbol.Bid() - 50 * pt), -1.0)) {
Print("[EXEC] SL moved");
}
step = 2;
}
if (Event.Kind() == Event.Closed) { Print("[EXEC] closed #" + ToString(Event.Ticket()) + " profit=" + ToString(Event.Profit())); }
if (Event.Kind() == Event.Rejected) { Print("[EXEC] broker rejected (" + ToString(Event.Error()) + "): " + Event.Comment()); }
}
Tick() {
string sym = Symbol();
if (step == 0) {
double point = Symbol.Point();
double ask = Symbol.Ask();
double sl = Symbol.NormalizePrice(ask - 150 * point);
double tp = Symbol.NormalizePrice(ask + 300 * point);
int ticket = Trade.Buy(sym, 0.1, sl, tp, "Entry", Magic);
if (ticket < 0) {
Print("[EXEC] rejected (" + ToString(Trade.LastError()) + "): " + Trade.LastErrorText());
step = 4;
} else {
Print("[EXEC] opened #" + ToString(ticket));
step = 1;
}
return;
}
if (!Time.IsNewBar()) { return; }
if (step == 2) {
// Remove the TP, keep the SL (0 = remove, -1 = keep)
if (Trade.Modify(Position.Ticket(sym, Magic), sym, -1.0, 0.0)) { Print("[EXEC] TP removed"); }
step = 3;
return;
}
if (step == 3) {
bars_held = bars_held + 1;
if (bars_held >= hold_bars) {
// Close all our longs on this symbol
Trade.CloseAll(sym, Side.Long, Magic);
step = 4;
}
}
}Event.Opened event (or for Position.Exists) before modifying a fresh position: live, the ticket returned by Trade.Buy is provisional until the broker confirms the fill.Results & Errors
Every Trade.* placement returns the ticket, or -1 when it was refused. Details of the last request:
| Function / Property | Returns | Description |
|---|---|---|
Trade.LastError() | int | 0 OK · 1 no quote · 2 invalid (volume / price / stops) · 3 rejected by the broker · 4 no connection · 5 queued (sent, waiting for the broker). |
Trade.LastErrorText() | string | Human-readable reason for the last refusal. |
Trade.LastTicket() | int | Ticket of the last successful request. |
Trade.LastPrice() | double | Price of the last request. |
Position.Count() on the next tick, so a strategy does not send duplicates. A later broker rejection arrives as Event.Rejected in Trade() with Event.Error() = 3. In the tester orders execute synchronously, so the fill is visible on the same tick.Order Checks (live and tester)
The strategy tester refuses orders exactly like the live broker, so a backtest never takes trades the account could not take:
| Function / Property | Description |
|---|---|
Volume | Must be between Symbol.LotMin() and Symbol.LotMax() and a multiple of Symbol.LotStep() (use Symbol.NormalizeVolume()). |
Total volume | At most 100 lots open in total. |
Margin | Free margin must cover the required margin × 1.1. Falling below the stop-out level closes positions (Reason.StopOut). |
Market SL / TP | Buy: SL below and TP above the bid. Sell: SL above and TP below the ask. |
Pending price | Limit orders on the favourable side of the market, stop orders on the other side (buy limit below ask, buy stop above ask, and the reverse for sells). |
Modify | Same SL / TP side checks against the current price; the position or order must exist. |
Magic Numbers & Filters
The magic number you pass when placing is stored on the position, the pending order and the closed deal, and comes back in every Event.Magic(). Give each strategy its own number and filter with it everywhere — manual trades (magic 0) and other strategies then never reach your logic.
| Function / Property | Description |
|---|---|
(sym, magic, dir) | The filter of Position.Count / Exists / AvgOpenPrice and of every Position property: "" = all symbols, -1 = any magic, -1 = both sides. |
Trade.CloseAll / CancelAll | Same filter order (sym, dir, magic) — note dir before magic here. |
History.Deals(from, to, magic, sym) | Closed deals of one magic / symbol. |
Event.Magic() | First line of every Trade() block: if (Event.Magic() != Magic) { return; } |
-1 for tickets and directions — a missing position never reads as Side.Long. Test with Position.Exists() first.Position.*
(symbol, magic, direction). With filters, a property reads the first matching position. Without arguments it reads the position selected by Position.SetIndex(i), which returns false past the end.| Function / Property | Returns | Description |
|---|---|---|
Position.Count(sym?, magic?, dir?) | int | Number of matching open positions (no arguments = all). |
Position.Exists(sym?, magic?, dir?) | bool | True if at least one matching position exists. |
Position.AvgOpenPrice(sym?, magic?, dir?) | double | Volume-weighted average entry price of matching positions. |
Position.SetIndex(i) | bool | Select position i. False past the end. |
Position.Ticket(sym?, magic?, dir?) | int | Ticket (-1 when not found). |
Position.Symbol(sym?, magic?, dir?) | string | Symbol name. |
Position.Direction(sym?, magic?, dir?) | int | Side.Long or Side.Short (-1 when not found). |
Position.Side() | int | Same as Direction() for the selected position. |
Position.Volume(sym?, magic?, dir?) | double | Lot size. |
Position.OpenPrice(sym?, magic?, dir?) | double | Entry price. |
Position.CurrentPrice(sym?, magic?, dir?) | double | Current close price (bid for longs, ask for shorts). |
Position.SL(sym?, magic?, dir?) | double | Stop loss price (0 if none). |
Position.TP(sym?, magic?, dir?) | double | Take profit price (0 if none). |
Position.Profit(sym?, magic?, dir?) | double | Floating profit / loss. |
Position.Swap(sym?, magic?, dir?) | double | Accumulated swap. |
Position.Commission(sym?, magic?, dir?) | double | Commission. |
Position.OpenTime(sym?, magic?, dir?) | datetime | Time the position was opened. |
Position.Duration(sym?, magic?, dir?) | int | Time the position has been open. |
Position.Magic(sym?, magic?, dir?) | int | Magic number. |
Position.Comment(sym?, magic?, dir?) | string | Position comment. |
// DOCS trade — Position loop: SetIndex, filter by magic + symbol, break-even
// Expect: one BUY (magic 7202, no TP, SL 300 points). When its floating profit is above
// be_money and the SL is still below the entry, the SL moves to the entry price
// ("[BE] #.. stop to entry .."). Positions with other magics / symbols are never touched.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: position loop / break-even";
}
parameters {
int Magic = 7202; // Magic Number
double be_money = 5.0; // Break-even after this profit (money)
int sl_points = 300; // Stop Loss (points)
}
Init() {
Print("[INIT] Break-even test on " + Symbol());
}
Tick() {
if (!Position.Exists(Symbol(), Magic) && Time.IsNewBar()) {
int t = Trade.Buy(Symbol(), 0.1, Symbol.NormalizePrice(Symbol.Ask() - sl_points * Symbol.Point()), 0, "BE test", Magic);
if (t < 0) { Print("[BE] entry refused: " + Trade.LastErrorText()); }
}
for (int i = 0; i < Position.Count(); i = i + 1) {
if (!Position.SetIndex(i)) { break; }
if (Position.Magic() != Magic || Position.Symbol() != Symbol()) { continue; }
double op = Position.OpenPrice();
double sl = Position.SL();
if (Position.Direction() == Side.Long && Position.Profit() > be_money && sl < op) {
Trade.Modify(Position.Ticket(), Symbol(), op, -1.0); // break-even, TP kept
Print("[BE] #" + ToString(Position.Ticket()) + " stop to entry " + ToString(op));
}
}
}Order.*
Pending orders. Properties take an optional ticket; without one they read the order selected by Order.SetIndex(i) or Order.Select(ticket).
| Function / Property | Returns | Description |
|---|---|---|
Order.Count() | int | Number of pending orders (all symbols, all magics — filter in the loop). |
Order.SetIndex(i) | bool | Select pending order i. False past the end. |
Order.Select(ticket) | bool | Select a pending order by ticket. |
Order.Ticket(i?) | int | Ticket of order i (no index = the selected order). |
Order.Symbol(ticket?) | string | Symbol name. |
Order.Type(ticket?) | int | OrderType.BuyLimit / SellLimit / BuyStop / SellStop. |
Order.Side(ticket?) | int | Side.Buy or Side.Sell. |
Order.Volume(ticket?) | double | Lot size. |
Order.Price(ticket?) | double | Order price. |
Order.StopPrice(ticket?) | double | Stop (trigger) price of a stop-limit order. |
Order.SL(ticket?) | double | Stop loss price. |
Order.TP(ticket?) | double | Take profit price. |
Order.Expiry(ticket?) | datetime | Expiry time (0 = none). |
Order.PlacedTime(ticket?) | datetime | Time the order was placed. |
Order.Magic(ticket?) | int | Magic number. |
Order.Comment(ticket?) | string | Order comment. |
// DOCS trade — Order loop: cancel our stale pending orders
// Expect: on a new bar with no order of ours, a BUY LIMIT 300 points below the ask (magic 7203,
// "[PLACE] #.."). After stale_min minutes without a fill it is cancelled ("[STALE] cancel #..",
// then Trade() prints "[CANCEL] #.."), and a new one is placed on the next bar.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: cancel stale pending orders";
}
parameters {
int Magic = 7203; // Magic Number
int stale_min = 10; // Cancel after (minutes)
int gap_points = 300; // Limit distance below the ask (points)
}
int OurOrders() {
int n = 0;
for (int i = 0; i < Order.Count(); i = i + 1) {
if (!Order.SetIndex(i)) { break; }
if (Order.Magic() == Magic) { n = n + 1; }
}
return n;
}
Init() {
Print("[INIT] Stale-order test on " + Symbol());
}
Trade() {
if (Event.Magic() != Magic) { return; }
if (Event.Kind() == Event.OrderCancelled) { Print("[CANCEL] #" + ToString(Event.Ticket())); }
if (Event.Kind() == Event.OrderFilled) { Print("[FILLED] #" + ToString(Event.Ticket())); }
}
Tick() {
for (int i = 0; i < Order.Count(); i = i + 1) {
if (!Order.SetIndex(i)) { break; }
if (Order.Magic() != Magic) { continue; }
if (Time.Now() > Order.PlacedTime() + stale_min * 60000) { // ms
Print("[STALE] cancel #" + ToString(Order.Ticket()));
Trade.CancelOrder(); // the selected order
}
}
if (!Time.IsNewBar()) { return; }
if (OurOrders() > 0) { return; }
double px = Symbol.NormalizePrice(Symbol.Ask() - gap_points * Symbol.Point());
int t = Trade.BuyLimit(Symbol(), 0.1, px, 0, 0, "Stale test", Magic);
if (t < 0) { Print("[PLACE] refused: " + Trade.LastErrorText()); } else { Print("[PLACE] #" + ToString(t)); }
}datetime values in milliseconds. Compare as Time.Now() > placed + minutes * 60000 rather than subtracting two times.Managing Pending Orders
A bracket of stop orders that follows the market: each new bar moves both orders to the new high / low with Trade.ModifyOrder (volume and expiry read back from Order.* so they stay unchanged), and Trade() cancels the other side when one fills.
// DOCS trade — Pending orders that follow the market (ModifyOrder) + OCO cancel in Trade()
// Expect: with no position of ours, a BUY STOP gap_points above the previous bar's high and a
// SELL STOP below its low (magic 7206). On every new bar while unfilled both orders move to the
// new high / low, with SL / TP moved along and volume / expiry kept ("[FOLLOW] #.. -> ..").
// When one fills, the other is cancelled ("[FILLED] .." then "[CANCEL] .."). A position closes
// at its SL / TP; then a new pair is placed.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: pending orders following the market";
}
parameters {
int Magic = 7206; // Magic Number
double Lot = 0.1; // Lot Size
int gap_points = 50; // Distance beyond high / low (points)
int sl_points = 300; // Stop Loss (points)
int tp_points = 600; // Take Profit (points)
}
Init() {
Print("[INIT] Pending follow test on " + Symbol());
}
Trade() {
if (Event.Magic() != Magic) { return; }
if (Event.Kind() == Event.OrderFilled) {
Print("[FILLED] #" + ToString(Event.Ticket()) + " @ " + ToString(Event.Price()));
Trade.CancelAll(Symbol(), -1, Magic); // one-cancels-other
}
if (Event.Kind() == Event.OrderCancelled) { Print("[CANCEL] #" + ToString(Event.Ticket())); }
if (Event.Kind() == Event.Rejected) { Print("[REJECTED] " + Event.Comment()); }
}
Tick() {
if (!Time.IsNewBar()) { return; }
string sym = Symbol();
if (Position.Exists(sym, Magic)) { return; }
double pt = Symbol.Point();
double up = Symbol.NormalizePrice(high(1) + gap_points * pt);
double dn = Symbol.NormalizePrice(low(1) - gap_points * pt);
double sl_dist = sl_points * pt;
double tp_dist = tp_points * pt;
int found = 0;
for (int i = 0; i < Order.Count(); i = i + 1) {
if (!Order.SetIndex(i)) { break; }
if (Order.Magic() != Magic || Order.Symbol() != sym) { continue; }
found = found + 1;
int tk = Order.Ticket();
if (Order.Type() == OrderType.BuyStop && Order.Price() != up) {
Trade.ModifyOrder(tk, sym, Order.Volume(), up, Symbol.NormalizePrice(up - sl_dist), Symbol.NormalizePrice(up + tp_dist), Order.Expiry());
Print("[FOLLOW] #" + ToString(tk) + " -> " + ToString(up));
}
if (Order.Type() == OrderType.SellStop && Order.Price() != dn) {
Trade.ModifyOrder(tk, sym, Order.Volume(), dn, Symbol.NormalizePrice(dn + sl_dist), Symbol.NormalizePrice(dn - tp_dist), Order.Expiry());
Print("[FOLLOW] #" + ToString(tk) + " -> " + ToString(dn));
}
}
if (found > 0) { return; }
int b = Trade.BuyStop(sym, Lot, up, Symbol.NormalizePrice(up - sl_dist), Symbol.NormalizePrice(up + tp_dist), "Follow Up", Magic);
if (b < 0) { Print("[BUYSTOP] refused: " + Trade.LastErrorText()); }
int s = Trade.SellStop(sym, Lot, dn, Symbol.NormalizePrice(dn + sl_dist), Symbol.NormalizePrice(dn - tp_dist), "Follow Down", Magic);
if (s < 0) { Print("[SELLSTOP] refused: " + Trade.LastErrorText()); }
}Partial Close
Take half off at a first target and move the stop of the rest to break-even. Trade.ClosePartial keeps the position's ticket, so a static ticket marks it as done.
// DOCS trade — Partial close at a first target, then break-even on the rest
// Expect: one BUY 0.2 (magic 7207, SL 300 / TP 900 points). When the bid is first_points above
// the entry: half the volume closes ("[PARTIAL] #.. closed 0.1") and the SL of the remaining
// 0.1 moves to the entry ("[PARTIAL] stop to entry"). Done once per position.
// In the tester a partial close shows as a Modified (volume) event, not as a deal.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: partial close + break-even";
}
parameters {
int Magic = 7207; // Magic Number
double Lot = 0.2; // Lot Size
int first_points = 300; // First Target (points)
}
static int done_ticket; // position already partially closed
Init() {
done_ticket = -1;
Print("[INIT] Partial close test on " + Symbol());
}
Tick() {
string sym = Symbol();
double pt = Symbol.Point();
if (!Position.Exists(sym, Magic)) {
if (Time.IsNewBar()) {
double ask = Symbol.Ask();
int t = Trade.Buy(sym, Lot, Symbol.NormalizePrice(ask - 300 * pt), Symbol.NormalizePrice(ask + 900 * pt), "Partial", Magic);
if (t < 0) { Print("[ENTRY] refused: " + Trade.LastErrorText()); }
}
return;
}
int ticket = Position.Ticket(sym, Magic, Side.Long);
if (ticket < 0 || ticket == done_ticket) { return; }
double op = Position.OpenPrice(sym, Magic, Side.Long);
if (Symbol.Bid() - op > first_points * pt) {
double half = Symbol.NormalizeVolume(Position.Volume(sym, Magic, Side.Long) / 2.0);
if (Trade.ClosePartial(ticket, half, sym)) {
Print("[PARTIAL] #" + ToString(ticket) + " closed " + ToString(half));
Trade.Modify(ticket, sym, op, -1.0);
Print("[PARTIAL] stop to entry");
}
done_ticket = ticket;
}
}Deal.* & History.*
| Function / Property | Returns | Description |
|---|---|---|
History.Deals(from?, to?, magic?, sym?) | int[] | Tickets of closed deals (from / to datetime in ms, 0 = no bound; magic -1 = any; sym "" = all). Read them with Deal.*(ticket). |
History.Deals.last() | int | Ticket of the newest deal of the whole history (-1 when none). Takes no filter — for one magic use the array. |
History.Deals.first() | int | Ticket of the oldest deal (-1 when none). |
History.Orders(from?, to?, magic?, sym?) | int[] | Tickets of completed orders. |
Deal.SetIndex(i) | bool | Select deal i. |
Deal.Select(ticket) | bool | Select a deal by ticket. |
Deal.Ticket(i?) | int | Ticket of deal i. |
Deal.OrderTicket(ticket?) | int | Ticket of the order that produced the deal. |
Deal.Symbol(ticket?) | string | Symbol name. |
Deal.Direction(ticket?) | int | Side.Long or Side.Short. |
Deal.Entry(ticket?) | int | Entry type of the deal. |
Deal.Volume(ticket?) | double | Executed lot size. |
Deal.Price(ticket?) | double | Close (execution) price. |
Deal.OpenPrice(ticket?) | double | Entry price of the closed position. |
Deal.Profit(ticket?) | double | Realised profit / loss. |
Deal.Commission(ticket?) | double | Commission. |
Deal.Swap(ticket?) | double | Swap. |
Deal.Time(ticket?) | datetime | Close time. |
Deal.OpenTime(ticket?) | datetime | Entry time. |
Deal.Magic(ticket?) | int | Magic number. |
Deal.Comment(ticket?) | string | Deal comment. |
// DOCS trade — History.Deals + Deal.*: pause after a losing trade, closed P/L report
// Expect: one position at a time (magic 7204, SL = TP = 200 points, direction of the last bar).
// After a losing close: "[PAUSE] last deal #.. lost .. - waiting" on each new bar for
// pause_min minutes, then entries resume. Once per new bar: "[HIST] deals=.. closed P/L=..".
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: history pause after a loss";
}
parameters {
int Magic = 7204; // Magic Number
int pause_min = 60; // Pause after a loss (minutes)
int sl_points = 200; // Stop Loss / Take Profit (points)
}
Init() {
Print("[INIT] History pause test on " + Symbol());
}
Tick() {
if (!Time.IsNewBar()) { return; }
int deals[] = History.Deals(0, 0, Magic, Symbol());
int n = length(deals);
double net = 0.0;
for (int i = 0; i < n; i = i + 1) {
net = net + Deal.Profit(deals[i]);
}
Print("[HIST] deals=" + ToString(n) + " closed P/L=" + ToString(net));
if (n > 0) {
int newest = deals[n - 1]; // newest deal
if (Deal.Profit(newest) < 0.0 && Time.Now() < Deal.Time(newest) + pause_min * 60000) {
Print("[PAUSE] last deal #" + ToString(newest) + " lost " + ToString(Deal.Profit(newest)) + " - waiting");
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(), 0.1, Symbol.NormalizePrice(ask - sl_points * pt), Symbol.NormalizePrice(ask + sl_points * pt), "Hist Long", Magic);
} else {
double bid = Symbol.Bid();
t = Trade.Sell(Symbol(), 0.1, Symbol.NormalizePrice(bid + sl_points * pt), Symbol.NormalizePrice(bid - sl_points * pt), "Hist Short", Magic);
}
if (t < 0) { Print("[ENTRY] refused: " + Trade.LastErrorText()); }
}Trade() & Timer()
Trade() { } runs once per trade event (in live trading and in the tester), before the next Tick(). Events come from the changes of your positions and pending orders between ticks, plus broker rejections. Read the event with Event.*. Timer() { } runs every Timer.Set(seconds): live on the broker clock in its own loop, so it fires on a quiet market too; in the tester each due call runs at its own scheduled simulated time.
| Function / Property | Description |
|---|---|
Event.Opened | A position opened (market order filled, or a pending order turned into a position). |
Event.Closed | A position closed — Event.Reason() says why, Event.Profit() is the realised result. |
Event.Modified | SL / TP of a position changed (in the tester also a partial close: volume change). |
Event.OrderPlaced | A pending order was accepted. |
Event.OrderFilled | A pending order filled. |
Event.OrderCancelled | A pending order was cancelled. |
Event.OrderExpired | A pending order reached its expiry. |
Event.Rejected | The broker refused a request — Event.Error() (3 = rejected), Event.Comment() = reason. |
Event.ObjectDragged | ChartEvent() only: an editable draw.* object was dropped. Event.Object() = its name. |
Event.ObjectClicked | ChartEvent() only: an editable draw.* object was clicked. Event.Object() = its name. |
Event.ChartClick | ChartEvent() only: empty chart was clicked. Event.Price() / Event.Time() = where. |
| Function / Property | Returns | Description |
|---|---|---|
Event.Kind() | int | One of the kinds above. |
Event.Ticket() | int | Position / order ticket. |
Event.Symbol() | string | Symbol. |
Event.Side() | int | Side.Buy / Side.Sell. |
Event.Volume() | double | Volume. |
Event.Price() | double | Price. |
Event.Profit() | double | Realised profit (Closed). |
Event.Magic() | int | Magic number. |
Event.Reason() | int | Reason.Manual, StopLoss, TakeProfit, StopOut, Expired, Strategy. |
Event.Error() | int | Error code for Rejected (same codes as Trade.LastError()). |
Event.Comment() | string | Comment / rejection text. |
Event.Object() | string | ChartEvent(): name of the dragged / clicked object ("" for a chart click). |
Event.Time() | datetime | Event time. |
Timer.Set(seconds) | bool | Start (or change) the Timer() period. Called inside Timer() it re-anchors on that call's time. |
Timer.Kill() | bool | Stop the timer. |
// DOCS trade — Trade() events with close reasons + Timer() equity line
// Expect (Journal): every 60 s, also on a quiet market: "[TIMER] equity=.. balance=..".
// For our positions (magic 7205): "[EVT] opened #..", on a close "[EVT] SL hit #.. ..",
// "[EVT] TP hit #.. .." or "[EVT] closed #.. by strategy/manual", and "[EVT] rejected (..): .."
// for refusals. Entry: one position, direction of the last bar, SL = TP = 150 points.
about {
author: "CoreXTrader";
version: "1.0.0";
about: "Docs: Trade() events and Timer()";
}
parameters {
int Magic = 7205; // Magic Number
int sl_points = 150; // Stop Loss / Take Profit (points)
}
Init() {
Timer.Set(60); // Timer() every minute
}
Trade() {
if (Event.Magic() != Magic) { return; }
int kind = Event.Kind();
if (kind == Event.Opened) {
Print("[EVT] opened #" + ToString(Event.Ticket()) + " " + ToString(Event.Volume()) + " @ " + ToString(Event.Price()));
} else if (kind == Event.Closed) {
if (Event.Reason() == Reason.StopLoss) {
Print("[EVT] SL hit #" + ToString(Event.Ticket()) + " " + ToString(Event.Profit()));
} else if (Event.Reason() == Reason.TakeProfit) {
Print("[EVT] TP hit #" + ToString(Event.Ticket()) + " " + ToString(Event.Profit()));
} else if (Event.Reason() == Reason.Strategy) {
Print("[EVT] closed #" + ToString(Event.Ticket()) + " by strategy");
} else {
Print("[EVT] closed #" + ToString(Event.Ticket()) + " manual / other (" + ToString(Event.Reason()) + ")");
}
} else if (kind == Event.Rejected) {
Print("[EVT] rejected (" + ToString(Event.Error()) + "): " + Event.Comment());
}
}
Timer() {
Print("[TIMER] equity=" + ToString(Account.Equity()) + " balance=" + ToString(Account.Balance()));
}
Tick() {
if (!Time.IsNewBar()) { return; }
if (Position.Exists(Symbol(), Magic)) { return; }
double pt = Symbol.Point();
if (close(1) > open(1)) {
double ask = Symbol.Ask();
Trade.Buy(Symbol(), 0.1, Symbol.NormalizePrice(ask - sl_points * pt), Symbol.NormalizePrice(ask + sl_points * pt), "Evt Long", Magic);
} else {
double bid = Symbol.Bid();
Trade.Sell(Symbol(), 0.1, Symbol.NormalizePrice(bid + sl_points * pt), Symbol.NormalizePrice(bid - sl_points * pt), "Evt Short", Magic);
}
}
Exit() {
Timer.Kill();
}Constants
Side.LongSide.ShortSide.BuySide.SellOrderType.BuyLimitOrderType.SellLimitOrderType.BuyStopOrderType.SellStopEvent.OpenedEvent.ClosedEvent.ModifiedEvent.OrderPlacedEvent.OrderFilledEvent.OrderCancelledEvent.OrderExpiredEvent.RejectedReason.ManualReason.StopLossReason.TakeProfitReason.StopOutReason.ExpiredReason.StrategySide.Buy equals Side.Long (0) and Side.Sell equals Side.Short (1).