### JavaScript Basic Syntax and Logging on FMZ Source: https://www.fmz.com/strategy/395725 Demonstrates basic JavaScript syntax including comments and logging. Log function is used instead of console.log for debugging on FMZ platform. ```JavaScript //文中的console.log在FMZ调试可以用Log函数代替 // 注释方式和C很像,这是单行注释 /* 这是多行 注释 */ // 语句可以以分号结束 doStuff(); // ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入(除了一些特殊情况)。 doStuff() // 因为这些特殊情况会导致意外的结果,所以我们在这里保留分号。 ``` -------------------------------- ### JavaScript: Main Function Setup Source: https://www.fmz.com/digest-topic/8438 Sets up the main execution environment by clearing persistent data and resetting logs. It then initializes `depthManager` and `positionManager` instances with specified exchange objects and trading parameters. ```javascript function main() { _G(null) // 清空持久化数据 LogReset(1) // 重置日志 // 以下代码可以切换OKEX模拟盘 // exchanges[0].IO("simulate", true) // exchanges[1].IO("simulate", true) var dm = depthManager(exchanges[0], exchanges[1], fuContractType, fuSymbol, spSymbol) var pm = positionManager(exchanges[0], exchanges[1], fuContractType, fuSymbol, spSymbol, step, buff, balanceType) } ``` -------------------------------- ### WebSocket subscription example to receive trades (JavaScript) Source: https://www.fmz.com/digest-topic/10574 Demonstrates connecting to the Hyperliquid WebSocket, sending a subscription request for SOL trade data, and reading incoming messages in a loop. Logs each received message and closes the connection after completion. ```JavaScript function main() {\n var loopCount = 20\n var subMsg = {\n \"method\": \"subscribe\", \n \"subscription\": {\n \"type\": \"trades\", \n \"coin\": \"SOL\"\n } \n }\n\n var conn = Dial(\"wss://api.hyperliquid.xyz/ws\")\n conn.write(JSON.stringify(subMsg))\n if (conn) {\n for (var i = 0; i < loopCount; i++) {\n var msg = conn.read(1000)\n if (msg) {\n Log(msg)\n }\n }\n }\n\n conn.close()\n Log(\"测试结束\")\n} ``` -------------------------------- ### Manual Host Deployment Source: https://www.fmz.com/user-guide/%E6%89%98%E7%AE%A1%E8%80%85/%E9%83%A8%E7%BD%B2%E6%89%98%E7%AE%A1%E8%80%85/%E6%89%8B%E5%8A%A8%E9%83%A8%E7%BD%B2%E6%89%98%E7%AE%A1%E8%80%85 Instructions for deploying host programs on different operating systems with required parameters. ```APIDOC ## Manual Host Deployment ### Description Deploy host programs on various operating systems including Linux, Mac, Windows, and Docker. ### Method N/A (Deployment instructions) ### Endpoint N/A (Deployment instructions) ### Parameters #### Required Parameters - **Communication Address** (string) - Required - Contains the FMZ Quant Trading Platform UID. - **Account Password** (string) - Required - The password corresponding to the FMZ Quant Trading Platform account. ### Request Example For Linux & Mac: ``` ./robot -s node.fmz.com/123456 -p 654321 ``` For Windows: ``` Fill in the parameters in the host program interface. ``` ### Response N/A (Deployment instructions) ``` -------------------------------- ### Get K-line Position (MyLang) Source: https://www.fmz.com/doc/2569 Returns the number of K-lines from the beginning up to the current one. It counts locally available K-lines, starting with 1 for the first available K-line. Examples show calculating the minimum value of local data and conditional value retrieval. ```MyLang BARPOS,返回从第一根K线开始到当前的周期数。 注: 1、BARPOS返回本地已有的K线根数,从本机上存在的数据开始算起。 2、本机已有的第一根K线上返回值为1。 例1:LLV(L,BARPOS); // 求本地已有数据的最小值。 例2:IFELSE(BARPOS=1,H,0); // 当前K线是本机已有的第一根K线取最高值,否则取0。 ``` -------------------------------- ### Pine Script String Input Example Source: https://www.fmz.com/doc/9315 Example demonstrating how to use the input.string function in Pine Script to get a string input from the user and log it. The input has a default value and a title. ```pine i_text = input.string("Hello!", "Message") runtime.log(i_text) ``` -------------------------------- ### Initialize HTTP server in Go Source: https://www.fmz.com/digest-topic/7968 Sets up a basic HTTP server with flag parsing for address configuration. Handles requests on a base path and logs server startup information. ```go func main() { var addr = flag.String("b", "127.0.0.1:6617", "bind addr") flag.Parse() if *addr == "" { flag.Usage() return } basePath := "/AOFEX" log.Println("Running ", fmt.Sprintf("http://%s%s", *addr, basePath), "...") http.HandleFunc(basePath, OnPost) http.ListenAndServe(*addr, nil) } ``` -------------------------------- ### Initialize Strategy Logic (JavaScript, Python, C++) Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E5%85%A5%E5%8F%A3%E5%87%BD%E6%95%B0/init Demonstrates the `init()` function for initializing strategy logic in JavaScript, Python, and C++. This function is automatically executed at the start of a strategy's runtime to perform setup tasks. It also includes a `main()` function for the primary program execution. ```javascript function main(){ Log("程序第一行代码执行!", "#FF0000") Log("退出!") } // 初始化函数 function init(){ Log("初始化!") } ``` ```python def main(): Log("程序第一行代码执行!", "#FF0000") Log("退出!") def init(): Log("初始化!") ``` ```c++ void main() { Log("程序第一行代码执行!", "#FF0000"); Log("退出!"); } void init() { Log("初始化!"); } ``` -------------------------------- ### Array slicing example (JavaScript) Source: https://www.fmz.com/digest-topic/6255 Demonstrates JavaScript array slicing with negative indices. Shows how to extract a portion of an array from specified start to end positions. ```javascript function main() { // index .. -8 -7 -6 -5 -4 -3 -2 -1 var arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Log(arr.slice(-5, -1)) // 会截取 4 ~ 1 这几个元素,返回一个新数组:[4,3,2,1] } ``` -------------------------------- ### Get Contract Exchange Code (CONTRACT) - mylang Source: https://www.fmz.com/doc/2569 Retrieves the exchange contract code mapped by the current contract settings. The example logs the contract information. ```mylang INFO(1, CONTRACT); ``` -------------------------------- ### Host Deployment Source: https://www.fmz.com/user-guide/%E6%89%98%E7%AE%A1%E8%80%85 Information on how to deploy the host software, either through a one-click rental service or manual deployment. ```APIDOC ## Host Deployment ### One-Click Host Rental This option allows for quick deployment of a host server. Select server configurations and regions, then proceed to purchase. The system will automatically deploy the host program, including common Python libraries. Note that servers rented through this method have limited system permissions and do not support remote login. For custom Python library needs, manual deployment on a private server is recommended. This service is billed separately from live trading. ### Manual Host Deployment Deploy the host program on your own devices (personal computers, servers, Raspberry Pi, etc.) across various operating systems: * **Linux:** AMD64, 386, ARM64, ARMv7 * **Mac:** Intel64, Apple Silicon * **Windows:** 64-bit, 32-bit (Command-line and GUI versions) * **Docker:** Images available Download the appropriate host program from the deployment page. Deployment requires setting two parameters: 1. **Communication Address:** The FMZ Quant Trading Platform UID communication address. 2. **Password:** The password corresponding to the UID. **Configuration Methods:** * **Windows GUI Version:** Input parameters directly into the interface fields. * **Command-line Versions (Linux/Mac Example):** ```bash ./robot -s node.fmz.com/123456 -p 654321 ``` * `./robot`: The host program executable. * `-s `: Specifies the communication address (e.g., `node.fmz.com/123456`). `123456` is the UID. * `-p `: Specifies the account password. It is recommended to omit this and enter the password when prompted for security reasons. Ensure the host program has sufficient execution permissions. ``` -------------------------------- ### Get Date (MyLang) Source: https://www.fmz.com/doc/2569 Retrieves the date (year, month, day) since 1900 for the current period. The example shows a value representing February 18, 2022. ```MyLang 例1: AA..DATE; // 测试时AA的值为220218,表示2022年2月18日 ``` -------------------------------- ### Managing Robots Source: https://www.fmz.com/user-guide/%E6%89%A9%E5%B1%95api%E6%8E%A5%E5%8F%A3/%E6%89%A9%E5%B1%95api%E6%8E%A5%E5%8F%A3%E8%BF%94%E5%9B%9E%E7%A0%81 Endpoints for managing trading robots, including listing, creating, starting, stopping, and retrieving details. ```APIDOC ## GetRobotList ### Description Retrieves a list of trading robots. ### Method GET ### Endpoint `/GetRobotList` ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. ### Request Example N/A (Assumes authentication via headers or query params) ### Response #### Success Response (200) - **code** (integer) - 0 for success. - **data** (object) - A list of robot objects. - **robotId** (string) - The ID of the robot. - **name** (string) - The name of the robot. - **status** (string) - The current status of the robot. #### Response Example ```json { "code": 0, "data": [ { "robotId": "robot_123", "name": "My Strategy Bot", "status": "running" } ] } ``` ## NewRobot ### Description Creates a new trading robot. ### Method POST ### Endpoint `/NewRobot` ### Parameters #### Request Body - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **name** (string) - Required - The name for the new robot. - **strategyId** (string) - Required - The ID of the strategy to use. - **exchangeId** (string) - Required - The ID of the exchange to trade on. - **parameters** (object) - Optional - Configuration parameters for the strategy. ### Request Example ```json { "apiKey": "YOUR_API_KEY", "signature": "YOUR_SIGNATURE", "timestamp": 1678886400, "name": "New Trading Bot", "strategyId": "strategy_abc", "exchangeId": "exchange_xyz", "parameters": { "takeProfit": 0.05, "stopLoss": 0.02 } } ``` ### Response #### Success Response (200) - **code** (integer) - 0 for success. - **data** (object) - **robotId** (string) - The ID of the newly created robot. #### Response Example ```json { "code": 0, "data": { "robotId": "robot_456" } } ``` ## CommandRobot ### Description Sends a command to a trading robot (e.g., start, stop). ### Method POST ### Endpoint `/CommandRobot` ### Parameters #### Request Body - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **robotId** (string) - Required - The ID of the robot to command. - **command** (string) - Required - The command to execute (e.g., "start", "stop", "restart"). ### Request Example ```json { "apiKey": "YOUR_API_KEY", "signature": "YOUR_SIGNATURE", "timestamp": 1678886401, "robotId": "robot_123", "command": "stop" } ``` ### Response #### Success Response (200) - **code** (integer) - 0 for success. #### Response Example ```json { "code": 0 } ``` ## GetRobotDetail ### Description Retrieves detailed information about a specific trading robot. ### Method GET ### Endpoint `/GetRobotDetail` ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **robotId** (string) - Required - The ID of the robot. ### Request Example N/A ### Response #### Success Response (200) - **code** (integer) - 0 for success. - **data** (object) - Detailed information about the robot. - **robotId** (string) - The ID of the robot. - **name** (string) - The name of the robot. - **strategyName** (string) - The name of the strategy. - **exchangeName** (string) - The name of the exchange. - **status** (string) - The current status of the robot. - **runningTime** (integer) - The duration the robot has been running in seconds. - **parameters** (object) - The configuration parameters of the strategy. #### Response Example ```json { "code": 0, "data": { "robotId": "robot_123", "name": "My Strategy Bot", "strategyName": "MACross", "exchangeName": "Binance", "status": "running", "runningTime": 3600, "parameters": { "takeProfit": 0.05, "stopLoss": 0.02 } } } ``` ## StopRobot ### Description Stops a running trading robot. ### Method POST ### Endpoint `/StopRobot` ### Parameters #### Request Body - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **robotId** (string) - Required - The ID of the robot to stop. ### Request Example ```json { "apiKey": "YOUR_API_KEY", "signature": "YOUR_SIGNATURE", "timestamp": 1678886402, "robotId": "robot_123" } ``` ### Response #### Success Response (200) - **code** (integer) - 0 for success. #### Response Example ```json { "code": 0 } ``` ## RestartRobot ### Description Restarts a stopped or running trading robot. ### Method POST ### Endpoint `/RestartRobot` ### Parameters #### Request Body - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **robotId** (string) - Required - The ID of the robot to restart. ### Request Example ```json { "apiKey": "YOUR_API_KEY", "signature": "YOUR_SIGNATURE", "timestamp": 1678886403, "robotId": "robot_123" } ``` ### Response #### Success Response (200) - **code** (integer) - 0 for success. #### Response Example ```json { "code": 0 } ``` ## DeleteRobot ### Description Deletes a trading robot. ### Method POST ### Endpoint `/DeleteRobot` ### Parameters #### Request Body - **apiKey** (string) - Required - Your API key for authentication. - **signature** (string) - Required - The signature of the request. - **timestamp** (integer) - Required - The Unix timestamp of the request. - **robotId** (string) - Required - The ID of the robot to delete. ### Request Example ```json { "apiKey": "YOUR_API_KEY", "signature": "YOUR_SIGNATURE", "timestamp": 1678886404, "robotId": "robot_123" } ``` ### Response #### Success Response (200) - **code** (integer) - 0 for success. #### Response Example ```json { "code": 0 } ``` ``` -------------------------------- ### JavaScript Strategy Entry Functions: main and onexit Examples Source: https://www.fmz.com/user-guide/%E7%AD%96%E7%95%A5%E5%85%A5%E5%8F%A3%E5%87%BD%E6%95%B0 Demonstrates the implementation of `main()` and `onexit()` functions in JavaScript for a trading strategy. The `main` function simulates a delay before stopping, triggering the `onexit` function for cleanup operations. This example is suitable for live trading scenarios. ```javascript function main(){ Log("开始运行,5秒后停止并执行清理函数!") Sleep(1000 * 5) } // 清理函数实现 function onexit(){ var beginTime = new Date().getTime() while(true){ var nowTime = new Date().getTime() Log("程序停止倒计时...清理开始,已经过去:", (nowTime - beginTime) / 1000, "秒!") Sleep(1000) } } ``` -------------------------------- ### HTTP Server Setup in Go Source: https://www.fmz.com/user-guide/%E5%9B%9E%E6%B5%8B%E7%B3%BB%E7%BB%9F This snippet demonstrates setting up an HTTP server in Go that listens on port 9090 and handles data requests. It includes JSON marshaling for response data. ```Go func main () { fmt.Println("listen http://localhost:9090") http.HandleFunc("/data", Handle) http.ListenAndServe(":9090", nil) } ``` -------------------------------- ### Get Low Price (MyLang) Source: https://www.fmz.com/doc/2569 Retrieves the lowest price (LOW) of a K-line. It can be abbreviated as 'L'. Examples show variable assignment, finding the minimum low over a period, and referencing the previous period's low price. ```MyLang LOW取得K线图的最低价。 注: 1、可简写为L。 例1: LL:=L; // 定义LL为最低价 例2: LL:=LLV(L,5); // 取得5个周期内最低价的最小值 例3: REF(L,1); // 取得前一根K线的最低价 ``` -------------------------------- ### Get High Price (MyLang) Source: https://www.fmz.com/doc/2569 Retrieves the highest price (HIGH) of a K-line. It can be abbreviated as 'H'. Examples show variable assignment, finding the maximum high over a period, and referencing the previous period's high price. ```MyLang HIGH取得K线图的最高价。 注: 1、可简写为H。 例1: HH:=H; // 定义HH为最高价 例2: HH:=HHV(H,5); // 取的5个周期内最高价的最大值 例3: REF(H,1); // 取的前一根K线的最高价 ``` -------------------------------- ### GetRobotLogs - Profit Log Example Source: https://www.fmz.com/user-guide/%E6%89%A9%E5%B1%95api%E6%8E%A5%E5%8F%A3/%E6%89%A9%E5%B1%95api%E6%8E%A5%E5%8F%A3%E8%AF%A6%E8%A7%A3/getrobotlogs Example of Profit Log data structure showing various profit log components ```plaintext Arr: [ [202, 2515.44, 1575896700315], [201, 1415.44, 1575896341568] ] Example: [202, 2515.44, 1575896700315] logId: 202, profit: 2515.44, timestamp: 1575896700315 ``` -------------------------------- ### Get Open Price (MyLang) Source: https://www.fmz.com/doc/2569 Retrieves the opening price (OPEN) of a K-line. It can be abbreviated as 'O'. Examples show variable assignment, calculating a moving average of the open price, and referencing the previous period's open price. ```MyLang OPEN取得K线图的开盘价。 注: 1、可简写为O。 例1: OO:=O; //定义OO为开盘价;注意O与0的区别。 例2: NN:=BARSLAST(DATE<>REF(DATE,1)); OO:=REF(O,NN); //取的当日的开盘价 例3: MA5:=MA(O,5); //定义开盘价的5周期均线(O为OPEN简写)。 ``` -------------------------------- ### Futures Funding Rate Data Request Example (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/%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F This is an example URL representing a request for futures funding rate data. It specifies parameters like exchange ID, symbol, time range, and data period for the backtesting system. ```url http://customserver:9090/data?custom=0&depth=20&detail=true&eid=Futures_Binance&from=1351641600&period=86400000&round=true&symbol=BTC_USDT.funding&to=1611244800&trades=0 ``` -------------------------------- ### Pine Script Trend Strategy with Backtest Setup Source: https://www.fmz.com/strategy/360018 This snippet implements a basic Pine Script v4 strategy for trend following, starting with input for source price (close) and backtest configuration for BTC_USD on Bitfinex from 2020 to 2022. It relies on TradingView's Pine environment and indicators like SMA, ADX, and ATR. Inputs include multiple SMA lengths, ATR factor/period, ADX type/length/threshold, cloud length, and volume multipliers; outputs trading signals based on crossovers and thresholds. Limitations: Partial code shown; full implementation needs login for complete logic, potential overfitting in backtests. ```Pine Script /*backtest start: 2020-01-28 00:00:00 end: 2022-04-27 00:00:00 period: 1d basePeriod: 1h exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ //@version=4 src = input(close) ``` -------------------------------- ### Command Line Arguments for Deploying Managed Hosts 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 snippet shows the command-line arguments for deploying managed hosts. It details options for specifying IP addresses, configuration files, DNS servers, and other deployment parameters. ```bash -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 ``` -------------------------------- ### Get Volume (MyLang) Source: https://www.fmz.com/doc/2569 Retrieves the trading volume (VOL) of a K-line. It can be abbreviated as 'V'. For tick data, it accumulates the total volume for the day. Examples show variable assignment, referencing the previous period's volume, and comparing volume. ```MyLang VOL取得K线图的成交量。 注: 可简写为V。 该函数在当根TICK上的返回值为当天所有TICK成交量的累计值。 例1: VV:=V; // 定义VV为成交量 例2: REF(V,1); // 表示前一个周期的成交量 例3: V>=REF(V,1); // 成交量大于前一个周期的成交量,表示成交量增加(V为VOL的简写) ```