JavaScript
Supports JavaScript language with the following integrated JavaScript libraries:
Program exceptions and API business errors
In JavaScript language strategies, when program exceptions or API business errors occur, the error log will display the specific line number where the error occurred in the strategy code, facilitating strategy debugging and bug tracking.
Supports JavaScript asynchronous programming features:
-
setTimeout / clearTimeout
javascriptfunction main() { let symbol = "ETH_USDT" let delay = 10 let depth = exchange.GetDepth(symbol) let callback = function(e, id, msg) { Log(msg + ", canceling order.") e.CancelOrder(id) } let ordersLen = 3 let arrTimerId = [] for (let i = 1 ; i <= ordersLen ; i++) { let orderId = exchange.CreateOrder(symbol, "buy", depth.Bids[i * 3].Price, i * 0.1) let timerId = setTimeout(callback, delay * 1000, exchange, orderId, `Delayed ${delay} seconds`) Log("i:", i, ", timerId:", timerId) arrTimerId.push(timerId) } // clearTimeout let clearTimeoutIdx = 1 Log("clearTimeoutIdx:", clearTimeoutIdx, `, arrTimerId[clearTimeoutIdx]:`, arrTimerId[clearTimeoutIdx]) clearTimeout(arrTimerId[clearTimeoutIdx]) Sleep(60 * 1000) } -
fetch
Thefetchfunction is an asynchronous version overload of theHttpQueryfunction.Using the
awaitkeyword to handle asynchronous operations with synchronous syntax:javascriptfunction main() { let url = "https://www.okx.com/api/v5/market/books?instId=BTC-USDT" const promiseBooks = new Promise(async function(resolve, reject) { Log("Start execution") let data = await fetch(url) Log("data.ok:", data.ok, ", data.text():", data.text()) if (data.ok) { Log("Successfully retrieved data:", data) return resolve(data.text()) } else { return reject(new Error("data invalid")) } }) promiseBooks.then(function(ret) { Log("ret:", ret) }).catch(function(err) { Log("err.name:", err.name, "err.stack:", err.stack, "err.message:", err.message) }) } -
Using
Promise.allto execute multiple asynchronous network requests concurrently:javascriptasync function main() { // let symbols = ["BTC-USDT", "ETH-USDT", "LTC-USDT"] // Request waiting time: 99ms let symbols = ["BTC-USDT", "ETH-USDT", "LTC-USDT", "SOL-USDT", "BNB-USDT", "ADA-USDT"] // Request waiting time: 99ms let arr = [] let beginTs1 = new Date().getTime() for (let symbol of symbols) { let url = `https://www.okx.com/api/v5/market/books?instId=${symbol}` arr.push(fetch(url).then(function(resp) { if (resp.ok) { return {"symbol": symbol, "json": resp.json()} } else { throw "req failed" } })) } let endTs1 = new Date().getTime() let beginTs2 = new Date().getTime() const ret = await Promise.all(arr) for (let data of ret) { Log(data) } let endTs2 = new Date().getTime() Log("Request creation time:", endTs1 - beginTs1, "ms") Log("Request waiting time:", endTs2 - beginTs2, "ms") LogStatus(_D(), ret) } -
Using
Promise.raceto get the firstresolvedorrejectedresult from multiple asynchronous requests:javascriptasync function getTicker(e) { return Promise.resolve().then(function() { /* Test if (e.GetName() == "Huobi" || e.GetName() == "Binance") { Sleep(1000) } */ let ret = e.GetTicker("BTC_USDT") return {"name": e.GetName(), "ret": ret} }) } async function main() { Log("begin") let arrPromise = [] for (let e of exchanges) { arrPromise.push(getTicker(e)) } let ret = await Promise.race(arrPromise) Log(ret) } -
Using
setTimeout()function inthreading.Thread:javascriptfunction test() { Log("Test function started") // step 3. Test function started let timerId1 = setTimeout(function() { Log("Timeout callback executed after 5 seconds") // step 5. Timeout callback executed after 5 seconds }, 5000) Log("Test function completed") // step 4. Test function completed } function main() { Log("Main function started") // step 1. Main function started let t1 = threading.Thread(test) Log("Worker thread created successfully") // step 2. Worker thread created successfully t1.join() Log("Main function completed") // step 6. Main function completed } -
Example of asynchronous processing for multi-threaded concurrent
tickerdata retrieval:
Sinceexchange.GetTicker()is a synchronous blocking operation, even when wrapped in a Promise, the internal execution is still synchronous; JavaScript is single-threaded, and synchronous operations will block the event loop; callback functions in the microtask queue are still executed serially.javascriptasync function getTicker(symbol) { Log("getTicker symbol:", symbol) return Promise.resolve().then(function() { // Note the difference from fetch request data let ret = exchange.GetTicker(symbol) Log(ret) return ret }) } async function main() { let symbols = ["BTC_USDT", "ETH_USDT", "SOL_USDT"] let t1 = threading.Thread(async function(symbols, func) { let arrPromise = [] for (let symbol of symbols) { arrPromise.push(func(symbol)) } let ret = await Promise.all(arrPromise) Log("ret:", ret) }, symbols, getTicker) t1.join() }