The resource loading... loading...

exchange.Go

Multi-threaded asynchronous support functions can turn the operations of all supported functions into asynchronous concurrent execution.

The exchange.Go() function returns a concurrent object immediately, and you can use the wait() method of that concurrent object to get the result of the concurrent request. object

exchange.Go(method) exchange.Go(method, …args)

The method parameter is used to specify the name of the concurrent function. Note that the parameter is a function name string, not a function reference. method true string Parameters to concurrently executing functions, there may be more than one parameter arg. The type and number of parameter arg depends on the parameters of the concurrent execution function. arg false string, number, bool, object, array, function, null, and all other types supported by the system

function main(){
    // The following four operations are concurrently executed asynchronously by multiple threads and do not take time and return immediately
    var a = exchange.Go("GetTicker")
    var b = exchange.Go("GetDepth") 
    var c = exchange.Go("Buy", 1000, 0.1)
    var d = exchange.Go("GetRecords", PERIOD_H1)
           
    // Call the wait method to wait for the return of the ticker results asynchronously 
    var ticker = a.wait()            
    // Returns the depth, or null if it fails 
    var depth = b.wait()             
    // return order number, limited to 1 second timeout, if timeout, returns undefined, the object can continue to call wait if the last wait timeout 
    var orderId = c.wait(1000)
    if(typeof(orderId) == "undefined") {
        // Timeout, reacquire
        orderId = c.wait()
    }
    var records = d.wait()
}
def main():
    a = exchange.Go("GetTicker")
    b = exchange.Go("GetDepth")
    c = exchange.Go("Buy", 1000, 0.1)
    d = exchange.Go("GetRecords", PERIOD_H1)            

    ticker, ok = a.wait()
    depth, ok = b.wait()
    orderId, ok = c.wait(1000)
    if ok == False:
        orderId, ok = c.wait()
    records, ok = d.wait()
void main() {
    auto a = exchange.Go("GetTicker");
    auto b = exchange.Go("GetDepth");
    auto c = exchange.Go("Buy", 1000, 0.1);
    auto d = exchange.Go("GetRecords", PERIOD_H1);            

    Ticker ticker;
    Depth depth;
    Records records;
    TId orderId;
    a.wait(ticker);
    b.wait(depth);
    if(!c.wait(orderId, 300)) {
        c.wait(orderId);
    }
    d.wait(records);
}

Exchange.Go() function usage example, to determine undefined to use typeof(xx) === "undefined", because null == undefined is valid in JavaScript.

function main() {
    var d = exchange.Go("GetRecords", PERIOD_H1)
    // Waiting for K-line results
    var records = d.wait()
    // Here waits an asynchronous operation that has been waited and finished, it will return null, and log the error message
    var ret = d.wait()
}
def main():
    d = exchange.Go("GetRecords", PERIOD_H1)
    records, ok = d.wait()
    ret, ok = d.wait()
void main() {
    auto d = exchange.Go("GetRecords", PERIOD_H1);
    Records records;
    d.wait(records);
    Records ret;
    d.wait(ret);
}

Calling the wait() method on a concurrent object that has been released will report an error:

function main() {
    while(true) {
        var beginTS = new Date().getTime()
        var arrRoutine = []
        var arrTicker = []
        var arrName = []
        for(var i = 0; i < exchanges.length; i++) {
            arrRoutine.push(exchanges[i].Go("GetTicker"))
            arrName.push(exchanges[i].GetName())
        }            

        for(var i = 0; i < arrRoutine.length; i++) {
            arrTicker.push(arrRoutine[i].wait())
        }
        var endTS = new Date().getTime()            

        var tbl = {
            type: "table", 
            title: "ticker", 
            cols: ["index", "name", "latest-deal-price"], 
            rows: []
        }
        
        for(var i = 0; i < arrTicker.length; i++) {
            tbl.rows.push([i, arrName[i], arrTicker[i].Last])
        }            

        LogStatus(_D(), "Total time taken to obtain tickers from multiple exchanges concurrently:", endTS - beginTS, "millisecond", "\n", "`" + JSON.stringify(tbl) + "`")
        Sleep(500)
    }
}
import time 
import json
def main():
    while True:
        beginTS = time.time()
        arrRoutine = []
        arrTicker = []
        arrName = []
        for i in range(len(exchanges)):
            arrRoutine.append(exchanges[i].Go("GetTicker"))
            arrName.append(exchanges[i].GetName())            

        for i in range(len(exchanges)):
            ticker, ok = arrRoutine[i].wait()
            arrTicker.append(ticker)            

        endTS = time.time()
        tbl = {
            "type": "table", 
            "title": "ticker", 
            "cols": ["index", "name", "latest-deal-price"], 
            "rows": [] 
        }            

        for i in range(len(arrTicker)):
            tbl["rows"].append([i, arrName[i], arrTicker[i]["Last"]])            

        LogStatus(_D(), "Total time taken to obtain tickers from multiple exchanges concurrently:", endTS - beginTS, "second", "\n", "`" + json.dumps(tbl) + "`")
        Sleep(500)
void main() {
    while(true) {
        int length = exchanges.size();
        auto beginTS = UnixNano() / 1000000;
        Ticker arrTicker[length] = {};
        string arrName[length] = {};
        
        // Note that to add several exchange objects, several exchanges[n].Go functions have to be executed here, this example is to add four exchange objects, the details can be modified
        auto r0 = exchanges[0].Go("GetTicker");
        auto r1 = exchanges[1].Go("GetTicker");
        auto r2 = exchanges[2].Go("GetTicker");
        auto r3 = exchanges[3].Go("GetTicker");
        GoObj *arrRoutine[length] = {&r0, &r1, &r2, &r3};
        
        for(int i = 0; i < length; i++) {
            arrName[i] = exchanges[i].GetName();
        }            

        for(int i = 0; i < length; i++) {
            Ticker ticker;
            arrRoutine[i]->wait(ticker);
            arrTicker[i] = ticker;
        }        
        auto endTS = UnixNano() / 1000000;            

        json tbl = R"({
            "type": "table", 
            "title": "ticker", 
            "cols": ["index", "name", "latest-deal-price"], 
            "rows": [] 
        })"_json;            

        for(int i = 0; i < length; i++) {
            json arr = R"(["", "", ""])"_json;
            arr[0] = format("%d", i);
            arr[1] = arrName[i];
            arr[2] = format("%f", arrTicker[i].Last);
            tbl["rows"].push_back(arr);
        }            

        LogStatus(_D(), "Total time taken to obtain tickers from multiple exchanges concurrently:", format("%d", endTS - beginTS), "millisecond", "\n", "`" + tbl.dump() + "`");
        Sleep(500);
    }
}

Concurrent access to multiple exchange tickers:

function main() {
    /*  
        Testing with OKX futures order interface
        POST /api/v5/trade/order        
    */
    
    var beginTS = new Date().getTime()
    var param = {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}
    var ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param))
    var ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param))
    var ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param))
    
    var id1 = ret1.wait()
    var id2 = ret2.wait()
    var id3 = ret3.wait()
    var endTS = new Date().getTime()                

    Log("id1:", id1)
    Log("id2:", id2)
    Log("id3:", id3)
    Log("Concurrent order placement time consumption:", endTS - beginTS, "millisecond")
}
import time
import json
def main():
    beginTS = time.time()
    param = {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}
    ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param))
    ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param))
    ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param))            

    id1, ok1 = ret1.wait()
    id2, ok2 = ret2.wait()
    id3, ok3 = ret3.wait()
    endTS = time.time()            

    Log("id1:", id1)
    Log("id2:", id2)
    Log("id3:", id3)
    Log("Concurrent order placement time consumption:", endTS - beginTS, "second")
void main() {
    auto beginTS = UnixNano() / 1000000;
    json param = R"({"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"})"_json;
    auto ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump());
    auto ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump());
    auto ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump());            

    json id1 = R"({})"_json;
    json id2 = R"({})"_json;
    json id3 = R"({})"_json;            

    ret1.wait(id1);
    ret2.wait(id2);
    ret3.wait(id3);
    auto endTS = UnixNano() / 1000000;            

    Log("id1:", id1);
    Log("id2:", id2);
    Log("id3:", id3);
    Log("Concurrent order placement time consumption:", endTS - beginTS, "millisecond");
}

Concurrent calls for exchange.IO("api", ...) function:

This function only creates multi-threaded execution tasks when running in real trading, backtesting does not support multi-threaded concurrent task execution (backtesting is available, but still executed sequentially). After the exchange.Go() function returns an object, its wait() function is called through that object to get the data returned by the thread. The wait() function must be called to get the data before the thread will be released automatically. If the timeout parameter of the wait() function is specified, the thread will not be released automatically even if a timeout occurs. The result of the thread must be obtained before it will be released automatically (regardless of the success or failure of the interface call for concurrent access). In simple terms, the requested thread must be obtained by the wait() function regardless of whether the execution succeeds or fails, and the resource of the thread requested by the exchange.Go() function must be released automatically by the docker. The wait() method supports a timeout parameter: Without a timeout parameter, that is, wait(), or with a timeout parameter of 0, that is, wait(0). The wait() function blocks and waits until the concurrent thread has finished running, returning the result of the concurrent thread’s execution. Set the timeout parameter -1, i.e. wait(-1). The wait() function returns immediately, with different return values for different programming languages, see this subsection for an example call. Set the specific timeout parameter, wait(300), and the wait() function will wait a maximum of 300 milliseconds before returning.

If the return result of the final wait() function is not obtained, the thread resources will not be released automatically, which will lead to the accumulation of threads requested, and more than 2000 will report an error: "too many routine wait, max is 2000". Supported functions: GetTicker, GetDepth, GetTrades, GetRecords, GetAccount, GetOrders, GetOrder, CancelOrder, Buy, Sell, GetPositions, IO. All these functions are executed based on the current {@var/EXCHANGE exchange} exchange object when called concurrently. The difference between Python language and JavaScript language is that the wait() function of concurrent objects in Python language returns two parameters. The first parameter is the result returned by an asynchronous API call, and the second parameter indicates whether the asynchronous call is completed.


def main():
    d = exchange.Go("GetRecords", PERIOD_D1)
    # ok will return True definitely, unless the strategy is stopped
    ret, ok = d.wait()          
    # If the wait times out, or if it waits for an instance that has already ended, ok returns False
    ret, ok = d.wait(100)  

{@fun/Global/Mail_Go Mail_Go}, {@fun/Global/HttpQuery_Go HttpQuery_Go}, {@fun/Global/EventLoop EventLoop}

exchange.Encode Account