Caching
Caching indicator results
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
{
// Customizable options
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)
{
// Fast SMA Calculation
var smaFast = ctx.GetData("SMA", new[] { PeriodFast.ToString() },
() => Series.SMA(sec.ClosePrices, PeriodFast));
// Slow SMA Calculation
var smaSlow = ctx.GetData("SMA", new[] { PeriodSlow.ToString() },
() => Series.SMA(sec.ClosePrices, PeriodSlow));
// Trading cycle
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 the script is in optimization mode, then you do not need to build graphs
if (ctx.IsOptimization)
{
return;
}
// Plotting
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?