Open platform

Script guide

How to write strategies and indicators for Triton. Scripts are C#, compiled and run in your browser. Each chapter teaches from one whole script that works, and every script here is compiled and run by Triton's own tests.

1 Your first strategy

What a script is, where to write one, and how to run it.

A script is one C# class. A strategy is a class that inherits from Strategy. Triton calls its OnBarUpdate once for every bar, at the moment the bar closes. Whatever the script orders there happens from the next bar on: a market order fills at the next bar's open. That is the whole shape.

Open Scripts from the toolbar and press New strategy. This is a complete one:

first-strategy.cs
// A moving average cross: long while the fast average is above the slow one, short while it is below.
public class AverageCross : Strategy
{
    [Parameter("Fast average", Min = 2, Max = 100)]
    public int Fast { get; set; } = 9;

    [Parameter("Slow average", Min = 5, Max = 300)]
    public int Slow { get; set; } = 21;

    protected override void OnBarUpdate()
    {
        if (CrossAbove(EMA(Fast), EMA(Slow))) EnterLong();
        if (CrossBelow(EMA(Fast), EMA(Slow))) EnterShort();
    }
}

EMA(Fast) is a series: one number per bar. CrossAbove(a, b) is true on the bar where a goes from at or under b to over it. EnterLong() buys at the next open. A strategy holds one position at a time, so EnterShort() while long closes the long first and then goes short.

Press Check to compile. The first time, the C# engine is downloaded, about 7 MB, and the browser keeps it after that. Problems are listed under the editor, each with a link to its line. Then press Test in Backtest, choose the market and how many bars, and Run backtest.

The two properties marked [Parameter] appear under the editor as settings, so their values can be changed without touching the code. Min and Max keep a setting inside sensible limits. Only int, double and bool properties can be settings.

2 Bars and series

Reading prices, and not reading past either end of them.

Close[0] is the close of the bar that just finished. Close[1] is the one before, Close[2] the one before that. The same goes for Open, High, Low, Volume, and for every indicator.

CurrentBar is the number of the current bar, counting from 0. On the first bar there is no Close[1], and asking for it stops the run with a message that says which bar and how far back. So a script that looks back starts by checking it can.

reading-bars.cs
// Buys when a bar closes above the high of an inside bar: a bar whose whole range sat within the bar before it.
public class InsideBarBreak : Strategy
{
    protected override void OnBarUpdate()
    {
        // [2] reaches two bars back, so there have to be three bars before this may run.
        if (CurrentBar < 2) return;

        bool inside = High[1] <= High[2] && Low[1] >= Low[2];
        if (inside && Close[0] > High[1] && Position.IsFlat)
        {
            Print("Inside bar broken on the bar that closed " + CloseTime[0].ToString("MMM d HH:mm") + ", at " + Close[0]);
            EnterLong();
        }

        // Out after ten bars, whatever has happened.
        if (Position.IsLong && BarsSinceEntry >= 10) ExitLong();
    }
}

A script can never read ahead: Close[-1] is refused. What a script knew on a bar in a backtest is what it would have known live.

Print writes a line to Script output, shown above the results. The first 500 lines of a run are kept. It is the quickest way to see what a script is doing.

Position.IsFlat, IsLong and IsShort say what is held. BarsSinceEntry counts the bars a position has been held, with the bar it was entered on as 1. Position.AveragePrice is where it was entered.

3 Orders

Market, limit and stop orders, with sizes and names.

There are three kinds of order. A market order fills at the next bar's open. A limit order waits for a price you name and fills there or better. A stop order waits for price to reach a level and then fills like a market order, which is how a breakout is bought.

orders.cs
// Two ways in. A limit order waits for a better price. A stop order waits for price to prove itself.
public class PullbackOrBreakout : Strategy
{
    [Parameter("Contracts", Min = 1, Max = 20)]
    public int Contracts { get; set; } = 2;

    protected override void OnBarUpdate()
    {
        if (CurrentBar < 20) return;
        var average = SMA(20);

        if (Position.IsFlat)
        {
            if (Close[0] > average[0])
            {
                // Above the average: try to buy a dip back to it. A limit order works for the next bar only,
                // so it is placed again on every bar the idea still holds, at the average's new value.
                EnterLongLimit(RoundToTick(average[0]), Contracts, "dip");
            }
            else
            {
                // Below it: buy only if price breaks the highest high of the last 20 bars.
                EnterLongStop(Highest(High, 20)[0] + TickSize, Contracts, "breakout");
            }
        }
        else if (BarsSinceEntry >= 30)
        {
            // A market order: it fills at the open of the next bar.
            ExitLong("time is up");
        }
    }
}
  • EnterLong(), EnterShort(): market orders, at the size in Quantity.
  • EnterLong(2, "name"): a size and a name. The name is yours: an exit can ask for it, and OnFill reports it.
  • EnterLongLimit(price, quantity, name) and EnterShortLimit: limit orders.
  • EnterLongStop(price, quantity, name) and EnterShortStop: stop orders.
  • ExitLong(), ExitShort(), ExitPosition(): close at the next open. ExitLong(1) closes part. ExitLong("why", "name") closes only the entry of that name.
  • ExitLongLimit, ExitLongStop and the short ones: exits that wait for a price.
  • CancelOrders(): cancels the limit and stop orders the script has working.

A limit or stop order works for the next bar and is then cancelled. To keep it, place it again on each bar: calling the same method with the same name moves the order instead of adding a second one. Or pass keep: true and it stays until it fills or is cancelled.

RoundToTick(price) moves a price to the nearest one the market trades at. An average is rarely on a tick, and an order should be.

MaxEntries is 1 unless the script says more. Set it to 3 in OnStart and three entries can be open at once, each with its own name, stop and target.

FillLimitsOnTouch is true unless the script says otherwise: a limit fills when price reaches it. Set it to false and price has to go through the limit, which is the more cautious reading, since in a live market an order at the very edge of a move often goes unfilled.

4 Stops, targets and fills

Protecting a trade, and hearing what happened to it.

A stop and a target can be set once, in OnStart, and every entry then gets them. OnStart runs once, before the first bar.

stops-and-fills.cs
// A stop and a target on every entry. Once the trade is 10 ticks ahead, the stop is moved up to the entry price.
public class Breakeven : Strategy
{
    [Parameter("Stop, ticks", Min = 2, Max = 200)]
    public int StopTicks { get; set; } = 16;

    [Parameter("Target, ticks", Min = 2, Max = 400)]
    public int TargetTicks { get; set; } = 32;

    private bool moved;

    protected override void OnStart()
    {
        // Set once, these go on with every entry from now on.
        SetStopLoss(StopTicks);
        SetProfitTarget(TargetTicks);
    }

    protected override void OnBarUpdate()
    {
        if (CurrentBar < 14) return;
        if (Position.IsFlat && CrossAbove(RSI(14), 50)) EnterLong("long");

        if (Position.IsLong && !moved && Position.TicksAt(Close[0]) >= 10)
        {
            MoveStop(Position.AveragePrice);
            moved = true;
        }
    }

    // Runs the moment an order fills, before the next bar.
    protected override void OnFill(Fill fill)
    {
        if (fill.IsEntry) moved = false;
        else Print(fill.Name + " closed the trade at " + fill.Price + ". Net so far: " + NetProfit);
    }
}
  • SetStopLoss(ticks), SetProfitTarget(ticks): a distance from the entry price, in ticks.
  • SetStopLossPrice(price), SetStopLossMoney(amount), SetStopLossPercent(0.01): the same, given as a price, as money at risk, or as a share of the entry price. The target has the same three.
  • SetTrailingStop(ticks): a stop that follows the best price the trade has seen.
  • MoveStop(price), MoveTarget(price): move the stop or target of what is open now.

The Set methods are about entries to come. Pass moveOpen: true to put the same stop on what is open as well.

OnFill runs the moment an order fills. The Fill it is handed has a Name (yours, or Triton's: Long, Short, Exit long, Exit short, Stop, Target, Trailing stop, Reversal, Session close), IsEntry, IsBuy, Quantity, Price, Time and Bar. An order placed inside OnFill works from the next prices on, so a script can place its own exits the moment it is in.

5 Indicators and your own series

What is built in, and how to feed an indicator something other than price.

Indicators are methods that give back a series. Asking for the same one twice gives back the one already made, so there is no need to store them: write SMA(20)[0] wherever it is wanted.

indicators.cs
// Trades a stochastic cross, but only when ADX says there is a trend and the bars are wider than usual.
public class TrendStochastic : Strategy
{
    private Series range = null!;

    protected override void OnStart()
    {
        // A series of your own: one number per bar, for you to fill in.
        range = NewSeries("range");
    }

    protected override void OnBarUpdate()
    {
        // Set this bar's value first. After that it can be fed to any indicator, like a price.
        range[0] = High[0] - Low[0];
        if (CurrentBar < 30) return;

        var stochastic = Stochastics(3, 14, 3);
        bool trending = ADX(14)[0] > 20;
        bool awake = range[0] > SMA(range, 20)[0];

        if (trending && awake && CrossAbove(stochastic.K, stochastic.D)) EnterLong();
        if (trending && awake && CrossBelow(stochastic.K, stochastic.D)) EnterShort();
    }
}

The built-in indicators come in two families, and the difference matters on the first bars of a run.

These are worked out by the formula the chart draws, and have no value until they have enough bars. Until then they are blank, and any comparison with a blank is false, so a script simply does nothing:

  • SMA, EMA, WMA, RSI, ATR, StdDev, Momentum, ROC, each taking a period, or a series and a period.
  • Highest(series, period) and Lowest(series, period).
  • Bollinger(period, multiplier) with .Upper, .Middle and .Lower.
  • MACD(fast, slow, signal) with .Value, .Signal and .Histogram.

These have a value from the first bar: an average of 20 bars is the average of however many there are until there are 20. Guard them with CurrentBar if the early values should not be traded:

  • HMA, DEMA, TEMA, VWMA, Sum(series, period).
  • Stochastics(periodD, periodK, smooth) with .K and .D.
  • ADX, CCI, WilliamsR, MFI, each taking a period, and OBV().
  • DonchianChannel(period) and KeltnerChannel(period, multiplier), each with .Upper, .Middle and .Lower.
  • Swing(strength) with .High and .Low: the last swing high and low, each known strength bars after it happened.
  • SessionSoFar() with .Open, .High, .Low, and PriorSession() with .Open, .High, .Low, .Close.

NewSeries() gives a series of your own. Set mine[0] on each bar and it can be fed to any indicator that takes a series, as the sample does with the bar's range.

CrossAbove and CrossBelow take two series, or a series and a level such as 70. Rising(series) and Falling(series) compare this bar with the one before.

6 Time and sessions

Trading by the clock, and knowing when a session starts.

Every bar has two times. Time[0] is when it opened and CloseTime[0] is when it closed. A rule like "be flat by 15:00" is about the bar that closes at 15:00, so it is CloseTime that such rules usually want.

sessions.cs
// Opening range breakout. The first 30 minutes of a session set a high and a low. After that,
// the first close beyond either is traded, once a session, and everything is closed by 15:00.
public class OpeningRange : Strategy
{
    [Parameter("Minutes in the opening range", Min = 5, Max = 120)]
    public int Minutes { get; set; } = 30;

    private double high;
    private double low;
    private DateTime rangeEnds;
    private bool traded;

    protected override void OnStart()
    {
        // Never hold through the daily shut.
        ExitAtSessionClose = true;
    }

    protected override void OnBarUpdate()
    {
        if (IsFirstBarOfSession)
        {
            high = High[0];
            low = Low[0];
            // Time is when a bar opened. CloseTime is when it closed.
            rangeEnds = Time[0].AddMinutes(Minutes);
            traded = false;
        }

        // A bar that closes at or before the end of the range belongs to it.
        if (CloseTime[0] <= rangeEnds)
        {
            high = Math.Max(high, High[0]);
            low = Math.Min(low, Low[0]);
            return;
        }

        // 150000 is 15:00:00, on the clock chosen on the Backtest form.
        bool late = ToTime(CloseTime[0]) >= 150000 && ToTime(CloseTime[0]) < 170000;
        if (late)
        {
            ExitPosition();
            return;
        }

        if (!traded && Position.IsFlat)
        {
            if (Close[0] > high) { EnterLong(); traded = true; }
            else if (Close[0] < low) { EnterShort(); traded = true; }
        }
    }
}

ToTime(CloseTime[0]) turns a time of day into a whole number: 9:30:00 is 93000. ToDay does the same for a date: March 2, 2026 is 20260302. Both make times easy to compare and easy to turn into settings.

Times are read on the clock chosen on the Backtest form, under Clock for times of day in the strategy. It starts as your device's. A strategy written with Eastern times in mind needs Eastern chosen there.

IsFirstBarOfSession is true on the first bar after the market was shut, which Triton tells from the bars: the first bar that starts more than half an hour late. For index futures that is the evening open, not midnight. For a market that never shuts it is the first bar of each day.

ExitAtSessionClose = true closes whatever is held at the last bar before the market shuts for the day.

7 Sizing from results

Letting a strategy read what it has made so far.

A strategy can see its own record while it runs. NetProfit is what its closed trades have made so far in money, with the commission from the Backtest form taken off. Trades is the list of those trades, oldest first.

sizing.cs
// Size follows results: one more contract after a week that made money, one fewer after a week that lost.
public class StepSizing : Strategy
{
    [Parameter("Most contracts", Min = 1, Max = 50)]
    public int Most { get; set; } = 5;

    private int size = 1;
    private double profitAtLastStep;
    private DateTime lastStep;

    protected override void OnBarUpdate()
    {
        if (CurrentBar < 50) return;

        if ((CloseTime[0] - lastStep).TotalDays >= 7)
        {
            // NetProfit is what the closed trades of this run have made so far, with commission taken off.
            double change = NetProfit - profitAtLastStep;
            if (change > 0) size = Math.Min(Most, size + 1);
            else if (change < 0) size = Math.Max(1, size - 1);
            profitAtLastStep = NetProfit;
            lastStep = CloseTime[0];

            // Trades is the list of closed trades, oldest first.
            int won = Trades.Count(t => t.Profit > 0);
            Print(CloseTime[0].ToString("MMM d") + ": " + Trades.Count + " trades, " + won + " won. Size is now " + size + ".");
        }

        if (CrossAbove(Close, SMA(50))) EnterLong(size);
        if (CrossBelow(Close, SMA(50))) EnterShort(size);
    }
}

Each trade in Trades has Profit, ProfitTicks, ProfitPoints, IsLong, Quantity, EntryPrice, ExitPrice, EntryTime, ExitTime, EntryName and ExitName.

For the trade that is still open, Position.ProfitAt(Close[0]) is what it would make at that price, and Position.TicksAt(Close[0]) is how many ticks it is ahead.

TickSize and PointValue describe the market: the smallest price step, and what one whole point is worth for a size of one. Risk in money for a stop of n ticks is n * TickSize * PointValue * size.

8 Writing an indicator

A script that draws on the chart instead of trading.

An indicator is a class that inherits from Indicator. In OnStart it says what it draws, and in OnBarUpdate it sets each plot's value for the bar. It has the same bars, series, indicators and time helpers as a strategy.

indicator.cs
// An indicator of your own: how far price is from its average, in ticks, drawn as bars in a pane under the chart.
public class DistanceFromAverage : Indicator
{
    [Parameter("Average length", Min = 2, Max = 300)]
    public int Length { get; set; } = 20;

    private Series distance = null!;

    protected override void OnStart()
    {
        // AddPlot gives back the series to fill in. The color is written as #rrggbb.
        distance = AddPlot("Distance, ticks", "#d4af37", PlotStyle.Histogram);
        AddLevel(0);
    }

    protected override void OnBarUpdate()
    {
        if (CurrentBar < Length) return;
        distance[0] = (Close[0] - SMA(Length)[0]) / TickSize;
    }
}

AddPlot(name, color, style) gives back a series to fill in. An indicator can have up to eight plots, drawn as a line, as bars with PlotStyle.Histogram, or as dots. A bar whose value is never set is left blank.

Overlay = true in OnStart draws over the candles. Without it the indicator gets a pane of its own under the chart, where AddLevel(value) marks a level across it.

Press Check, then Add to chart. The indicator appears on the trading chart and in the Indicators panel, with its settings. It runs over the newest 20,000 bars at most, again when a bar is added, and every few seconds while the newest bar is moving. A chart holds up to six script indicators, and one that runs for more than ten seconds is stopped.

9 How fills are worked out

What a backtest assumes, which decides how far its result can be trusted.

A backtest has bars, not every trade that happened inside them, so it has to make assumptions. These are Triton's:

  • A script decides when a bar has closed. A market order fills at the open of the next bar, moved against the trade by the slippage on the Backtest form.
  • A stop order fills at its price, or at the open when the bar opens beyond it, and slips. A limit order fills at its price, or at the open when that is better, and does not slip.
  • Inside one bar the order of prices is not known. When a bar reaches both a stop and a target, the stop is taken to have come first.
  • On the bar an entry fills inside, a stop counts if the bar reached it. A target counts only when price must have reached it after the entry.
  • With an uploaded file finer than the bars tested, such as ticks under five-minute bars, the finer data is walked in order and none of this guessing is needed.
  • A position still open on the last bar is closed at that bar's close.

The cautious reading is chosen every time. A result that survives it has earned more trust than one that depends on the kind reading. Even so: no past result says what a strategy will do next.

10 Testing without fooling yourself

The tools around a script, and the traps they are there for.

Set slippage and commission on the Backtest form before believing anything. A strategy that only works with free fills does not work.

The chart's own futures feed is simulated for now, and a test on it says nothing about a real market. Upload real bars or ticks to test for real. The file is read on your device and is not sent anywhere.

Try a range of values runs a script once for each combination of one or two settings. The best of many tries always looks better than it is, because some of what put it on top is luck in that stretch of data. So hold back the newest data, or use walk-forward, which chooses settings on one stretch and checks them on the next, several times over. Trust those figures over the top row.

Past runs keeps what each test made, with the script and settings that made it, so a result can be found again and run again.

11 Coming from NinjaTrader

Running a NinjaTrader strategy as it is, and converting it to Triton's own library.

A strategy written for NinjaTrader 8 runs in Triton unchanged. Paste the whole file into the editor and press Check. It runs on Triton's own engine behind NinjaTrader's names, and follows NinjaTrader where a script leans on it without saying so: bars stamped with their closing time, limits filled only when price goes through them, a position closed when the market shuts, orders that last one bar.

Convert to Triton, which appears beside Check when the editor holds a NinjaTrader strategy, rewrites it against Triton's own library, so that no NinjaTrader name is left in it. It lists what it left out or could not carry over, each with the line of the original, and says whether the result compiles. Run both on the same data and compare the trades before relying on the converted one.

What the converter does by rule, and what to do by hand when it could not:

  • OnStateChange becomes OnStart. What was set in State.SetDefaults, Configure and DataLoaded moves there.
  • [NinjaScriptProperty] with [Display(Name = ...)] and [Range] becomes [Parameter("...", Min = ..., Max = ...)]. Starting values move onto the properties.
  • Time[0] becomes CloseTime[0], since NinjaTrader stamps a bar with its closing time. Closes[0][0] becomes Close[0], Volumes[0] becomes Volume.
  • Position.MarketPosition == MarketPosition.Long becomes Position.IsLong. Position.Quantity becomes Position.Size.
  • EnterLongStopMarket becomes EnterLongStop. In the limit and stop orders the price comes first: EnterLongLimit(price, quantity, name).
  • SetStopLoss(CalculationMode.Ticks, 20) becomes SetStopLoss(20). Price, Currency and Percent become SetStopLossPrice, SetStopLossMoney and SetStopLossPercent. SetTrailStop becomes SetTrailingStop.
  • OnExecutionUpdate becomes OnFill(Fill fill): execution.Order.Name is fill.Name, price is fill.Price, and so on.
  • SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit becomes NetProfit. SystemPerformance.AllTrades becomes Trades, and trade.ProfitCurrency becomes trade.Profit.
  • Bars.IsFirstBarOfSession becomes IsFirstBarOfSession. BarsSinceEntryExecution() becomes BarsSinceLastEntry().
  • MAX and MIN become Highest and Lowest. Bollinger(deviations, period) becomes Bollinger(period, deviations). MACD's .Avg and .Diff become .Signal and .Histogram.
  • IsExitOnSessionCloseStrategy, BarsRequiredToTrade, IsFillLimitOnTouch and EntriesPerDirection become ExitAtSessionClose, BarsBeforeTrading, FillLimitsOnTouch and MaxEntries. NinjaTrader's starting values for the first three are written into OnStart, so the converted script behaves the same.
  • State == State.Realtime becomes IsLive, which is false for now: scripts do not trade live yet.
  • Drawing calls, sounds and alerts are left out.

Not carried over, and marked for you to look at: OnOrderUpdate and OnPositionUpdate, orders kept in a variable (Order o = EnterLongLimit(...)), CountIf, MRO, LRO, a second data series, the unmanaged order methods and ATM strategies. A script that uses them still runs as a NinjaTrader strategy.

One difference to know about after converting: Triton's SMA, EMA and the other chart-matching indicators have no value until they have enough bars, where NinjaTrader's have one from the first bar, and Triton's EMA starts from an average. A script that trades in its first bars can differ there.

12 What a script cannot do

The walls a script runs inside, and why.

A script runs sealed. It gets the bars it is given and can reach nothing else: no account, no cookies or storage, no page, no files of yours, and no network. That holds whoever wrote the script, which is what makes it safe to run one from the library. A script that calls the web is told nothing was sent.

A script runs in your browser. It is not sent to Triton to run, and saving it is the only thing that puts it in your account.

  • One market and one bar size per run: the ones chosen on the form.
  • Backtests and charts only. Trading live from a script is not built yet.
  • A run-time error says which bar the script was on and what went wrong, but not the line.
  • A script that never finishes is ended with Stop, beside the run button.
  • The editor takes scripts of up to 200,000 characters. A saved script can be up to 20,000.

Open the script editor Help