Writing scripts on the API

Introduction

In order to write a script on the TSLab API, you must create a class inherited from the IExternalScript interface.

This interface has the following implementation:

public interface IExternalScript : IExternalScriptBase, IStreamHandler, IHandler, IOneSourceHandler
{
    void Execute(IContext ctx, ISecurity sec);
}

As you can see, the interface has only one Execute method, which takes two parameters.

IContext - contains the general script context; it is needed for drawing graphs and caching.

ISecurity - allows you to work with the tool, contains candles, ticks, you can work with positions.

The Execute method is called each time TSLab starts a script recount.

You can also use other interfaces, they differ only in the number of tools in the parameters:

IExternalScript2 - two tools at the input (ISecurity)

IExternalScript3 - three tools at the input (ISecurity)

IExternalScript4 - four tools at the input (ISecurity)

IExternalScriptMultiSec - input array of tools (ISecurity)

Scripts template

To write scripts, you can use the following template:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TSLab.Script;
using TSLab.Script.Handlers;
using TSLab.DataSource;

namespace MyLib
{
    public class MyScript : IExternalScript
    {
        public void Execute(IContext ctx, ISecurity sec)
        {
            // Find the last formed bar for calculations
            var barsCount = sec.Bars.Count;
            if (!ctx.IsLastBarUsed)
            {
                barsCount--;
            }

            // Trading cycle
            for (int i = ctx.TradeFromBar; i < barsCount; i++)
            {
                // Here work with positions (sec.Positions)
            }

            // If the optimization process is ongoing, then you do not need to draw graphics, this slows down the work
            if (ctx.IsOptimization)
            {
                return;
            }

            // Charting
            // ctx.First - main panel
        }
    }
}

Main properties and methods

Last updated