Trade
exchange.Buy
The exchange.Buy() function is used to place a buy order. The Buy() function is a member function of the exchange object exchange. The Buy() function operates on the exchange account bound to the exchange object exchange. The purpose of the member functions (methods) of the exchange object is only related to exchange, which will not be repeated in the rest of this document.
exchange.Buy(price, amount)
exchange.Buy(price, amount, ...args)Examples
-
The order number returned by
exchange.Buy()can be used to query order information and cancel orders.javascriptfunction main() { var id = exchange.Buy(100, 1); Log("id:", id); }pythondef main(): id = exchange.Buy(100, 1) Log("id:", id)rustfn main() { let id = exchange.Buy(100, 1).unwrap(); Log!("id:", id); }c++void main() { auto id = exchange.Buy(100, 1); Log("id:", id); } -
When placing an order for a cryptocurrency futures contract, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported:
```log
direction is sell, invalid order type Buy
direction is buy, invalid order type Sell
direction is closebuy, invalid order type Buy
direction is closesell, invalid order type Sell
```
javascript// The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set the short direction exchange.SetDirection("sell") // Placing a buy order will report an error; shorting can only sell var id = exchange.Buy(50, 1) // Set the long direction exchange.SetDirection("buy") // Placing a sell order will report an error; going long can only buy var id2 = exchange.Sell(60, 1) // Set the close-long direction exchange.SetDirection("closebuy") // Placing a buy order will report an error; closing long can only sell var id3 = exchange.Buy(-1, 1) // Set the close-short direction exchange.SetDirection("closesell") // Placing a sell order will report an error; closing short can only buy var id4 = exchange.Sell(-1, 1) }python# The following are incorrect calls def main(): exchange.SetContractType("quarter") exchange.SetDirection("sell") id = exchange.Buy(50, 1) exchange.SetDirection("buy") id2 = exchange.Sell(60, 1) exchange.SetDirection("closebuy") id3 = exchange.Buy(-1, 1) exchange.SetDirection("closesell") id4 = exchange.Sell(-1, 1)rust// The following are incorrect calls fn main() { let _ = exchange.SetContractType("quarter"); // Set the short direction let _ = exchange.SetDirection("sell"); // Placing a buy order will report an error; shorting can only sell let id = exchange.Buy(50, 1); // Set the long direction let _ = exchange.SetDirection("buy"); // Placing a sell order will report an error; going long can only buy let id2 = exchange.Sell(60, 1); // Set the close-long direction let _ = exchange.SetDirection("closebuy"); // Placing a buy order will report an error; closing long can only sell let id3 = exchange.Buy(-1, 1); // Set the close-short direction let _ = exchange.SetDirection("closesell"); // Placing a sell order will report an error; closing short can only buy let id4 = exchange.Sell(-1, 1); }c++// The following are incorrect calls void main() { exchange.SetContractType("quarter"); exchange.SetDirection("sell"); auto id = exchange.Buy(50, 1); exchange.SetDirection("buy"); auto id2 = exchange.Sell(60, 1); exchange.SetDirection("closebuy"); auto id3 = exchange.Buy(-1, 1); exchange.SetDirection("closesell"); auto id4 = exchange.Sell(-1, 1); } -
Spot market order.
javascript// For example, trading pair: ETH_BTC, market order buy function main() { // Place a market order to buy, buying ETH worth 0.1 BTC (quote currency) exchange.Buy(-1, 0.1) }pythondef main(): exchange.Buy(-1, 0.1)rust// For example, trading pair: ETH_BTC, market order buy fn main() { // Place a market order to buy, buying ETH worth 0.1 BTC (quote currency) let _ = exchange.Buy(-1, 0.1); }c++void main() { exchange.Buy(-1, 0.1); }
Returns
| Type | Description |
string / null value | Returns the order Id if the order is placed successfully, and returns a null value if the order fails. The |
Arguments
| Name | Type | Required | Description |
price | number | Yes | The |
amount | number | Yes | The |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | Extension parameter used to output accompanying information to this order log. Multiple |
See Also
exchange.Sell exchange.SetContractType exchange.SetDirection exchange.IO (API rate limit control; the Buy function is affected by the CreateOrder rate limit setting)
Remarks
When placing an order for a futures contract, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported. Unless otherwise specified, the order amount on cryptocurrency futures contract exchanges is denominated in number of contracts.
When the price parameter is set to -1, it is used to place a market order. This feature requires the exchange's order placement interface to support market orders. When placing a buy order for cryptocurrency spot in the form of a market order, the order amount parameter amount is the amount denominated in the quote currency. When placing an order for a cryptocurrency futures contract in the form of a market order, the unit of the order amount parameter amount is number of contracts. In live trading, a few cryptocurrency exchanges do not support the market order interface. For a few spot exchanges, the order amount of a market buy order is the number of trading coins. For details, please refer to the Exchange Special Notes in the "User Guide".
If you are using an older version of the docker, the order Id returned by the exchange.Buy() function may differ from the return value order Id described in the current document.
It should be noted that the order placement interfaces of the following three exchanges are relatively special. For spot market buy orders, the order amount is the number of coins rather than the amount.
-
AscendEx -
BitMEX -
Bitfinex
exchange.Sell
The exchange.Sell() function is used to place a sell order.
exchange.Sell(price, amount)
exchange.Sell(price, amount, ...args)Examples
-
The order number returned by
exchange.Sell()can be used to query order information and cancel orders.javascriptfunction main(){ var id = exchange.Sell(100, 1) Log("id:", id) }pythondef main(): id = exchange.Sell(100, 1) Log("id:", id)rustfn main() { let id = exchange.Sell(100, 1).unwrap(); Log!("id:", id); }c++void main() { auto id = exchange.Sell(100, 1); Log("id:", id); } -
When placing orders for cryptocurrency futures contracts, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported:
logdirection is sell, invalid order type Buy direction is buy, invalid order type Sell direction is closebuy, invalid order type Buy direction is closesell, invalid order type Selljavascript// The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set the short direction exchange.SetDirection("sell") // Placing a buy order will report an error; shorting can only sell var id = exchange.Buy(50, 1) // Set the long direction exchange.SetDirection("buy") // Placing a sell order will report an error; going long can only buy var id2 = exchange.Sell(60, 1) // Set the close-long direction exchange.SetDirection("closebuy") // Placing a buy order will report an error; closing a long can only sell var id3 = exchange.Buy(-1, 1) // Set the close-short direction exchange.SetDirection("closesell") // Placing a sell order will report an error; closing a short can only buy var id4 = exchange.Sell(-1, 1) }python# The following are incorrect calls def main(): exchange.SetContractType("quarter") exchange.SetDirection("sell") id = exchange.Buy(50, 1) exchange.SetDirection("buy") id2 = exchange.Sell(60, 1) exchange.SetDirection("closebuy") id3 = exchange.Buy(-1, 1) exchange.SetDirection("closesell") id4 = exchange.Sell(-1, 1)rust// The following are incorrect calls fn main() { let _ = exchange.SetContractType("quarter"); // Set the short direction let _ = exchange.SetDirection("sell"); // Placing a buy order will report an error; shorting can only sell let id = exchange.Buy(50, 1); // Set the long direction let _ = exchange.SetDirection("buy"); // Placing a sell order will report an error; going long can only buy let id2 = exchange.Sell(60, 1); // Set the close-long direction let _ = exchange.SetDirection("closebuy"); // Placing a buy order will report an error; closing a long can only sell let id3 = exchange.Buy(-1, 1); // Set the close-short direction let _ = exchange.SetDirection("closesell"); // Placing a sell order will report an error; closing a short can only buy let id4 = exchange.Sell(-1, 1); }c++// The following are incorrect calls void main() { exchange.SetContractType("quarter"); exchange.SetDirection("sell"); auto id = exchange.Buy(50, 1); exchange.SetDirection("buy"); auto id2 = exchange.Sell(60, 1); exchange.SetDirection("closebuy"); auto id3 = exchange.Buy(-1, 1); exchange.SetDirection("closesell"); auto id4 = exchange.Sell(-1, 1); } -
Spot market order.
javascript// For example, trading pair: ETH_BTC, sell with a market order function main() { // Note: place a market order to sell, selling 0.2 ETH exchange.Sell(-1, 0.2) }pythondef main(): exchange.Sell(-1, 0.2)rust// For example, trading pair: ETH_BTC, sell with a market order fn main() { // Note: place a market order to sell, selling 0.2 ETH let _ = exchange.Sell(-1, 0.2); }c++void main() { exchange.Sell(-1, 0.2); }
Returns
| Type | Description |
string / null value | Returns the order Id when the order is placed successfully, and returns a null value when the order fails. The |
Arguments
| Name | Type | Required | Description |
price | number | Yes | The |
amount | number | Yes | The |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extension parameter used to output additional information attached to this order log. Multiple |
See Also
exchange.Buy exchange.SetContractType exchange.SetDirection exchange.IO (API rate limit control; the Sell function is affected by the CreateOrder rate limit setting)
Remarks
When placing orders for futures contracts, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported. For cryptocurrency futures contract exchanges, the order size is denominated in number of contracts unless otherwise specified.
When the price parameter is set to -1, it is used to place a market order, which requires the exchange's order interface to support market orders. When trading cryptocurrency spot with market orders, when placing a sell order, the order size parameter amount is denominated in the trading currency. When trading cryptocurrency futures contracts with market orders, the order size parameter amount is denominated in number of contracts. In live trading, a few cryptocurrency exchanges do not support the market order interface.
If you are using an older version of the docker, the order Id returned by the exchange.Sell() function may differ from the returned order Id described in the current documentation.
exchange.CreateOrder
exchange.CreateOrder() function is used to place orders.
exchange.CreateOrder(symbol, side, price, amount)
exchange.CreateOrder(symbol, side, price, amount, ...args)Examples
-
Both spot exchange objects and futures exchange objects place orders by calling the
exchange.CreateOrder()function.javascriptfunction main() { var id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) // Spot exchange object places an order, trading the BTC_USDT spot trading pair // var id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id) }pythondef main(): id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) # Spot exchange object places an order, trading the BTC_USDT spot trading pair # id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) # Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id)rustfn main() { let id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01); // Spot exchange object places an order, trading the BTC_USDT spot trading pair // let id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01); // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log!("Order Id:", id); }c++void main() { auto id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01); // Spot exchange object places an order, trading the BTC_USDT spot trading pair // auto id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01); // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id); } -
Place an order with additional parameters (option), used to pass exchange-specific parameters.
javascriptfunction main() { // Pass the option parameter in JSON format var option = { "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" } var sideWithOption = "buy;" + JSON.stringify(option) var id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1) Log("Order Id:", id) Sleep(2000) Log(exchange.GetOrder(id)) }pythonimport json def main(): # Pass the option parameter in JSON format option = { "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" } sideWithOption = "buy;" + json.dumps(option) id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1) Log("Order Id:", id) Sleep(2000) Log(exchange.GetOrder(id))rustfn main() { // Pass the option parameter in JSON format (Rust does not support JSON.stringify, so construct the JSON text directly using a raw string) let option = r#"{"type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1"}"#; let sideWithOption = format!("buy;{}", option); let id = exchange.CreateOrder("SOL_USDT.swap", &sideWithOption, -1, 1).unwrap(); Log!("Order Id:", id); Sleep(2000); Log!(exchange.GetOrder(&id)); }c++void main() { // Pass the option parameter in JSON format json option = R"({ "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" })"_json; string sideWithOption = "buy;" + option.dump(); auto id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1); Log("Order Id:", id); Sleep(2000); Log(exchange.GetOrder(id)); }
Returns
| Type | Description |
string / null value | Returns the order Id when the order is placed successfully, and returns a null value when the order fails. The When calling the |
Arguments
| Name | Type | Required | Description |
symbol | string | Yes | The When calling the When calling the When calling the |
side | string | Yes | The For spot exchange objects, the available values for the For futures exchange objects, the available values for the Supports additional parameters (option): You can pass additional parameters via the For example: Additional parameters are used to pass exchange-specific parameters (such as order type, time-in-force rules, etc.); the specific parameters supported depend on the exchange API. |
price | number | Yes | The |
amount | number | Yes | The |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extension parameter used to output accompanying information to the log of this order; the |
See Also
Remarks
Additional parameters (option) can be passed via the side parameter to specify exchange-specific parameters. The additional parameters must be merged into the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value&key=value" (URL-encoded format). For example: "buy;{\"type\":\"TRAILING_STOP_MARKET\"}".
The option parameters supported by different exchanges vary. The specific supported parameters are subject to the exchange's API documentation. Common parameters include: order type (type), time in force (timeInForce), activation price (activationPrice), callback rate (callbackRate), etc.
When using the option parameters, you still need to provide the price and amount parameters. If certain parameters have already been passed via option, these base parameters may be overridden by the corresponding parameters in option; the specific behavior depends on the exchange's API implementation.
exchange.CancelOrder
The exchange.CancelOrder() function is used to cancel an order. In the order Order structure of the FMZ platform, the property Id is composed of the exchange's symbol code and the exchange's original order Id, separated by an English comma. For example, for an order of the OKX exchange spot trading pair ETH_USDT, the format of its Id property is: ETH-USDT,1547130415509278720.
When calling the exchange.CancelOrder() function to cancel an order, the passed-in parameter orderId is consistent with the Id property of the order Order structure.
exchange.CancelOrder(orderId)
exchange.CancelOrder(orderId, ...args)Examples
-
Cancel an order.
javascriptfunction main(){ var id = exchange.Sell(99999, 1) exchange.CancelOrder(id) }pythondef main(): id = exchange.Sell(99999, 1) exchange.CancelOrder(id)rustfn main() { let id = exchange.Sell(99999, 1).unwrap(); let _ = exchange.CancelOrder(&id); }c++void main() { auto id = exchange.Sell(99999, 1); exchange.CancelOrder(id); } -
Among FMZ's API functions, functions that can produce log output (such as
Log(),exchange.Buy(),exchange.CancelOrder(), etc.) can all be accompanied by some output parameters after the required parameters.For example:
exchange.CancelOrder(orders[i].Id, orders[i]), that is, when canceling the order with Idorders[i].Id, additionally output the information of that order, i.e. theOrderstructureorders[i].javascriptfunction main() { if (exchange.GetName().includes("Futures_")) { Log("Set contract to: perpetual swap, set direction to: open long.") exchange.SetContractType("swap") exchange.SetDirection("buy") } var ticker = exchange.GetTicker() exchange.Buy(ticker.Last * 0.5, 0.1) var orders = exchange.GetOrders() for (var i = 0 ; i < orders.length ; i++) { exchange.CancelOrder(orders[i].Id, "Canceled order:", orders[i]) Sleep(500) } }pythondef main(): if exchange.GetName().find("Futures_") != -1: Log("Set contract to: perpetual swap, set direction to: open long.") exchange.SetContractType("swap") exchange.SetDirection("buy") ticker = exchange.GetTicker() exchange.Buy(ticker["Last"] * 0.5, 0.1) orders = exchange.GetOrders() for i in range(len(orders)): exchange.CancelOrder(orders[i]["Id"], "Canceled order:", orders[i]) Sleep(500)rustfn main() { if exchange.GetName().contains("Futures_") { Log!("Set contract to: perpetual swap, set direction to: open long."); let _ = exchange.SetContractType("swap"); let _ = exchange.SetDirection("buy"); } let ticker = exchange.GetTicker(None).unwrap(); let _ = exchange.Buy(ticker.Last * 0.5, 0.1); let orders = exchange.GetOrders(None).unwrap(); for i in 0..orders.len() { // Rust does not support appending output parameters after the required parameters of CancelOrder; after canceling the order, call the Log! macro separately to output the accompanying information let _ = exchange.CancelOrder(&orders[i].Id); Log!("Canceled order:", orders[i]); Sleep(500); } }c++void main() { if (exchange.GetName().find("Futures_") != std::string::npos) { Log("Set contract to: perpetual swap, set direction to: open long."); exchange.SetContractType("swap"); exchange.SetDirection("buy"); } auto ticker = exchange.GetTicker(); exchange.Buy(ticker.Last * 0.5, 0.1); auto orders = exchange.GetOrders(); for (int i = 0 ; i < orders.size() ; i++) { exchange.CancelOrder(orders[i].Id, "Canceled order:", orders[i]); Sleep(500); } }
Returns
| Type | Description |
bool | The |
Arguments
| Name | Type | Required | Description |
orderId | string | Yes | The parameter |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extension parameter used to output accompanying information into this order-cancellation log; multiple |
See Also
Remarks
If you are using an older version of the docker (hosting agent), the parameter orderId of the exchange.CancelOrder() function may differ from the orderId described in the current documentation.
exchange.GetOrder
The exchange.GetOrder() function is used to obtain order information.
exchange.GetOrder(orderId)Examples
javascript
function main(){
var id = exchange.Sell(1000, 1)
// The parameter id is the order number; fill in the number of the order you want to query
var order = exchange.GetOrder(id)
Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:",
order.DealAmount, "Status:", order.Status, "Type:", order.Type)
}
python
def main():
id = exchange.Sell(1000, 1)
order = exchange.GetOrder(id)
Log("Id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:",
order["DealAmount"], "Status:", order["Status"], "Type:", order["Type"])
rust
fn main() {
let id = exchange.Sell(1000, 1).unwrap();
// The parameter id is the order number; fill in the number of the order you want to query
let order = exchange.GetOrder(&id).unwrap();
Log!("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:",
order.DealAmount, "Status:", order.Status, "Type:", order.Type);
}
c++
void main() {
auto id = exchange.Sell(1000, 1);
auto order = exchange.GetOrder(id);
Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:",
order.DealAmount, "Status:", order.Status, "Type:", order.Type);
}Returns
| Type | Description |
| Queries order details based on the order Id. Returns the |
Arguments
| Name | Type | Required | Description |
orderId | string | Yes | The When calling the |
See Also
Remarks
Some exchanges do not support the exchange.GetOrder() function. The AvgPrice attribute in the return value Order structure is the average filled price; some exchanges do not support this field, and if it is not supported it will be set to 0.
If you are using an older version of the docker, the orderId parameter of the exchange.GetOrder() function may differ from the orderId described in the current documentation.
Exchanges that do not support the exchange.GetOrder() function:
| Function Name | Unsupported Spot Exchanges | Unsupported Futures Exchanges |
|---|---|---|
| GetOrder | Zaif / Coincheck / Bitstamp | -- |
exchange.GetOrders
The exchange.GetOrders() function is used to obtain the current unfilled orders.
exchange.GetOrders()
exchange.GetOrders(symbol)Examples
-
Using a spot exchange object, place buy orders for multiple different trading pairs at half of the current price as the order price, then query the information of unfilled orders.
javascript/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"] for (var symbol of arrSymbol) { var t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t.Last / 2, 0.01) } var spotOrders = exchange.GetOrders() var tbls = [] for (var orders of [spotOrders]) { var tbl = {type: "table", title: "test GetOrders", cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []} for (var order of orders) { tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) } tbls.push(tbl) } LogStatus("`" + JSON.stringify(tbls) + "`") // Print the information once and then return, to prevent orders from being filled during subsequent backtesting, which would affect data observation return }python'''backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"] for symbol in arrSymbol: t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t["Last"] / 2, 0.01) spotOrders = exchange.GetOrders() tbls = [] for orders in [spotOrders]: tbl = {"type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": []} for order in orders: tbl["rows"].append([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) tbls.append(tbl) LogStatus("`" + json.dumps(tbls) + "`") returnrust/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ fn main() { let arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"]; for symbol in arrSymbol { let t = exchange.GetTicker(symbol).unwrap(); let _ = exchange.CreateOrder(symbol, "buy", t.Last / 2.0, 0.01); } let spotOrders = exchange.GetOrders(None).unwrap(); // Rust does not support JSON.stringify, use format! to build the table's JSON text let mut tbls = Vec::new(); for orders in [&spotOrders] { let mut rows = Vec::new(); for order in orders { rows.push(format!(r#"["{}", "{}", {}, {}, {}, {}, {}, {}, {}, "{}"]"#, order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType)); } let tbl = format!(r#"{{"type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [{}]}}"#, rows.join(",")); tbls.push(tbl); } LogStatus!(format!("`[{}]`", tbls.join(","))); // Print the information once and then return, to prevent orders from being filled during subsequent backtesting, which would affect data observation return; }c++/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 0.01); } auto spotOrders = exchange.GetOrders(); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {spotOrders}; for (const auto& orders : arr) { json tbl = R"({ "type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back("Symbol"); arrJson.push_back("Id"); arrJson.push_back(order.Price); arrJson.push_back(order.Amount); arrJson.push_back(order.DealAmount); arrJson.push_back(order.AvgPrice); arrJson.push_back(order.Status); arrJson.push_back(order.Type); arrJson.push_back(order.Offset); arrJson.push_back(order.ContractType); tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); } LogStatus(_D(), "\n", "`" + tbls.dump() + "`"); return; } -
Use the futures exchange object to place orders on multiple symbols with different trading pairs and contract codes. The order prices are set far away from the counterparty price at the top of the order book, keeping the orders in an unfilled state, and then query the orders in various ways.
javascript/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] for (var symbol of arrSymbol) { var t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t.Last / 2, 1) exchange.CreateOrder(symbol, "sell", t.Last * 2, 1) } var defaultOrders = exchange.GetOrders() var swapOrders = exchange.GetOrders("USDT.swap") var futuresOrders = exchange.GetOrders("USDT.futures") var btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap") var tbls = [] var arr = [defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders] var tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"] for (var index in arr) { var orders = arr[index] var tbl = {type: "table", title: tblDesc[index], cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []} for (var order of orders) { tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) } tbls.push(tbl) } LogStatus("`" + JSON.stringify(tbls) + "`") // Print the output once and then return immediately, to prevent orders from being filled later in the backtest and affecting the data observation return }python'''backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] for symbol in arrSymbol: t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t["Last"] / 2, 1) exchange.CreateOrder(symbol, "sell", t["Last"] * 2, 1) defaultOrders = exchange.GetOrders() swapOrders = exchange.GetOrders("USDT.swap") futuresOrders = exchange.GetOrders("USDT.futures") btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap") tbls = [] arr = [defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders] tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"] for index in range(len(arr)): orders = arr[index] tbl = {"type": "table", "title": tblDesc[index], "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": []} for order in orders: tbl["rows"].append([order["Symbol"], order["Id"], order["Price"], order["Amount"], order["DealAmount"], order["AvgPrice"], order["Status"], order["Type"], order["Offset"], order["ContractType"]]) tbls.append(tbl) LogStatus("`" + json.dumps(tbls) + "`") returnrust/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ fn main() { let arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"]; for symbol in arrSymbol { let t = exchange.GetTicker(symbol).unwrap(); let _ = exchange.CreateOrder(symbol, "buy", t.Last / 2.0, 1); let _ = exchange.CreateOrder(symbol, "sell", t.Last * 2.0, 1); } let defaultOrders = exchange.GetOrders(None).unwrap(); let swapOrders = exchange.GetOrders("USDT.swap").unwrap(); let futuresOrders = exchange.GetOrders("USDT.futures").unwrap(); let btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap").unwrap(); // Rust does not support JSON.stringify, so format! is used here to assemble the JSON text of the table let mut tbls = Vec::new(); let arr = [&defaultOrders, &swapOrders, &futuresOrders, &btcUsdtSwapOrders]; let tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"]; for index in 0..arr.len() { let orders = arr[index]; let mut rows = Vec::new(); for order in orders { rows.push(format!(r#"["{}", "{}", {}, {}, {}, {}, {}, {}, {}, "{}"]"#, order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType)); } let tbl = format!(r#"{{"type": "table", "title": "{}", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [{}]}}"#, tblDesc[index], rows.join(",")); tbls.push(tbl); } LogStatus!(format!("`[{}]`", tbls.join(","))); // Print the output once and then return immediately, to prevent orders from being filled later in the backtest and affecting the data observation return; }c++/*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 1); exchange.CreateOrder(symbol, "sell", t.Last * 2, 1); } auto defaultOrders = exchange.GetOrders(); auto swapOrders = exchange.GetOrders("USDT.swap"); auto futuresOrders = exchange.GetOrders("USDT.futures"); auto btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap"); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders}; std::string tblDesc[] = {"defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"}; for (int index = 0; index < arr.size(); index++) { auto orders = arr[index]; json tbl = R"({ "type": "table", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; tbl["title"] = tblDesc[index]; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back(order.Symbol); arrJson.push_back(to_string(order.Id)); // The Id attribute in the Order struct is of type TId, so the FMZ platform's built-in C++ function to_string is used here for encoding arrJson.push_back(order.Price); arrJson.push_back(order.Amount); arrJson.push_back(order.DealAmount); arrJson.push_back(order.AvgPrice); arrJson.push_back(order.Status); arrJson.push_back(order.Type); arrJson.push_back(order.Offset); arrJson.push_back(order.ContractType); tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); } LogStatus(_D(), "\n", "`" + tbls.dump() + "`"); return; } -
When calling the
exchange.GetOrders()function, you can pass in theSymbolparameter to request order data for a specific trading pair or contract code.javascriptfunction main() { var orders = exchange.GetOrders("BTC_USDT") // Spot symbol example // var orders = exchange.GetOrders("BTC_USDT.swap") // Futures symbol example Log("orders:", orders) }pythondef main(): orders = exchange.GetOrders("BTC_USDT") # Spot symbol example # orders = exchange.GetOrders("BTC_USDT.swap") # Futures symbol example Log("orders:", orders)rustfn main() { let orders = exchange.GetOrders("BTC_USDT"); // Spot symbol example // let orders = exchange.GetOrders("BTC_USDT.swap"); // Futures symbol example Log!("orders:", orders); }c++void main() { auto orders = exchange.GetOrders("BTC_USDT"); // Spot symbol example // auto orders = exchange.GetOrders("BTC_USDT.swap"); // Futures symbol example Log("orders:", orders); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The For a spot exchange object, if the For a futures exchange object, if the |
See Also
Remarks
In the GetOrders function, the use cases of the symbol parameter are summarized as follows:
| Exchange Object Category | symbol Parameter | Query Range | Remarks |
|---|---|---|---|
| Spot | Do not pass the symbol parameter | Query all spot trading pairs | Applicable to all calling scenarios; if the exchange interface does not support it, an error is reported and a null value is returned, which will not be repeated below |
| Spot | Specify a trading instrument, with the symbol parameter as: "BTC_USDT" | Query the specified BTC_USDT trading pair | For a spot exchange object, the format of the symbol parameter is: "BTC_USDT" |
| Futures | Do not pass the symbol parameter | Query all trading instruments within the dimension range of the current trading pair and contract code | If the current trading pair is BTC_USDT and the contract code is swap, this queries all USDT-margined perpetual contracts. Equivalent to calling GetOrders("USDT.swap") |
| Futures | Specify a trading instrument, with the symbol parameter as: "BTC_USDT.swap" | Query the specified BTC USDT-margined perpetual contract | For a futures exchange object, the format of the symbol parameter is: a combination of the trading pair and contract code defined by the FMZ platform, separated by the character ".". |
| Futures | Specify a range of trading instruments, with the symbol parameter as: "USDT.swap" | Query all USDT-margined perpetual contracts | - |
| Futures exchange supporting options | Do not pass the symbol parameter | Query all option contracts within the dimension range of the current trading pair | If the current trading pair is BTC_USDT and the contract is set to an option contract, for example the Binance option contract: BTC-240108-40000-C |
| Futures exchange supporting options | Specify a specific trading instrument | Query the specified option contract | For example, for the Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C |
| Futures exchange supporting options | Specify a range of trading instruments, with the symbol parameter as: "USDT.option" | Query all USDT-margined option contracts | - |
In the GetOrders function, the query dimension ranges for a futures exchange object are summarized as follows:
| symbol Parameter | Request Range Definition | Remarks |
|---|---|---|
| USDT.swap | Range of USDT-margined perpetual contracts. | For dimensions not supported by the exchange API interface, an error is reported and a null value is returned when called. |
| USDT.futures | Range of USDT-margined delivery contracts. | - |
| USD.swap | Range of coin-margined perpetual contracts. | - |
| USD.futures | Range of coin-margined delivery contracts. | - |
| USDT.option | Range of USDT-margined option contracts. | - |
| USD.option | Range of coin-margined option contracts. | - |
| USDT.futures_combo | Range of spread combo contracts. | Futures_Deribit exchange |
| USD.futures_ff | Range of multi-collateral delivery contracts. | Futures_Kraken exchange |
| USD.swap_pf | Range of multi-collateral perpetual contracts. | Futures_Kraken exchange |
When the account represented by the exchange object exchange has no open orders (i.e., active orders in an unfilled state) within the query range or on the specified trading instrument, calling this function will return an empty array, that is: [].
The following exchanges require a symbol parameter to be passed in for the interface that queries current unfilled orders. When calling the GetOrders function on these exchanges, if the symbol parameter is not passed in, only the unfilled orders of the current instrument are requested, rather than the unfilled orders of all instruments (because the exchange interface does not support it).
Zaif, MEXC, LBank, Korbit, Coinw, BitMart, Bithumb, BitFlyer, BigONE.
Exchanges that do not support the exchange.GetOrders() function:
| Function Name | Unsupported Spot Exchanges | Unsupported Futures Exchanges |
|---|---|---|
| GetOrders | -- | Futures_Bibox |
exchange.GetHistoryOrders
exchange.GetHistoryOrders() function is used to retrieve the historical orders of the current trading pair or contract, and supports specifying a particular trading instrument.
exchange.GetHistoryOrders()
exchange.GetHistoryOrders(symbol)
exchange.GetHistoryOrders(symbol, since)
exchange.GetHistoryOrders(symbol, since, limit)
exchange.GetHistoryOrders(since)
exchange.GetHistoryOrders(since, limit)Examples
javascript
function main() {
var historyOrders = exchange.GetHistoryOrders()
Log(historyOrders)
}
python
def main():
historyOrders = exchange.GetHistoryOrders()
Log(historyOrders)
rust
fn main() {
let historyOrders = exchange.GetHistoryOrders(None, None, None);
Log!(historyOrders);
}
c++
void main() {
auto historyOrders = exchange.GetHistoryOrders();
Log(historyOrders);
}Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The If querying order data for an options contract, the |
since | number | No | The |
limit | number | No | The |
See Also
Remarks
-
When the
symbol,since, andlimitparameters are not specified, the historical orders of the current trading pair or contract are queried by default, i.e., the historical orders within a certain range closest to the current time are queried. The specific query range depends on the single-query range of the exchange's interface. -
When the
symbolparameter is specified, the historical orders of the set trading instrument are queried. -
When the
sinceparameter is specified, the query starts from thesincetimestamp and proceeds toward the current time. -
When the
limitparameter is specified, the query returns once a sufficient number of records is reached. -
This function is only supported by exchanges that provide a historical order query interface.
Exchanges that do not support the exchange.GetHistoryOrders() function:
| Function Name | Unsupported Spot Exchanges | Unsupported Futures Exchanges |
|---|---|---|
| GetHistoryOrders | Zaif / Upbit / Coincheck / Bitstamp / Bithumb / BitFlyer / BigONE | Futures_Bibox / Futures_ApolloX |
exchange.CreateConditionOrder
The exchange.CreateConditionOrder() function is used to create a conditional order. A conditional order is a type of order that is automatically executed when specific trigger conditions are met.
exchange.CreateConditionOrder(symbol, side, amount, condition)
exchange.CreateConditionOrder(symbol, side, amount, condition, ...args)Examples
-
Create a take-profit order (TP): automatically sell when the price rises to the target price.
javascriptfunction main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, // Take-profit order TpTriggerPrice: 65000, // Trigger price TpOrderPrice: 65000 // Execution price, can also be set to -1 for a market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id) }pythondef main(): # Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, # Take-profit order "TpTriggerPrice": 65000, # Trigger price "TpOrderPrice": 65000 # Execution price, can also be set to -1 for a market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id)rustfn main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, // Take-profit order TpTriggerPrice: 65000.0, // Trigger price TpOrderPrice: 65000.0, // Execution price, can also be set to -1 for a market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("TP order Id:", id); }c++void main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("TP order Id:", id); } -
Create a stop-loss order (SL): when the price drops to the stop-loss trigger price, automatically sell in the configured manner.
javascriptfunction main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price var condition = { ConditionType: ORDER_CONDITION_TYPE_SL, // Stop-loss order SlTriggerPrice: 58000, // Trigger price SlOrderPrice: -1 // -1 indicates a market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id) }pythondef main(): # Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price condition = { "ConditionType": ORDER_CONDITION_TYPE_SL, # Stop-loss order "SlTriggerPrice": 58000, # Trigger price "SlOrderPrice": -1 # -1 indicates a market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id)rustfn main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, // Stop-loss order SlTriggerPrice: 58000.0, // Trigger price SlOrderPrice: -1.0, // -1 indicates a market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("SL order Id:", id); }c++void main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = -1}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("SL order Id:", id); } -
Create an OCO order: set take-profit and stop-loss simultaneously. Once either one is triggered, the other is automatically canceled.
javascriptfunction main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 var condition = { ConditionType: ORDER_CONDITION_TYPE_OCO, // OCO order TpTriggerPrice: 65000, // Take-profit trigger price TpOrderPrice: 65000, // Take-profit execution price SlTriggerPrice: 58000, // Stop-loss trigger price SlOrderPrice: 58000 // Stop-loss execution price } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("OCO order Id:", id) }pythondef main(): # Create an OCO order: take-profit price 65000, stop-loss price 58000 condition = { "ConditionType": ORDER_CONDITION_TYPE_OCO, # OCO order "TpTriggerPrice": 65000, # Take-profit trigger price "TpOrderPrice": 65000, # Take-profit execution price "SlTriggerPrice": 58000, # Stop-loss trigger price "SlOrderPrice": 58000 # Stop-loss execution price } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("OCO order Id:", id)rustfn main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_OCO, // OCO order TpTriggerPrice: 65000.0, // Take-profit trigger price TpOrderPrice: 65000.0, // Take-profit execution price SlTriggerPrice: 58000.0, // Stop-loss trigger price SlOrderPrice: 58000.0 // Stop-loss execution price }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("OCO order Id:", id); }c++void main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_OCO, .TpTriggerPrice = 65000, .TpOrderPrice = 65000, .SlTriggerPrice = 58000, .SlOrderPrice = 58000}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("OCO order Id:", id); } -
Create a conditional order with an additional parameter (option), used to pass exchange-specific parameters.
javascriptfunction main() { // Pass the option parameter in JSON format var option = { "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" } var sideWithOption = "buy;" + JSON.stringify(option) var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77, TpOrderPrice: 71 } var id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition) Log("Condition Order Id:", id) Sleep(2000) Log(exchange.GetConditionOrder(id)) }pythonimport json def main(): # Pass the option parameter in JSON format option = { "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" } sideWithOption = "buy;" + json.dumps(option) condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 77, "TpOrderPrice": 71 } id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition) Log("Condition Order Id:", id) Sleep(2000) Log(exchange.GetConditionOrder(id))rustfn main() { // Pass the option parameter in JSON format (Rust has no JSON serialization capability, so a raw string is used directly here to construct it) let option = r#"{"type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1"}"#; let sideWithOption = format!("buy;{}", option); let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 71.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", &sideWithOption, 1, &condition).unwrap(); Log!("Condition Order Id:", id); Sleep(2000); Log!(exchange.GetConditionOrder(&id)); }c++void main() { // Pass the option parameter in JSON format json option = R"({ "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" })"_json; string sideWithOption = "buy;" + option.dump(); OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 71}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition); Log("Condition Order Id:", id); Sleep(2000); Log(exchange.GetConditionOrder(id)); }
Returns
| Type | Description |
string / null value | When the conditional order is created successfully, the conditional order Id is returned; when creation fails, a null value is returned. The format of the conditional order Id is similar to that of an ordinary order Id, consisting of the exchange symbol code and the exchange's original conditional order Id, separated by an English comma. |
Arguments
| Name | Type | Required | Description |
symbol | string | Yes | The When calling the When calling the When calling the |
side | string | Yes | The For a spot exchange object, the available values of the For a futures exchange object, the available values of the Additional parameters (option) are supported: additional parameters can be passed through the For example: Additional parameters are used to pass exchange-specific parameters (such as order type, effective rules, etc.). The specific supported parameters depend on the exchange API. |
amount | number | Yes | The |
condition | object | Yes | The
|
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extension parameter used to output additional information to the log of this conditional order. Multiple |
See Also
Condition exchange.CancelConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders exchange.ModifyConditionOrder
Remarks
Whether conditional orders are supported depends on the specific exchange; some exchanges may not support conditional orders.
A conditional order does not lock up account funds before it is triggered; the order is only actually placed and funds are only committed after it is triggered.
Different exchanges may vary in their level of support for conditional orders and in the specific parameters involved. Please consult the API documentation of the corresponding exchange before use.
Additional parameters (option) can be passed via the side parameter to supply exchange-specific parameters. The additional parameters must be merged into the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value&key=value" (URL-encoded format). For example: "buy;{\"type\":\"TRAILING_STOP_MARKET\"}".
The option parameters supported vary from exchange to exchange; the specific supported parameters depend on the exchange's API documentation. Common parameters include: order type (type), time in force (timeInForce), activation price (activatePrice), callback rate (callbackRate), and so on.
When using option parameters, you still need to provide the amount and condition parameters. If certain parameters in the exchange API have already been passed via option, these base parameters may be overridden by the corresponding parameters in option; the exact behavior depends on the exchange API's implementation.
exchange.ModifyOrder
The exchange.ModifyOrder() function is used to modify an existing regular order, allowing you to modify the order's price and quantity. This function supports modifying other order attributes via additional parameters (depending on the support of the exchange API).
exchange.ModifyOrder(orderId, side, price, amount)Examples
-
Modify the price and quantity of a regular order.
javascriptfunction main() { // Create a limit buy order var id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1) Log("Original Order ID:", id) Sleep(2000) // Query the original order info var order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) // Modify the order's price and quantity var newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) // Query the modified order info var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel the order exchange.CancelOrder(newId) }pythondef main(): # Create a limit buy order id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1) Log("Original Order ID:", id) Sleep(2000) # Query the original order info order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) # Modify the order's price and quantity newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) # Query the modified order info newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel the order exchange.CancelOrder(newId)rustfn main() { // Create a limit buy order let id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1).unwrap(); Log!("Original Order ID:", id); Sleep(2000); // Query the original order info let order = exchange.GetOrder(&id).unwrap(); Log!("Original Order Info:", order); Sleep(1000); // Modify the order's price and quantity let newId = exchange.ModifyOrder(&id, "buy", 77, 2).unwrap(); Log!("Modified Order ID:", newId); Sleep(2000); // Query the modified order info let newOrder = exchange.GetOrder(&newId).unwrap(); Log!("Modified Order Info:", newOrder); // Cancel the order let _ = exchange.CancelOrder(&newId); }c++void main() { // Create a limit buy order auto id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1); Log("Original Order ID:", id); Sleep(2000); // Query the original order info auto order = exchange.GetOrder(id); Log("Original Order Info:", order); Sleep(1000); // Modify the order's price and quantity auto newId = exchange.ModifyOrder(id, "buy", 77, 2); Log("Modified Order ID:", newId); Sleep(2000); // Query the modified order info auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel the order exchange.CancelOrder(newId); } -
Use the additional parameter (option) to modify the order's price match mode.
javascriptfunction main() { // Create a limit buy order var id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1) Log("Original Order ID:", id) Sleep(2000) // Modify the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter var option = {"priceMatch": "QUEUE_20"} var sideWithOption = "buy;" + JSON.stringify(option) var newId = exchange.ModifyOrder(id, sideWithOption, -1, 2) Log("Modified Order ID:", newId) Sleep(2000) // Query the modified order information var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel the order exchange.CancelOrder(newId) }pythonimport json def main(): # Create a limit buy order id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1) Log("Original Order ID:", id) Sleep(2000) # Modify the order and set the price match mode to QUEUE_20 # Pass the additional parameter (JSON format) via the side parameter option = {"priceMatch": "QUEUE_20"} sideWithOption = "buy;" + json.dumps(option) newId = exchange.ModifyOrder(id, sideWithOption, -1, 2) Log("Modified Order ID:", newId) Sleep(2000) # Query the modified order information newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel the order exchange.CancelOrder(newId)rustfn main() { // Create a limit buy order let id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1).unwrap(); Log!("Original Order ID:", id); Sleep(2000); // Modify the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter; Rust does not support JSON.stringify, so construct the JSON text directly using a raw string let option = r#"{"priceMatch": "QUEUE_20"}"#; let sideWithOption = format!("buy;{}", option); let newId = exchange.ModifyOrder(&id, &sideWithOption, -1, 2).unwrap(); Log!("Modified Order ID:", newId); Sleep(2000); // Query the modified order information let newOrder = exchange.GetOrder(&newId).unwrap(); Log!("Modified Order Info:", newOrder); // Cancel the order let _ = exchange.CancelOrder(&newId); }c++void main() { // Create a limit buy order auto id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1); Log("Original Order ID:", id); Sleep(2000); // Modify the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter json option = R"({"priceMatch": "QUEUE_20"})"_json; string sideWithOption = "buy;" + option.dump(); auto newId = exchange.ModifyOrder(id, sideWithOption, -1, 2); Log("Modified Order ID:", newId); Sleep(2000); // Query the modified order information auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel the order exchange.CancelOrder(newId); }
Returns
| Type | Description |
string / null value | Returns the order ID when the order modification succeeds, and returns a null value when the modification fails. The returned order ID may be the same as the original order ID or different, depending on the exchange API implementation. Some exchanges return a new order ID after modifying the order, while others keep the order ID unchanged. |
Arguments
| Name | Type | Required | Description |
orderId | string | Yes | The |
side | string | Yes | The For spot exchange objects, the available values for the For futures exchange objects, the available values for the Supports additional parameters (option): Additional parameters can be passed via the For example: Additional parameters are used to modify other order attributes (such as the price match mode, etc.); the specific parameters supported depend on the exchange API. |
price | number | Yes | The |
amount | number | Yes | The |
See Also
Remarks
The order ID returned by the exchange.ModifyOrder() function may behave differently depending on the exchange API implementation. Some exchange APIs return an updated order ID, while others keep it unchanged. It is recommended to use the returned new order ID for subsequent operations.
The exchange.ModifyOrder() function does not validate the validity of parameters according to the exchange interface rules, but instead submits the parameters directly to the exchange API. When invalid parameters are passed in (such as a price or quantity of -1), the parameters may be ignored by the exchange, and the order will retain its original attributes unchanged.
Supports passing additional parameters (option) via the side parameter to modify other order attributes. Additional parameters must be merged with the side parameter before being passed in, in the format "side;{JSON object}" (recommended) or "side;key=value" (URL-encoded format). For example, to modify the price match mode: "buy;{\"priceMatch\":\"QUEUE_20\"}".
For modifying market orders among regular orders, you need to check specifically whether the exchange API supports it. Some exchanges do not support modifying market orders.
When modifying an order, the order's other attributes (such as order type, position mode, account mode, leverage, order time-in-force rules, etc.) usually retain the settings of the original order. If you need to modify these attributes, they can be passed in via additional parameters (option), provided the exchange API supports it.
Certain exchange APIs may convert an order into a market order when the price parameter is not received (price is -1 or null). For spot market buy orders, note that the unit of the order quantity may be the amount rather than the number of coins.
Support for the order modification feature depends on the specific exchange; some exchanges may not support the order modification feature, or may only support modifying certain parameters. Please consult the API documentation of the corresponding exchange before use.
exchange.ModifyConditionOrder
The exchange.ModifyConditionOrder() function is used to modify an existing conditional order, allowing modification of the order amount, trigger condition, and execution price of the conditional order. It supports modifying other properties of the conditional order through additional parameters (depending on the specific support of the exchange API).
exchange.ModifyConditionOrder(orderId, side, amount, condition)Examples
-
Modify the quantity and trigger conditions of a conditional order.
javascriptfunction main() { // Create a take-profit conditional order var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77, TpOrderPrice: 76 } var id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition) Log("Original Condition Order ID:", id) Sleep(2000) // Query the original conditional order information var order = exchange.GetConditionOrder(id) Log("Original Condition Order Info:", order) Sleep(1000) // Modify the quantity and trigger conditions of the conditional order var newCondition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75, TpOrderPrice: 71 } var newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) // Query the modified conditional order information var newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) // Cancel the conditional order exchange.CancelConditionOrder(newId) }pythondef main(): # Create a take-profit conditional order condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 77, "TpOrderPrice": 76 } id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition) Log("Original Condition Order ID:", id) Sleep(2000) # Query the original conditional order information order = exchange.GetConditionOrder(id) Log("Original Condition Order Info:", order) Sleep(1000) # Modify the quantity and trigger conditions of the conditional order newCondition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 75, "TpOrderPrice": 71 } newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) # Query the modified conditional order information newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) # Cancel the conditional order exchange.CancelConditionOrder(newId)rustfn main() { // Create a take-profit conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 76.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, &condition).unwrap(); Log!("Original Condition Order ID:", id); Sleep(2000); // Query the original conditional order information let order = exchange.GetConditionOrder(&id); Log!("Original Condition Order Info:", order); Sleep(1000); // Modify the quantity and trigger conditions of the conditional order let newCondition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75.0, TpOrderPrice: 71.0, ..Default::default() }; let newId = exchange.ModifyConditionOrder(&id, "buy", 2, &newCondition).unwrap(); Log!("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information let newOrder = exchange.GetConditionOrder(&newId); Log!("Modified Condition Order Info:", newOrder); // Cancel the conditional order let _ = exchange.CancelConditionOrder(&newId); }c++void main() { // Create a take-profit conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 76}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition); Log("Original Condition Order ID:", id); Sleep(2000); // Query the original conditional order information auto order = exchange.GetConditionOrder(id); Log("Original Condition Order Info:", order); Sleep(1000); // Modify the quantity and trigger conditions of the conditional order OrderCondition newCondition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 75, .TpOrderPrice = 71}; auto newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition); Log("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information auto newOrder = exchange.GetConditionOrder(newId); Log("Modified Condition Order Info:", newOrder); // Cancel the conditional order exchange.CancelConditionOrder(newId); } -
Use the additional parameter (option) to modify the trigger price type of a conditional order.
javascriptfunction main() { // Create a take-profit conditional order var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77, TpOrderPrice: 76 } var id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition) Log("Original Condition Order ID:", id) Sleep(2000) // Modify the conditional order and set the trigger price type to index price (index) // Pass the additional parameter via the side parameter (in JSON format) var option = {"newTpTriggerPxType": "index"} var sideWithOption = "buy;" + JSON.stringify(option) var newCondition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75, TpOrderPrice: 71 } var newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) // Query the modified conditional order information var newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) // Cancel the conditional order exchange.CancelConditionOrder(newId) }pythonimport json def main(): # Create a take-profit conditional order condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 77, "TpOrderPrice": 76 } id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition) Log("Original Condition Order ID:", id) Sleep(2000) # Modify the conditional order and set the trigger price type to index price (index) # Pass the additional parameter via the side parameter (in JSON format) option = {"newTpTriggerPxType": "index"} sideWithOption = "buy;" + json.dumps(option) newCondition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 75, "TpOrderPrice": 71 } newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) # Query the modified conditional order information newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) # Cancel the conditional order exchange.CancelConditionOrder(newId)rustfn main() { // Create a take-profit conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 76.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, &condition).unwrap(); Log!("Original Condition Order ID:", id); Sleep(2000); // Modify the conditional order and set the trigger price type to index price (index) // Pass the additional parameter via the side parameter (in JSON format; Rust has no JSON serialization here, so a raw string literal is used directly) let sideWithOption = r#"buy;{"newTpTriggerPxType": "index"}"#; let newCondition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75.0, TpOrderPrice: 71.0, ..Default::default() }; let newId = exchange.ModifyConditionOrder(&id, sideWithOption, 2, &newCondition).unwrap(); Log!("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information let newOrder = exchange.GetConditionOrder(&newId); Log!("Modified Condition Order Info:", newOrder); // Cancel the conditional order let _ = exchange.CancelConditionOrder(&newId); }c++void main() { // Create a take-profit conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 76}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition); Log("Original Condition Order ID:", id); Sleep(2000); // Modify the conditional order and set the trigger price type to index price (index) // Pass the additional parameter via the side parameter (in JSON format) json option = R"({"newTpTriggerPxType": "index"})"_json; string sideWithOption = "buy;" + option.dump(); OrderCondition newCondition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 75, .TpOrderPrice = 71}; auto newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition); Log("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information auto newOrder = exchange.GetConditionOrder(newId); Log("Modified Condition Order Info:", newOrder); // Cancel the conditional order exchange.CancelConditionOrder(newId); }
Returns
| Type | Description |
string / null value | When the conditional order is successfully modified, the conditional order ID is returned; when the modification fails, a null value is returned. The returned conditional order ID may be the same as the original conditional order ID, or it may be different, depending on the specific implementation of the exchange API. Some exchanges return a new conditional order ID after modifying the conditional order, while some exchanges keep the conditional order ID unchanged. |
Arguments
| Name | Type | Required | Description |
orderId | string | Yes | The |
side | string | Yes | The For spot exchange objects, the available values for the For futures exchange objects, the available values for the Additional parameters (option) supported: Additional parameters can be passed through the For example: Additional parameters are used to modify other properties of the conditional order (such as the trigger price type, etc.), and the specific parameters supported depend on the exchange API. |
amount | number | Yes | The |
condition | object | Yes | The
|
See Also
Condition exchange.CreateConditionOrder exchange.CancelConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders
Remarks
The conditional order ID returned by the exchange.ModifyConditionOrder() function may exhibit different behaviors depending on the exchange API implementation. Some exchange APIs return an updated conditional order ID, while others keep it unchanged. It is recommended to use the returned new conditional order ID for subsequent operations.
The exchange.ModifyConditionOrder() function does not validate the validity of the parameters according to the exchange interface rules, but submits the parameters directly to the exchange API. When invalid parameters are passed in (such as an amount of -1), the parameter may be ignored by the exchange, and the conditional order retains its original properties unchanged.
Passing additional parameters (option) through the side parameter is supported, used to modify other properties of the conditional order. The additional parameters need to be merged with the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value" (URL-encoded format). For example, to modify the trigger price type: "buy;{\"newTpTriggerPxType\":\"index\"}".
For market order modification of conditional orders, you need to specifically check whether the exchange API supports it. Setting TpOrderPrice or SlOrderPrice in the condition parameter to -1 indicates a market order.
When modifying a conditional order, other properties of the conditional order (such as condition type, position mode, account mode, leverage, etc.) are usually retained from the original conditional order's settings. If you need to modify these properties, you can pass them in through additional parameters (option), provided that the exchange API supports it.
The trigger price type can be modified through additional parameters, for example, changing the trigger price type from the last price (last) to the index price (index) or the mark price (mark). The specific parameter names and support status depend on the exchange API documentation.
The support for the conditional order modification feature depends on the specific exchange. Some exchanges may not support the conditional order modification feature, or may only support modifying some parameters. Please consult the API documentation of the corresponding exchange before use.
exchange.CancelConditionOrder
exchange.CancelConditionOrder() function is used to cancel a conditional order. The format of the conditional order Id is similar to that of a regular order Id, consisting of the exchange symbol code and the exchange's original conditional order Id, separated by an English comma.
When calling the exchange.CancelConditionOrder() function to cancel a conditional order, the conditionOrderId parameter passed in is consistent with the Id attribute of the conditional order structure.
exchange.CancelConditionOrder(conditionOrderId)
exchange.CancelConditionOrder(conditionOrderId, ...args)Examples
-
Cancel a conditional order.
javascriptfunction main(){ // Create a stop-loss conditional order var condition = { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000, SlOrderPrice: -1 // Market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Sleep(1000) exchange.CancelConditionOrder(id) }pythondef main(): # Create a stop-loss conditional order condition = { "ConditionType": ORDER_CONDITION_TYPE_SL, "SlTriggerPrice": 58000, "SlOrderPrice": -1 # Market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Sleep(1000) exchange.CancelConditionOrder(id)rustfn main() { // Create a stop-loss conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000.0, SlOrderPrice: -1.0, // Market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition).unwrap(); Sleep(1000); let _ = exchange.CancelConditionOrder(&id); }c++void main() { // Create a stop-loss conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = -1}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Sleep(1000); exchange.CancelConditionOrder(id); } -
Batch cancel condition orders, with condition order information output.
javascriptfunction main() { // Create several condition orders var condition1 = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000, TpOrderPrice: 65000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1) var condition2 = { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000, SlOrderPrice: 58000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition2) Sleep(1000) var orders = exchange.GetConditionOrders() for (var i = 0 ; i < orders.length ; i++) { exchange.CancelConditionOrder(orders[i].Id, "Canceled condition order:", orders[i]) Sleep(500) } }pythondef main(): # Create several condition orders condition1 = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 65000, "TpOrderPrice": 65000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1) condition2 = { "ConditionType": ORDER_CONDITION_TYPE_SL, "SlTriggerPrice": 58000, "SlOrderPrice": 58000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition2) Sleep(1000) orders = exchange.GetConditionOrders() for i in range(len(orders)): exchange.CancelConditionOrder(orders[i]["Id"], "Canceled condition order:", orders[i]) Sleep(500)rustfn main() { // Create several condition orders let condition1 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000.0, TpOrderPrice: 65000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition1); let condition2 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000.0, SlOrderPrice: 58000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition2); Sleep(1000); let orders = exchange.GetConditionOrders(None).unwrap(); for i in 0..orders.len() { // In Rust, CancelConditionOrder does not support extended parameters; output the accompanying information with Log let _ = exchange.CancelConditionOrder(&orders[i].Id); Log!("Canceled condition order:", orders[i]); Sleep(500); } }c++void main() { // Create several condition orders OrderCondition condition1 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1); OrderCondition condition2 = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = 58000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition2); Sleep(1000); auto orders = exchange.GetConditionOrders(); for (int i = 0 ; i < orders.size() ; i++) { exchange.CancelConditionOrder(orders[i].Id, "Canceled condition order:", orders[i]); Sleep(500); } }
Returns
| Type | Description |
bool | The |
Arguments
| Name | Type | Required | Description |
conditionOrderId | string | Yes | The |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extended parameter used to output additional information to the log of this canceled conditional order. Multiple |
See Also
exchange.CreateConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders exchange.ModifyConditionOrder
Remarks
The return value of the exchange.CancelConditionOrder() function only indicates whether the cancellation request was sent successfully or failed. To determine whether the exchange has actually canceled the conditional order, you can call the exchange.GetConditionOrders() function for confirmation.
Only untriggered conditional orders can be canceled; conditional orders that have already been triggered and converted into regular orders cannot be canceled through this function.
exchange.GetConditionOrder
The exchange.GetConditionOrder() function is used to retrieve information about a specified conditional order.
exchange.GetConditionOrder(conditionOrderId)Examples
javascript
function main(){
// Create a take-profit conditional order
var condition = {
ConditionType: ORDER_CONDITION_TYPE_TP,
TpTriggerPrice: 65000,
TpOrderPrice: 65000
}
var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition)
Sleep(1000)
// The parameter id is the conditional order number; fill in the number of the conditional order you want to query
var order = exchange.GetConditionOrder(id)
Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount,
"Status:", order.Status, "Type:", order.Type, "Condition:", order.Condition)
}
python
def main():
# Create a take-profit conditional order
condition = {
"ConditionType": ORDER_CONDITION_TYPE_TP,
"TpTriggerPrice": 65000,
"TpOrderPrice": 65000
}
id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition)
Sleep(1000)
order = exchange.GetConditionOrder(id)
Log("Id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"],
"Status:", order["Status"], "Type:", order["Type"], "Condition:", order["Condition"])
rust
fn main() {
// Create a take-profit conditional order
let condition = OrderCondition {
ConditionType: ORDER_CONDITION_TYPE_TP,
TpTriggerPrice: 65000.0,
TpOrderPrice: 65000.0,
..Default::default()
};
let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition).unwrap();
Sleep(1000);
// The parameter id is the conditional order number; fill in the number of the conditional order you want to query
let order = exchange.GetConditionOrder(&id).unwrap();
Log!("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount,
"Status:", order.Status, "Type:", order.Type, "Condition:", order.Condition);
}
c++
void main() {
// Create a take-profit conditional order
OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000};
auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition);
Sleep(1000);
auto order = exchange.GetConditionOrder(id);
Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount,
"Status:", order.Status, "Type:", order.Type);
}Returns
| Type | Description |
| Query the details of a conditional order by its conditional order Id. When the query succeeds, the The returned Order structure contains a |
Arguments
| Name | Type | Required | Description |
conditionOrderId | string | Yes | The The |
See Also
Remarks
Some exchanges do not support the exchange.GetConditionOrder() function.
The returned conditional order structure contains information such as the trigger condition, trigger price, and order status.
Conditional order statuses include: not triggered, triggered, canceled, etc. The specific status values are determined by the exchange.
exchange.GetConditionOrders
exchange.GetConditionOrders() function is used to obtain unfinished conditional orders (conditional orders that have not yet been triggered or canceled).
exchange.GetConditionOrders()
exchange.GetConditionOrders(symbol)Examples
-
Use the spot exchange object to create multiple condition orders, then query the pending condition order information.
javascriptfunction main() { // Create multiple condition orders var condition1 = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000, TpOrderPrice: 65000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1) var condition2 = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 3200, TpOrderPrice: 3200 } exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, condition2) Sleep(1000) // Query all pending condition orders var orders = exchange.GetConditionOrders() Log("Pending condition orders count:", orders.length) for (var i = 0; i < orders.length; i++) { Log("Condition order", i+1, ":", orders[i]) } }pythondef main(): # Create multiple condition orders condition1 = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 65000, "TpOrderPrice": 65000 } exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1) condition2 = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 3200, "TpOrderPrice": 3200 } exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, condition2) Sleep(1000) # Query all pending condition orders orders = exchange.GetConditionOrders() Log("Pending condition orders count:", len(orders)) for i in range(len(orders)): Log("Condition order", i+1, ":", orders[i])rustfn main() { // Create multiple condition orders let condition1 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000.0, TpOrderPrice: 65000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition1); let condition2 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 3200.0, TpOrderPrice: 3200.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, &condition2); Sleep(1000); // Query all pending condition orders let orders = exchange.GetConditionOrders(None).unwrap(); Log!("Pending condition orders count:", orders.len()); for i in 0..orders.len() { Log!("Condition order", i + 1, ":", orders[i]); } }c++void main() { // Create multiple condition orders OrderCondition condition1 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1); OrderCondition condition2 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 3200, .TpOrderPrice = 3200}; exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, condition2); Sleep(1000); // Query all pending condition orders auto orders = exchange.GetConditionOrders(); Log("Pending condition orders count:", orders.size()); for (int i = 0; i < orders.size(); i++) { Log("Condition order", i+1, ":", orders[i]); } } -
Query the pending condition orders for a specified trading pair.
javascriptfunction main() { // Query the pending condition orders for the BTC_USDT trading pair var orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders) }pythondef main(): # Query the pending condition orders for the BTC_USDT trading pair orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders)rustfn main() { // Query the pending condition orders for the BTC_USDT trading pair let orders = exchange.GetConditionOrders("BTC_USDT"); Log!("BTC_USDT pending condition orders:", orders); }c++void main() { // Query the pending condition orders for the BTC_USDT trading pair auto orders = exchange.GetConditionOrders("BTC_USDT"); Log("BTC_USDT pending condition orders:", orders); }
Returns
| Type | Description |
| The The returned Order structure contains a |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The For spot exchange objects, when the For futures exchange objects, when the |
See Also
Remarks
In the GetConditionOrders function, the use cases of the symbol parameter are summarized as follows:
| Exchange Object Category | symbol Parameter | Query Scope | Remarks |
|---|---|---|---|
| Spot | symbol parameter not passed | Query all spot trading pairs | Applicable to all call scenarios; if the exchange interface does not support it, an error is reported and a null value is returned, which will not be repeated below |
| Spot | Specify a trading instrument, with symbol parameter as: "BTC_USDT" | Query the specified BTC_USDT trading pair | For spot exchange objects, the format of the symbol parameter is: "BTC_USDT" |
| Futures | symbol parameter not passed | Query all trading instruments within the dimension range of the current trading pair and contract code | Assuming the current trading pair is BTC_USDT and the contract code is swap, this queries all USDT-margined perpetual contracts. Equivalent to calling GetConditionOrders("USDT.swap") |
| Futures | Specify a trading instrument, with symbol parameter as: "BTC_USDT.swap" | Query the specified BTC USDT-margined perpetual contract | For futures exchange objects, the format of the symbol parameter is: a combination of the trading pair and contract code defined by the FMZ platform, with the two separated by the character ".". |
| Futures | Specify a range of trading instruments, with symbol parameter as: "USDT.swap" | Query all USDT-margined perpetual contracts | - |
| Futures exchange supporting options | symbol parameter not passed | Query all option contracts within the dimension range of the current trading pair | Assuming the current trading pair is BTC_USDT and the contract is set to an option contract, such as a Binance option contract: BTC-240108-40000-C |
| Futures exchange supporting options | Specify a specific trading instrument | Query the specified option contract | For example, for the Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C |
| Futures exchange supporting options | Specify a range of trading instruments, with symbol parameter as: "USDT.option" | Query all USDT-margined option contracts | - |
In the GetConditionOrders function, the query dimension ranges of the futures exchange object are summarized as follows:
| symbol Parameter | Request Scope Definition | Remarks |
|---|---|---|
| USDT.swap | USDT-margined perpetual contract range. | For dimensions not supported by the exchange API interface, an error is reported and a null value is returned when called. |
| USDT.futures | USDT-margined delivery contract range. | - |
| USD.swap | Coin-margined perpetual contract range. | - |
| USD.futures | Coin-margined delivery contract range. | - |
| USDT.option | USDT-margined option contract range. | - |
| USD.option | Coin-margined option contract range. | - |
| USDT.futures_combo | Spread combination contract range. | Futures_Deribit exchange |
| USD.futures_ff | Mixed-margin delivery contract range. | Futures_Kraken exchange |
| USD.swap_pf | Mixed-margin perpetual contract range. | Futures_Kraken exchange |
When the account represented by the exchange object exchange has no unfinished conditional orders within the query scope or on the specified trading instrument, calling this function will return an empty array, i.e.: [].
Support for the conditional order feature depends on the specific exchange; some exchanges may not support the conditional order feature.
exchange.GetHistoryConditionOrders
The exchange.GetHistoryConditionOrders() function is used to retrieve the historical conditional orders (including triggered, canceled, and expired conditional orders) for the current trading pair or contract, and supports specifying a particular trading instrument.
exchange.GetHistoryConditionOrders()
exchange.GetHistoryConditionOrders(symbol)
exchange.GetHistoryConditionOrders(symbol, since)
exchange.GetHistoryConditionOrders(symbol, since, limit)
exchange.GetHistoryConditionOrders(since)
exchange.GetHistoryConditionOrders(since, limit)Examples
-
Query historical conditional orders. The returned results are sorted in ascending order by time.
javascriptfunction main() { var historyConditionOrders = exchange.GetHistoryConditionOrders() Log("Historical condition orders count:", historyConditionOrders.length) // Iterate and display; orders are sorted in ascending order by the Time property for (var i = 0; i < historyConditionOrders.length; i++) { Log("Order", i+1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status) } }pythondef main(): historyConditionOrders = exchange.GetHistoryConditionOrders() Log("Historical condition orders count:", len(historyConditionOrders)) # Iterate and display; orders are sorted in ascending order by the Time property for i in range(len(historyConditionOrders)): Log("Order", i+1, "Created at:", historyConditionOrders[i]["Time"], "ID:", historyConditionOrders[i]["Id"], "Status:", historyConditionOrders[i]["Status"])rustfn main() { let historyConditionOrders = exchange.GetHistoryConditionOrders(None, None, None).unwrap(); Log!("Historical condition orders count:", historyConditionOrders.len()); // Iterate and display; orders are sorted in ascending order by the Time property for i in 0..historyConditionOrders.len() { Log!("Order", i + 1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status); } }c++void main() { auto historyConditionOrders = exchange.GetHistoryConditionOrders(); Log("Historical condition orders count:", historyConditionOrders.size()); // Iterate and display; orders are sorted in ascending order by the Time property for (int i = 0; i < historyConditionOrders.size(); i++) { Log("Order", i+1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status); } } -
Query the historical conditional orders of a specified trading pair, and limit the number of results returned.
javascriptfunction main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair var historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders) }pythondef main(): # Query the 10 most recent historical conditional orders for the BTC_USDT trading pair historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders)rustfn main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair let historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10); Log!("BTC_USDT historical condition orders:", historyConditionOrders); }c++void main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair auto historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10); Log("BTC_USDT historical condition orders:", historyConditionOrders); } -
Query historical conditional orders by time range.
javascriptfunction main() { // Query historical conditional orders starting from the specified timestamp var startTime = new Date("2024-01-01").getTime() var historyConditionOrders = exchange.GetHistoryConditionOrders(startTime, 50) Log("Historical condition orders since:", historyConditionOrders) }pythondef main(): # Query historical conditional orders starting from the specified timestamp import time startTime = int(time.mktime(time.strptime("2024-01-01", "%Y-%m-%d")) * 1000) historyConditionOrders = exchange.GetHistoryConditionOrders(startTime, 50) Log("Historical condition orders since:", historyConditionOrders)rustfn main() { // Query historical conditional orders starting from the specified timestamp let startTime: i64 = 1704067200000; // Timestamp for 2024-01-01 // In Rust, passing None for the symbol parameter means the current trading pair let historyConditionOrders = exchange.GetHistoryConditionOrders(None, startTime, 50); Log!("Historical condition orders since:", historyConditionOrders); }c++void main() { // Query historical conditional orders starting from the specified timestamp auto startTime = 1704067200000; // Timestamp for 2024-01-01 // In C++, the symbol parameter cannot be omitted; pass "" to indicate the current trading pair auto historyConditionOrders = exchange.GetHistoryConditionOrders("", startTime, 50); Log("Historical condition orders since:", historyConditionOrders); }
Returns
| Type | Description |
| The The returned Order structure contains a |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The If you are querying conditional order data for an options contract, set the |
since | number | No | The |
limit | number | No | The |
See Also
Remarks
-
When the
symbol,since, andlimitparameters are not specified, the historical conditional orders of the current trading pair or contract are queried by default, i.e., the historical conditional orders within a certain range closest to the current time are queried. The query range depends on the single-query range of the exchange interface. -
When the
symbolparameter is specified, the historical conditional orders of the set trading instrument are queried. -
When the
sinceparameter is specified, the query starts from thesincetimestamp and proceeds toward the current time. -
When the
limitparameter is specified, the query returns after a sufficient number of records has been found. -
This function is only supported by exchanges that provide a historical conditional order query interface.
Historical conditional orders include conditional orders in states such as triggered (converted to regular orders), canceled, and expired.
The returned array of historical conditional orders is sorted in ascending order by order creation time (the Time attribute), i.e., orders with the earliest time are at the front of the array, and orders with the latest time are at the back.
Support for the conditional order feature depends on the specific exchange. Some exchanges may not support the conditional order feature or the historical conditional order query feature.
exchange.SetPrecision
The exchange.SetPrecision() function is used to set the precision of the price and order amount for the exchange exchange object. Once set, the system will automatically ignore any excess portion of the data that exceeds the specified precision.
exchange.SetPrecision(pricePrecision, amountPrecision)Examples
javascript
function main(){
// Set the price decimal precision to 2 digits and the order amount decimal precision to 3 digits
exchange.SetPrecision(2, 3)
}
python
def main():
exchange.SetPrecision(2, 3)
rust
fn main() {
// Set the price decimal precision to 2 digits and the order amount decimal precision to 3 digits
exchange.SetPrecision(2, 3);
}
c++
void main() {
exchange.SetPrecision(2, 3);
}Arguments
| Name | Type | Required | Description |
pricePrecision | number | Yes | The |
amountPrecision | number | Yes | The |
See Also
Remarks
The backtesting system does not support this function; the numerical precision in the backtesting system is handled automatically by the system.
exchange.SetRate
Sets the current exchange rate for the exchange object.
exchange.SetRate(rate)Examples
javascript
function main(){
Log(exchange.GetTicker())
// Set the exchange rate conversion
exchange.SetRate(7)
Log(exchange.GetTicker())
// Set to 1, no conversion
exchange.SetRate(1)
}
python
def main():
Log(exchange.GetTicker())
exchange.SetRate(7)
Log(exchange.GetTicker())
exchange.SetRate(1)
rust
fn main() {
Log!(exchange.GetTicker(None));
// Set the exchange rate conversion
exchange.SetRate(7);
Log!(exchange.GetTicker(None));
// Set to 1, no conversion
exchange.SetRate(1);
}
c++
void main() {
Log(exchange.GetTicker());
exchange.SetRate(7);
Log(exchange.GetTicker());
exchange.SetRate(1);
}Arguments
| Name | Type | Required | Description |
rate | number | Yes | The |
See Also
Remarks
If you set an exchange rate value using the exchange.SetRate() function (for example, set it to 7), then all price information represented by the current exchange object — such as tickers, depth, order prices, and so on — will be multiplied by the set rate of 7 for conversion.
For example, exchange is an exchange with USD as its quote currency. After executing exchange.SetRate(7), all prices in live trading will be multiplied by 7, converting them to prices close to those quoted in CNY.
exchange.IO
exchange.IO() function is used to call other interfaces related to the exchange object.
exchange.IO(k, ...args)Examples
-
Use the
"api"mode to call the OKX futures batch order placement interface, and pass the JSON-formatted order data via therawparameter:javascriptfunction main() { var arrOrders = [ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ] // Call exchange.IO to directly access the exchange's batch order placement interface var ret = exchange.IO("api", "POST", "/api/v5/trade/batch-orders", "", JSON.stringify(arrOrders)) Log(ret) }pythonimport json def main(): arrOrders = [ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ] ret = exchange.IO("api", "POST", "/api/v5/trade/batch-orders", "", json.dumps(arrOrders)) Log(ret)rustfn main() { // Rust has no JSON serialization; construct the order array directly using a raw string let arrOrders = r#"[ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ]"#; // Call exchange.IO to directly access the exchange's batch order placement interface; multiple parameters are passed in as a tuple let ret = exchange.IO(("api", "POST", "/api/v5/trade/batch-orders", "", arrOrders)); Log!(ret); }c++void main() { json arrOrders = R"([ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ])"_json; auto ret = exchange.IO("api", "POST", "/api/v5/trade/batch-orders", "", arrOrders.dump()); Log(ret); } -
When the value of a key in the
paramsparameter is of string type, you need to wrap the parameter value with single quotes:javascriptvar amount = 1 var price = 10 var basecurrency = "ltc" function main () { // Note that there is a ' character on both the left and right sides of amount.toString() and price.toString() var message = "symbol=" + basecurrency + "&amount='" + amount.toString() + "'&price='" + price.toString() + "'&side=buy" + "&type=limit" var id = exchange.IO("api", "POST", "/v1/order/new", message) }pythonamount = 1 price = 10 basecurrency = "ltc" def main(): message = "symbol=" + basecurrency + "&amount='" + str(amount) + "'&price='" + str(price) + "'&side=buy" + "&type=limit" id = exchange.IO("api", "POST", "/v1/order/new", message)rustfn main() { let amount = 1; let price = 10; let basecurrency = "ltc"; // Note that there is a ' character on both the left and right sides of the amount and price parameter values let message = format!("symbol={}&amount='{}'&price='{}'&side=buy&type=limit", basecurrency, amount, price); let id = exchange.IO(("api", "POST", "/v1/order/new", message)); }c++void main() { auto amount = 1.0; auto price = 10.0; auto basecurrency = "ltc"; string message = str_format("symbol=%s&amount=\"%.1f\"&price=\"%.1f\"&side=buy&type=limit", basecurrency, amount, price); auto id = exchange.IO("api", "POST", "/v1/order/new", message); } -
The
resourceparameter supports passing in a complete URL:javascriptfunction main() { var ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC") Log(ret) }pythondef main(): ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC") Log(ret)rustfn main() { let ret = exchange.IO(("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC")); Log!(ret); }c++void main() { auto ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC"); Log(ret); } -
A GET request that does not use the
rawparameter:javascriptfunction main(){ var ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT") Log(ret) }pythondef main(): ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT") Log(ret)rustfn main() { let ret = exchange.IO(("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT")); Log!(ret); }c++void main() { auto ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT"); Log(ret); } -
Switch trading pair at runtime:
javascriptfunction main() { // For example, when the live bot starts, the exchange object's current trading pair is BTC_USDT; print the ticker of the current trading pair Log(exchange.GetTicker()) // Switch the trading pair to LTC_BTC exchange.IO("currency", "LTC_BTC") Log(exchange.GetTicker()) }pythondef main(): Log(exchange.GetTicker()) exchange.IO("currency", "LTC_BTC") Log(exchange.GetTicker())rustfn main() { // For example, when the live bot starts, the exchange object's current trading pair is BTC_USDT; print the ticker of the current trading pair Log!(exchange.GetTicker(None)); // Switch the trading pair to LTC_BTC let _ = exchange.IO(("currency", "LTC_BTC")); Log!(exchange.GetTicker(None)); }c++void main() { Log(exchange.GetTicker()); exchange.IO("currency", "LTC_BTC"); Log(exchange.GetTicker()); } -
Switch the exchange API base address:
javascriptfunction main () { // exchanges[0] is the first exchange object added when the live bot was created exchanges[0].IO("base", "https://api.huobi.pro") }pythondef main(): exchanges[0].IO("base", "https://api.huobi.pro")rustfn main() { // exchanges[0] is the first exchange object added when the live bot was created let _ = exchanges[0].IO(("base", "https://api.huobi.pro")); }c++void main() { exchanges[0].IO("base", "https://api.huobi.pro"); } -
Switch the market data API base address via
"mbase"(using Bitfinex as an example):javascriptfunction main() { exchange.SetBase("https://api.bitfinex.com") exchange.IO("mbase", "https://api-pub.bitfinex.com") }pythondef main(): exchange.SetBase("https://api.bitfinex.com") exchange.IO("mbase", "https://api-pub.bitfinex.com")rustfn main() { exchange.SetBase("https://api.bitfinex.com"); let _ = exchange.IO(("mbase", "https://api-pub.bitfinex.com")); }c++void main() { exchange.SetBase("https://api.bitfinex.com"); exchange.IO("mbase", "https://api-pub.bitfinex.com"); } -
Switch between the demo/live trading environment (using OKX Futures as an example):
javascriptfunction main() { exchange.IO("simulate", true) // Switch to demo trading environment // ... trading logic ... exchange.IO("simulate", false) // Switch back to live trading environment }pythondef main(): exchange.IO("simulate", True) # ... trading logic ... exchange.IO("simulate", False)rustfn main() { let _ = exchange.IO(("simulate", true)); // Switch to demo trading environment // ... trading logic ... let _ = exchange.IO(("simulate", false)); // Switch back to live trading environment }c++void main() { exchange.IO("simulate", true); // ... trading logic ... exchange.IO("simulate", false); } -
Switch contract margin mode and position mode (using Binance Futures as an example):
javascriptfunction main() { exchange.IO("dual", true) // Switch to hedge mode (dual position) exchange.IO("dual", false) // Switch to one-way mode exchange.SetContractType("swap") exchange.IO("cross", true) // Switch to cross margin exchange.IO("cross", false) // Switch to isolated margin }pythondef main(): exchange.IO("dual", True) exchange.IO("dual", False) exchange.SetContractType("swap") exchange.IO("cross", True) exchange.IO("cross", False)rustfn main() { let _ = exchange.IO(("dual", true)); // Switch to hedge mode (dual position) let _ = exchange.IO(("dual", false)); // Switch to one-way mode let _ = exchange.SetContractType("swap"); let _ = exchange.IO(("cross", true)); // Switch to cross margin let _ = exchange.IO(("cross", false)); // Switch to isolated margin }c++void main() { exchange.IO("dual", true); exchange.IO("dual", false); exchange.SetContractType("swap"); exchange.IO("cross", true); exchange.IO("cross", false); } -
Switch to unified account mode (using Binance Futures as an example):
javascriptfunction main() { exchange.IO("unified", true) // Switch to unified account mode exchange.IO("unified", false) // Switch to normal mode }pythondef main(): exchange.IO("unified", True) exchange.IO("unified", False)rustfn main() { let _ = exchange.IO(("unified", true)); // Switch to unified account mode let _ = exchange.IO(("unified", false)); // Switch to normal mode }c++void main() { exchange.IO("unified", true); exchange.IO("unified", false); } -
Set self-trade prevention mode (using Binance as an example):
javascriptfunction main() { // "NONE" means disable STP mode, other parameters: "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH" exchange.IO("selfTradePreventionMode", "NONE") }pythondef main(): exchange.IO("selfTradePreventionMode", "NONE")rustfn main() { // "NONE" means disable STP mode, other parameters: "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH" let _ = exchange.IO(("selfTradePreventionMode", "NONE")); }c++void main() { exchange.IO("selfTradePreventionMode", "NONE"); } -
Futures_edgeX calculates the order Hash and signs it:
javascriptfunction main() { var strJson = `{ "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": true, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 }` var signature = exchange.IO("calcOrderHashAndSign", strJson) Log(signature) }pythonimport json def main(): params = { "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": True, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 } signature = exchange.IO("calcOrderHashAndSign", json.dumps(params)) Log(signature)rustfn main() { let strJson = r#"{ "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": true, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 }"#; let signature = exchange.IO(("calcOrderHashAndSign", strJson)); Log!(signature); }c++void main() { json params = R"({ "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": true, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 })"_json; auto signature = exchange.IO("calcOrderHashAndSign", params.dump()); Log(signature); } -
rate mode rate limiting - Limit GetTicker to a maximum of 10 calls per second; returns null when the limit is exceeded:
javascriptfunction main() { exchange.IO("rate", "GetTicker", 10, "1s") for (var i = 0; i < 20; i++) { var ticker = exchange.GetTicker("BTC_USDT") if (ticker) { Log("Ticker:", ticker.Last) } else { Log("Rate limit exceeded") } } }pythondef main(): exchange.IO("rate", "GetTicker", 10, "1s") for i in range(20): ticker = exchange.GetTicker("BTC_USDT") if ticker: Log("Ticker:", ticker["Last"]) else: Log("Rate limit exceeded")rustfn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s")); for _i in 0..20 { // GetTicker returns Err when the limit is exceeded match exchange.GetTicker("BTC_USDT") { Ok(ticker) => Log!("Ticker:", ticker.Last), Err(_) => Log!("Rate limit exceeded"), } } }c++// C++ is not supported yet -
rate mode rate limiting - Use the
"delay"parameter to automatically wait instead of returning null when the limit is exceeded:javascriptfunction main() { exchange.IO("rate", "GetTicker", 10, "1s", "delay") for (var i = 0; i < 20; i++) { var ticker = exchange.GetTicker("BTC_USDT") Log("Call", i+1, "Ticker:", ticker.Last) } }pythondef main(): exchange.IO("rate", "GetTicker", 10, "1s", "delay") for i in range(20): ticker = exchange.GetTicker("BTC_USDT") Log("Call", i+1, "Ticker:", ticker["Last"])rustfn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s", "delay")); for i in 0..20 { let ticker = exchange.GetTicker("BTC_USDT").unwrap(); Log!("Call", i + 1, "Ticker:", ticker.Last); } }c++// C++ is not supported yet -
Multiple functions sharing a rate limit quota:
javascriptfunction main() { // GetTicker and GetDepth share the rate limit quota, with a combined maximum of 10 calls per second exchange.IO("rate", "GetTicker,GetDepth", 10, "1s") for (var i = 0; i < 20; i++) { if (i % 2 == 0) { Log("Ticker:", exchange.GetTicker("BTC_USDT")) } else { Log("Depth:", exchange.GetDepth("BTC_USDT")) } } }pythondef main(): exchange.IO("rate", "GetTicker,GetDepth", 10, "1s") for i in range(20): if i % 2 == 0: Log("Ticker:", exchange.GetTicker("BTC_USDT")) else: Log("Depth:", exchange.GetDepth("BTC_USDT"))rustfn main() { // GetTicker and GetDepth share the rate limit quota, with a combined maximum of 10 calls per second let _ = exchange.IO(("rate", "GetTicker,GetDepth", 10, "1s")); for i in 0..20 { if i % 2 == 0 { Log!("Ticker:", exchange.GetTicker("BTC_USDT")); } else { Log!("Depth:", exchange.GetDepth("BTC_USDT")); } } }c++// C++ is not supported yet -
Use a wildcard to uniformly limit the call frequency of all APIs:
javascriptfunction main() { exchange.IO("rate", "*", 100, "1m") for (var i = 0; i < 10; i++) { exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") exchange.GetAccount() Log("Round", i+1, "completed") Sleep(1000) } }pythondef main(): exchange.IO("rate", "*", 100, "1m") for i in range(10): exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") exchange.GetAccount() Log("Round", i+1, "completed") Sleep(1000)rustfn main() { let _ = exchange.IO(("rate", "*", 100, "1m")); for i in 0..10 { let _ = exchange.GetTicker("BTC_USDT"); let _ = exchange.GetDepth("BTC_USDT"); let _ = exchange.GetAccount(); Log!("Round", i + 1, "completed"); Sleep(1000); } }c++// C++ is not supported yet -
quota mode - strict rate limiting aligned to time windows:
javascriptfunction main() { exchange.IO("quota", "GetTicker", 3, "1s") for (var i = 0; i < 10; i++) { var ticker = exchange.GetTicker("BTC_USDT") if (ticker) { Log(_D(), "Ticker:", ticker.Last) } else { Log(_D(), "Quota exceeded, waiting for next window") } Sleep(100) } }pythondef main(): exchange.IO("quota", "GetTicker", 3, "1s") for i in range(10): ticker = exchange.GetTicker("BTC_USDT") if ticker: Log(_D(), "Ticker:", ticker["Last"]) else: Log(_D(), "Quota exceeded, waiting for next window") Sleep(100)rustfn main() { let _ = exchange.IO(("quota", "GetTicker", 3, "1s")); for _i in 0..10 { match exchange.GetTicker("BTC_USDT") { Ok(ticker) => Log!(_D(None), "Ticker:", ticker.Last), Err(_) => Log!(_D(None), "Quota exceeded, waiting for next window"), } Sleep(100); } }c++// C++ not supported yet -
quota mode - intraday quota, resets daily at the specified time:
javascriptfunction main() { exchange.IO("quota", "GetTicker", 1000, "@0815") var count = 0 while (true) { var ticker = exchange.GetTicker("BTC_USDT") if (ticker) { count++ Log("Call count:", count, "Ticker:", ticker.Last) } else { Log("Daily quota exceeded, waiting for reset at 08:15") Sleep(60000) // Wait 1 minute } Sleep(1000) } }pythondef main(): exchange.IO("quota", "GetTicker", 1000, "@0815") count = 0 while True: ticker = exchange.GetTicker("BTC_USDT") if ticker: count += 1 Log("Call count:", count, "Ticker:", ticker["Last"]) else: Log("Daily quota exceeded, waiting for reset at 08:15") Sleep(60000) # Wait 1 minute Sleep(1000)rustfn main() { let _ = exchange.IO(("quota", "GetTicker", 1000, "@0815")); let mut count = 0; loop { match exchange.GetTicker("BTC_USDT") { Ok(ticker) => { count += 1; Log!("Call count:", count, "Ticker:", ticker.Last); } Err(_) => { Log!("Daily quota exceeded, waiting for reset at 08:15"); Sleep(60000); // Wait 1 minute } } Sleep(1000); } }c++// C++ not supported yet -
Combining multiple rate-limiting rules:
javascriptfunction main() { exchange.IO("rate", "GetTicker", 10, "1s") // GetTicker 10 times per second exchange.IO("rate", "GetDepth", 5, "1s") // GetDepth 5 times per second exchange.IO("rate", "CreateOrder", 2, "1s") // CreateOrder 2 times per second exchange.IO("quota", "*", 1000, "@0000") // All APIs reset daily at 00:00, cap of 1000 calls Log("Rate limits configured successfully") for (var i = 0; i < 5; i++) { exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") Sleep(200) } }pythondef main(): exchange.IO("rate", "GetTicker", 10, "1s") # GetTicker 10 times per second exchange.IO("rate", "GetDepth", 5, "1s") # GetDepth 5 times per second exchange.IO("rate", "CreateOrder", 2, "1s") # CreateOrder 2 times per second exchange.IO("quota", "*", 1000, "@0000") # All APIs reset daily at 00:00, cap of 1000 calls Log("Rate limits configured successfully") for i in range(5): exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") Sleep(200)rustfn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s")); // GetTicker 10 times per second let _ = exchange.IO(("rate", "GetDepth", 5, "1s")); // GetDepth 5 times per second let _ = exchange.IO(("rate", "CreateOrder", 2, "1s")); // CreateOrder 2 times per second let _ = exchange.IO(("quota", "*", 1000, "@0000")); // All APIs reset daily at 00:00, cap of 1000 calls Log!("Rate limits configured successfully"); for _i in 0..5 { let _ = exchange.GetTicker("BTC_USDT"); let _ = exchange.GetDepth("BTC_USDT"); Sleep(200); } }c++// C++ is not supported yet
Returns
| Type | Description |
string / number / bool / object / array / any | The |
Arguments
| Name | Type | Required | Description |
k | string | Yes | Call type identifier. Different values correspond to different functions; please refer to the descriptions in each section below for details. |
arg | string / number / bool / object / array / any | Yes | Extended parameters. Different parameters need to be passed in according to the different |
See Also
Remarks
I. Directly Calling Exchange APIs ("api" mode)
javascript
exchange.IO("api", httpMethod, resource, params, raw)
Used to call the exchange's native API endpoints that are not wrapped by FMZ. FMZ automatically handles signature verification; you only need to fill in the request parameters.
| Parameter | Type | Required | Description |
|---|---|---|---|
| httpMethod | string | Yes | GET, POST, etc. |
| resource | string | Yes | Request path or full URL |
| params | string | No | Request parameters in URL-encoded format |
| raw | string | No | Raw request body (JSON, etc.) |
Returns a null value on failure, and this mode is only supported in live trading.
II. Switching Trading Pairs at Runtime ("currency" mode)
javascript
exchange.IO("currency", "ETH_USDT")
Used to dynamically switch trading pairs at runtime. The trading pair format is uppercase letters separated by an underscore. This instruction is equivalent to exchange.SetCurrency.
In backtesting mode, only spot is supported, and you can only switch to a trading pair with the same quote currency. After switching trading pairs for futures, you need to call
exchange.SetContractType()again.
III. Switching the Base Address ("base" / "mbase" mode)
-
"base": Switches the base address of the trading interface, equivalent toexchange.SetBase(). -
"mbase": Switches the base address of the market data interface, suitable for exchanges that use different domain names for market data and trading.
IV. Common Trading Mode Instructions
The following instructions are common across multiple exchanges. For the specific support of each exchange, please refer to the description in Section V.
| Instruction | Parameter | Function |
|---|---|---|
simulate | bool | Simulated trading (true) / Live trading (false) |
cross | bool | Cross margin (true) / Isolated margin (false) |
dual | bool | Hedge mode (true) / One-way mode (false) |
unified | bool | Unified account (true) / Standard account (false) |
trade_margin | none | Switch to isolated margin mode |
trade_super_margin | none | Switch to cross margin mode |
trade_normal | none | Switch back to normal spot mode |
selfTradePreventionMode | string | Self-Trade Prevention (STP) mode |
V. Exchange-Specific IO Commands
All exchanges support the "api" and "currency" commands; only the exchange-specific commands are listed below.
Spot Exchanges
Binance
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to isolated margin mode |
trade_super_margin | None | Switch to cross margin mode |
trade_normal | None | Switch back to normal spot mode |
unified | bool | Unified account mode |
selfTradePreventionMode | string | Self-trade prevention; options: EXPIRE_TAKER/EXPIRE_MAKER/EXPIRE_BOTH/NONE |
OKX
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Switch between demo and live trading |
trade_margin | None | Isolated margin (tdMode=isolated) |
trade_super_margin | None | Cross margin (tdMode=cross) |
trade_normal | None | Switch back to normal spot mode |
tdMode | string | Directly set the trading mode; cross must be used in portfolio margin mode |
Huobi
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to isolated margin mode |
trade_super_margin | None | Switch to cross margin mode |
trade_normal | None | Switch back to normal spot mode |
Bybit
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to margin mode |
trade_normal | None | Switch back to normal spot mode |
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to isolated margin mode |
trade_super_margin | None | Switch to cross margin mode |
trade_normal | None | Switch back to normal spot mode |
unified | bool | Unified account mode |
Bitget
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Switch between demo and live trading |
CoinEx
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to margin mode |
trade_normal | None | Switch back to normal mode |
WOO
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to margin mode |
trade_normal | None | Switch back to normal mode |
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to margin mode |
trade_normal | None | Switch back to normal mode |
AscendEx
| Command | Parameter | Description |
|---|---|---|
trade_margin | None | Switch to margin mode |
trade_normal | None | Switch back to normal mode |
Gemini
| Command | Parameter | Description |
|---|---|---|
subAccount | string | Set the sub-account name |
Poloniex
| Command | Parameter | Description |
|---|---|---|
accountId | string | Set the account ID |
Bitfinex
| Command | Parameter | Description |
|---|---|---|
version | None | Get the current API version number |
Backpack
| Command | Parameter | Description |
|---|---|---|
selfTradePreventionMode | string | Self-trade prevention; options: Allow/RejectTaker/RejectMaker/RejectBoth/Ban |
Hyperliquid (Spot)
| Command | Parameter | Description |
|---|---|---|
source | "a"/"b" | Switch the API data source |
vaultAddress | string | Set the vault address; pass an empty string to disable |
walletAddress | string | Set the wallet address |
expiresAfter | number | Order expiration time (milliseconds); set to 0 to disable |
Futures Exchanges
Futures_Binance (Binance Futures)
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
unified | bool | Unified account (uses papi.binance.com after switching) |
selfTradePreventionMode | string | Self-trade prevention; options: EXPIRE_TAKER/EXPIRE_MAKER/EXPIRE_BOTH/NONE |
extend_key | string | Set extended fields in the API response (comma-separated) |
Futures_OKX (OKX Futures)
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Switch between demo and live trading |
cross | bool | Cross/isolated margin; defaults to cross |
dual | bool | Hedge (long_short_mode)/one-way (net_mode) position mode |
Futures_HuobiDM (Huobi Futures)
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin; defaults to isolated. Only supported for XXX_USDT perpetual swaps (swap) |
dual | bool | Hedge (dual_side)/one-way (single_side) position mode |
unified | bool | Unified account mode |
signHost | string | Set the API signature Host address; pass an empty string to disable |
Futures_Bybit
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
Futures_KuCoin
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_GateIO
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
unified | bool | Unified account mode |
Futures_Bitget
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Switch between demo and live trading |
cross | bool | Cross (crossed)/isolated (isolated) margin |
dual | bool | Hedge (hedge_mode)/one-way (one_way_mode) position mode |
Futures_MEXC
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_BitMEX
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_CoinEx
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_WOO
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
Futures_Kraken
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin (only supported for multi-collateral accounts) |
Futures_Aevo
| Command | Parameter | Description |
|---|---|---|
signingKey | string | Set the signing key and return the public key. Must be obtained from the exchange's API Key page; note that it is time-sensitive |
Futures_Hyperliquid
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
source | "a"/"b" | Switch the API data source |
vaultAddress | string | Set the vault address; pass an empty string to disable |
walletAddress | string | Set the wallet address |
expiresAfter | number | Order expiration time (milliseconds); set to 0 to disable |
Futures_Deepcoin
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
merge | bool | Merge positions (true)/split positions (false) |
Futures_DigiFinex
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Switch between demo and live trading |
cross | bool | Cross/isolated margin |
Futures_ApolloX
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_Aster
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
Futures_CoinW
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_BitMart
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
Futures_Backpack
| Command | Parameter | Description |
|---|---|---|
selfTradePreventionMode | string | Self-trade prevention; options: Allow/RejectTaker/RejectMaker/RejectBoth/Ban |
Futures_Lighter
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
expiry | number | Order expiration timestamp (milliseconds); defaults to 29 days, minimum 4 minutes |
Futures_Crypto.com
| Command | Parameter | Description |
|---|---|---|
accountId | string | Set the trading account ID |
Futures_Bitfinex
| Command | Parameter | Description |
|---|---|---|
mbase | string | Set the market data API base address |
Futures_edgeX
| Command | Parameter | Description |
|---|---|---|
calcOrderHashAndSign | string(JSON) | Compute the order hash and sign it; returns the signature string |
Futures_Bibox
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin; defaults to cross |
Futures_Pionex
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin |
dual | bool | Hedge/one-way position mode |
Futures_Phemex
| Command | Parameter | Description |
|---|---|---|
dual | bool | Hedge/one-way position mode. Cross/isolated margin must be set on the exchange's web interface |
Futures_WooFi
Only the generic commands
"api"and"currency"are supported; no exchange-specific commands.
VI. Special Platform IO Commands
Polymarket (Prediction Market)
| Command | Parameters | Description |
|---|---|---|
nonce | [number] | Gets or sets the order's nonce value. Returns the current nonce when no parameter is passed; sets a new nonce when a value is passed |
proxyWalletAddress | None | Gets the proxy wallet address |
redeem | symbol, [wait] | Redeems settled positions (gas-free via Relayer). wait defaults to true, waiting for transaction confirmation; when wait is false, returns {"transactionID": "..."} immediately |
merge | symbol, [amount], [wait] | Merges and redeems YES+NO tokens into USDC (gas-free via Relayer). When amount is 0 or not passed, automatically takes the smaller position size of the two outcomes. wait defaults to true, waiting for transaction confirmation |
l2_credentials | None | Gets L2 authentication information, returns {"apiKey":"","secret":"","passphrase":""}, used for scenarios such as WebSocket connections |
batchOrders | array | Batch order placement; the parameter is an array of order objects, each object containing symbol, side, price, amount fields, as well as an optional option field |
Web3 (Blockchain)
| Command | Parameters | Description |
|---|---|---|
abi | contract address, ABI string | Registers a contract ABI |
address | [private key] | Gets the wallet address |
encode / pack | type, data... | ABI-encodes data |
encodePacked | type, data... | ABI tightly-packed encodes data |
hash | param 1-4 | Computes the hash value |
decode / unpack | type, data... | ABI-decodes data |
key | string | Switches the private key used for operations |
IB (Interactive Brokers)
| Command | Parameters | Description |
|---|---|---|
status | None | Gets the connection status |
time | None | Gets the IB server time |
reqId | None | Forces retrieval of a new request ID |
orderId | None | Gets the next available order ID |
ignore | string (array) | Ignores the specified error codes |
scan | string (JSON) | Executes the market scanner |
wait | [number] | Waits for a market data event, with an optional timeout in seconds |
debug | bool | Debug mode |
marketDataType | number | Market data type (1 real-time / 2 frozen / 3 delayed / 4 delayed frozen) |
Futu (Futu Securities)
| Command | Parameters | Description |
|---|---|---|
refresh | bool | Cache refresh; when caching is disabled, the rate limit is a maximum of 10 times per 30 seconds |
accounts | None | Gets the list of all accounts |
status | None | Gets the connection status |
lock | None | Locks trading |
unlock | None | Unlocks trading |
wait | None | Waits for a market data event |
VII. API Rate Limiting Control ("rate" / "quota" modes)
javascript
exchange.IO("rate", functionNames, maxCalls, period, [behavior])
exchange.IO("quota", functionNames, maxCalls, period, [behavior])
- rate: Smooth rate limiting, not strictly aligned to time windows.
- quota: Quota-based rate limiting, strictly aligned to time windows.
| Parameter | Type | Description |
|---|---|---|
| functionNames | string | Function names, separated by commas for multiple; * means all |
| maxCalls | number | Maximum number of calls within a single time period |
| period | string | Time period ("1s"/"1m"/"1h") or reset time point ("@0815") |
| behavior | string | Optional; "delay" means wait when the limit is exceeded, defaults to returning null |
The rate limiting of
Buy/Sellfollows the settings ofCreateOrder;Gofollows the settings of the actual concurrent function;IO/apionly takes effect forexchange.IO("api", ...).
exchange.Log
The exchange.Log() function is used to output order placement and cancellation logs in the log column area. When this function is called, it does not actually place an order; it is only used to output and record trading logs.
exchange.Log(orderType, price, amount)
exchange.Log(orderType, price, amount, ...args)Examples
Using exchange.Log(orderType, price, amount) allows you to perform live order-following tests and simulated order placement, and it can also assist in recording order information.
The most common use case is: accessing the exchange's conditional order creation interface through the exchange.IO function, but calling the exchange.IO() function does not output trading log information in the live log.
In this case, you can use the exchange.Log() function to supplement the log output in order to record the order information. The same applies to cancellation operations.
javascript
var id = 123
function main() {
// Order type buy, price 999, quantity 0.1
exchange.Log(LOG_TYPE_BUY, 999, 0.1)
// Cancel order
exchange.Log(LOG_TYPE_CANCEL, id)
}
python
id = 123
def main():
exchange.Log(LOG_TYPE_BUY, 999, 0.1)
exchange.Log(LOG_TYPE_CANCEL, id)
rust
fn main() {
let id = 123;
// Order type buy, price 999, quantity 0.1
exchange.Log(LOG_TYPE_BUY, 999, 0.1);
// Cancel order; when orderType is LOG_TYPE_CANCEL, the price parameter is the order Id to be canceled (in Rust the amount parameter is required and can be passed as 0)
exchange.Log(LOG_TYPE_CANCEL, id, 0);
}
c++
void main() {
auto id = 123;
exchange.Log(LOG_TYPE_BUY, 999, 0.1);
exchange.Log(LOG_TYPE_CANCEL, id);
}Arguments
| Name | Type | Required | Description |
orderType | number | Yes | The |
price | number | Yes | The |
amount | number | Yes | The |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | An extension parameter used to output additional information to this log entry. Multiple |
See Also
Remarks
When the orderType parameter is LOG_TYPE_CANCEL, the price parameter represents the order Id to be canceled, which is used to print the cancellation log when canceling an order by directly calling the exchange.IO() function.
The exchange.Log() function is a member function of the exchange exchange object, which is distinct from the global function Log.
exchange.Encode
The exchange.Encode() function is used to perform signature and encryption computations.
exchange.Encode(algo, inputFormat, outputFormat, data)
exchange.Encode(algo, inputFormat, outputFormat, data, keyFormat, key)Examples
Example of BitMEX position change push (wss protocol):
javascript
function main() {
var APIKEY = "your Access Key(Bitmex API ID)"
var expires = parseInt(Date.now() / 1000) + 10
var signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + expires, "hex", "{{secretkey}}")
var client = Dial("wss://www.bitmex.com/realtime", 60)
var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"})
var pos = 0
client.write(auth)
client.write('{"op": "subscribe", "args": "position"}')
while (true) {
var bitmexData = JSON.parse(client.read())
if(bitmexData.table == 'position' && pos != parseInt(bitmexData.data[0].currentQty)){
Log('position change', pos, parseInt(bitmexData.data[0].currentQty), '@')
pos = parseInt(bitmexData.data[0].currentQty)
}
}
}
python
import time
def main():
APIKEY = "your Access Key(Bitmex API ID)"
expires = int(time.time() + 10)
signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + expires, "hex", "{{secretkey}}")
client = Dial("wss://www.bitmex.com/realtime", 60)
auth = json.dumps({"args": [APIKEY, expires, signature], "op": "authKeyExpires"})
pos = 0
client.write(auth)
client.write('{"op": "subscribe", "args": "position"}')
while True:
bitmexData = json.loads(client.read())
if "table" in bitmexData and bitmexData["table"] == "position" and len(bitmexData["data"]) != 0 and pos != bitmexData["data"][0]["currentQty"]:
Log("position change", pos, bitmexData["data"][0]["currentQty"], "@")
pos = bitmexData["data"][0]["currentQty"]
c++
void main() {
auto APIKEY = "your Access Key(Bitmex API ID)";
auto expires = Unix() + 10;
auto signature = exchange.Encode("sha256", "string", "hex", str_format("GET/realtime%d", expires), "hex", "{{secretkey}}");
auto client = Dial("wss://www.bitmex.com/realtime", 60);
json auth = R"({"args": [], "op": "authKeyExpires"})"_json;
auth["args"].push_back(APIKEY);
auth["args"].push_back(expires);
auth["args"].push_back(signature);
auto pos = 0;
client.write(auth.dump());
client.write("{\"op\": \"subscribe\", \"args\": \"position\"}");
while(true) {
auto bitmexData = json::parse(client.read());
if(bitmexData["table"] == "position" && bitmexData["data"][0].find("currentQty") != bitmexData["data"][0].end() && pos != bitmexData["data"][0]["currentQty"]) {
Log("Test");
Log("position change", pos, bitmexData["data"][0]["currentQty"], "@");
pos = bitmexData["data"][0]["currentQty"];
}
}
}Returns
| Type | Description |
string | The |
Arguments
| Name | Type | Required | Description |
algo | string | Yes | The It supports the following settings: "raw" (no algorithm), "sign", "signTx", "md4", "md5", "sha256", "sha512", "sha1", "keccak256", "sha3.224", "sha3.256", "sha3.384", "sha3.512", "sha3.keccak256", "sha3.keccak512", "sha512.384", "sha512.256", "sha512.224", "ripemd160", "blake2b.256", "blake2b.512", "blake2s.128", "blake2s.256". The The |
inputFormat | string | Yes | Used to specify the data format of the |
outputFormat | string | Yes | Used to specify the output data format. The |
data | string | Yes | The |
keyFormat | string | No | Used to specify the data format of the |
key | string | No | The |
See Also
Remarks
Only live trading supports calling the exchange.Encode() function. The reference methods "{{accesskey}}" and "{{secretkey}}" are only valid when calling the exchange.Encode() function.
exchange.Go
Multi-threaded asynchronous support function that can convert the operations of all supported functions into asynchronous concurrent execution.
exchange.Go(method)
exchange.Go(method, ...args)Examples
-
exchange.Go()function usage example. When checking forundefined, you must usetypeof(xx) === "undefined", becausenull == undefinedholds true in JavaScript.javascriptfunction main(){ // The following four operations execute concurrently in asynchronous multi-threaded mode; they take no 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 result of the asynchronous ticker retrieval var ticker = a.wait() // Returns the depth data; it may also return null if the retrieval fails var depth = b.wait() // Returns the order ID with a 1-second timeout; returns undefined on timeout. If the previous wait timed out, this object can continue calling wait var orderId = c.wait(1000) if(typeof(orderId) == "undefined") { // Timed out, retrieve again orderId = c.wait() } var records = d.wait() }pythondef 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()rustfn main() { // In Rust, exchange.Go uses a typed form: use the Go:: method token to specify the concurrent function; pass () for no arguments and a tuple for arguments // The following four operations execute concurrently in asynchronous multi-threaded mode; they take no time and return immediately let a = exchange.Go(Go::GetTicker, ()); let b = exchange.Go(Go::GetDepth, ()); // There is no Buy token in Rust; it is equivalent to CreateOrder, where the first argument "" indicates the current trading pair let c = exchange.Go(Go::CreateOrder, ("", "buy", 1000, 0.1)); let d = exchange.Go(Go::GetRecords, (PERIOD_H1,)); // Call the wait method to wait for the result of the asynchronous ticker retrieval; wait(0) blocks until the concurrent thread finishes running (corresponding to the parameterless wait() in JS) let ticker = a.wait(0); // Returns the depth data; it may also return Err if the retrieval fails let depth = b.wait(0); // Returns the order ID with a 1-second timeout; returns Err on timeout. If the previous wait timed out, this object can continue calling wait // Note: Err may also indicate that the order placement itself failed (indistinguishable from a timeout); in this case, calling wait again will return Err and log the error message let mut orderId = c.wait(1000); if orderId.is_err() { // Timed out, retrieve again orderId = c.wait(0); } let records = d.wait(0); }c++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); } -
Calling the
wait()method on a released concurrent object will raise an error:javascriptfunction main() { var d = exchange.Go("GetRecords", PERIOD_H1) // Wait for the K-line data results to return var records = d.wait() // Calling wait again here on an asynchronous operation that has already been waited on and finished will return null and log an error message var ret = d.wait() }pythondef main(): d = exchange.Go("GetRecords", PERIOD_H1) records, ok = d.wait() ret, ok = d.wait()rustfn main() { // In Rust, exchange.Go uses a typed syntax: specify the concurrent function via the Go:: method token let d = exchange.Go(Go::GetRecords, (PERIOD_H1,)); // Wait for the K-line data results to return; wait(0) blocks until execution completes (equivalent to JS's parameterless wait()) let records = d.wait(0); // Calling wait again here on an asynchronous operation that has already been waited on and finished will return Err and log an error message let ret = d.wait(0); }c++void main() { auto d = exchange.Go("GetRecords", PERIOD_H1); Records records; d.wait(records); Records ret; d.wait(ret); } -
Concurrently retrieve market data from multiple exchanges:
javascriptfunction 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: "Market Data", cols: ["Index", "Name", "Last Price"], rows: [] } for(var i = 0; i < arrTicker.length; i++) { tbl.rows.push([i, arrName[i], arrTicker[i].Last]) } LogStatus(_D(), "Total time for concurrent ticker retrieval:", endTS - beginTS, "ms", "\n", "`" + JSON.stringify(tbl) + "`") Sleep(500) } }pythonimport 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": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [] } for i in range(len(arrTicker)): tbl["rows"].append([i, arrName[i], arrTicker[i]["Last"]]) LogStatus(_D(), "Total time for concurrent ticker retrieval:", endTS - beginTS, "seconds", "\n", "`" + json.dumps(tbl) + "`") Sleep(500)rustfn main() { loop { let beginTS = UnixNano() / 1000000; let mut arrRoutine = Vec::new(); let mut arrTicker = Vec::new(); let mut arrName = Vec::new(); for e in exchanges.iter() { // In Rust, exchange.Go is a typed form; the token is Go::GetTicker arrRoutine.push(e.Go(Go::GetTicker, ())); arrName.push(e.GetName()); } // On failure, record None as a placeholder to stay index-aligned with arrName for r in arrRoutine.iter() { arrTicker.push(r.wait(0).ok()); } let endTS = UnixNano() / 1000000; // Rust has no built-in JSON serialization; use format! to assemble the table's JSON text let mut rows = String::new(); for i in 0..arrTicker.len() { if let Some(ticker) = &arrTicker[i] { if !rows.is_empty() { rows.push(','); } rows += &format!(r#"[{}, "{}", {}]"#, i, arrName[i], ticker.Last); } } let tbl = format!(r#"{{"type": "table", "title": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [{}]}}"#, rows); LogStatus!(_D(None), "Total time for concurrent ticker retrieval:", endTS - beginTS, "ms", "\n", format!("`{}`", tbl)); Sleep(500); } }c++void main() { while(true) { int length = exchanges.size(); auto beginTS = UnixNano() / 1000000; vector<Ticker> arrTicker(length); vector<string> arrName(length); // Note: run the exchanges[n].Go function once for each exchange object you add. This example requires adding four exchange objects; adjust as needed auto r0 = exchanges[0].Go("GetTicker"); auto r1 = exchanges[1].Go("GetTicker"); auto r2 = exchanges[2].Go("GetTicker"); auto r3 = exchanges[3].Go("GetTicker"); vector<GoObj*> arrRoutine = {&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": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [] })"_json; for(int i = 0; i < length; i++) { json arr = R"(["", "", ""])"_json; arr[0] = str_format("%d", i); arr[1] = arrName[i]; arr[2] = str_format("%f", arrTicker[i].Last); tbl["rows"].push_back(arr); } LogStatus(_D(), "Total time for concurrent ticker retrieval:", str_format("%d", endTS - beginTS), "ms", "\n", "`" + tbl.dump() + "`"); Sleep(500); } } -
Concurrently call the
exchange.IO("api", ...)function:javascriptfunction main() { /* Test the OKX futures order placement endpoint 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 time:", endTS - beginTS, "ms") }pythonimport 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 time:", endTS - beginTS, "seconds")rustfn main() { /* Test the OKX futures order placement endpoint POST /api/v5/trade/order */ let beginTS = UnixNano() / 1000000; // Rust does not support JSON serialization, so construct the parameters directly using a raw string let param = r#"{"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}"#; // In Rust, exchange.Go uses a typed form: the token is Go::IO, and the parameters are passed as a tuple let ret1 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let ret2 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let ret3 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let id1 = ret1.wait(0); let id2 = ret2.wait(0); let id3 = ret3.wait(0); let endTS = UnixNano() / 1000000; Log!("id1:", id1); Log!("id2:", id2); Log!("id3:", id3); Log!("Concurrent order time:", endTS - beginTS, "ms"); }c++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 time:", endTS - beginTS, "ms"); } -
Testing the automatic release mechanism
javascriptfunction main() { var counter = 0 var arr = [] // Variables used to test persistently referencing concurrent objects var symbols = ["BTC_USDT", "ETH_USDT", "SOL_USDT", "LTC_USDT", "EOS_USDT"] while (true) { var arrRoutine = [] for (var symbol of symbols) { var r = exchange.Go("GetTicker", symbol) arrRoutine.push(r) // Record the concurrent object, used to call the r.wait() function to get the result; cleared every loop iteration // arr.push(r) // If this line is used, the runtime will persistently reference the concurrent objects, preventing them from being automatically released; when the number of concurrent tasks exceeds 2000, it will report an error: ```InternalError: too many routine wait, max is 2000```. counter++ } // Iterate over arrRoutine and call r.wait() to get the results LogStatus(_D(), "routine number:", counter) Sleep(50) } }rustfn main() { let mut counter = 0; let mut arr: Vec<TypedRoutine<Go::GetTicker>> = Vec::new(); // Variables used to test persistently referencing concurrent objects let symbols = ["BTC_USDT", "ETH_USDT", "SOL_USDT", "LTC_USDT", "EOS_USDT"]; loop { let mut arrRoutine = Vec::new(); for symbol in symbols { // In Rust, exchange.Go uses a typed form, with the token being Go::GetTicker let r = exchange.Go(Go::GetTicker, (symbol,)); arrRoutine.push(r); // Record the concurrent object, used to call the r.wait(0) function to get the result; cleared every loop iteration // arr.push(r); // If this line is used, the runtime will persistently reference the concurrent objects, preventing them from being automatically released; when the number of concurrent tasks exceeds 2000, it will report an error: InternalError: too many routine wait, max is 2000. counter += 1; } // Iterate over arrRoutine and call r.wait(0) to get the results LogStatus!(_D(None), "routine number:", counter); Sleep(50); } }
Returns
| Type | Description |
object | The |
Arguments
| Name | Type | Required | Description |
method | string | Yes | The |
arg | string / number / bool / object / array / function / any (any type supported by the platform) | No | The parameters of the concurrent execution function. The |
See Also
Mail_Go HttpQuery_Go EventLoop exchange.IO (API rate limiting control)
Remarks
This function only creates multi-threaded execution tasks when running in live trading. Backtesting does not support multi-threaded concurrent execution of tasks (it can be used in backtesting, but is still executed sequentially).
After the exchange.Go() function returns an object, you can call its wait() function through that object to obtain the data returned by the thread. When the concurrent multi-threaded tasks have finished executing and the related variables are no longer referenced, the underlying system will automatically handle resource reclamation.
The wait() method supports a timeout parameter:
-
Do not set the timeout parameter, i.e.
wait(), or set the timeout parameter to 0, i.e.wait(0). In this case, thewait()function will block and wait until the concurrent thread finishes running, and return the execution result of the concurrent thread. -
Set the timeout parameter to -1, i.e.
wait(-1). In this case, thewait()function will return immediately. The return value differs across programming languages; for details, please refer to the call examples in this section. -
Set a specific timeout parameter, i.e.
wait(300). In this case, thewait()function will wait at most 300 milliseconds before returning.
Although the underlying system has an automatic reclamation mechanism, if the related variables are continuously referenced, the concurrent threads will not be released. When the number of concurrent threads exceeds 2000, an error will be reported: "too many routine wait, max is 2000".
Supported functions: GetTicker, GetDepth, GetTrades, GetRecords, GetAccount, GetOrders, GetOrder, CancelOrder, Buy, Sell, GetPositions, IO, etc. When these functions are called concurrently, they are all executed based on the current exchange exchange object.
The difference between the Python language and the JavaScript language is that in Python, the wait() function of a concurrent object returns two values: the first is the result returned by the asynchronous API call, and the second indicates whether the asynchronous call is completed.
python
def main():
d = exchange.Go("GetRecords", PERIOD_D1)
# ok is guaranteed to return True, unless the strategy is stopped
ret, ok = d.wait()
# If the wait times out, or you wait on an instance that has already finished, ok returns False
ret, ok = d.wait(100)