OS
FMZ Quant Trading Platform supports file read/write operations. The os library provides a complete file system operation interface to help users with data persistence, configuration management, and logging during strategy development.
Note that this feature only supports JavaScript language strategies.
The os library supports: File objects, File list objects, and File information objects.
| Object | Description | Notes |
|---|---|---|
| File Object: File | Provides file read/write, positioning and other operations. | Obtained through os.open(), need to call close() to release resources after use. |
| File List Object: ListFilesResult | Used to record directory listing information. | Supports wildcard matching patterns, returned by os.listFiles() function. |
| File Information Object: FileStat | File statistics information. | Returned by os.stat() function. |
Supports live trading and backtesting systems.
- Live trading environment:
The default directory for live trading is thefilesfolder at the same level as the live trading database file in the docker directory, i.e.:/logs/storage/xxx/files, wherexxxis the live trading ID, and the docker program (robot) is at the same level aslogs. - Backtesting system environment:
The backtesting system is a sandbox environment. The system simulates a file directory with the default directory:/logs/storage/1/files.
When backtesting ends, the created file contents will be cleared.
os
The os library provides a complete file system operation interface for the FMZ Quant Trading Platform.
open
Open a file in the specified mode.
open(filename)
open(filename, mode)Examples
Create a file, write data, then read it.
javascript
function main() {
let fileHandle = os.open("output.txt", "w+")
if (!fileHandle) {
Log("Failed to open file")
return
}
let bytesWritten = fileHandle.write("Hello FMZ!")
Log("Bytes written:", bytesWritten) // Bytes written: 10
fileHandle.seek(0, 0)
let fileContent = fileHandle.read()
Log("File content read:", fileContent) // File content read: Hello FMZ!
fileHandle.close()
}Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | File name. The parameter |
mode | string | No | Specify the file opening mode. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
File opening modes:
-
r: read (read-only, file must exist) -
w: write (write-only, creates file if it doesn't exist, clears content if it exists) -
a: append (append write, creates file if it doesn't exist, writes to the end if it exists) -
+: Adding + after r/w/a means both read and write are allowed (e.g., "r+", "w+", "a+") -
b: binary (binary mode, commonly used in Windows to distinguish text/binary files, e.g., "rb", "wb")
Files are opened/created in the files folder under the live trading database file directory (xxx.db3, where xxx is the live trading Id).
fgets
Read the entire file content at once.
fgets(filename)Examples
Read the content of a configuration file.
javascript
function main() {
// 先创建、写入文件
// let fileHandle = os.open("config.json", "w+")
// if (!fileHandle) {
// Log("Failed to open file")
// return
// }
// let objJson = {"name": "tom", "age": 18}
// fileHandle.write(JSON.stringify(objJson))
// fileHandle.close()
let content = os.fgets("config.json")
Log("Config content:", content) // Config content: {"name":"tom","age":18}
}Returns
| Type | Description |
string | Returns the complete content of the file. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | File path, including the filename to be read. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Suitable for quick reading of small files, loading the entire file content into memory at once.
If the file does not exist, the fgets() function will throw an error: InternalError: failed to open file: openat config.json: no such file or directory at main.
fputs
Write content to a file.
fputs(filename, content)
fputs(filename, content, append)Examples
Save strategy configuration to file.
javascript
function main() {
let config = '{"strategy": "MA", "period": 20}'
let bytesWritten = os.fputs("strategy_config.json", config)
Log("Bytes written:", bytesWritten) // Bytes written: 32
Log(`os.fgets("strategy_config.json"):`, os.fgets("strategy_config.json")) // os.fgets("strategy_config.json"): {"strategy": "MA", "period": 20}
// 追加日志信息
let logInfo = "\n[" + new Date().toISOString() + "] Config saved"
os.fputs("strategy_config.json", logInfo, true)
Log(`os.fgets("strategy_config.json"):`, os.fgets("strategy_config.json")) // os.fgets("strategy_config.json"): {"strategy": "MA", "period": 20} [2025-09-08T07:20:30.563Z] Config saved
}Returns
| Type | Description |
number | Returns the actual number of bytes written. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | File path. |
content | string | Yes | Content to write. |
append | bool | No | Whether to write in append mode, defaults to false (overwrite mode). |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Convenient file writing method, overwrites file content by default. Set append to true to append to the end of the file.
mmap
Memory-mapped file, returns the binary data of the file.
mmap(filename)Examples
Map the binary data of a file.
javascript
function ab2str(buf) {
let arr = new Uint8Array(buf)
return String.fromCharCode.apply(null, arr)
}
function main() {
let buffer = os.mmap("strategyConfig/testData.txt")
Log("File size in bytes:", buffer.byteLength)
let arr = Array.from(new Uint8Array(buffer))
Log("arr:", arr) // arr: [72,101,108,108,111,32,70,77,90,33]
Log("ab2str(buffer):", ab2str(buffer)) // ab2str(buffer): Hello FMZ!
}Returns
| Type | Description |
ArrayBuffer | Returns the binary data of the file content. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | File path. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Suitable for efficient reading and processing of large files, maps the file into memory and returns it as an ArrayBuffer.
getRootDir
Get the root directory path for file operations.
getRootDir()Examples
Get and display the root directory path.
javascript
function main() {
let rootDir = os.getRootDir()
Log("Root directory:", rootDir)
}Returns
| Type | Description |
string | Returns the path of the root directory. |
See Also
listFiles
List files and subdirectories in the specified directory.
listFiles()
listFiles(pattern)Examples
List matched files and directories.
javascript
function main() {
// 列出所有json文件
let result = os.listFiles("*.json")
Log("result:", result)
// 列出所有内容
let allFiles = os.listFiles()
Log("allFiles:", allFiles)
}Returns
| Type | Description |
ListFilesResult object | Returns an object containing - files: Array of matched file names. - dirs: Array of subdirectory names in the current directory. |
Arguments
| Name | Type | Required | Description |
pattern | string | No | Optional matching pattern, supports wildcards (e.g., .txt, data_.json), can specify directory path. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
When pattern parameter is not specified, lists all files and subdirectories in the current directory (../files).
exists
Check if the specified file or directory exists.
exists(filename)Examples
Check if a file or path exists.
javascript
function main() {
Log(`os.exists("./strategyConfig"):`, os.exists("./strategyConfig")) // os.exists("./strategyConfig"): true
Log(`os.exists("./strategyConfig/testData.txt"):`, os.exists("./strategyConfig/testData.txt")) // os.exists("./strategyConfig/testData.txt"): true
// Log(`os.exists("/strategyConfig"):`, os.exists("/strategyConfig")) // InternalError: invalid filename: path traversal or absolute path not allowed at main
Log(`os.exists("test_1.txt"):`, os.exists("test_1.txt")) // os.exists("test_1.txt"): true
Log(`os.exists("test_2.txt"):`, os.exists("test_2.txt")) // os.exists("test_2.txt"): false
}Returns
| Type | Description |
bool | Returns true if the file or directory exists, otherwise returns false. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | The file or directory path to check. |
See Also
remove
Delete the specified file.
remove(filename)Examples
Example of deleting a file.
javascript
function main() {
let tempFile = "test_1.txt"
if (os.exists(tempFile)) {
let success = os.remove(tempFile)
Log("Temp file deleted:", success)
}
}Returns
| Type | Description |
bool | Returns true on successful deletion, false on failure. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | The file path to delete. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
This function is only for deleting files, not for deleting directories. To delete directories, please use the rmdir() function.
mkdir
Create a directory.
mkdir(dirname)Examples
Create a data storage directory, create a file and write data.
javascript
function main() {
let success = os.mkdir("data/backtest/results")
Log("Directory created:", success)
if (success) {
os.fputs("data/backtest/results/summary.txt", "Backtest completed")
}
}Returns
| Type | Description |
bool | Returns true if creation is successful, otherwise returns false. |
Arguments
| Name | Type | Required | Description |
dirname | string | Yes | The directory path to create. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Supports recursive creation of multi-level directories. If parent directories do not exist, they will be created automatically.
rmdir
Remove a directory and all its contents.
rmdir(dirname)Examples
Remove a directory and all its contents.
javascript
function main() {
let tempDir = "data"
if (os.exists(tempDir)) {
let success = os.rmdir(tempDir)
Log("directory removed:", success)
}
}Returns
| Type | Description |
bool | Returns true on successful deletion, false on failure. |
Arguments
| Name | Type | Required | Description |
dirname | string | Yes | The directory path to be removed. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
This operation will permanently delete the directory and all its contents, please use with caution.
rename
Rename or move a file.
rename(oldName, newName)Examples
Rename a file and move it to another directory.
javascript
function main() {
let oldFileName = "output.txt"
let newFileName = "outputFiles/" + new Date().getTime() + "output.txt"
// let retRename = os.rename(oldFileName, newFileName)
// Log("retRename:", retRename) // InternalError: failed to rename file: renameat output.txt outputFiles/1757322073139output.txt: no such file or directory at main
os.mkdir("outputFiles")
retRename = os.rename(oldFileName, newFileName)
Log("retRename:", retRename) // retRename: true
}Returns
| Type | Description |
bool | Returns true on success, false on failure. |
Arguments
| Name | Type | Required | Description |
oldName | string | Yes | Original file name or path. |
newName | string | Yes | New file name or path. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Can be used to rename files or move files to different directories. If the directory of the new path does not exist, the operation will fail.
stat
Get detailed statistics information of a file.
stat(filename)Examples
Get file information and check file size.
javascript
function main() {
if (os.exists("strategyConfig/testData.txt")) {
let stat = os.stat("strategyConfig/testData.txt") // stat: {"size":10,"mode":420,"mtime":1757312981796,"atime":1757312981796,"ctime":1757312981796}
Log("stat:", stat)
}
}Returns
| Type | Description |
FileStat object | Returns an object containing file statistics information. |
Arguments
| Name | Type | Required | Description |
filename | string | Yes | File path. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
The returned FileStat object contains the following fields:
-
size: File size.
-
mode: File permissions.
-
mtime: Last modification time.
-
atime: Last access time.
-
ctime: Creation time.
exit
Exit the program.
exit()
exit(status)Examples
Exit program after checking conditions.
javascript
function main() {
if (!os.exists("required_config.json")) {
Log("Required configuration file not found!")
os.exit(1) // Abnormal exit
}
Log("Configuration found, continuing...")
// Normal strategy logic...
}Returns
| Type | Description |
never | This function does not return a value, the program will terminate execution directly. |
Arguments
| Name | Type | Required | Description |
status | number | No | Optional exit status code, default value is 0. |
See Also
File ListFilesResult FileStat open fgets fputs mmap getRootDir listFiles exists remove mkdir rmdir rename stat exit
Remarks
Immediately terminates program execution. Status code 0 indicates normal exit, non-zero values indicate abnormal exit (will be displayed as error in live trading).
File
File object that provides file read/write, positioning and other operations.
close
Close the file and release associated resources.
close()Examples
Example of proper file operation workflow.
javascript
function main() {
let file = os.open("data.txt", "w")
file.write("Hello FMZ!")
file.close() // 必须关闭文件
}See Also
Remarks
This method must be called after using the file object to release system resources.
puts
Write one or more strings to a file.
puts(data1, data2, ...dataN)Examples
Write multiple strings to a file.
javascript
function main() {
let file = os.open("output.txt", "w+")
let bytes = file.puts("Hello", " ", "World", "!")
Log("Bytes written:", bytes) // Bytes written: 12
file.seek(0, 0)
let data = file.read()
Log("data:", data) // If using os.open("output.txt", "w") may result in data being undefined
// data: Hello World!
// file.puts() // error: puts requires at least 1 argument at main
file.puts(", Hello FMZ!")
file.seek(0, 0)
data = file.read()
Log("data:", data) // data: Hello World!, Hello FMZ!
file.close()
}Returns
| Type | Description |
number | Returns the actual number of bytes written. |
Arguments
| Name | Type | Required | Description |
data | string | Yes | String data to be written, multiple parameters can be passed. |
See Also
Remarks
Multiple string parameters can be written at once, they will be concatenated in order and then written.
printf
Write formatted data to file.
printf(format)
printf(format, arg1, arg2, ...argN)Examples
Write formatted trading data.
javascript
function main() {
let file = os.open("trade_log.txt", "w+")
let price = 100.25
let volume = 1000
let bytes = file.printf("Price: %.2f, Volume: %d\n", price, volume)
Log("Formatted bytes written:", bytes)
file.seek(0, 0)
let data = file.read()
Log("data:", data) // data: Price: 100.25, Volume: 1000
// file.printf("| Price: %.2f, Volume: %d\n") // "| Price: %!f(MISSING), Volume: %!d(MISSING)"
// file.seek(0, 0)
// data = file.read()
// Log("data:", data)
file.close()
}Returns
| Type | Description |
number | Returns the actual number of bytes written. |
Arguments
| Name | Type | Required | Description |
format | string | Yes | Format string. |
args | any (any type supported by the platform) | No | Format arguments. |
See Also
flush
Flush the file buffer to ensure data is written to disk.
flush()Examples
Write important log data in real-time.
javascript
function main() {
let logFile = os.open("critical.log", "a")
logFile.printf("[%s] Critical event occurred\n", new Date().toISOString()) // [2025-09-09T03:15:43.895Z] Critical event occurred
logFile.flush() // Immediately write data to disk
// Continue with other operations...
logFile.close()
}See Also
tell
Get the current file pointer position.
tell()Examples
Track position during file operations.
javascript
function main() {
let file = os.open("data.txt", "r+")
Log("Initial position:", file.tell()) // Initial position: 0
file.write("Hello")
Log("After write position:", file.tell()) // After write position: 5
file.close()
}Returns
| Type | Description |
number | Returns the current file pointer position (offset in bytes). |
See Also
Remarks
Returns the byte offset of the current file pointer relative to the beginning of the file.
seek
Move the file pointer to a specified position.
seek(offset, whence)Examples
Read characters in reverse order.
javascript
function main() {
let str = "Hello FMZ!"
let file = os.open("data.txt", "w+")
file.write(str)
// If i > str.length: will throw InternalError: seek .../xxx/data.txt: invalid argument at main
for (let i = 1; i <= str.length; i++) {
file.seek(-i, 2)
let data = file.read(1)
Log("i:", i, ", data:", data)
}
file.close()
}Returns
| Type | Description |
number | Returns the new file pointer position. |
Arguments
| Name | Type | Required | Description |
offset | number | Yes | Offset (in bytes). |
whence | number | Yes | Reference position: 0=beginning of file, 1=current position, 2=end of file. |
See Also
Remarks
Used to position the file pointer, the offset parameter can be negative (indicating backward movement).
eof
Check if the file pointer has reached the end of file.
eof()Examples
Read file line by line until end of file.
javascript
function main() {
let file = os.open("data.txt", "r")
let lineCount = 0
while (!file.eof()) {
let line = file.getline()
if (line) {
lineCount++
Log("Line", lineCount + ":", line)
}
}
Log("Total lines:", lineCount)
file.close()
}Returns
| Type | Description |
bool | Returns true if end of file has been reached, otherwise returns false. |
See Also
Remarks
Used to determine whether all content has been read when reading a file.
read
Read data from a file.
read()
read(size)Examples
Read file content in chunks.
javascript
function main() {
let file = os.open("data.txt", "r")
// data.txt
// This is a test line: Line 1.
// This is a test line: Line 2.
// ...
let chunkSize = 29
let totalBytes = 0
while (!file.eof()) {
let chunk = file.read(chunkSize)
if (chunk) {
totalBytes += chunk.length || chunk.byteLength
Log("Read chunk, total bytes so far:", totalBytes, ", chunk:", chunk)
}
}
file.close()
}Returns
| Type | Description |
string / ArrayBuffer / undefined | Returns the content read. Returns |
Arguments
| Name | Type | Required | Description |
size | number | No | Number of bytes to read. If not specified, reads all remaining content in the file. |
See Also
Remarks
Can read a specified number of bytes or all remaining content in the file. The return type may be string or ArrayBuffer.
write
Write string data to a file.
write(data)Examples
Writing trade records
javascript
function main() {
let file = os.open("trades.log", "a")
let timestamp = new Date().toISOString()
let tradeInfo = `${timestamp},BUY,50000,1\n`
let bytes = file.write(tradeInfo)
Log("Trade record written, bytes:", bytes)
file.close()
}Returns
| Type | Description |
number | Returns the actual number of bytes written. |
Arguments
| Name | Type | Required | Description |
data | string | Yes | The string data to be written. |
See Also
Remarks
Writes string data to the current position in the file.
getline
Read the next line from the file.
getline()Examples
Read file line by line until the end.
javascript
function main() {
let file = os.open("data.txt", "r")
let lineCount = 0
while (!file.eof()) {
let line = file.getline()
if (line) {
lineCount++
Log("Line", lineCount + ":", line)
}
}
Log("Total lines:", lineCount)
file.close()
}Returns
| Type | Description |
string / undefined | Returns the next line content, returns |
See Also
Remarks
Read file content line by line in sequential order.
toString
Get the string representation of the file object.
toString()Examples
Get the description information of the file object.
javascript
function main() {
let file = os.open("data/data.txt", "r")
Log("File info:", file.toString()) // File info: File(data/data.txt)
file.close()
}Returns
| Type | Description |
string | Returns the string description information of the file object. |
See Also
Remarks
Returns the description information of the file object.
ListFilesResult
File list object used to record directory listing information. This object contains two array properties: files (file list) and dirs (directory list).
See Also
Remarks
ListFilesResult object structure:
javascript
{
files: string[], // Array of searched file names
dirs: string[] // Array of subdirectory names in the current directory
}
This object is returned by the os.listFiles() function.
FileStat
File statistics information object.
See Also
Remarks
FileStat object structure:
javascript
{
size: number, // File size (bytes)
mode: number, // File permission mode
mtime: number, // Modification time, millisecond timestamp
atime: number, // Access time, millisecond timestamp
ctime: number // Creation time, millisecond timestamp
}
This object is returned by the os.stat() function.