Кеширование индикаторов
var smaFast = Series.SMA(sec.ClosePrices, PeriodFast)var smaFast = ctx.GetData("SMA", new[] { PeriodFast.ToString() }, () => Series.SMA(sec.ClosePrices, PeriodFast));using TSLab.Script;
using TSLab.Script.Handlers;
using TSLab.Script.Helpers;
using TSLab.Script.Optimization;
namespace MyLib
{
public class SimpleCache : IExternalScript
{
// Настраиваемые параметры
public OptimProperty PeriodFast = new OptimProperty(100, 10, 200, 10);
public OptimProperty PeriodSlow = new OptimProperty(500, 200, 2000, 100);
public void Execute(IContext ctx, ISecurity sec)
{
// Расчет быстрой SMA
var smaFast = ctx.GetData("SMA", new[] { PeriodFast.ToString() },
() => Series.SMA(sec.ClosePrices, PeriodFast));
// Расчет медленной SMA
var smaSlow = ctx.GetData("SMA", new[] { PeriodSlow.ToString() },
() => Series.SMA(sec.ClosePrices, PeriodSlow));
// Торговый цикл
for (int i = 0; i < ctx.BarsCount; i++)
{
var posLong = sec.Positions.GetLastActiveForSignal("LE", i);
if (posLong == null)
{
if (smaFast[i] > smaSlow[i] && smaFast[i - 1] <= smaSlow[i - 1])
sec.Positions.BuyAtMarket(i + 1, 1, "LE");
}
else
{
if (smaFast[i] < smaSlow[i] && smaFast[i - 1] >= smaSlow[i - 1])
posLong.CloseAtMarket(i + 1, "LX");
}
}
// Если скрипт в режиме оптимизации, то не нужно строить графики
if (ctx.IsOptimization)
{
return;
}
// Построение графиков
ctx.First.AddList(string.Format("SMA fast ({0})", PeriodFast), smaFast, ListStyles.LINE, ScriptColors.Green,
LineStyles.SOLID, PaneSides.RIGHT);
ctx.First.AddList(string.Format("SMA slow ({0})", PeriodSlow), smaSlow, ListStyles.LINE, ScriptColors.Red,
LineStyles.SOLID, PaneSides.RIGHT);
}
}
}Last updated
Was this helpful?