Python
Strategies can be written in Python 3; Python 2 is not supported. Live trading, and backtests that run on a docker, use the Python interpreter installed on the docker's machine.
Interpreter
The docker looks for an interpreter in this order and uses the first program that starts and is Python 3:
- the interpreter given by the environment variable
PYTHON_BIN; python3;python.
To use a specific interpreter (for example the Python of a virtual environment), set the environment variable before starting the docker:
bash
export PYTHON_BIN=/opt/venv/bin/python3
A first line such as #!python3 or #!python2 in the strategy is no longer used to choose the interpreter.
Structure and parameters
The entry point is def main(). The optional init() and onexit() are called automatically by the docker (Python does not support onerror()); see Writing Strategies → Strategy Structure. Interface parameters are global variables with the same names; to assign a new value to one inside a function, declare it with global first.
Errors and return values
When an API call fails it returns None and writes the error to the log. Check the return value before using it, or retry with _C(). An uncaught exception ends the strategy, and the error is recorded in the log.
Output
The output of print() goes to the docker process's standard output and does not appear in the live trading log. Use Log for anything that should show up in the log.
Third-party packages
A strategy can import any package installed in the interpreter. Install packages with the same interpreter the docker uses, for example:
bash
python3 -m pip install numpy
# when PYTHON_BIN is set
$PYTHON_BIN -m pip install numpy
To use talib, install TA-Lib (the talib package) and numpy on the docker's machine.
Your own modules
While a strategy runs, its current directory and PYTHONPATH are a temporary directory created by the docker for that run and deleted afterwards; .py files placed under the docker's directory (for example logs/storage/<live trading ID>/) are not found automatically. There are two ways to import your own modules:
- install the module into the interpreter's
site-packages(for example package it and install it withpip install, or copy it into thesite-packagesdirectory); - in the strategy, append the absolute path of the module's directory to
sys.path, then import it.
For example, with the module file /home/user/fmz_modules/mymath.py:
python
# mymath.py
def add(a, b):
return a + b
the strategy code is:
python
import sys
sys.path.append("/home/user/fmz_modules") # absolute path of the module's directory
import mymath
def main():
Log("mymath.add(1, 2):", mymath.add(1, 2))
Keeping the core logic in a module on your own docker, with only the calling code in the strategy, is also a way to avoid uploading that logic to the platform.