How to speed up the processing of a script on the API
1. Measure the running time of the script
In order to improve something, it must be measured. Therefore, it is good practice to measure the execution of the script. At the beginning of the script we put: var sw = Stopwatch.StartNew(); At the end: ctx.Log($"Time: {sw.Elapsed}", MessageType.Info, true); After the script is executed, the execution time will be written in the log. You can also measure individual sections of the code. Example:
public void Execute(IContext ctx, ISecurity sec)
{
var sw = Stopwatch.StartNew();
// here is the script code
if (!ctx.Runtime.IsAgentMode) // write to the log only in the Laboratory mode
ctx.Log($"Time: {sw.Elapsed}", MessageType.Info, true);
}
2. Get the required data from ISecurity before the cycle
This is about properties in ISecurity: ClosePrices, OpenPrices, HighPrices, LowPrices, Volumes. There is caching inside them, because of this, getting this data will be slow. Therefore, it is recommended to get all the necessary data before the trading cycle and use them in the cycle. var closePrices = sec.ClosePrices; var openPrices = sec.OpenPrices; var highPrices = sec.HighPrices; var lowPrices = sec.LowPrices; var volumes = sec.Volumes;
Example:
var closePrices = sec.ClosePrices;
for (int i = startBar; i < barsCount; i++)
{
var signal = closePrices[i] > closePrices[i - 1];
...
}
3. Create objects before the loop
If possible, create the necessary objects before the cycle in which they are used. For example, there is a code like this that uses time:
var bars = sec.Bars;
for (int i = startBar; i < barsCount; i++)
{
var signal = bars[i].Date.TimeOfDay >= new TimeSpan(10, 00, 00) && bars[i].Date.TimeOfDay < new TimeSpan(20, 00, 00);
...
}
It is better to render TimeSpan creation before the loop:
var bars = sec.Bars;
var timeStart = new TimeSpan(10, 00, 00);
var timeFinish = new TimeSpan(20, 00, 00);
for (int i = startBar; i < barsCount; i++)
{
var signal = bars[i].Date.TimeOfDay >= timeStart && bars[i].Date.TimeOfDay < timeFinish;
...
}
4. Use indicator caching
More details here: Caching.
Last updated
Was this helpful?