Strategy Entry Functions
For strategies written in JavaScript, Python, Rust, and C++, the FMZ Quant Trading Platform has already defined the following entry functions.
| Function Name | Description |
|---|---|
main() | The entry function, i.e., the main function of the strategy. |
onexit() | The cleanup function executed upon normal exit, with a maximum execution time of 5 minutes; it does not have to be declared. If execution times out, an interrupt error will be reported. In live trading, if the onerror() function has already been triggered first, the onexit() function will no longer be triggered. |
onerror() | The function triggered upon abnormal exit, with a maximum execution time of 5 minutes; it does not have to be declared. Strategies written in Python and C++ do not support this function, and the backtesting system does not support this function either. |
init() | The initialization function, which the strategy program automatically calls first when it starts running; it does not have to be declared. |
Notes:
-
When the
main()function finishes executing, all created child threads will be automatically terminated. -
In
Rustlanguage strategies, you can directly definefn main(),fn init(), andfn onexit()(which are automatically called by the bootstrap layer); you can also callOnExit()in the strategy code to register additional exit hooks. For details, see "Rust Strategy Writing Guide".
onexit()
The onexit() function is used to handle the cleanup work of a strategy. Its maximum execution time is 5 minutes, and it must be implemented by the user.
Examples
-
Test the
onexit()function:javascriptfunction main(){ Log("Starting, will stop after 5 seconds and execute cleanup function!") Sleep(1000 * 5) } // Implementation of the cleanup function function onexit(){ var beginTime = new Date().getTime() while(true){ var nowTime = new Date().getTime() Log("Program stop countdown..cleanup started, elapsed time:", (nowTime - beginTime) / 1000, "seconds!") Sleep(1000) } }pythonimport time def main(): Log("Starting, will stop after 5 seconds and execute cleanup function!") Sleep(1000 * 5) def onexit(): beginTime = time.time() * 1000 while True: ts = time.time() * 1000 Log("Program stop countdown..cleanup started, elapsed time:", (ts - beginTime) / 1000, "seconds!") Sleep(1000)rustfn main() { Log!("Starting, will stop after 5 seconds and execute cleanup function!"); Sleep(1000 * 5); } // Implementation of the cleanup function fn onexit() { let beginTime = Unix() * 1000; loop { let nowTime = Unix() * 1000; Log!("Program stop countdown..cleanup started, elapsed time:", (nowTime - beginTime) / 1000, "seconds!"); Sleep(1000); } }c++void main() { Log("Starting, will stop after 5 seconds and execute cleanup function!"); Sleep(1000 * 5); } void onexit() { auto beginTime = Unix() * 1000; while(true) { auto ts = Unix() * 1000; Log("Program stop countdown..cleanup started, elapsed time:", (ts - beginTime) / 1000, "seconds!"); Sleep(1000); } } -
Since a strategy in the backtesting system is usually designed as an infinite loop that continuously polls and executes, the
onexit()function implemented by the strategy cannot be triggered in the backtesting system. You can trigger the execution of theonexit()function by detecting the backtesting system's end marker (the EOF exception).javascriptfunction main() { if (exchange.GetName().startsWith("Futures_")) { Log("Exchange is futures") exchange.SetContractType("swap") } else { Log("Exchange is spot") } if (IsVirtual()) { try { onTick() } catch (e) { Log("error:", e) } } else { onTick() } } function onTick() { while (true) { var ticker = exchange.GetTicker() LogStatus(_D(), ticker ? ticker.Last : "--") Sleep(500) } } function onexit() { Log("Executing cleanup function") }pythondef main(): if exchange.GetName().startswith("Futures_"): Log("Exchange is futures") else: Log("Exchange is spot") if IsVirtual(): try: onTick() except Exception as e: Log(e) else: onTick() def onTick(): while True: ticker = exchange.GetTicker() LogStatus(_D(), ticker["Last"] if ticker else "--") Sleep(500) def onexit(): Log("Executing cleanup function")rustfn onTick() { loop { match exchange.GetTicker(None) { Ok(ticker) => LogStatus!(_D(None), ticker.Last), Err(e) => { // When the backtest ends, the API call returns Err; exit the loop so that main returns, thereby triggering the onexit() cleanup function Log!("error:", e); break; } } Sleep(500); } } fn main() { if exchange.GetName().starts_with("Futures_") { Log!("Exchange is futures"); let _ = exchange.SetContractType("swap"); } else { Log!("Exchange is spot"); } onTick(); } fn onexit() { Log!("Executing cleanup function"); }c++#include <iostream> #include <exception> #include <string> void onTick() { while (true) { auto ticker = exchange.GetTicker(); LogStatus(_D(), ticker); Sleep(500); } } void main() { std::string prefix = "Futures_"; bool startsWith = exchange.GetName().substr(0, prefix.length()) == prefix; if (startsWith) { Log("Exchange is futures"); exchange.SetContractType("swap"); } else { Log("Exchange is spot"); } if (IsVirtual()) { try { onTick(); } catch (...) { std::cerr << "Caught unknown exception" << std::endl; } } else { onTick(); } } void onexit() { Log("Executing cleanup function"); }
init()
init() is the initialization function implemented by the user. When a strategy starts running, the init() function is automatically executed first to complete the initialization tasks designed within the strategy.
Examples
javascript
function main(){
Log("First line of code executed!", "#FF0000")
Log("Exiting!")
}
// Initialization function
function init(){
Log("Initializing!")
}
python
def main():
Log("First line of code executed!", "#FF0000")
Log("Exiting!")
def init():
Log("Initializing!")
rust
fn main() {
Log!("First line of code executed!", "#FF0000");
Log!("Exiting!");
}
// Initialization function
fn init() {
Log!("Initializing!");
}
c++
void main() {
Log("First line of code executed!", "#FF0000");
Log("Exiting!");
}
void init() {
Log("Initializing!");
}onerror()
onerror(), triggered when an exception occurs, the onerror() function will be executed. This function is not supported in Python and C++ language strategies. The onerror() function can accept a msg parameter, which contains the error message when the exception is triggered.
Examples
javascript
function main() {
var arr = []
Log(arr[6].Close) // Intentionally trigger a program exception here
}
function onerror(msg) {
Log("Error:", msg)
}
python
# Python not supported
c++
// C++ not supported