### Executing Robot Commands via Command Line Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E7%BC%96%E8%BE%91%E5%99%A8/%E8%AF%AD%E6%B3%95%E6%89%8B%E5%86%8C%E9%80%9F%E6%9F%A5 This snippet shows how to use the command line to interact with and manage trading robots. It includes examples for common commands like starting, stopping, and restarting robots. ```bash # Start a robot # fmz-cli robot start --id YOUR_ROBOT_ID # Stop a robot # fmz-cli robot stop --id YOUR_ROBOT_ID # Restart a robot # fmz-cli robot restart --id YOUR_ROBOT_ID # Get robot details # fmz-cli robot detail --id YOUR_ROBOT_ID ``` -------------------------------- ### JavaScript Strategy Example - init() function Source: https://www.fmz.com/user-guide/index Example of the init() function in a JavaScript strategy. This function is typically called once when the strategy starts. It's used for initializing variables and setting up the trading environment. Ensure all necessary libraries are imported before use. ```javascript function init() { // Initialize strategy parameters and variables here Log("Strategy initialized."); } ``` -------------------------------- ### C++ Strategy Example - Initialization Source: https://www.fmz.com/user-guide/index Basic C++ code snippet for initializing a trading strategy. This example shows a simple initialization function. C++ strategies require compilation and may involve manual memory management. Ensure the FMZ C++ environment is properly configured. ```cpp #include extern "C" { int init() { std::cout << "Strategy initialized." << std::endl; return 0; // Success } // Other strategy functions like onTick, onExit, onError would follow } ``` -------------------------------- ### Python Example - Basic Strategy Structure Source: https://www.fmz.com/user-guide/index A basic structure for a Python trading strategy on the FMZ platform. This includes placeholder functions for initialization, execution, and error handling. Ensure the Python environment is correctly set up and necessary libraries are installed. ```python def init(): # Initialize strategy variables print("Strategy initialized.") def on_tick(): # Trading logic executed on each tick pass def on_exit(): # Cleanup operations when the strategy exits print("Strategy exited.") def on_error(error): # Handle errors during strategy execution print(f"An error occurred: {error}") ``` -------------------------------- ### Extended API Interface Examples Source: https://www.fmz.com/user-guide/%E5%AE%9E%E7%9B%98%E6%8A%A5%E9%94%99%E3%80%81%E5%BC%82%E5%B8%B8%E9%80%80%E5%87%BA%E7%9A%84%E5%B8%B8%E8%A7%81%E5%8E%9F%E5%9B%A0 This section provides examples of how to interact with the FMZ platform's extended API interfaces. It includes functions for managing robots, accounts, and strategies, as well as handling API responses and errors. ```JavaScript // Example: Get a list of robots var robots = exchange.GetRobotList(); // Example: Command a robot to start var ret = exchange.CommandRobot(robotId, 'start'); ``` -------------------------------- ### Hoster Program Command Line Parameters Source: https://www.fmz.com/user-guide/%E6%89%98%E7%AE%A1%E8%80%85 This section details various command-line parameters for the hoster program. These parameters control version display, verbose logging, server connection, password input, node naming, and listing supported exchanges. The examples provided are for the Mac operating system. ```shell ./robot -v ``` ```shell ./robot -vv ``` ```shell ./robot -s node.fmz.com/xxxxxxx ``` ```shell ./robot -s node.fmz.com/xxxxxxx -p abc123456 ``` ```shell ./robot -n macTest -s node.fmz.com/xxxxxxx ``` ```shell ./robot -l ``` -------------------------------- ### JavaScript Web3 Example - Calling Ethereum RPC Source: https://www.fmz.com/user-guide/index Demonstrates how to interact with the Ethereum blockchain using Web3 in JavaScript. This snippet shows configuring the Web3 exchange object, registering an ABI, and calling an Ethereum RPC method. It requires a configured Web3 exchange and a valid ABI. ```javascript // Assume 'exchange' is a pre-configured Web3 exchange object // Assume 'abi' is the contract's ABI array var web3 = exchange.Get('web3'); var contract = new web3.eth.Contract(abi, contractAddress); // Example: Calling a 'getBalance' function on the smart contract contract.methods.getBalance(address).call(function(error, result) { if (error) { Log("Error calling getBalance: " + error); } else { Log("Balance: " + result); } }); ``` -------------------------------- ### Python Strategy Example Source: https://www.fmz.com/user-guide/alpha%E5%9B%A0%E5%AD%90%E5%88%86%E6%9E%90%E5%B7%A5%E5%85%B7/%E5%85%B6%E5%AE%83 Demonstrates a basic strategy structure in Python for the FMZ platform. This is suitable for users who prefer Python for quantitative trading. It outlines the entry points and basic logging functionality. ```Python def init(): log("Initializing strategy...") def onexit(): log("Exiting strategy...") def main(): log("Strategy running...") while True: # Trading logic here Sleep(1000) ``` -------------------------------- ### C++ Strategy Writing Instructions Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E7%BC%96%E8%BE%91%E5%99%A8/%E8%AF%AD%E6%B3%95%E6%89%8B%E5%86%8C%E9%80%9F%E6%9F%A5 Instructions for writing strategies in C++. This section will outline the necessary setup, core functions like init(), onTick(), and onExit(), and any platform-specific C++ APIs available. ```cpp #include "fmz.h" int init() { // Initialization code here return 0; } void onTick() { // Trading logic here } void onExit() { // Cleanup code here } ``` -------------------------------- ### WebHook Push Example Source: https://www.fmz.com/user-guide/%E5%AE%9E%E7%9B%98%E6%B6%88%E6%81%AF%E6%8E%A8%E9%80%81 Provides an example of configuring a WebHook for message pushing. When a push message is sent, the system makes a GET request to the specified URL, replacing the {body} placeholder with the message content. This demonstrates an external integration for receiving push notifications. ```bash http://abc.com/push.php?data={body} ``` -------------------------------- ### Python - Using TA-Lib for Technical Analysis Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E7%BC%96%E8%BE%91%E5%99%A8/%E8%AF%AD%E6%B3%95%E6%89%8B%E5%86%8C%E9%80%9F%E6%9F%A5 Example of using the TA-Lib library in Python for calculating technical analysis indicators. This requires the TA-Lib library to be installed and accessible. ```python import talib import numpy as np # Assume 'close_prices' is a numpy array of closing prices # close_prices = np.random.random(100) # Calculate Simple Moving Average (SMA) # sma = talib.SMA(close_prices, timeperiod=14) # Calculate Relative Strength Index (RSI) # rsi = talib.RSI(close_prices, timeperiod=14) # print("SMA:", sma) # print("RSI:", rsi) ``` -------------------------------- ### C++ Strategy Entry Functions and Global Functions Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet demonstrates the structure of strategy entry functions like init(), onexit(), onerror(), and examples of using global functions within a C++ trading strategy. ```cpp // Strategy Entry Functions void init() { Log("Strategy initialized."); } void onexit() { Log("Strategy exiting."); } void onerror() { Log("An error occurred."); } // Example of using global functions void onTick() { int price = GetTickCount(); Log("Current tick count: %d", price); Account account = GetAccount(); Log("Account balance: %f", account.Balance); } ``` -------------------------------- ### Custom Data Source Configuration Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E6%BA%90 Configuration details for setting up a custom data source for the backtesting system. The backtesting system uses the GET method to request external data from a specified URL. ```APIDOC ## Custom Data Source ### Description The backtesting system supports custom data sources. It uses the `GET` method to request data from a specified URL (which can be publicly accessible). ### Method `GET` ### Endpoint `http://customserver:9090/data` ### Parameters #### Query Parameters - **symbol** (string) - Required - The symbol name (e.g., `BTC_USDT` for spot, `BTC_USDT.swap` for futures, `BTC_USDT.funding` for funding rates, `BTC_USDT.index` for index prices). - **eid** (string) - Required - The exchange identifier (e.g., `OKX`, `Futures_OKX`). - **round** (boolean) - Required - Set to `true` to indicate that the custom data source defines specific precision. The platform sends `round=true` by default. - **period** (integer) - Required - The period of K-line data in milliseconds (e.g., `60000` for 1 minute). - **depth** (integer) - Required - The number of depth levels (1-20). - **trades** (integer) - Required - Whether to request tick data (1 for true, 0 for false). - **from** (integer) - Required - Start time as a Unix timestamp. - **to** (integer) - Required - End time as a Unix timestamp. - **detail** (boolean) - Required - Set to `true` if detailed information about the symbol is required from the custom data source. The platform sends `detail=true` by default. - **custom** (any) - Optional - This parameter can be ignored. ### Request Example ``` http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Bitget&from=1351641600&period=86400000&round=true&symbol=BTC_USDT&to=1611244800&trades=1 http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Futures_OKX&from=1351641600&period=86400000&round=true&symbol=BTC_USDT.swap&to=1611244800&trades=1 ``` ### Response (Details about the expected response format from the custom data source are not provided in the input.) ``` -------------------------------- ### Python Strategy Entry Functions and Global Functions Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet outlines the structure of strategy entry functions like init(), onexit(), onerror(), and provides examples of using global functions within a Python trading strategy. ```python # Strategy Entry Functions def init(): Log("Strategy initialized.") def onexit(): Log("Strategy exiting.") def onerror(): Log("An error occurred.") # Example of using global functions def onTick(): price = GetTickCount() Log("Current tick count: ", price) account = GetAccount() Log("Account balance: ", account.Balance) ``` -------------------------------- ### Golang Custom Data Source HTTP Server Example Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F This Golang program implements an HTTP server to act as a custom data source for FMZ. It handles incoming GET requests for market data, parses query parameters, and returns data in a JSON format compatible with FMZ's data source requirements. The response includes details about the trading pair and the historical price data. ```golang package main import ( "fmt" "net/http" "encoding/json" ) func Handle (w http.ResponseWriter, r *http.Request) { // e.g. set on backtest DataSourse: http://xxx.xx.x.xx:9090/data // request: GET http://xxx.xx.x.xx:9090/data?custom=0&depth=20&detail=true&eid=OKX&from=1584921600&period=86400000&round=true&symbol=BTC_USDT&to=1611244800&trades=1 // http://xxx.xx.x.xx:9090/data?custom=0&depth=20&detail=true&eid=Futures_Binance&from=1599958800&period=3600000&round=true&symbol=BTC_USDT.swap&to=1611244800&trades=0 fmt.Println("request:", r) // response defer func() { // response data /* e.g. data { "detail": { "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10 }, "schema": [ "time", "open", "high", "low", "close", "vol" ], "data": [ [1610755200000, 3673743, 3795000, 3535780, 3599498, 8634843151], [1610841600000, 3599498, 3685250, 3385000, 3582861, 8015772738], [1610928000000, 3582499, 3746983, 3480000, 3663127, 7069811875], [1611014400000, 3662246, 3785000, 3584406, 3589149, 7961130777], [1611100800000, 3590194, 3641531, 3340000, 3546823, 8936842292], [1611187200000, 3546823, 3560000, 3007100, 3085013, 13500407666], [1611273600000, 3085199, 3382653, 2885000, 3294517, 14297168405], [1611360000000, 3295000, 3345600, 3139016, 3207800, 6459528768], [1611446400000, 3207800, 3307100, 3090000, 3225990, 5797803797], [1611532800000, 3225945, 3487500, 3191000, 3225420, 8849922692] ] } */ // /* 模拟级Tick ret := map[string]interface{}{ "detail": map[string]interface{}{ "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10, }, "schema": []string{"time","open","high","low","close","vol"}, "data": []interface{}{ []int64{1610755200000, 3673743, 3795000, 3535780, 3599498, 8634843151}, // 1610755200000 : 2021-01-16 08:00:00 []int64{1610841600000, 3599498, 3685250, 3385000, 3582861, 8015772738}, // 1610841600000 : 2021-01-17 08:00:00 []int64{1610928000000, 3582499, 3746983, 3480000, 3663127, 7069811875}, []int64{1611014400000, 3662246, 3785000, 3584406, 3589149, 7961130777}, []int64{1611100800000, 3590194, 3641531, 3340000, 3546823, 8936842292}, []int64{1611187200000, 3546823, 3560000, 3007100, 3085013, 13500407666}, []int64{1611273600000, 3085199, 3382653, 2885000, 3294517, 14297168405}, []int64{1611360000000, 3295000, 3345600, 3139016, 3207800, 6459528768}, []int64{1611446400000, 3207800, 3307100, 3090000, 3225990, 5797803797}, []int64{1611532800000, 3225945, 3487500, 3191000, 3225420, 8849922692}, }, } // */ /* 实盘级Tick ret := map[string]interface{}{ "detail": map[string]interface{}{ "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10, }, "schema": []string{"time", "asks", "bids", "trades", "close", "vol"}, */ jsonData, err := json.Marshal(ret) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(jsonData) }() } func main() { http.HandleFunc("/data", Handle) fmt.Println("Server starting on port 9090...") err := http.ListenAndServe(":9090", nil) if err != nil { fmt.Println("Error starting server: ", err) } } ``` -------------------------------- ### C++ Strategy Development Guide for FMZ Source: https://www.fmz.com/user-guide/%E5%AE%9E%E7%9B%98%E6%8A%A5%E9%94%99%E3%80%81%E5%BC%82%E5%B8%B8%E9%80%80%E5%87%BA%E7%9A%84%E5%B8%B8%E8%A7%81%E5%8E%9F%E5%9B%A0 This section outlines the process of creating trading strategies using C++ on the FMZ Quant Trading Platform. It details the specific requirements and considerations for C++ development in this environment. ```C++ #include "fmz.h" int init() { // Initialization code return 0; } void onTick() { // Trading logic } void onexit() { // Cleanup code } ``` -------------------------------- ### Place Order Example with Sleep() - JavaScript, Python, C++ Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E6%A1%86%E6%9E%B6%E4%B8%8Eapi%E5%87%BD%E6%95%B0 A simple example demonstrating how to place a buy order at a specified price and quantity every second using JavaScript, Python, and C++. The Sleep() function is used to control the interval between orders. ```javascript function onTick(){ // 这个仅仅是例子,回测或者实盘会很快把资金全部用于下单,实盘请勿使用 exchange.Buy(100, 1) } function main(){ while(true){ onTick() // 暂停多久可自定义,单位为毫秒,1秒等于1000毫秒 Sleep(1000) } } ``` ```python def onTick(): exchange.Buy(100, 1) def main(): while True: onTick() Sleep(1000) ``` ```c++ void onTick() { exchange.Buy(100, 1); } void main() { while(true) { onTick(); Sleep(1000); } } ``` -------------------------------- ### Price Index Data Request URL Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E6%BA%90 This URL is an example request for price index data. It specifies parameters such as the exchange, symbol, and time range, which the backtesting system uses to retrieve the required index price information. ```url http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Futures_Binance&from=1351641600&period=86400000&round=true&symbol=BTC_USDT.index&to=1611244800&trades=0 ``` -------------------------------- ### Custom Data Source Request Example for Backtesting System Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E6%BA%90 Examples of requests sent by the Invent Fangliang Quant Trading Platform's backtesting system to a custom data source URL. These requests fetch historical market data for spot and futures exchanges, including parameters for symbol, exchange ID, data precision, period, depth, trade data, time range, and detailed information. ```http http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Bitget&from=1351641600&period=86400000&round=true&symbol=BTC_USDT&to=1611244800&trades=1 http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Futures_OKX&from=1351641600&period=86400000&round=true&symbol=BTC_USDT.swap&to=1611244800&trades=1 ``` -------------------------------- ### Python Strategy Development Guide for FMZ Source: https://www.fmz.com/user-guide/%E5%AE%9E%E7%9B%98%E6%8A%A5%E9%94%99%E3%80%81%E5%BC%82%E5%B8%B8%E9%80%80%E5%87%BA%E7%9A%84%E5%B8%B8%E8%A7%81%E5%8E%9F%E5%9B%A0 Instructions for developing trading strategies in Python on the FMZ platform. It addresses potential compatibility issues, especially when deploying or renting encrypted strategies, and outlines Python version requirements. ```Python def init(): # Initialization code pass def on_tick(): # Trading logic pass def on_exit(): # Cleanup code pass ``` -------------------------------- ### Python Get Exchange List and Account Information Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet demonstrates how to retrieve a list of supported exchanges and fetch account information using Python. ```python # Get a list of supported exchanges exchange_list = GetExchangeList() Log("Supported Exchanges:", exchange_list) # Get account information for a specific exchange account = GetAccount() # Assumes GetAccount() retrieves current active account Log("Account balance: ", account.Balance) Log("Account currency: ", account.Currency) ``` -------------------------------- ### JavaScript Strategy Entry Functions and Global Functions Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet shows the structure of strategy entry functions like init(), onexit(), onerror(), and examples of using global functions within a JavaScript trading strategy. ```javascript // Strategy Entry Functions function init() { Log("Strategy initialized."); } function onexit() { Log("Strategy exiting."); } function onerror() { Log("An error occurred."); } // Example of using global functions function onTick() { var price = GetTickCount(); Log("Current tick count: ", price); var account = GetAccount(); Log("Account balance: ", account.Balance); } ``` -------------------------------- ### Explain Code Snippet with AI Assistant Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E7%BC%96%E8%BE%91%E5%99%A8/ai%E5%8A%A9%E6%89%8B This snippet shows how to use the AI assistant to get explanations for selected code snippets. After selecting code, right-clicking and choosing '解释这段代码' will provide a detailed breakdown of the code's logic. ```text Select code -> Right-click -> 解释这段代码 ``` -------------------------------- ### C++ Get Exchange List and Account Information Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet shows how to retrieve a list of supported exchanges and fetch account information using C++. ```cpp // Get a list of supported exchanges std::vector exchangeList = GetExchangeList(); for (const auto& exchange : exchangeList) { Log("Supported Exchange: %s", exchange.c_str()); } // Get account information for a specific exchange Account account = GetAccount(); // Assumes GetAccount() retrieves current active account Log("Account balance: %f", account.Balance); Log("Account currency: %s", account.Currency.c_str()); ``` -------------------------------- ### JavaScript Get Exchange List and Account Information Source: https://www.fmz.com/user-guide/web3/%E6%B3%A2%E5%9C%BA/%E6%94%AF%E6%8C%81%E5%88%87%E6%8D%A2%E7%A7%81%E9%92%A5 This snippet shows how to retrieve a list of supported exchanges and fetch account information using JavaScript. ```javascript // Get a list of supported exchanges var exchangeList = GetExchangeList(); Log("Supported Exchanges:", exchangeList); // Get account information for a specific exchange var account = GetAccount(); // Assumes GetAccount() retrieves current active account Log("Account balance: ", account.Balance); Log("Account currency: ", account.Currency); ``` -------------------------------- ### Strategy Framework and API Functions Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E6%A1%86%E6%9E%B6%E4%B8%8Eapi%E5%87%BD%E6%95%B0 This section details the fundamental structure of strategies across JavaScript, Python, and C++, emphasizing the crucial role of the `Sleep()` function for controlling execution speed and API request frequency. It provides examples for basic framework implementation, simple order placement, and an On-Bar architecture. ```APIDOC ## Strategy Framework and API Functions In strategies written in `JavaScript`, `Python`, and `C++`, the `Sleep()` function must be called within the main strategy loop. This function controls the execution speed during backtesting and the polling interval in live trading, thereby managing the frequency of requests to exchange API interfaces. ### Basic Framework Example (Cryptocurrency Strategies) #### JavaScript ```javascript function onTick(){ // Write strategy logic here. It will be called continuously, for example, to print ticker information. Log(exchange.GetTicker()) } function main(){ while(true){ onTick() // The Sleep function is mainly used to control the polling frequency of cryptocurrency strategies, preventing excessive requests to the exchange API. Sleep(60000) } } ``` #### Python ```python def onTick(): Log(exchange.GetTicker()) def main(): while True: onTick() Sleep(60000) ``` #### C++ ```cpp void onTick() { Log(exchange.GetTicker()); } void main() { while(true) { onTick(); Sleep(60000); } } ``` ### Simple Order Placement Example This example demonstrates how to place a buy order with a price of 100 and a quantity of 1 every second. #### JavaScript ```javascript function onTick(){ // This is just an example. In backtesting or live trading, funds will be depleted quickly. Do not use in live trading without proper risk management. exchange.Buy(100, 1) } function main(){ while(true){ onTick() // The pause duration can be customized. Units are milliseconds (1 second = 1000 milliseconds). Sleep(1000) } } ``` #### Python ```python def onTick(): exchange.Buy(100, 1) def main(): while True: onTick() Sleep(1000) ``` #### C++ ```cpp void onTick() { exchange.Buy(100, 1); } void main() { while(true) { onTick(); Sleep(1000); } } ``` ### On-Bar Architecture Strategy Design This example illustrates how to design a strategy that reacts to new bars (candlesticks). #### JavaScript ```javascript function onTick() { Log("K-line updated, 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) } } ``` #### Python ```python def onTick(): Log("K-line updated, 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) ``` #### C++ ```cpp void onTick() { Log("K-line updated, 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); } } ``` ### API Interface Quick Reference A quick reference table for all API interfaces is provided below. For detailed API descriptions, please refer to the "Inventors Quantitative Trading Platform API Manual." ``` -------------------------------- ### Strategy Using Template Library Parameters (JavaScript, Python, C++) Source: https://www.fmz.com/user-guide/%E6%A8%A1%E6%9D%BF%E7%B1%BB%E5%BA%93 Provides an example of a main strategy that utilizes template library functions to get and set a parameter. This demonstrates how a strategy can interact with the parameters defined within a referenced template library across JavaScript, Python, and C++. ```javascript function main () { Log("调用$.GetParam1:", $.GetParam1()) Log("调用$.SetParam1:", "#FF0000") $.SetParam1(20) Log("调用$.GetParam1:", $.GetParam1()) } ``` ```python def main(): Log("调用ext.GetParam1:", ext.GetParam1()) Log("调用ext.SetParam1:", "#FF0000") ext.SetParam1(20) Log("调用ext.GetParam1:", ext.GetParam1()) ``` ```c++ void main() { Log("调用ext::GetParam1:", ext::GetParam1()); Log("调用ext::SetParam1:", "#FF0000"); ext::SetParam1(20); Log("调用ext::GetParam1:", ext::GetParam1()); } ``` -------------------------------- ### JavaScript Strategy Development Guide Source: https://www.fmz.com/user-guide/%E5%AE%9E%E7%9B%98%E6%8A%A5%E9%94%99%E3%80%81%E5%BC%82%E5%B8%B8%E9%80%80%E5%87%BA%E7%9A%84%E5%B8%B8%E8%A7%81%E5%8E%9F%E5%9B%A0 This section provides guidance on developing strategies using JavaScript within the FMZ platform. It covers common pitfalls and best practices for writing robust JavaScript trading strategies, including asynchronous operations and error handling. ```JavaScript function init() { // Initialization code } function onTick() { // Trading logic } function onexit() { // Cleanup code } ``` -------------------------------- ### Golang Custom Data Source Server Example Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E6%BA%90/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%95%B0%E6%8D%AE%E6%BA%90%E8%8C%83%E4%BE%8B This Golang code snippet demonstrates a basic HTTP server designed to act as a custom data source. It handles incoming requests, parses parameters, and returns data in a specified JSON format, including exchange details, schema, and historical price data. This can be used to provide custom trading data for backtesting or live trading on platforms like FMZ. ```golang package main import ( "fmt" "net/http" "encoding/json" ) func Handle (w http.ResponseWriter, r *http.Request) { // e.g. set on backtest DataSourse: http://xxx.xx.x.xx:9090/data // request: GET http://xxx.xx.x.xx:9090/data?custom=0&depth=20&detail=true&eid=OKX&from=1584921600&period=86400000&round=true&symbol=BTC_USDT&to=1611244800&trades=1 // http://xxx.xx.x.xx:9090/data?custom=0&depth=20&detail=true&eid=Futures_Binance&from=1599958800&period=3600000&round=true&symbol=BTC_USDT.swap&to=1611244800&trades=0 fmt.Println("request:", r) // response defer func() { // response data /* e.g. data { "detail": { "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10 }, "schema": [ "time", "open", "high", "low", "close", "vol" ], "data": [ [1610755200000, 3673743, 3795000, 3535780, 3599498, 8634843151], [1610841600000, 3599498, 3685250, 3385000, 3582861, 8015772738], [1610928000000, 3582499, 3746983, 3480000, 3663127, 7069811875], [1611014400000, 3662246, 3785000, 3584406, 3589149, 7961130777], [1611100800000, 3590194, 3641531, 3340000, 3546823, 8936842292], [1611187200000, 3546823, 3560000, 3007100, 3085013, 13500407666], [1611273600000, 3085199, 3382653, 2885000, 3294517, 14297168405], [1611360000000, 3295000, 3345600, 3139016, 3207800, 6459528768], [1611446400000, 3207800, 3307100, 3090000, 3225990, 5797803797], [1611532800000, 3225945, 3487500, 3191000, 3225420, 8849922692] ] } */ // /* 模拟级Tick ret := map[string]interface{}{ "detail": map[string]interface{}{ "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10, }, "schema": []string{"time","open","high","low","close","vol"}, "data": []interface{}{ []int64{1610755200000, 3673743, 3795000, 3535780, 3599498, 8634843151}, // 1610755200000 : 2021-01-16 08:00:00 []int64{1610841600000, 3599498, 3685250, 3385000, 3582861, 8015772738}, // 1610841600000 : 2021-01-17 08:00:00 []int64{1610928000000, 3582499, 3746983, 3480000, 3663127, 7069811875}, []int64{1611014400000, 3662246, 3785000, 3584406, 3589149, 7961130777}, []int64{1611100800000, 3590194, 3641531, 3340000, 3546823, 8936842292}, []int64{1611187200000, 3546823, 3560000, 3007100, 3085013, 13500407666}, []int64{1611273600000, 3085199, 3382653, 2885000, 3294517, 14297168405}, []int64{1611360000000, 3295000, 3345600, 3139016, 3207800, 6459528768}, []int64{1611446400000, 3207800, 3307100, 3090000, 3225990, 5797803797}, []int64{1611532800000, 3225945, 3487500, 3191000, 3225420, 8849922692}, }, } // */ /* 实盘级Tick ret := map[string]interface{}{ "detail": map[string]interface{}{ "eid": "Binance", "symbol": "BTC_USDT", "alias": "BTCUSDT", "baseCurrency": "BTC", "quoteCurrency": "USDT", "marginCurrency": "USDT", "basePrecision": 5, "quotePrecision": 2, "minQty": 0.00001, "maxQty": 9000, "minNotional": 5, "maxNotional": 9000000, "priceTick": 0.01, "volumeTick": 0.00001, "marginLevel": 10, }, "schema": []string{"time", "asks", "bids", "trades", "close", "vol"}, */ json.Marshal(ret) w.Write([]byte("success")) }() } func main() { http.HandleFunc("/data", Handle) fmt.Println("Server starting on port 9090...") http.ListenAndServe(":9090", nil) } ``` -------------------------------- ### Fetch Robot Details using FMZ API (Go) Source: https://www.fmz.com/user-guide/%E6%89%A9%E5%B1%95api%E6%8E%A5%E5%8F%A3/%E9%AA%8C%E8%AF%81%E6%96%B9%E5%BC%8F/%E7%9B%B4%E6%8E%A5%E9%AA%8C%E8%AF%81 This Go program defines a function `api` to interact with the FMZ Quant Trading Platform's API. It constructs HTTP GET requests to specified methods and arguments, including API key and secret for authentication. The `main` function calls `GetRobotDetail` for robot ID 186515 and prints the result. It requires the FMZ API key and secret key to be configured. ```go package main import ( "fmt" "encoding/json" "net/http" "io/ioutil" "net/url" ) // 填写自己的FMZ平台api key var apiKey string = "your access_key" // 填写自己的FMZ平台secret key var secretKey string = "your secret_key" var baseApi string = "https://www.fmz.com/api/v1" func api(method string, args ... interface{}) (ret interface{}) { jsonStr, err := json.Marshal(args) if err != nil { panic(err) } params := map[string]string{ "access_key" : apiKey, "secret_key" : secretKey, "method" : method, "args" : string(jsonStr), } // http request client := &http.Client{} // request urlValue := url.Values{} for k, v := range params { urlValue.Add(k, v) } urlStr := urlValue.Encode() request, err := http.NewRequest("GET", baseApi + "?" + urlStr, nil) if err != nil { panic(err) } resp, err := client.Do(request) if err != nil { panic(err) } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } ret = string(b) return } func main() { method := "GetRobotDetail" fmt.Println("调用接口:", method) ret := api(method, 186515) fmt.Println("main ret:", ret) } ``` -------------------------------- ### Web3 - Ethereum RPC Methods Source: https://www.fmz.com/user-guide/index This section details how to interact with the Ethereum blockchain using the FMZ platform's Web3 functionalities. It covers configuring the Web3 exchange object, registering ABI, calling RPC methods, and handling encoding/decoding. ```APIDOC ## Web3 - Ethereum Interaction ### Description This section details how to interact with the Ethereum blockchain using the FMZ platform's Web3 functionalities. It covers configuring the Web3 exchange object, registering ABI, calling RPC methods, and handling encoding/decoding. ### Key Features - **Web3 Exchange Object Configuration**: Set up and configure the connection to an Ethereum node. - **Register ABI**: Register the Application Binary Interface (ABI) for smart contracts. - **Call Ethereum RPC Methods**: Execute various JSON-RPC methods for Ethereum. - **Encoding and Decoding**: Support for `encode` and `encodePacked` for transaction data, and `decode` for received data. - **Private Key Switching**: Ability to switch between different private keys for transaction signing. - **Call Smart Contract Methods**: Interact with functions defined in smart contracts. ### Example Usage (Conceptual) ```javascript // Initialize Web3 exchange object for Ethereum var ether = exchanges.NewExchange('web3', 'ETH', { "urls": { "api": "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID" }, "private_key": "0x...YOUR_PRIVATE_KEY..." }); // Register ABI for a smart contract var contractABI = [ // ... ABI definition ... ]; var contractAddress = "0x..."; var contract = ether.AddContract(contractAddress, contractABI); // Call a smart contract function var result = contract.MyFunction(arg1, arg2); // Call a raw RPC method var blockNumber = ether.Call('eth_blockNumber'); // Encode data var encodedData = ether.Encode(methodSignature, args); ``` ### Supported RPC Methods (Examples) - `eth_blockNumber` - `eth_getBalance` - `eth_sendRawTransaction` - ...and others ### Supported Encoding Functions - `Encode(methodSignature, args)` - `EncodePacked(methodSignature, args)` ### Supported Decoding Functions - `Decode(data, types)` ``` -------------------------------- ### JavaScript Strategy Example - onerror() function Source: https://www.fmz.com/user-guide/index Example of the onerror() function in a JavaScript strategy. This function is executed when an error occurs during strategy execution. It's crucial for logging errors and potentially taking corrective actions. Handle errors gracefully to prevent unexpected behavior. ```javascript function onerror(err) { // Log the error message Log("An error occurred: " + err); } ``` -------------------------------- ### JavaScript Strategy Example - onexit() function Source: https://www.fmz.com/user-guide/index Example of the onexit() function in a JavaScript strategy. This function is called once when the strategy is stopped or exits. It's commonly used for cleanup operations, such as closing positions or saving final states. Ensure no critical operations are left incomplete. ```javascript function onexit() { // Perform cleanup operations here Log("Strategy exited."); } ``` -------------------------------- ### JavaScript - Using TA-Lib for Technical Analysis Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E7%BC%96%E8%BE%91%E5%99%A8/%E8%AF%AD%E6%B3%95%E6%89%8B%E5%86%8C%E9%80%9F%E6%9F%A5 Example of using the TA-Lib library in JavaScript for calculating technical analysis indicators. This requires the TA-Lib library to be installed and configured for Node.js. ```javascript // Assuming 'talib' is imported or required // const talib = require('talib'); // Assume 'closePrices' is an array of closing prices // const closePrices = [10.5, 11.2, 11.8, 12.1, 12.5, 12.3, 12.8, 13.0, 13.5, 13.2]; // Calculate Simple Moving Average (SMA) // const smaPeriod = 3; // const sma = talib.SMA(closePrices, smaPeriod); // Calculate Relative Strength Index (RSI) // const rsiPeriod = 5; // const rsi = talib.RSI(closePrices, rsiPeriod); // console.log("SMA:", sma); // console.log("RSI:", rsi); ``` -------------------------------- ### FMZ Deployer Command-Line Arguments (Global IP Address) Source: https://www.fmz.com/user-guide/%E6%89%98%E7%AE%A1%E8%80%85/%E5%85%A8%E5%B1%80%E6%8C%87%E5%AE%9Aip%E5%9C%B0%E5%9D%80 This section details the command-line arguments for deploying the FMZ Quant Trading Platform's deployer program, particularly focusing on specifying a custom local IP address using the `-I` parameter. It outlines various other parameters for configuration, networking, and logging. ```Go log -I string custom local ip address -c string config file -d string custom dns resolve server -e string docker node executable path -f string docker settings json -i string docker image name -n string node name -p string password -s string server address -u string run as system user -v version info -vv show verbose log -w string working directory ```