Sumber daya yang dimuat... Pemuatan...

exchange.Go

Fungsi pendukung asinkron multi-threaded dapat mengubah operasi semua fungsi yang didukung menjadi eksekusi serentak asinkron.

Peraturanexchange.Go()fungsi mengembalikan objek bersamaan segera, dan Anda dapat menggunakanwait()metode dari objek bersamaan untuk mendapatkan hasil permintaan bersamaan. objek

pertukaran.Go (metode) pertukaran.Go ((metode,... args)

Peraturanmethodparameter digunakan untuk menentukan nama fungsi bersamaan. Perhatikan bahwa parameter adalah string nama fungsi, bukan referensi fungsi. metode benar string Parameter untukFungsi yang dilakukan secara bersamaan, mungkin ada lebih dari satu parameterarg. Jenis dan jumlah parameterargtergantung pada parameter darifungsi eksekusi bersamaanAku tidak tahu. arg palsu string, number, bool, object, array, function, null, dan semua tipe lain yang didukung oleh sistem

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()contoh penggunaan fungsi, untuk menentukanundefineduntuk digunakantypeof(xx) === "undefined", karenanull == undefinedadalah valid di 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);
}

Menelponwait()Metode pada objek paralel yang telah dirilis akan melaporkan kesalahan:

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);
    }
}

Akses bersamaan ke beberapa ticker pertukaran:

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");
}

Serentakexchange.IO("api", ...)Fungsi:

Fungsi ini hanya membuat tugas eksekusi multi-threaded saat berjalan dalam perdagangan nyata, backtesting tidak mendukung eksekusi tugas serentak multi-threaded (backtesting tersedia, tetapi masih dijalankan secara berurutan). Setelahexchange.Go()fungsi mengembalikan objek, nyawait()fungsi dipanggil melalui objek itu untuk mendapatkan data yang dikembalikan oleh thread.wait()fungsi harus dipanggil untuk mendapatkan data sebelum thread akan dirilis secara otomatis.wait()jika fungsi ditentukan, thread tidak akan dirilis secara otomatis bahkan jika timeout terjadi. Hasil thread harus diperoleh sebelum dirilis secara otomatis (terlepas dari keberhasilan atau kegagalan panggilan antarmuka untuk akses bersamaan).wait()fungsi terlepas dari apakah eksekusi berhasil atau gagal, dan sumber daya dari thread yang diminta olehexchange.Go()fungsi harus dilepaskan secara otomatis oleh docker. Peraturanwait()Metode ini mendukung parameter timeout: Tanpa parameter timeout, yaitu,wait(), atau dengan parameter timeout 0, yaitu,wait(0).wait()fungsi blok dan menunggu sampai thread bersamaan telah selesai berjalan, mengembalikan hasil dari thread paralels eksekusi. Atur parameter timeout -1, yaituwait(-1).wait()fungsi mengembalikan langsung, dengan nilai pengembalian yang berbeda untuk bahasa pemrograman yang berbeda, lihat subbagian ini untuk contoh panggilan. Tetapkan parameter timeout tertentu,wait(300), danwait()fungsi akan menunggu maksimal 300 milidetik sebelum kembali.

Jika hasil dari hasil akhirwait()fungsi tidak diperoleh, sumber daya thread tidak akan dirilis secara otomatis, yang akan menyebabkan akumulasi thread yang diminta, dan lebih dari 2000 akan melaporkan kesalahan:"too many routine wait, max is 2000"Aku tidak tahu. Fungsi yang didukung:GetTicker, GetDepth, GetTrades, GetRecords, GetAccount, GetOrders, GetOrder, CancelOrder, Buy, Sell, GetPositions, IO. Semua fungsi ini dijalankan berdasarkan objek pertukaran {@var/EXCHANGE exchange} saat dipanggil secara bersamaan. Perbedaan antara bahasa Python dan bahasa JavaScript adalah bahwawait()fungsi dari objek bersamaan dalam bahasa Python mengembalikan dua parameter. parameter pertama adalah hasil yang dikembalikan oleh panggilan API asinkron, dan parameter kedua menunjukkan apakah panggilan asinkron selesai.


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 Rekening