Main strategy function, written by the user. It is automatically started after clicking on the [Train], [Test], and [Trade] buttons. After that, it is run once for every bar of the simulation. This is continued until the end of the simulation data or until [Stop] is hit. The run function initializes sliders and sets up all needed indicators.
- The run function normally runs at the end of every bar. The open, close, high and low prices of the current bar are known and lie in the past, while all prices of the next bar are unknown and lie in the future. In the simulation, trade enter or exit commands are normally executed
either at the current price plus a slippage offset, or at the open of the next bar,
dependent on Fill mode.
- If StartDate is set to NOW, the run function is executed in live trading mode immediately after the lookback period, regardless whether the current bar has ended. After that first live run, it is furtherhin executed at the end of every bar.
- For executing the run function several times within a candle, make the BarPeriod shorter and set up the candle width with TimeFrame so that several bars lie within a candle.
- At the first call of the run function, is(INITRUN) and is(FIRSTTINITRUN) are true. Price and bar data are not yet set up at that initial run before the first asset call, and all price functions and indicators return 0.
- If the script has both a main and a run function, the main function is executed before the first run, and can be used for initializing variables.
- Local variables 'forget' their values after every call of the run function, but static and global variables keep their values. !! When AutoCompile is set, static and global variables really keep their values until the script is compiled again, which happens only when it was modified or when the [Edit] button was clicked. Therefore make sure to initialize them at every cycle start (is(INITRUN)) to their initial values when this is required.
- For running a simulation in greater steps for special purposes, bars can be skipped by adding a number to Bar at the end of the run function. F.i. Bar += 9; will call the run function only every 10th bar. Anything inbetween, such as handling trades
or plotting curves, is skipped.
- For debugging the run function, use the STEPWISE flag and watch commands. For starting debugging after the lookback period, use if(!is(LOOKBACK)) set(STEPWISE);.
- For immediate script reaction on an incoming price quote, use the tick function. For repeated actions independent on bars or price quotes, use the tock function.
vars SmoothPrice = series(LowPass(series(price()),100));
Workshop 4, Bars and Candles, Bar, BarPeriod, tick, tock, user supplied functions