Fungsi sokongan asynchronous pelbagai benang boleh mengubah operasi semua fungsi yang disokong menjadi pelaksanaan serentak asynchronous.
Peraturanexchange.Go()
fungsi mengembalikan objek serentak dengan serta-merta, dan anda boleh menggunakanwait()
kaedah objek serentak itu untuk mendapatkan hasil permintaan serentak.
objek
pertukaran.Go (cara) pertukaran.Go ((metode,... args)
Peraturanmethod
parameter digunakan untuk menentukan nama fungsi serentak. Perhatikan bahawa parameter adalah rentetan nama fungsi, bukan rujukan fungsi.
kaedah
betul
senar
Parameter untukmelaksanakan fungsi secara serentak, mungkin terdapat lebih daripada satu parameterarg
. Jenis dan nombor parameterarg
bergantung kepada parameterfungsi pelaksanaan serentak.
arg
palsu
string, nombor, bool, objek, array, fungsi, null, dan semua jenis lain yang disokong 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 menentukanundefined
untuk digunakantypeof(xx) === "undefined"
, kerananull == undefined
adalah sah dalam 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);
}
Menghubungiwait()
kaedah pada objek serentak yang telah dilepaskan akan melaporkan ralat:
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 serentak kepada pelbagai pertukaran ticker:
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");
}
Permintaan serentak untukexchange.IO("api", ...)
fungsi:
Fungsi ini hanya mewujudkan tugas pelaksanaan berbilang benang apabila dijalankan dalam perdagangan sebenar, backtesting tidak menyokong pelaksanaan tugas serentak berbilang benang (backtesting tersedia, tetapi masih dijalankan secara berurutan).
Selepasexchange.Go()
fungsi mengembalikan objek,wait()
fungsi dipanggil melalui objek itu untuk mendapatkan data yang dikembalikan oleh benang.wait()
fungsi mesti dipanggil untuk mendapatkan data sebelum benang akan dibebaskan secara automatik.wait()
fungsi ditentukan, utas tidak akan dibebaskan secara automatik walaupun masa tamat berlaku. Hasil utas mesti diperoleh sebelum ia akan dibebaskan secara automatik (tidak kira kejayaan atau kegagalan panggilan antara muka untuk akses serentak).wait()
fungsi tanpa mengira sama ada pelaksanaan berjaya atau gagal, dan sumber benang yang diminta olehexchange.Go()
fungsi mesti dibebaskan secara automatik oleh pelabuhan.
Peraturanwait()
kaedah menyokong parameter timeout:
Tanpa parameter timeout, iaitu,wait()
, atau dengan parameter timeout 0, iaitu,wait(0)
.wait()
blok fungsi dan menunggu sehingga thread serentak selesai berjalan, mengembalikan hasil pelaksanaan thread serentak.
Tetapkan parameter waktu henti -1, iaituwait(-1)
.wait()
fungsi kembali dengan segera, dengan nilai pulangan yang berbeza untuk bahasa pengaturcaraan yang berbeza, lihat subbahagian ini untuk panggilan contoh.
Tetapkan parameter masa lapang tertentu,wait(300)
, danwait()
Fungsi akan menunggu maksimum 300 milisaat sebelum kembali.
Jika hasil pulangan akhirwait()
fungsi tidak diperolehi, sumber thread tidak akan dibebaskan secara automatik, yang akan membawa kepada pengumpulan utas yang diminta, dan lebih daripada 2000 akan melaporkan ralat:"too many routine wait, max is 2000"
.
Fungsi yang disokong:GetTicker
, GetDepth
, GetTrades
, GetRecords
, GetAccount
, GetOrders
, GetOrder
, CancelOrder
, Buy
, Sell
, GetPositions
, IO
. Semua fungsi ini dilaksanakan berdasarkan objek pertukaran semasa {@var/EXCHANGE exchange} apabila dipanggil secara serentak.
Perbezaan antara bahasa Python dan bahasa JavaScript adalah bahawawait()
fungsi objek serentak dalam bahasa Python mengembalikan dua parameter. Parameter pertama adalah hasil yang dikembalikan oleh panggilan API asynchronous, dan parameter kedua menunjukkan sama ada panggilan asynchronous 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 Akaun