Docs / Trade Language

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 / PropertyReturnsDescription
Trade.Buy(sym?, vol, sl?, tp?, comment?, magic?, dev?)intMarket buy. Returns the ticket, or -1 when refused. sl / tp 0 = none.
Trade.Sell(sym?, vol, sl?, tp?, comment?, magic?, dev?)intMarket sell. Returns the ticket, or -1 when refused.
Trade.BuyLimit(sym?, vol, px, sl?, tp?, comment?, magic?, exp?)intPending buy limit (px below the ask). Ticket or -1.
Trade.SellLimit(sym?, vol, px, sl?, tp?, comment?, magic?, exp?)intPending sell limit (px above the bid). Ticket or -1.
Trade.BuyStop(sym?, vol, px, sl?, tp?, comment?, magic?, exp?)intPending buy stop (px above the ask). Ticket or -1.
Trade.SellStop(sym?, vol, px, sl?, tp?, comment?, magic?, exp?)intPending sell stop (px below the bid). Ticket or -1.
Trade.BuyStopLimit(sym?, vol, px, limit, sl?, tp?, comment?, magic?, exp?)intBuy 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?)intSell stop at px; when triggered it becomes a sell limit at limit. Ticket or -1.
Trade.Close(ticket?, sym?, dir?, magic?, comment?)boolClose one position. No ticket = the SetIndex-ed position.
Trade.CloseAll(sym?, dir?, magic?, comment?)boolClose all matching positions ("" = all symbols, -1 = any side / magic).
Trade.ClosePartial(ticket, vol, sym?, comment?)boolClose vol lots of a position; the rest stays open with the same ticket.
Trade.Modify(ticket?, sym?, sl?, tp?, comment?)boolChange 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?)boolChange a pending order (volume, price, SL / TP, expiry). Pass every value — read the ones you keep from Order.*.
Trade.CancelOrder(ticket?, sym?, comment?)boolCancel a pending order. No ticket = the SetIndex / Select-ed order.
Trade.CancelAll(sym?, dir?, magic?, type?, comment?)boolCancel all matching pending orders (type = OrderType.*, -1 = any).
Trade.Positions()int[]Tickets of all open positions.
Trade.Orders()int[]Tickets of all pending orders.
trade_order_execution.tdslTDSL
// 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;
        }
    }
}
Tip
Wait for the 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 / PropertyReturnsDescription
Trade.LastError()int0 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()stringHuman-readable reason for the last refusal.
Trade.LastTicket()intTicket of the last successful request.
Trade.LastPrice()doublePrice of the last request.
Note
In live trading the ticket is provisional until the broker confirms; the in-flight order already counts as a position for 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 / PropertyDescription
VolumeMust be between Symbol.LotMin() and Symbol.LotMax() and a multiple of Symbol.LotStep() (use Symbol.NormalizeVolume()).
Total volumeAt most 100 lots open in total.
MarginFree margin must cover the required margin × 1.1. Falling below the stop-out level closes positions (Reason.StopOut).
Market SL / TPBuy: SL below and TP above the bid. Sell: SL above and TP below the ask.
Pending priceLimit 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).
ModifySame 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 / PropertyDescription
(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 / CancelAllSame 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; }
Note
Not found: a property read with a filter that matches nothing returns -1 for tickets and directions — a missing position never reads as Side.Long. Test with Position.Exists() first.

Position.*

Note
Filters are (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 / PropertyReturnsDescription
Position.Count(sym?, magic?, dir?)intNumber of matching open positions (no arguments = all).
Position.Exists(sym?, magic?, dir?)boolTrue if at least one matching position exists.
Position.AvgOpenPrice(sym?, magic?, dir?)doubleVolume-weighted average entry price of matching positions.
Position.SetIndex(i)boolSelect position i. False past the end.
Position.Ticket(sym?, magic?, dir?)intTicket (-1 when not found).
Position.Symbol(sym?, magic?, dir?)stringSymbol name.
Position.Direction(sym?, magic?, dir?)intSide.Long or Side.Short (-1 when not found).
Position.Side()intSame as Direction() for the selected position.
Position.Volume(sym?, magic?, dir?)doubleLot size.
Position.OpenPrice(sym?, magic?, dir?)doubleEntry price.
Position.CurrentPrice(sym?, magic?, dir?)doubleCurrent close price (bid for longs, ask for shorts).
Position.SL(sym?, magic?, dir?)doubleStop loss price (0 if none).
Position.TP(sym?, magic?, dir?)doubleTake profit price (0 if none).
Position.Profit(sym?, magic?, dir?)doubleFloating profit / loss.
Position.Swap(sym?, magic?, dir?)doubleAccumulated swap.
Position.Commission(sym?, magic?, dir?)doubleCommission.
Position.OpenTime(sym?, magic?, dir?)datetimeTime the position was opened.
Position.Duration(sym?, magic?, dir?)intTime the position has been open.
Position.Magic(sym?, magic?, dir?)intMagic number.
Position.Comment(sym?, magic?, dir?)stringPosition comment.
trade_position_loop.tdslTDSL
// 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 / PropertyReturnsDescription
Order.Count()intNumber of pending orders (all symbols, all magics — filter in the loop).
Order.SetIndex(i)boolSelect pending order i. False past the end.
Order.Select(ticket)boolSelect a pending order by ticket.
Order.Ticket(i?)intTicket of order i (no index = the selected order).
Order.Symbol(ticket?)stringSymbol name.
Order.Type(ticket?)intOrderType.BuyLimit / SellLimit / BuyStop / SellStop.
Order.Side(ticket?)intSide.Buy or Side.Sell.
Order.Volume(ticket?)doubleLot size.
Order.Price(ticket?)doubleOrder price.
Order.StopPrice(ticket?)doubleStop (trigger) price of a stop-limit order.
Order.SL(ticket?)doubleStop loss price.
Order.TP(ticket?)doubleTake profit price.
Order.Expiry(ticket?)datetimeExpiry time (0 = none).
Order.PlacedTime(ticket?)datetimeTime the order was placed.
Order.Magic(ticket?)intMagic number.
Order.Comment(ticket?)stringOrder comment.
trade_cancel_stale.tdslTDSL
// 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)); }
}
Tip
Times are 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.

trade_pending_follow.tdslTDSL
// 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()); }
}
Note
A move that would put a stop order on the wrong side of the market (for example a buy stop below the ask) is refused like a new order would be; the order then simply stays where it was.

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.

trade_partial_close.tdslTDSL
// 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 / PropertyReturnsDescription
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()intTicket of the newest deal of the whole history (-1 when none). Takes no filter — for one magic use the array.
History.Deals.first()intTicket of the oldest deal (-1 when none).
History.Orders(from?, to?, magic?, sym?)int[]Tickets of completed orders.
Deal.SetIndex(i)boolSelect deal i.
Deal.Select(ticket)boolSelect a deal by ticket.
Deal.Ticket(i?)intTicket of deal i.
Deal.OrderTicket(ticket?)intTicket of the order that produced the deal.
Deal.Symbol(ticket?)stringSymbol name.
Deal.Direction(ticket?)intSide.Long or Side.Short.
Deal.Entry(ticket?)intEntry type of the deal.
Deal.Volume(ticket?)doubleExecuted lot size.
Deal.Price(ticket?)doubleClose (execution) price.
Deal.OpenPrice(ticket?)doubleEntry price of the closed position.
Deal.Profit(ticket?)doubleRealised profit / loss.
Deal.Commission(ticket?)doubleCommission.
Deal.Swap(ticket?)doubleSwap.
Deal.Time(ticket?)datetimeClose time.
Deal.OpenTime(ticket?)datetimeEntry time.
Deal.Magic(ticket?)intMagic number.
Deal.Comment(ticket?)stringDeal comment.
trade_history_pause.tdslTDSL
// 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 / PropertyDescription
Event.OpenedA position opened (market order filled, or a pending order turned into a position).
Event.ClosedA position closed — Event.Reason() says why, Event.Profit() is the realised result.
Event.ModifiedSL / TP of a position changed (in the tester also a partial close: volume change).
Event.OrderPlacedA pending order was accepted.
Event.OrderFilledA pending order filled.
Event.OrderCancelledA pending order was cancelled.
Event.OrderExpiredA pending order reached its expiry.
Event.RejectedThe broker refused a request — Event.Error() (3 = rejected), Event.Comment() = reason.
Event.ObjectDraggedChartEvent() only: an editable draw.* object was dropped. Event.Object() = its name.
Event.ObjectClickedChartEvent() only: an editable draw.* object was clicked. Event.Object() = its name.
Event.ChartClickChartEvent() only: empty chart was clicked. Event.Price() / Event.Time() = where.
Function / PropertyReturnsDescription
Event.Kind()intOne of the kinds above.
Event.Ticket()intPosition / order ticket.
Event.Symbol()stringSymbol.
Event.Side()intSide.Buy / Side.Sell.
Event.Volume()doubleVolume.
Event.Price()doublePrice.
Event.Profit()doubleRealised profit (Closed).
Event.Magic()intMagic number.
Event.Reason()intReason.Manual, StopLoss, TakeProfit, StopOut, Expired, Strategy.
Event.Error()intError code for Rejected (same codes as Trade.LastError()).
Event.Comment()stringComment / rejection text.
Event.Object()stringChartEvent(): name of the dragged / clicked object ("" for a chart click).
Event.Time()datetimeEvent time.
Timer.Set(seconds)boolStart (or change) the Timer() period. Called inside Timer() it re-anchors on that call's time.
Timer.Kill()boolStop the timer.
trade_events_timer.tdslTDSL
// 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 constants
Side.LongSide.ShortSide.BuySide.Sell
OrderType constants
OrderType.BuyLimitOrderType.SellLimitOrderType.BuyStopOrderType.SellStop
Event kinds
Event.OpenedEvent.ClosedEvent.ModifiedEvent.OrderPlacedEvent.OrderFilledEvent.OrderCancelledEvent.OrderExpiredEvent.Rejected
Close reasons
Reason.ManualReason.StopLossReason.TakeProfitReason.StopOutReason.ExpiredReason.Strategy

Side.Buy equals Side.Long (0) and Side.Sell equals Side.Short (1).