### HTTP/WebSocket Client Connection Example Source: https://www.fmz.com/syntax-guide/fun/global Demonstrates establishing a TLS connection to www.baidu.com, sending an HTTP GET request, and reading the response in Python. This showcases basic client-server communication. ```python def main(): client = Dial("tls://www.baidu.com:443") if client: client.write("GET / HTTP/1.1\nConnection: Closed\n\n") while True: buf = client.read() if not buf: break Log(buf) client.close() __ ``` -------------------------------- ### FMZ Thread Creation and Management Source: https://www.fmz.com/syntax-guide/fun/os/os/mkdir Provides examples of creating and managing threads using the 'threading' module. This includes starting new threads, getting current threads, and synchronization primitives like Lock, Condition, and Event. ```javascript var t = threading.Thread(function() { Log("Thread running"); }); t.start(); var main = threading.mainThread(); var current = threading.currentThread(); var lock = threading.Lock(); lock.acquire(); lock.release(); var cond = threading.Condition(); cond.notify(); cond.notifyAll(); cond.wait(); var event = threading.Event(); event.set(); event.clear(); event.wait(); ``` -------------------------------- ### HTTP/WebSocket Client Connection Example Source: https://www.fmz.com/syntax-guide/fun/global Demonstrates establishing a TLS connection to www.baidu.com, sending an HTTP GET request, and reading the response. It shows basic client-server interaction using the Dial function. ```javascript function main(){ // Dial支持tcp://,udp://,tls://,unix://协议,可加一个参数指定超时的秒数 var client = Dial("tls://www.baidu.com:443") if (client) { // write可再跟一个数字参数指定超时,write返回成功发送的字节数 client.write("GET / HTTP/1.1\nConnection: Closed\n\n") while (true) { // read可再跟一个数字参数指定超时,单位:毫秒。返回null指出错或者超时或者socket已经关闭 var buf = client.read() if (!buf) { break } Log(buf) } client.close() } } __ ``` -------------------------------- ### HTTP/WebSocket Client Connection Example Source: https://www.fmz.com/syntax-guide/fun/global Illustrates making a TLS connection to www.baidu.com, sending an HTTP GET request, and reading the server's response using C++. This example highlights fundamental client-server interaction. ```c++ void main() { auto client = Dial("tls://www.baidu.com:443"); if(client.Valid) { client.write("GET / HTTP/1.1\nConnection: Closed\n\n"); while(true) { auto buf = client.read(); if(buf == "") { break; } Log(buf); } client.close(); } } __ ``` -------------------------------- ### Example: Fetching and Displaying Funding Rates (C++) Source: https://www.fmz.com/syntax-guide/fun/futures This C++ example illustrates how to retrieve funding rate data using exchange.GetFundings() and present it in a structured table. It also demonstrates handling calls with and without the symbol parameter. ```c++ /*backtest start: 2024-10-01 00:00:00 end: 2024-10-23 00:05:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDC"}] */ void main() { // LPT_USDT.swap 4小时周期 json arrSymbol = R"([])"_json; std::string symbols[] = {"SOL_USDT.swap", "ETH_USDT.swap", "LTC_USDT.swap", "SOL_USDC.swap", "ETH_USDC.swap", "BTC_USD.swap", "BTC_USDT.quarter", "LPT_USDT.swap"}; for (const std::string& symbol : symbols) { exchange.GetTicker(symbol); arrSymbol.push_back(symbol); } std::vector> arr = {}; std::string arrParams[] = {"no param", "LTC_USDT.swap", "USDT.swap", "USD.swap", "USDC.swap", "USDT.futures", "BTC_USDT.quarter"}; for (const std::string& p : arrParams) { if (p == "no param") { arr.push_back(exchange.GetFundings()); } else { arr.push_back(exchange.GetFundings(p)); } } json tbls = R"([])"_json; int index = 0; for (int i = 0; i < arr.size(); i++) { auto fundings = arr[i]; json tbl = R"({ "type": "table", "cols": ["Symbol", "Interval", "Time", "Rate"], "rows": [] })"_json; tbl["title"] = arrParams[index]; for (int j = 0; j < fundings.size(); j++) { auto f = fundings[j]; // json arrJson = {f.Symbol, f.Interval / 3600000, _D(f.Time), string(f.Rate * 100) + " %"}; json arrJson = {f.Symbol, f.Interval / 3600000, _D(f.Time), f.Rate}; tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); index++; } LogStatus(_D(), "\n 已经请求过的行情品种:", arrSymbol.dump(), "\n`" + tbls.dump() + "`"); } __ ``` -------------------------------- ### Backpack.exchange WebSocket Private API Example Source: https://www.fmz.com/syntax-guide/fun A practical example demonstrating how to connect to the Backpack.exchange private WebSocket API, subscribe to account updates, and handle potential issues with special characters in the payload when constructing the Dial address. ```APIDOC ## BackPack.exchange WebSocket Private API Example ### Description This example shows how to establish a WebSocket connection to Backpack.exchange, authenticate, and subscribe to order updates using the `Dial` function. It highlights a common issue where directly embedding a JSON payload with special characters into the `Dial` address string can lead to parsing errors. The recommended approach is to establish the connection first and then use `client.write()` to send the payload. ### Method `Dial(address string)` and `client.write(data string)` ### Endpoint `wss://ws.backpack.exchange` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Payload is sent via `client.write()`) ### Request Example ```javascript var client = null function main() { // base64编码的秘钥对公钥,即在FMZ上配置的access key var base64ApiKey = "xxx" var ts = String(new Date().getTime()) var data = "instruction=subscribe×tamp=" + ts + "&window=5000" // 由于signEd25519最终返回的是base64编码,其中会有字符"=" var signature = signEd25519(data) // payload 被JSON编码后可能包含字符"=" payload = { "method": "SUBSCRIBE", "params": ["account.orderUpdate"], "signature": [base64ApiKey, signature, ts, "5000"] } // Recommended: Establish connection first client = Dial("wss://ws.backpack.exchange") if (!client) { Log("连接失败, 程序退出") return } client.write(JSON.stringify(payload)) while (true) { var buf = client.read() Log(buf) } } function onexit() { client.close() } function signEd25519(data) { return exchange.Encode("ed25519.seed", "raw", "base64", data, "base64", "{{secretkey}}") } ``` **Incorrect approach (avoid):** ```javascript // Incorrect: Directly embedding payload in Dial address can cause issues // client = Dial("wss://ws.backpack.exchange|payload=" + JSON.stringify(payload)) ``` ### Response #### Success Response (200) - **string** - Data received from the WebSocket. #### Response Example ```json { "channel": "account.orderUpdate", "data": { ... } } ``` ``` -------------------------------- ### HttpQuery with Proxy Source: https://www.fmz.com/syntax-guide/fun/global/httpquery Example of setting up a proxy for the HttpQuery function. ```APIDOC ## HttpQuery with Proxy ### Description This section provides examples of using the `HttpQuery` function with proxy settings. ### Method ``` HttpQuery(url) ``` ### Endpoint N/A (This is a function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example #### Javascript Example ```javascript function main() { // Set proxy and send HTTP request without username or password. // This HTTP request will be sent via the proxy. HttpQuery("socks5://127.0.0.1:8889/http://www.baidu.com/"); // Set proxy with username and password, effective only for the current HttpQuery call. // Subsequent calls to HttpQuery("http://www.baidu.com") will not use the proxy. HttpQuery("socks5://username:password@127.0.0.1:8889/http://www.baidu.com/"); } ``` #### C++ Example ```cpp void main() { HttpQuery("socks5://127.0.0.1:8889/http://www.baidu.com/"); HttpQuery("socks5://username:password@127.0.0.1:8889/http://www.baidu.com/"); } ``` ### Response #### Success Response (200) - **response** (string / object) - Returns the response data of the request. Parsed as JSON if `debug` is true, otherwise a string. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Query gasPrice Source: https://www.fmz.com/syntax-guide/fun/web3/exchange.ioapi-blockchain-... Example of how to query the current gas price on the Ethereum network. ```APIDOC ## Query gasPrice ### Description Retrieves the current gas price on the Ethereum network. ### Method POST ### Endpoint `/api/blockchain/rpc` ### Parameters #### Request Body - **k** (string) - Required - Set to "api". - **blockChain** (string) - Required - Set to "eth". - **rpcMethod** (string) - Required - Set to "eth_gasPrice". ### Request Example ```json { "k": "api", "blockChain": "eth", "rpcMethod": "eth_gasPrice" } ``` ### Response #### Success Response (200) - **result** (string) - The current gas price in wei (hexadecimal format). #### Response Example ```json { "result": "0x530101c400" } ``` ``` -------------------------------- ### Query ETH Balance Source: https://www.fmz.com/syntax-guide/fun/web3/exchange.ioapi-blockchain-... Example of how to query the ETH balance of a wallet using the exchange.IO API. ```APIDOC ## Query ETH Balance ### Description Retrieves the ETH balance for a given wallet address. ### Method POST ### Endpoint `/api/blockchain/rpc` ### Parameters #### Request Body - **k** (string) - Required - Set to "api". - **blockChain** (string) - Required - Set to "eth". - **rpcMethod** (string) - Required - Set to "eth_getBalance". - **args** (array) - Required - Contains the wallet address and block parameter (e.g., "owner", "latest"). ### Request Example ```json { "k": "api", "blockChain": "eth", "rpcMethod": "eth_getBalance", "args": ["0xOwnerAddressHere", "latest"] } ``` ### Response #### Success Response (200) - **result** (string) - The ETH balance in hexadecimal format (e.g., "0x9b19ce56113070"). #### Response Example ```json { "result": "0x9b19ce56113070" } ``` ``` -------------------------------- ### FMZ Data Structures: Dictionary Operations Source: https://www.fmz.com/syntax-guide/fun/web3/exchange.ioencode-... Illustrates the use of the `Dict` data structure in FMZ for key-value storage. Includes examples of creating a dictionary, setting values using `set`, and retrieving values using `get`. `Dict` is often used for configuration or temporary data storage. ```javascript function main() { const myConfig = new Dict(); myConfig.set("strategyName", "MyAwesomeStrategy"); myConfig.set("leverage", 10); myConfig.set("enabled", true); Log("Strategy Name:", myConfig.get("strategyName")); Log("Leverage:", myConfig.get("leverage")); // Check if a key exists if (myConfig.get("enabled")) { Log("Strategy is enabled."); } } ``` -------------------------------- ### HTTP Request Log Output Example Source: https://www.fmz.com/syntax-guide/struct/otherstruct This is an example of the HTTP request that would be sent when the above JavaScript code is executed. It shows the request method, headers, and body content as it would appear in a log. ```log POST / HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cookie: session_id=12345; lang=en Host: 127.0.0.1:8080 Test-Http-Query: 123 Transfer-Encoding: chunked User-Agent: Mozilla/5.0 (Macintosh; ... Accept-Encoding: gzip, deflate, br e a=10&b=20&c=30 0 ``` -------------------------------- ### Get Thread Object by Thread ID Source: https://www.fmz.com/syntax-guide/fun Demonstrates how to retrieve a specific thread object using its ID with the `getThread(threadId)` function. This is useful for interacting with or inspecting threads after they have been created, as shown in the example where a thread gets itself. ```javascript function main() { var t1 = threading.Thread(function () { // Thread 对象有方法:id(),用于获取线程的Id,可以查看文档对应Thread对象的章节 var id = threading.currentThread().id() var thread1 = threading.getThread(id) Log("id:", id, ", thread1.id():", thread1.id()) Log(`id == thread1.id():`, id == thread1.id()) }) t1.join() } ``` -------------------------------- ### Python Web3 Contract Interaction (ABI Example) Source: https://www.fmz.com/syntax-guide/fun/futures Shows how to interact with a smart contract on the blockchain using the `Web3` library in Python, specifically demonstrating the use of `exchange.IO("abi", ...)` to handle contract functionalities based on its ABI. ```python # Assuming 'web3' and 'contract_address' are initialized # abi_json = "..." # JSON string of the contract's ABI # contract = web3.eth.contract(address=contract_address, abi=abi_json) # result = exchange.IO("abi", contract, "function_name", arg1, arg2) print("Example of Web3 contract interaction with ABI.") ``` -------------------------------- ### Create HTTP, TCP, and WebSocket Services with __Serve (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/global/__serve Demonstrates how to use the __Serve function in JavaScript to create an HTTP server supporting WebSocket upgrades, and a TCP server. The HTTP server handles different paths for basic responses, ticker data, and WebSocket connections. The example also shows how to test these services using HttpQuery and Dial. ```javascript function main() { let httpServer = __Serve("http://:8088?gzip=true", function (ctx) { Log("http connect from: ", ctx.remoteAddr(), "->", ctx.localAddr()) let path = ctx.path() if (path == "/") { ctx.write(JSON.stringify({ path: ctx.path(), method: ctx.method(), headers: ctx.headers(), cookie: ctx.header("Cookie"), remote: ctx.remoteAddr(), query: ctx.rawQuery() })) } else if (path == "/tickers") { let ret = exchange.GetTickers() if (!ret) { ctx.setStatus(500) ctx.write(GetLastError()) } else { ctx.write(JSON.stringify(ret)) } } else if (path == "/wss") { if (ctx.upgrade("websocket")) { // upgrade to websocket while (true) { let r = ctx.read(10) if (r == "") { break } else if (r) { if (r == "ticker") { ctx.write(JSON.stringify(exchange.GetTicker())) } else { ctx.write("not support") } } } Log("websocket closed", ctx.remoteAddr()) } } else { ctx.setStatus(404) } }) let echoServer = __Serve("tcp://:8089", function (ctx) { Log("tcp connect from: ", ctx.remoteAddr(), "->", ctx.localAddr()) while (true) { let d = ctx.read() if (!d) { break } ctx.write(d) } Log("connect closed") }) Log("http serve on", httpServer, "tcp serve on", echoServer) for (var i = 0; i < 5; i++) { if (i == 2) { // test Http var retHttp = HttpQuery("http://127.0.0.1:8088?num=123&limit=100", {"debug": true}) Log("retHttp:", retHttp) } else if (i == 3) { // test TCP var tcpConn = Dial("tcp://127.0.0.1:8089") tcpConn.write("Hello TCP Server") var retTCP = tcpConn.read() Log("retTCP:", retTCP) } else if (i == 4) { // test Websocket var wsConn = Dial("ws://127.0.0.1:8088/wss|compress=gzip") wsConn.write("ticker") var retWS = wsConn.read(1000) Log("retWS:", retWS) // no depth wsConn.write("depth") retWS = wsConn.read(1000) Log("retWS:", retWS) } Sleep(1000) } } __ ``` -------------------------------- ### Get Current Thread Object and ID (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/threads/threading/currentthread The currentThread() function retrieves the current thread object. This example shows how to use it to log the ID of the current thread. It requires the 'threading' module. ```javascript function test() { Log("当前线程的Id:", threading.currentThread().id()) } function main() { var t1 = threading.Thread(test) t1.join() } ``` -------------------------------- ### OS Module: Creating a Directory Source: https://www.fmz.com/syntax-guide/fun/log/chart Demonstrates creating a new directory using os.mkdir. This function takes the path of the directory to be created as an argument. ```javascript os.mkdir("/path/to/new_directory"); Log("Directory created."); ``` -------------------------------- ### Trade Execution - Placing Orders Source: https://www.fmz.com/syntax-guide/fun/os/file/getline Illustrates how to place buy and sell orders using the exchange object's trade functions. It covers basic order placement and setting precision for trades. ```javascript exchange.SetPrecision(2, 4); // Set precision for price and amount var buyResult = exchange.Buy(symbol, amount, price); Log("Buy Order Result:", buyResult); var sellResult = exchange.Sell(symbol, amount, price); Log("Sell Order Result:", sellResult); ``` -------------------------------- ### FMZ exchange.IO: Simple API Get Request (JavaScript, Python, C++) Source: https://www.fmz.com/syntax-guide/fun This example demonstrates a straightforward API GET request using exchange.IO() without the 'raw' parameter. It fetches pending orders for the SPOT instrument type from the OKX API. This method is suitable for simple data retrieval from exchange endpoints. ```javascript function main(){ var ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT") Log(ret) } __ ``` ```python def main(): ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT") Log(ret) __ ``` ```cpp void main() { auto ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT"); Log(ret); } __ ``` -------------------------------- ### FMZ NetSettings Proxy Configuration Source: https://www.fmz.com/syntax-guide/fun/os/os/mkdir Demonstrates setting a proxy server for network requests using exchange.SetProxy(). ```javascript exchange.SetProxy("http://proxy.example.com:8080"); Log("Proxy set."); ``` -------------------------------- ### JavaScript: Global Built-in Functions Source: https://www.fmz.com/syntax-guide/fun/web3/exchange.ioabi-... Provides examples of various global built-in functions available in FMZ JavaScript, such as Sleep for pausing execution, GetPid for retrieving the process ID, and UnixNano for getting nanosecond timestamps. ```javascript // Pause execution for 1 second Sleep(1000); // Get the current process ID let pid = GetPid(); console.log("Process ID:", pid); // Get current time in nanoseconds let nanoTime = UnixNano(); console.log("Nanosecond Timestamp:", nanoTime); ``` -------------------------------- ### FMZ __Serve: Create HTTP, TCP, WebSocket Servers (JavaScript) Source: https://www.fmz.com/syntax-guide/fun This JavaScript example demonstrates how to use the __Serve function to create an HTTP server that handles various requests including root path, tickers, and WebSocket upgrades. It also sets up a TCP echo server and shows how to test these services using HttpQuery, Dial for TCP, and Dial for WebSocket connections. The server URI specifies the protocol, host, and port, with options like gzip compression. ```javascript function main() { let httpServer = __Serve("http://:8088?gzip=true", function (ctx) { Log("http connect from: ", ctx.remoteAddr(), ">", ctx.localAddr()) let path = ctx.path() if (path == "/") { ctx.write(JSON.stringify({ path: ctx.path(), method: ctx.method(), headers: ctx.headers(), cookie: ctx.header("Cookie"), remote: ctx.remoteAddr(), query: ctx.rawQuery() })) } else if (path == "/tickers") { let ret = exchange.GetTickers() if (!ret) { ctx.setStatus(500) ctx.write(GetLastError()) } else { ctx.write(JSON.stringify(ret)) } } else if (path == "/wss") { if (ctx.upgrade("websocket")) { // upgrade to websocket while (true) { let r = ctx.read(10) if (r == "") { break } else if (r) { if (r == "ticker") { ctx.write(JSON.stringify(exchange.GetTicker())) } else { ctx.write("not support") } } } Log("websocket closed", ctx.remoteAddr()) } } else { ctx.setStatus(404) } }) let echoServer = __Serve("tcp://:8089", function (ctx) { Log("tcp connect from: ", ctx.remoteAddr(), ">", ctx.localAddr()) while (true) { let d = ctx.read() if (!d) { break } ctx.write(d) } Log("connect closed") }) Log("http serve on", httpServer, "tcp serve on", echoServer) for (var i = 0; i < 5; i++) { if (i == 2) { // test Http var retHttp = HttpQuery("http://127.0.0.1:8088?num=123&limit=100", {"debug": true}) Log("retHttp:", retHttp) } else if (i == 3) { // test TCP var tcpConn = Dial("tcp://127.0.0.1:8089") tcpConn.write("Hello TCP Server") var retTCP = tcpConn.read() Log("retTCP:", retTCP) } else if (i == 4) { // test Websocket var wsConn = Dial("ws://127.0.0.1:8088/wss|compress=gzip") wsConn.write("ticker") var retWS = wsConn.read(1000) Log("retWS:", retWS) // no depth wsConn.write("depth") retWS = wsConn.read(1000) Log("retWS:", retWS) } Sleep(1000) } } __ ``` -------------------------------- ### GetLastError: Get Last Error Message (JS, Python, C++) Source: https://www.fmz.com/syntax-guide/fun/global GetLastError retrieves the most recent error message. It is important to note that this function does not work in the backtesting system. Examples are provided for JavaScript, Python, and C++. ```javascript function main(){ // 因为不存在编号为123的订单,所以会产生错误 exchange.GetOrder("123") var error = GetLastError() Log(error) } ``` ```python def main(): exchange.GetOrder("123") error = GetLastError() Log(error) ``` ```cpp void main() { // 订单ID类型:TId,因此不能传入字符串,我们下一个不符合交易所规范的订单来触发错误 exchange.GetOrder(exchange.Buy(1, 1)); auto error = GetLastError(); Log(error); } ``` -------------------------------- ### Using NATS, MQTT, AMQP, and Kafka Communication Protocols (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/global/dial Demonstrates connecting to and using NATS, MQTT, AMQP, and Kafka communication protocols within FMZ strategies. Requires pre-configured proxy servers for each protocol. The example shows both writing and reading data for each protocol. ```javascript // 需要先配置、部署完成各个协议的代理服务器 // 为了便于演示,主题test_topic的订阅(read操作)、发布(write操作)都在当前这个策略中进行 var arrConn = [] var arrName = [] function main() { LogReset(1) conn_nats = Dial("nats://admin@127.0.0.1:4222?topic=test_topic") conn_mqtt = Dial("mqtt://127.0.0.1:1883?topic=test_topic") conn_amqp = Dial("amqp://q:admin@127.0.0.1:5672/?queue=test_Queue") conn_kafka = Dial("kafka://localhost:9092/test_topic") arrConn = [conn_nats, conn_amqp, conn_mqtt, conn_kafka] arrName = ["nats", "amqp", "mqtt", "kafka"] while (true) { for (var i in arrConn) { var conn = arrConn[i] var name = arrName[i] // 写数据 conn.write(name + ", time: " + _D() + ", test msg.") // 读数据 var readMsg = conn.read(1000) Log(name + " readMsg: ", readMsg, "#FF0000") } Sleep(1000) } } function onexit() { for (var i in arrConn) { arrConn[i].close() Log("关闭", arrName[i], "连接") } } ``` -------------------------------- ### Get Specific Funding Rate Data by Symbol (FMZ) Source: https://www.fmz.com/syntax-guide/fun/futures This example demonstrates how to use exchange.GetFundings(symbol) to retrieve funding rate data for a specific trading pair. The function returns an array of Funding structures on success or null on failure. ```javascript exchange.GetFundings(symbol) ``` ```python exchange.GetFundings(p) ``` ```c++ exchange.GetFundings(p) ``` -------------------------------- ### Basic Input/Output and String Formatting in FMZ Source: https://www.fmz.com/syntax-guide/fun/threads/thread/terminate Demonstrates fundamental input/output operations using file descriptors and `printf` for formatted output. Includes functions for flushing buffers and seeking within files. ```javascript var fd = 1; // Standard output printf(fd, "Value: %d\n", 123); os.flush(fd); ``` -------------------------------- ### FMZ Threading Module: Basic Thread Management Source: https://www.fmz.com/syntax-guide/fun/web3/exchange Illustrates the creation and management of threads using the threading module. This includes starting new threads, getting the main thread, current thread, and terminating threads. ```javascript // Function to be executed in a thread function threadTask(id) { console.log('Thread', id, 'started.'); Sleep(1000); console.log('Thread', id, 'finished.'); } // Create and start a new thread var t1 = threading.Thread(threadTask, 1); console.log('Thread 1 created.'); // Get main thread and current thread console.log('Main Thread:', threading.mainThread()); console.log('Current Thread:', threading.currentThread()); // Wait for thread to finish (optional) t1.join(); // Terminate a thread (use with caution) // t1.terminate(); ``` -------------------------------- ### Get Thread ID with id() in JavaScript Source: https://www.fmz.com/syntax-guide/fun/threads/thread/id The id() function retrieves the threadId of a multithreaded object. This example creates a new thread, assigns some data to it, and then logs the thread's ID using t1.id(). The thread is then joined to ensure proper execution. ```javascript function main() { var t1 = threading.Thread(function() { threading.currentThread().setData("data", 100) }) Log(`t1.id():`, t1.id()) t1.join() } ``` -------------------------------- ### FMZ Built-in Global Functions (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/global/getlasterror Provides examples of using various global utility functions available in the FMZ environment. This includes functions for sleeping, getting process information, error handling, and generating unique IDs. ```javascript Sleep(1000); var pid = GetPid(); var uuid = UUID(); var error = GetLastError(); ``` -------------------------------- ### File System Operations in FMZ (OS Library) Source: https://www.fmz.com/syntax-guide/fun/log/enablelog Provides examples of basic file system operations such as reading directories, checking file existence, creating directories, and file manipulation. ```javascript os.listFiles("/data") os.exists("config.json") os.mkdir("new_dir") os.remove("old_file.txt") ``` -------------------------------- ### FMZ: Exchange API - Tickers and Depth Source: https://www.fmz.com/syntax-guide/fun/os/file/write Provides examples of fetching market data from an exchange using the FMZ exchange API. This includes getting ticker information and order book depth. These functions are crucial for real-time trading analysis. ```javascript // Get ticker information for a specific market var ticker = exchange.GetTicker(); // Get the order book depth for a specific market var depth = exchange.GetDepth(); ``` -------------------------------- ### FMZ Technical Analysis Indicator Calculation (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/global/json Calculates various technical analysis indicators using the `TA` module. This example shows how to get the Moving Average Convergence Divergence (MACD) values. It requires historical price data. ```javascript var kLine = exchange.GetRecords("BTC_USDT", "1h"); var macd = TA.MACD(kLine, "close", 12, 26, 9); if (macd) { Log("MACD Diff:", macd.diff[macd.diff.length - 1]); Log("MACD Signal:", macd.signal[macd.signal.length - 1]); Log("MACD Hist:", macd.macd[macd.macd.length - 1]); } ``` -------------------------------- ### Logging and Error Handling in FMZ Source: https://www.fmz.com/syntax-guide/fun/web3/exchange.ioencodepacked-... Provides examples of logging information, errors, and profit-related data within the FMZ environment. It also shows how to enable logging and reset log files. ```javascript Log("This is an informational message."); console.error("This is an error message."); LogProfit(100); LogProfitReset(); EnableLog(); LogReset(); ``` -------------------------------- ### FMZ NetSettings Base Configuration Source: https://www.fmz.com/syntax-guide/fun/os/os/mkdir Shows how to set the base currency for network settings using exchange.SetBase(). ```javascript exchange.SetBase("BTC"); Log("Base currency set."); ``` -------------------------------- ### FMZ Exchange Market Data Functions (JavaScript) Source: https://www.fmz.com/syntax-guide/fun/global/isvirtual Provides examples of how to retrieve market data from exchanges using the `exchange` object in JavaScript. This includes getting ticker information, order book depth, trade history, and historical K-line data. ```javascript // Get ticker information let ticker = exchange.GetTicker(); console.log("Ticker:", ticker); // Get order book depth let depth = exchange.GetDepth(); console.log("Depth:", depth); // Get recent trades let trades = exchange.GetTrades(); console.log("Trades:", trades); // Get historical K-line data (e.g., 1-hour period) let records = exchange.GetRecords(null, "1h"); console.log("K-line Records:", records); ``` -------------------------------- ### Get Funding Rate Data (Python) Source: https://www.fmz.com/syntax-guide/fun/futures/exchange This Python function illustrates the use of exchange.GetFundings() to fetch funding rate data. It mirrors the JavaScript example by calling GetTicker for multiple symbols and then retrieving funding rates, both with and without a specified symbol. The output is then logged. ```python '''backtest start: 2024-10-01 00:00:00 end: 2024-10-23 00:05:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDC"}] ''' import json def main(): # LPT_USDT.swap 4小时周期 symbols = ["SOL_USDT.swap", "ETH_USDT.swap", "LTC_USDT.swap", "SOL_USDC.swap", "ETH_USDC.swap", "BTC_USD.swap", "BTC_USDT.quarter", "LPT_USDT.swap"] for symbol in symbols: exchange.GetTicker(symbol) arr = [] arrParams = ["no param", "LTC_USDT.swap", "USDT.swap", "USD.swap", "USDC.swap", "USDT.futures", "BTC_USDT.quarter"] for p in arrParams: if p == "no param": arr.append(exchange.GetFundings()) else: arr.append(exchange.GetFundings(p)) tbls = [] index = 0 for fundings in arr: tbl = { "type": "table", "title": arrParams[index], "cols": ["Symbol", "Interval", "Time", "Rate"], "rows": [], } for f in fundings: tbl["rows"].append([f["Symbol"], f["Interval"] / 3600000, _D(f["Time"]), str(f["Rate"] * 100) + " %"]) tbls.append(tbl) index += 1 LogStatus(_D(), "\n 已经请求过的行情品种:", symbols, "\n`" + json.dumps(tbls) + "`") __ ``` -------------------------------- ### Talib Technical Indicators Example Source: https://www.fmz.com/syntax-guide/fun/global/httpquery Showcases the integration and usage of a wide range of technical analysis indicators from the Talib library. This includes candlestick patterns, trend indicators, oscillators, and more. You need to ensure Talib is correctly installed and accessible within the FMZ environment. ```javascript // Assuming 'closePrices', 'openPrices', 'highPrices', 'lowPrices' are arrays of price data // Candlestick Pattern: Doji const doji = talib.CDLDOJI(openPrices, highPrices, lowPrices, closePrices); Log("Doji Pattern:", doji); // Candlestick Pattern: Engulfing const engulfing = talib.CDLENGULFING(openPrices, highPrices, lowPrices, closePrices); Log("Engulfing Pattern:", engulfing); // Trend Indicator: Moving Average Exponential const ema = talib.EMA(closePrices, 10); Log("EMA (10 periods):", ema); // Oscillator: Relative Strength Index const rsi = talib.RSI(closePrices, 14); Log("RSI (14 periods):", rsi); // Momentum Indicator: Moving Average Convergence Divergence const macd = talib.MACD(closePrices, 12, 26, 9); Log("MACD:", macd); // Volatility Indicator: Average True Range const natr = talib.NATR(highPrices, lowPrices, closePrices, 14); Log("NATR (14 periods):", natr); ``` -------------------------------- ### Order Execution with FMZ Exchange API Source: https://www.fmz.com/syntax-guide/fun/global/__serve Illustrates how to place buy and sell orders, create new orders, cancel existing orders, and retrieve order information using the `exchange` object's trade methods. Precision and rate settings are also shown. ```javascript exchange.SetPrecision(8, 8); var buyOrder = exchange.Buy("BTC_USD", 10000, 0.1); var sellOrder = exchange.Sell("BTC_USD", 10000, 0.1); var orderInfo = exchange.GetOrder(buyOrder.id); exchange.CancelOrder(buyOrder.id); ``` -------------------------------- ### Operating System File Operations in FMZ Source: https://www.fmz.com/syntax-guide/fun/global/__serve Provides examples of interacting with the operating system's file system using FMZ's `os` and `File` objects. This includes reading/writing files, checking existence, creating/removing directories, and getting file statistics. ```javascript var files = os.listFiles("."); var f = os.open("data.txt", "w"); f.write("hello"); f.close(); var exists = os.exists("data.txt"); os.mkdir("new_dir"); ``` -------------------------------- ### FMZ Exchange Order Placement (Buy/Sell) Source: https://www.fmz.com/syntax-guide/fun/log/logprofitreset Provides examples of placing buy and sell orders on an exchange using the exchange object. Requires parameters like symbol, price, and amount. ```javascript exchange.Buy(symbol, price, amount); exchange.Sell(symbol, price, amount); ``` -------------------------------- ### FMZ OS Module: Creating and Removing Directories Source: https://www.fmz.com/syntax-guide/fun/os/os/remove Demonstrates creating a directory with `os.mkdir()` and removing an empty directory with `os.rmdir()`. These are fundamental file system operations. ```javascript var newDir = "/path/to/new_directory"; os.mkdir(newDir); Log("Directory created."); // To remove: os.rmdir(newDir); ``` -------------------------------- ### Get Thread Name with name() in JavaScript Source: https://www.fmz.com/syntax-guide/fun/threads/thread/name This example demonstrates how to create a new thread using threading.Thread and then retrieve its name using the name() function. The thread is set up to perform a simple data operation, and its name is logged to the console. The name() function returns a string identifier for the thread. ```javascript function main() { var t1 = threading.Thread(function() { threading.currentThread().setData("data", 100) }) Log(`t1.name():`, t1.name()) // t1.name(): Thread-1 t1.join() } ``` -------------------------------- ### Network Settings Configuration (FMZ Exchange API) Source: https://www.fmz.com/syntax-guide/fun/threads/thread/peekmessage Examples for configuring network-related settings like base currency, proxy, and timeouts using the FMZ exchange API. ```javascript // Set the base currency exchange.SetBase("USD"); // Set a proxy server exchange.SetProxy("http://proxy.example.com:8080"); // Set the request timeout in milliseconds exchange.SetTimeout(5000); ``` -------------------------------- ### FMZ OS Create Directory Source: https://www.fmz.com/syntax-guide/fun/global/md5 Shows how to create a new directory using `os.mkdir`. This function is useful for organizing files and managing the file system structure. ```javascript var newDirPath = '/path/to/new/directory'; if (os.mkdir(newDirPath)) { console.log('Directory created successfully.'); } else { console.log('Failed to create directory.'); } ``` -------------------------------- ### Backtest: Get All Market Data After Invoking Market Functions Source: https://www.fmz.com/syntax-guide/fun/market This example demonstrates how exchange.GetMarkets() behaves within a backtesting environment. Initially, it might only return data for the default trading pair. However, after calling other market data functions like GetTicker(), subsequent calls to GetMarkets() will return data for all requested symbols. ```javascript /*backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] var tbl1 = { type: "table", title: "markets1", cols: ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], rows: [] } var markets1 = exchange.GetMarkets() for (var key in markets1) { var market = markets1[key] tbl1.rows.push([key, market.Symbol, market.BaseAsset, market.QuoteAsset, market.TickSize, market.AmountSize, market.PricePrecision, market.AmountPrecision, market.MinQty, market.MaxQty, market.MinNotional, market.MaxNotional, market.CtVal]) } for (var symbol of arrSymbol) { exchange.GetTicker(symbol) } var tbl2 = { type: "table", title: "markets2", cols: ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], rows: [] } var markets2 = exchange.GetMarkets() for (var key in markets2) { var market = markets2[key] tbl2.rows.push([key, market.Symbol, market.BaseAsset, market.QuoteAsset, market.TickSize, market.AmountSize, market.PricePrecision, market.AmountPrecision, market.MinQty, market.MaxQty, market.MinNotional, market.MaxNotional, market.CtVal]) } LogStatus("`" + JSON.stringify([tbl1, tbl2]) + "`") } ``` ```python '''backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] tbl1 = { "type": "table", "title": "markets1", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] } markets1 = exchange.GetMarkets() for key in markets1: market = markets1[key] tbl1["rows"].append([key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]]) for symbol in arrSymbol: exchange.GetTicker(symbol) tbl2 = { "type": "table", "title": "markets2", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] } markets2 = exchange.GetMarkets() for key in markets2: market = markets2[key] tbl2["rows"].append([key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]]) LogStatus("`" + json.dumps([tbl1, tbl2]) + "`") ``` ```c++ /*backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"}; json tbl1 = R"({ "type": "table", "title": "markets1", ```