Optimizations

Optimizations

When a script is backtested, we are testing every single minute in the whole backtest period. Although this hurts the backtest speed, it is necessary for the most accurate results. On this page, we will go over a few things that will help you improve the backtest speed.

Sections marked with SE (Script Editor), VE (Visual Editor), or CC (Custom Command), are specific for that type. ​

Loops (SE)

Looping/Iterating over data takes time. In all cases try to avoid this as much as possible or keep the loop counts to the absolute minimum. With over 500 commands in HaasScript, there is almost always a way to use the commands instead. ​

OptimizedForInterval (SE)

In the script editor we can use OptimizedForInterval() . This command takes an interval and a callback. The command reduces the number of times the callback is executed. Execution of the callback is allowed when the candle on the specified interval closes. If for example, the script uses a MACD on 1h interval it will calculate the MACD once every 60 minutes and reduces the time it takes for the whole script to execute and in the end a faster backtest.

MA = OptimizedForInterval(CurrentInterval(), function() 
    return MA(ClosePrices(), 12)
end)

DefineIntervalOptimization (CC)

If a custom command works on interval based data, like the MadHatter RSI, we can use DefineIntervalOptimization() in our command scripts. This command will have the same effect as OptimizedForInterval() and increases the backtest speed.

local interval = DefineParameter(NumberType, 'interval', 'The interval of the command', true, 1)
DefineIntervalOptimization(interval)

If the command takes a source as parameter we can get the interval with the CurrentInterval() command.

local source = DefineParameter(ListNumberType, 'source', 'Source data for the command', true, ClosePrices())
local interval = CurrentInterval(source)
DefineIntervalOptimization(interval)

Finalize

The Finalize() command works like the OptimizedForInterval. It takes a callback but is only executed when we are doing the last step in a backtest or running the script in a real bot. This command should only be used with specific commands (CustomReport) or under specific conditions (Log() with a cumulative value).

Last updated