The resource loading... loading...

Strategy Framework and API Functions

In the strategies written in JavaScript, Python and cpp, the Sleep() function needs to be called in the main loop of those strategies. It will be used to control the backtracking speed. In live trading, it is used to control the strategy polling intervals, and also control the requesting frequency of accessing the API interface of the exchange.

function onTick(){
    //Write strategy logic here, and it will be called constantly, such as printing ticker information
    Log(exchange.GetTicker())
}

function main(){
    while(true){
        onTick()
        // The function "Sleep" is mainly used to control the polling frequency of cryptocurrency strategies to prevent accessing the exchange API interafce too frequently
        Sleep(60000)
    }
}
def onTick():
    Log(exchange.GetTicker())

def main():
    while True:
        onTick()
        Sleep(60000)
void onTick() {
    Log(exchange.GetTicker());
}

void main() {
    while(true) {
        onTick();
        Sleep(60000);
    }
}

Basic framework examples of cryptocurrency strategies:

function onTick(){
    // It is just an example; for all the assets will be used to place orders fast during backtest or in live trading, do not implement the example in live trading
    exchange.Buy(100, 1)
}

function main(){
    while(true){
        onTick()
        // The pause period can be customized in millisecond (1 second = 1000 milliseconds)
        Sleep(1000)
    }
}
def onTick():
    exchange.Buy(100, 1)

def main():
    while True:
        onTick()
        Sleep(1000)
void onTick() {
    exchange.Buy(100, 1);
}

void main() {
    while(true) {
        onTick();
        Sleep(1000);
    }
}

Take the simplest example, if I want to place a buy order with a price of 100 and a quantity of 1 on the exchange every second, I can write it like this:

function onTick() {
    Log("K-line update, new BAR generated")
}

function main() {
    var exName = exchange.GetName()
    if (exName.includes("Futures_")) {
        exchange.SetContractType("swap")
    }
    
    var lastTs = 0
    while (true) {
        var r = _C(exchange.GetRecords)
        if (r.length > 0 && r[r.length - 1].Time != lastTs) {
            onTick()
            lastTs = r[r.length - 1].Time
        }
        Sleep(1000)
    }
}
def onTick():
    Log("K-line update, new BAR generated")
    
def main():
    exName = exchange.GetName()
    if "Futures_" in exName:
        exchange.SetContractType("swap")
    
    lastTs = 0
    while True:
        r = _C(exchange.GetRecords)
        if len(r) > 0 and r[-1]["Time"] != lastTs:
            onTick()
            lastTs = r[-1].Time
        Sleep(1000)
void onTick() {
    Log("K-line update, new BAR generated");
}

void main() {
    auto exName = exchange.GetName();
    if (exName.find("Futures_") != std::string::npos) {
        exchange.SetContractType("swap");
    }
    
    Record lastBar;
    lastBar.Time = 0;
    while (true) {
        auto r = _C(exchange.GetRecords);
        if (r.size() > 0 && r[r.size() - 1].Time != lastBar.Time) {
            onTick();
            lastBar.Time = r[r.size() - 1].Time;
        }
        Sleep(1000);
    }
}

Design an On Bar architecture strategy The following shows the commonly used API functions in strategy development and design. For more detailed API descriptions, please refer to: FMZ Quant Trading Platform API Manual.

Global Function

Function Name Brief Introduction
Version Returns the current version number of the system
Sleep Sleep function, parameter is the value of milliseconds to pause
IsVirtual Determine the execution environment, return a true value to indicate a backtest environment
Mail Send an email
Mail_Go Asynchronous version of the Mail function
SetErrorFilter Filter error logs, the parameter is a regular expression string, the error logs matched by this regular expression will not be uploaded to the logging system
GetPid Get the bot process Id
GetLastError Get the last error message
GetCommand Get strategy interaction commands, strategy interaction control settings can be queried: interaction control
GetMeta Get the value of Meta written when generating the strategy registration code
Dial Used for raw socket access
HttpQuery Send Http request
HttpQuery_Go Asynchronous version of the HttpQuery function
Encode Data encoding function
UnixNano Get nanosecond timestamps
Unix Get second-level timestamps
GetOS Getting system information
MD5 Calculate MD5
DBExec Database functions that can be used to execute SQL statements and perform database operations
UUID Generate UUID
EventLoop Listen for events and return after any websocket is readable or concurrent tasks such as exchange.Go, HttpQuery_Go, etc. are completed, this function is only available for live tradings
_G Persistently saving data, this function implements a saveable global dictionary function. The data structure is a KV table, which is stored in the docker’s local database file permanently
_D Timestamp handler, converts a millisecond timestamp or Date object to a time string
_N Formatting a floating point number, e.g. _N(3.1415, 2) will remove the value of 3.1415 after two decimal places, and the function returns 3.14
_C Retry function for interface fault tolerance. Note that, for example, fault tolerance for the exchange.GetTicker function is _C(exchange.GetTicker) and not _C(exchange.GetTicker())
_Cross Cross judgment function, _Cross() function’s return value is a positive number indicates the period of the upward penetration, a negative number indicates the period of the downward penetration, and 0 refers to the current price of the same
JSONParse Parsing JSON, which can correctly parse JSON strings containing larger values, will parse larger values to a string type. The JSONParse() function is not supported in the backtesting system.

Log Functions

Function Name Brief Introduction
Log Output logs, support for setting log text color, support for setting push, support for printing images after base64 encoding
LogProfit Output P&L data, print P&L values and plot yield curves based on P&L values
LogProfitReset Empty the LogProfit function outputs all earnings logs, earnings charts
LogStatus Output information in the status bar, support for designing button controls in the status bar, support for outputting forms
EnableLog Turn logging of order information on or off
Chart Charting functions, based on Highcharts/Highstocks charting library
KLineChart Pine language style drawing function, which is used for customized drawing at the strategy runtime using a Pine-like language drawing style
LogReset Clear logs, support to retain a certain number of recent logs through the parameter settings
LogVacuum Reclaim SQLite resources for reclaiming storage space occupied by SQLite when deleting data after clearing the log by calling the LogReset() function
console.log Output debugging information in the “Debug Information” column on the live trading page
console.error Error information is output in the “Debug Information” column of the live trading page

Ticker Functions

Function Name Brief Introduction
exchange.GetTicker Get the Tick quote
exchange.GetDepth Get order book depth data
exchange.GetTrades Get market turnover data
exchange.GetRecords Get K-line data
exchange.GetPeriod Get the current K-period
exchange.SetMaxBarLen Setting the maximum length of the K-line
exchange.GetRawJSON Get the raw content returned by the most recent rest request
exchange.GetRate Get the current set exchange rate
exchange.GetUSDCNY Get the latest USD/CNY exchange rate
exchange.SetData Set the data loaded when the strategy is running
exchange.GetData Get loaded data or data provided by external links
exchange.GetMarkets Get the exchange market information
exchange.GetTickers Get aggregated market data from exchanges

Transaction Functions

Function Name Brief Introduction
exchange.Buy Submit a buy order, futures contracts must pay attention to the direction of the transaction is set correctly, if the direction of the transaction and the transaction function does not match, the error will be reported!
exchange.Sell Submit sell orders, futures contracts when placing orders must pay attention to the transaction direction is set correctly, if the transaction direction and the transaction function does not match, it will report an error
exchange.CreateOrder Submit an order and specify the transaction type, transaction direction, price, and quantity through parameters
exchange.CancelOrder Cancel order
exchange.GetOrder Get order information, data structure is Order structure
exchange.GetOrders Get unfilled orders with data structure Order struct array (list)
exchange.GetHistoryOrders Get the historical orders of the current trading pair and contract; support specifying specific trading products
exchange.SetPrecision Set the precision of the price and order quantity of the exchange object, after setting the system will automatically ignore the data redundancy.
exchange.SetRate Set the exchange rate
exchange.IO For other interface calls related to exchange objects
exchange.Log Output, record transaction logs and do not place orders
exchange.Encode signature encryption calculation
exchange.Go Multi-threaded asynchronous support functions
exchange.GetAccount Get account information
exchange.GetAssets Request exchange account asset information
exchange.GetName Get the name of the exchange object
exchange.GetLabel Get the label of the exchange object
exchange.GetCurrency Get the current trading pair
exchange.SetCurrency Switch trading pairs
exchange.GetQuoteCurrency Get the name of the currency of the current trading pair

Futures Functions

Function Name Brief Introduction
[exchange.GetPositions(/syntax-guide#fun_exchange.getpositions) Get futures positions with data structure Position struct array (list)
exchange.SetMarginLevel Set the leverage
exchange.SetDirection Function used to set the exchange.Buy function, exchange.Sell function to carry out the futures contract order order direction
exchange.SetContractType Set the contract code, for example: exchange.SetContractType("swap") function sets the contract code to swap, which sets the contract for the current operation to be a perpetual contract
exchange.GetContractType Get the current set contract code
exchange.GetFundings Get the current futures exchange perpetual contract funding rate data

Network Functions

Function Name Brief Introduction
exchange.SetBase Sets the base address of the wrapped Exchange API interface
exchange.GetBase Get the current exchange API interface base address
exchange.SetProxy Set up the proxy
exchange.SetTimeout Set rest protocol timeout

JavaScript Multi-Threading

The FMZ Quant Trading Platform truly supports the multi-threaded function of the JavaScript language strategy from the bottom of the system, and implements the following objects:

Objects Directions Remarks
threading Multithreaded global object Member functions: Thread, getThread, mainThread, etc.
Thread Thread object Member functions: peekMessage, postMessage, join, etc.
ThreadLock Thread lock object Member functions: acquire, release. They can be passed into the thread environment as parameters of the thread execution function.
ThreadEvent Event object Member functions: set, clear, wait, isSet. They can be passed into the thread environment as a parameter of the thread execution function.
ThreadCondition Condition object Member functions: notify, notifyAll, wait, acquire, release. They can be passed into the thread environment as a parameter of the thread execution function.
ThreadDict Dictionary object Member functions: get, set. They can be passed into the thread environment as parameters of the thread execution function.

FMZ Quant Trading Platform Syntax Manual:JavaScript Multi-Threading

Web3

Function Name Brief Introduction
exchange.IO(“abi”, …) Register for ABI
exchange.IO(“api”, “eth”, …) Calling the Ethernet RPC method
exchange.IO(“encode”, …) coding function
exchange.IO(“encodePacked”, …) encodePacked encoding function
exchange.IO(“decode”, …) decoding function
exchange.IO(“key”, …) Used to switch private keys
exchange.IO(“api”, …) Methods to invoke a smart contract
exchange.IO(“address”) Get the currently configured wallet address
exchange.IO(“base”, …) Setting up RPC nodes

TA Indicator Library

Function Name Brief Introduction
TA.MACD Calculate the exponential smoothed divergence average indicator
TA.KDJ Calculation of stochastic indicators
TA.RSI Calculate the strength indicator
TA.ATR Calculate the average true volatility indicator
TA.OBV Calculation of energy tide indicators
TA.MA Calculating moving average indicators
TA.EMA Calculation of indicators of exponential averages
TA.BOLL Calculate the Bollinger Band indicator
TA.Alligator Calculate the Alligator Line Indicator
TA.CMF Calculation of the Chaikin Money Flow indicator
TA.Highest Calculate the period maximum price
TA.Lowest Calculate the period minimum price
TA.SMA Calculate the simple moving average indicators

talib Indicator Library

The talib indicator library has numerous trading indicators, such as talib.CDL2CROWS. You can go to the syntax manual for specifics.

Strategy Entry Functions Template Libraries