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 member functions (methods) of the exchange object is only related to exchange, which will not be repeated in subsequent documentation.
exchange.Buy(price, amount)
exchange.Buy(price, amount, ...args)Examples
-
The order ID 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)c++void main() { auto id = exchange.Buy(100, 1); Log("id:", id); } -
When placing orders for cryptocurrency futures contracts, you must ensure the trading direction is set correctly. If the trading direction does not match the trading function, an error will occur:
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 short direction exchange.SetDirection("sell") // Place buy order, will error, short can only sell var id = exchange.Buy(50, 1) // Set long direction exchange.SetDirection("buy") // Place sell order, will error, long can only buy var id2 = exchange.Sell(60, 1) // Set close long direction exchange.SetDirection("closebuy") // Place buy order, will error, close long can only sell var id3 = exchange.Buy(-1, 1) // Set close short direction exchange.SetDirection("closesell") // Place sell order, will error, close 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)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 buy order function main() { // Place market buy order, buy ETH worth 0.1 BTC (quote currency) exchange.Buy(-1, 0.1) }pythondef main(): exchange.Buy(-1, 0.1)c++void main() { exchange.Buy(-1, 0.1); }
Returns
| Type | Description |
string / null | Returns the order Id on successful order placement, returns null on failure. 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 | Extended parameters that can output additional information to this order log. Multiple |
See Also
exchange.Sell exchange.SetContractType exchange.SetDirection exchange.IO (API rate limiting control Buy function is affected by CreateOrder rate limit settings)
Remarks
When placing orders for futures contracts, you must ensure the trading direction is set correctly. An error will be reported if the trading direction does not match the trading function. Unless otherwise specified, the order quantity for cryptocurrency futures contract exchanges is in number of contracts.
Setting the price parameter to -1 is used to place market orders, which requires the exchange's order interface to support market orders. For cryptocurrency spot market orders, when placing buy orders, the order quantity parameter amount is the amount in quote currency. For cryptocurrency futures contract market orders, the order quantity parameter amount is in number of contracts. In live trading, a few cryptocurrency exchanges do not support market order interfaces. For some spot exchanges, the order quantity for market buy orders is in base currency. Please refer to the Exchange Special Instructions in the "User Guide" for details.
If using an older version of the docker, the return value order Id of the exchange.Buy() function may differ from the return value order Id described in the current documentation.
Note that the following three exchanges have special order interfaces. For spot market buy orders, the order quantity is in coins, not in 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 ID 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)c++void main() { auto id = exchange.Sell(100, 1); Log("id:", id); } -
When placing orders for cryptocurrency futures contracts, you must ensure the trading direction is set correctly. If the trading direction does not match the trading function, an error will occur:
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 short direction exchange.SetDirection("sell") // Place buy order, will error, short can only sell var id = exchange.Buy(50, 1) // Set long direction exchange.SetDirection("buy") // Place sell order, will error, long can only buy var id2 = exchange.Sell(60, 1) // Set close long direction exchange.SetDirection("closebuy") // Place buy order, will error, close long can only sell var id3 = exchange.Buy(-1, 1) // Set close short direction exchange.SetDirection("closesell") // Place sell order, will error, close 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)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 sell order function main() { // Note: Place market sell order, sell 0.2 ETH exchange.Sell(-1, 0.2) }pythondef main(): exchange.Sell(-1, 0.2)c++void main() { exchange.Sell(-1, 0.2); }
Returns
| Type | Description |
string / null | Returns the order Id on successful order placement, returns null on failed order placement. 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 | Extended parameters that can output additional information to this order log entry. Multiple |
See Also
exchange.Buy exchange.SetContractType exchange.SetDirection exchange.IO (API rate limiting control Sell function is affected by CreateOrder rate limit settings)
Remarks
When placing orders for futures contracts, ensure the trading direction is set correctly. An error will occur if the trading direction does not match the trading function. Unless otherwise specified, the order quantity for cryptocurrency futures contract exchanges is in number of contracts.
Setting the price parameter to -1 places a market order, which requires the exchange's order interface to support market orders. For cryptocurrency spot market orders, when placing a sell order, the order quantity parameter amount is denominated in the trading currency. For cryptocurrency futures contract market orders, the order quantity parameter amount is denominated in number of contracts. In live trading, a few cryptocurrency exchanges do not support market order interfaces.
If using an older version of the docker, the return value order Id from the exchange.Sell() function may differ from the return value order Id described in the current documentation.
exchange.CreateOrder
The exchange.CreateOrder() function is used to place an order.
exchange.CreateOrder(symbol, side, price, amount)
exchange.CreateOrder(symbol, side, price, amount, ...args)Examples
-
Spot exchange objects and futures exchange objects call the
exchange.CreateOrder()function to place orders.javascriptfunction main() { var id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) // Spot exchange object places order for BTC_USDT spot trading pair // var id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) // Futures exchange object places order for BTC USDT-margined perpetual contract Log("Order Id:", id) }pythondef main(): id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) # Spot exchange object places order for BTC_USDT spot trading pair # id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) # Futures exchange object places order for BTC 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 order for BTC_USDT spot trading pair // auto id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01); // Futures exchange object places order for BTC USDT-margined perpetual contract Log("Order Id:", id); } -
Place orders using additional parameters (option) to pass exchange-specific parameters.
javascriptfunction main() { // Pass 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 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))c++void main() { // Pass 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 if the order is placed successfully, returns null value if the order fails. The When calling the |
Arguments
| Name | Type | Required | Description |
symbol | string | Yes | The parameter When calling the When calling the When calling the |
side | string | Yes | The parameter For spot exchange objects, the optional values for the For futures exchange objects, the optional values for the Supports additional parameters (option): Additional parameters can be passed through the For example: Additional parameters are used to pass exchange-specific parameters (such as order type, time-in-force rules, etc.), and the specific supported parameters depend on the exchange API. |
price | number | Yes | The parameter |
amount | number | Yes | The parameter |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | Extended parameters, can output additional information to this order log, the |
See Also
Remarks
Supports passing additional parameters (option) through the side parameter to pass exchange-specific parameters. The additional parameters need to be merged with 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\"}".
Different exchanges support different option parameters. Please refer to the exchange API documentation for specific supported parameters. Common parameters include: order type (type), time in force (timeInForce), activation price (activationPrice), callback rate (callbackRate), etc.
When using the option parameter, the price and amount parameters still need to be provided. If certain parameters in the exchange API have already been passed through option, these basic parameters may be overridden by the corresponding parameters in option. The specific behavior depends on the exchange API implementation.
exchange.CancelOrder
The exchange.CancelOrder() function is used to cancel an order. The Id attribute of the FMZ platform's order Order structure consists of the exchange product code and the exchange's original order ID, separated by an English comma. For example, the Id attribute format for an order of the spot trading pair ETH_USDT on the OKX exchange is: ETH-USDT,1547130415509278720.
When calling the exchange.CancelOrder() function to cancel an order, the orderId parameter passed in should be consistent with the Id attribute 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)c++void main() { auto id = exchange.Sell(99999, 1); exchange.CancelOrder(id); } -
In FMZ's API functions that can generate log output, such as
Log(),exchange.Buy(),exchange.CancelOrder(), etc., additional output parameters can be appended after the required parameters. For example:exchange.CancelOrder(orders[i].Id, orders[i]), this way when canceling the order with Idorders[i].Id, it will also output the order information, 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)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 |
arg | string / number / bool / object / array / any (any type supported by the platform) | No | Extended parameters that can output additional information to this cancel order log. Multiple |
See Also
Remarks
If using an older version of the docker, the orderId parameter of the exchange.CancelOrder() function may differ from the orderId described in the current documentation.
exchange.GetOrder
The exchange.GetOrder() function is used to get order information.
exchange.GetOrder(orderId)Examples
javascript
function main(){
var id = exchange.Sell(1000, 1)
// The parameter id is the order number, you need to fill in the order number 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"])
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 |
| Query order details by 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 returned Order structure is the average execution price. Some exchanges do not support this field, and it is set to 0 when not supported.
If 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 get unfilled orders.
exchange.GetOrders()
exchange.GetOrders(symbol)Examples
-
Using spot exchange objects to operate on multiple different trading pairs, placing buy orders at half the current price, then querying pending order information.
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) + "`") // 打印输出一次信息后返回,防止后续回测时订单成交,影响数据观察 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) + "`") returnc++/*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 futures exchange object to place orders for multiple trading pairs and contract codes. Set order prices far from the order book counterparty prices to keep orders in unfilled status, and query 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) + "`") // 打印输出一次信息后返回,防止后续回测时订单成交,影响数据观察 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) + "`") returnc++/*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)); // Order订单结构中的Id属性类型为TId,使用FMZ平台内置的C++函数to_string进行编码 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, pass theSymbolparameter to specify the order data for the trading pair or contract code to be queried.javascriptfunction main() { var orders = exchange.GetOrders("BTC_USDT") // 现货品种举例 // var orders = exchange.GetOrders("BTC_USDT.swap") // 期货品种举例 Log("orders:", orders) }pythondef main(): orders = exchange.GetOrders("BTC_USDT") # 现货品种举例 # orders = exchange.GetOrders("BTC_USDT.swap") # 期货品种举例 Log("orders:", orders)c++void main() { auto orders = exchange.GetOrders("BTC_USDT"); // 现货品种举例 // auto orders = exchange.GetOrders("BTC_USDT.swap"); // 期货品种举例 Log("orders:", orders); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The For spot exchange objects, when the For futures exchange objects, when the |
See Also
Remarks
Summary of symbol parameter usage scenarios in the GetOrders function:
| Exchange Object Category | symbol Parameter | Query Scope | Notes |
|---|---|---|---|
| Spot | No symbol parameter | Query all spot trading pairs | In all usage scenarios, if the exchange API does not support it, an error will be reported and null value returned, not repeated hereafter |
| Spot | Specify trading variety, symbol parameter: "BTC_USDT" | Query the specified BTC_USDT trading pair | For spot exchange objects, the symbol parameter format is: "BTC_USDT" |
| Futures | No symbol parameter | Query all trading varieties within the current trading pair and contract code dimension | Assuming 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 trading variety, symbol parameter: "BTC_USDT.swap" | Query the specified BTC USDT-margined perpetual contract | For futures exchange objects, the symbol parameter format is: a combination of trading pair and contract code defined by the FMZ platform, separated by the character "." |
| Futures | Specify trading variety range, symbol parameter: "USDT.swap" | Query all USDT-margined perpetual contracts | - |
| Futures exchanges supporting options | No symbol parameter | Query all option contracts within the current trading pair dimension | Assuming the current trading pair is BTC_USDT and the contract is set to option contracts, for example Binance option contract: BTC-240108-40000-C |
| Futures exchanges supporting options | Specify specific trading variety | Query the specified option contract | For example, for Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C |
| Futures exchanges supporting options | Specify trading variety range, symbol parameter: "USDT.option" | Query all USDT-margined option contracts | - |
Summary of futures exchange object query dimension ranges in the GetOrders function:
| symbol Parameter | Request Scope Definition | Notes |
|---|---|---|
| USDT.swap | USDT-margined perpetual contract range. | For dimensions not supported by the exchange API interface, calling will report an error and return null value. |
| 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 | Multi-collateral delivery contract range. | Futures_Kraken exchange |
| USD.swap_pf | Multi-collateral perpetual contract range. | Futures_Kraken exchange |
When the account represented by the exchange object exchange has no pending orders (active orders in unfilled status) within the query scope or specified trading variety, calling this function returns an empty array, i.e.: [].
The following exchanges require a symbol parameter when querying current unfilled orders. When calling the GetOrders function with these exchanges, if no symbol parameter is passed, only the unfilled orders of the current variety are requested, not all varieties' unfilled orders (because the exchange API 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
The exchange.GetHistoryOrders() function is used to get historical orders for the current trading pair or contract, and supports specifying specific trading instruments.
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)
c++
void main() {
auto historyOrders = exchange.GetHistoryOrders();
Log(historyOrders);
}Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The If querying option contract order data, set the |
since | number | No | The |
limit | number | No | The |
See Also
Remarks
-
When
symbol,since, andlimitparameters are not specified, it defaults to querying historical orders for the current trading pair or contract. It queries historical orders within a certain range closest to the current time, with the query range determined by the single query range of the exchange API. -
When the
symbolparameter is specified, it queries historical orders for the specified trading instrument. -
When the
sinceparameter is specified, it queries from thesincetimestamp towards the current time. -
When the
limitparameter is specified, it returns after querying the sufficient number of entries. -
This function only supports exchanges that provide historical order query interfaces.
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
exchange.CreateConditionOrder() function is used to create a conditional order. A conditional order is an order type that automatically executes 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 TP order: When BTC_USDT price rises to 65000, sell 0.01 BTC at price 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 market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id) }pythondef main(): # Create TP order: When BTC_USDT price rises to 65000, sell 0.01 BTC at price 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 market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id)c++void main() { // Create TP order: When BTC_USDT price rises to 65000, sell 0.01 BTC at price 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): Automatically sell when the price drops to the stop loss price.
javascriptfunction main() { // Create SL order: When 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 means market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id) }pythondef main(): # Create SL order: When 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 means market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id)c++void main() { // Create SL order: When 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 OCO order: Set take-profit and stop-loss simultaneously. When either one is triggered, the other is automatically canceled.
javascriptfunction main() { // Create 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 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)c++void main() { // Create 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 condition order using additional parameters (option) to pass exchange-specific parameters.
javascriptfunction main() { // Pass option parameter using 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 option parameter using 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))c++void main() { // Pass option parameter using 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 | Returns the conditional order ID when the conditional order is created successfully, returns null value when creation fails. The conditional order ID format is similar to regular order ID, consisting of the exchange instrument code and the exchange's original conditional order ID, separated by a comma. |
Arguments
| Name | Type | Required | Description |
symbol | string | Yes | The parameter When calling the When calling the When calling the |
side | string | Yes | The parameter For spot exchange objects, the optional values for the For futures exchange objects, the optional values for the Supports additional parameters (option): Additional parameters can be passed through the For example: Additional parameters are used to pass exchange-specific parameters (such as order type, time-in-force rules, etc.), and the specific supported parameters depend on the exchange API. |
amount | number | Yes | The parameter |
condition | object | Yes | The parameter
|
arg | string / number / bool / object / array / any (any type supported by the platform) | No | Extended parameters, can output additional information to the log of this conditional order. Multiple |
See Also
Condition exchange.CancelConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders exchange.ModifyConditionOrder
Remarks
Support for conditional orders depends on the specific exchange; some exchanges may not support conditional order functionality.
Conditional orders do not occupy account funds before being triggered; funds are only occupied when the order is actually placed after triggering.
Different exchanges may have varying levels of support and specific parameters for conditional orders. Please refer to the corresponding exchange's API documentation before use.
Supports passing additional parameters (option) through the side parameter for exchange-specific parameters. Additional parameters need to be merged with 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\"}".
Different exchanges support different option parameters; 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), etc.
When using option parameters, the amount and condition parameters still need to be provided. If certain parameters in the exchange API have been passed through option, these basic parameters may be overridden by the corresponding parameters in option; the specific behavior depends on the exchange API implementation.
exchange.ModifyOrder
The exchange.ModifyOrder() function is used to modify existing regular orders, allowing modification of order price and quantity. Supports modifying other order attributes through additional parameters (depending on exchange API support).
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 original order information var order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) // Modify order price and quantity var newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) // Query modified order information var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel 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 original order information order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) # Modify order price and quantity newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) # Query modified order information newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel order 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 original order information auto order = exchange.GetOrder(id); Log("Original Order Info:", order); Sleep(1000); // Modify order price and quantity auto newId = exchange.ModifyOrder(id, "buy", 77, 2); Log("Modified Order ID:", newId); Sleep(2000); // Query modified order information auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel order exchange.CancelOrder(newId); } -
Use additional parameters (option) to modify the order's price matching 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 order and set price matching mode to QUEUE_20 // Pass additional parameters (JSON format) through 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 modified order information var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel 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 order and set price matching mode to QUEUE_20 # Pass additional parameters (JSON format) through 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 modified order information newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel order 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 order and set price matching mode to QUEUE_20 // Pass additional parameters (JSON format) through 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 modified order information auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel order exchange.CancelOrder(newId); }
Returns
| Type | Description |
string / null | Returns the order ID when order modification is successful, returns null when modification fails. The returned order ID may be the same as or different from the original order ID, depending on the exchange API implementation. Some exchanges return a new order ID after order modification, 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 optional values for the For futures exchange objects, the optional values for the Supports additional parameters (option): Additional parameters can be passed through the For example: Additional parameters are used to modify other order attributes (such as price matching mode, etc.), and the specific supported parameters 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 will update the returned 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 parameter validity according to exchange interface rules and will submit parameters directly to the exchange API. When invalid parameters are passed (such as price or quantity being -1), the parameters may be ignored by the exchange, and the order maintains its original attributes unchanged.
Supports passing additional parameters (option) through the side parameter to modify other order attributes. Additional parameters need to be merged with the side parameter in the format "side;{JSON object}" (recommended) or "side;key=value" (URL encoding format). For example, to modify price matching mode: "buy;{\"priceMatch\":\"QUEUE_20\"}".
For market order modification of regular orders, you need to check specifically whether the exchange API supports it. Some exchanges do not support market order modification operations.
When modifying orders, other order attributes (such as order type, position mode, account mode, leverage, order validity rules, etc.) usually retain the original order settings. If you need to modify these attributes, you can pass them through additional parameters (option), provided the exchange API supports it.
Some exchange APIs may convert orders to market orders when price parameters are not received (price is -1 or null). For spot market buy orders, note that the order quantity unit may be amount rather than coin quantity.
Support for order modification functionality depends on the specific exchange. Some exchanges may not support order modification functionality or only support modification of certain parameters. Please consult the corresponding exchange's API documentation before use.
exchange.ModifyConditionOrder
The exchange.ModifyConditionOrder() function is used to modify an existing conditional order, allowing modification of the order quantity, trigger conditions, and execution price. It supports modifying other attributes of the conditional order through additional parameters (depending on exchange API support).
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 original conditional order info 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 modified conditional order info 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 original conditional order info 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 modified conditional order info newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) # Cancel the conditional order 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 original conditional order info 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 modified conditional order info auto newOrder = exchange.GetConditionOrder(newId); Log("Modified Condition Order Info:", newOrder); // Cancel the conditional order exchange.CancelConditionOrder(newId); } -
Use additional parameters (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 // Pass additional parameters (JSON format) through the side parameter 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 # Pass additional parameters (JSON format) through the side parameter 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)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 // Pass additional parameters (JSON format) through the side parameter 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 | Returns the conditional order ID when modification is successful, returns null value when modification fails. The returned conditional order ID may be the same as or different from the original conditional order ID, depending on the exchange API implementation. Some exchanges return a new conditional order ID after modifying a conditional order, while others keep the conditional order ID unchanged. |
Arguments
| Name | Type | Required | Description |
orderId | string | Yes | The parameter |
side | string | Yes | The parameter For spot exchange objects, the optional values for the For futures exchange objects, the optional values for the Supports additional parameters (option): Additional parameters can be passed through the For example: Additional parameters are used to modify other attributes of the conditional order (such as trigger price type, etc.), and the specific supported parameters depend on the exchange API. |
amount | number | Yes | The parameter |
condition | object | Yes | The parameter
|
See Also
Condition exchange.CreateConditionOrder exchange.CancelConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders
Remarks
The conditional order ID returned by the exchange.ModifyConditionOrder() function may behave differently 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 parameter validity according to exchange interface rules, but submits parameters directly to the exchange API. When invalid parameters are passed (such as quantity of -1), the parameters may be ignored by the exchange, and the conditional order retains its original attributes.
Supports passing additional parameters (option) through the side parameter to modify other attributes of the conditional order. 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 check whether the exchange API supports it. Setting TpOrderPrice or SlOrderPrice to -1 in the condition parameter indicates a market order.
When modifying a conditional order, other attributes of the conditional order (such as condition type, position mode, account mode, leverage, etc.) usually retain the original conditional order settings. If you need to modify these attributes, you can pass them through additional parameters (option), provided that the exchange API supports it.
You can modify the trigger price type through additional parameters, for example, changing the trigger price type from last price (last) to index price (index) or mark price (mark). The specific parameter names and support depend on the exchange API documentation.
Support for the modify conditional order function depends on the specific exchange. Some exchanges may not support the modify conditional order function or may only support modification of certain parameters. Please refer to the corresponding exchange's API documentation before use.
exchange.CancelConditionOrder
The exchange.CancelConditionOrder() function is used to cancel a conditional order. The conditional order ID format is similar to regular order IDs, consisting of the exchange instrument code and the exchange's original conditional order ID, separated by a comma.
When calling the exchange.CancelConditionOrder() function to cancel a conditional order, the conditionOrderId parameter passed should match the Id property 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)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 and output condition order information.
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)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 | Extended parameters that can output additional information to the cancel conditional order log. Multiple |
See Also
exchange.CreateConditionOrder exchange.GetConditionOrder exchange.GetConditionOrders exchange.ModifyConditionOrder
Remarks
The return value of the exchange.CancelConditionOrder() function only indicates whether the request was sent successfully or failed. To determine whether the exchange has actually canceled the conditional order, you can call the exchange.GetConditionOrders() function to confirm.
Only untriggered conditional orders can be canceled. Conditional orders that have been triggered and converted to regular orders cannot be canceled through this function.
exchange.GetConditionOrder
The exchange.GetConditionOrder() function is used to get conditional order information.
exchange.GetConditionOrder(conditionOrderId)Examples
javascript
function main(){
// Create 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 ID, enter the ID 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 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"])
c++
void main() {
// Create 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 |
| Queries conditional order details by conditional order ID. Returns an 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 trigger conditions, trigger price, order status, etc.
Conditional order statuses include: not triggered, triggered, canceled, etc. The specific status values depend on the exchange.
exchange.GetConditionOrders
The exchange.GetConditionOrders() function is used to get unfulfilled conditional orders (conditional orders that have not been triggered or canceled).
exchange.GetConditionOrders()
exchange.GetConditionOrders(symbol)Examples
-
Use a spot exchange object to create multiple condition orders and then query 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])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 pending condition orders for a specific trading pair.
javascriptfunction main() { // Query pending condition orders for BTC_USDT trading pair var orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders) }pythondef main(): # Query pending condition orders for BTC_USDT trading pair orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders)c++void main() { // Query pending condition orders for BTC_USDT trading pair auto orders = exchange.GetConditionOrders("BTC_USDT"); Log("BTC_USDT pending condition orders:", orders); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The parameter |
See Also
Remarks
Summary of usage scenarios for the symbol parameter in the GetConditionOrders function:
| Exchange Object Category | symbol Parameter | Query Range | Remarks |
|---|---|---|---|
| Spot | No symbol parameter passed | Query all spot trading pairs | For all calling scenarios, if the exchange interface does not support it, an error will be reported and null will be returned, which will not be repeated |
| Spot | Specify trading instrument, symbol parameter: "BTC_USDT" | Query the specified BTC_USDT trading pair | For spot exchange objects, the symbol parameter format is: "BTC_USDT" |
| Futures | No symbol parameter passed | Query all trading instruments within the current trading pair and contract code dimension range | If the current trading pair is BTC_USDT and the contract code is swap, it queries all USDT-margined perpetual contracts. Equivalent to calling GetConditionOrders("USDT.swap") |
| Futures | Specify trading instrument, symbol parameter: "BTC_USDT.swap" | Query the specified BTC USDT-margined perpetual contract | For futures exchange objects, the symbol parameter format is: a combination of trading pair and contract code defined by the FMZ platform, separated by the character "." |
| Futures | Specify trading instrument range, symbol parameter: "USDT.swap" | Query all USDT-margined perpetual contracts | - |
| Futures exchanges supporting options | No symbol parameter passed | Query all option contracts within the current trading pair dimension range | If the current trading pair is BTC_USDT and the contract is set to an option contract, e.g., Binance option contract: BTC-240108-40000-C |
| Futures exchanges supporting options | Specify specific trading instrument | Query the specified option contract | For example, for Binance Futures exchange, symbol parameter: BTC_USDT.BTC-240108-40000-C |
| Futures exchanges supporting options | Specify trading instrument range, symbol parameter: "USDT.option" | Query all USDT-margined option contracts | - |
Summary of query dimension ranges for futures exchange objects in the GetConditionOrders function:
| symbol Parameter | Request Range Definition | Remarks |
|---|---|---|
| USDT.swap | USDT-margined perpetual contract range | For dimensions not supported by the exchange API interface, an error will be reported and null will be 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 unfulfilled conditional orders within the query range or for the specified trading instrument, calling this function returns 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 get historical conditional orders (including triggered, cancelled, and expired conditional orders) for the current trading pair and contract; supports specifying specific trading instruments.
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, results are returned 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 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 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"])c++void main() { auto historyConditionOrders = exchange.GetHistoryConditionOrders(); Log("Historical condition orders count:", historyConditionOrders.size()); // Iterate and display, orders are sorted in ascending order by 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 historical conditional orders for a specified trading pair with a limit on the number of results.
javascriptfunction main() { // Query the last 10 historical conditional orders for BTC_USDT trading pair var historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders) }pythondef main(): # Query the last 10 historical conditional orders for BTC_USDT trading pair historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders)c++void main() { // Query the last 10 historical conditional orders for BTC_USDT trading pair auto historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10); Log("BTC_USDT historical condition orders:", historyConditionOrders); } -
Query historical conditional orders based on a specified time range.
javascriptfunction main() { // Query historical conditional orders starting from a 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 a 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)c++void main() { // Query historical conditional orders starting from a specified timestamp auto startTime = 1704067200000; // Timestamp for 2024-01-01 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 querying conditional order data for option contracts, set the |
since | number | No | The |
limit | number | No | The |
See Also
Remarks
-
When
symbol,since, andlimitparameters are not specified, it defaults to querying historical conditional orders for the current trading pair and contract. It queries historical conditional orders within a certain range from the current time, with the query range determined by the exchange API's single query range. -
When the
symbolparameter is specified, it queries historical conditional orders for the specified trading instrument. -
When the
sinceparameter is specified, it queries from thesincetimestamp towards the current time. -
When the
limitparameter is specified, it returns after querying enough entries. -
This function only supports exchanges that provide historical conditional order query interfaces.
Historical conditional orders include: triggered (converted to regular orders), cancelled, expired, and other status conditional orders.
The returned historical conditional order array is sorted in ascending order by order creation time (Time attribute), i.e., the earliest orders are at the front of the array and the latest orders are at the back.
Conditional order functionality support depends on the specific exchange; some exchanges may not support conditional order functionality or historical conditional order query functionality.
exchange.SetPrecision
The exchange.SetPrecision() function is used to set the price and order amount precision for the exchange exchange object. After setting, the system will automatically ignore the excess part of the data.
exchange.SetPrecision(pricePrecision, amountPrecision)Examples
javascript
function main(){
// 设置价格小数位精度为2位,品种下单量小数位精度为3位
exchange.SetPrecision(2, 3)
}
python
def main():
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 of the backtesting system will be handled automatically.
exchange.SetRate
Set the current exchange rate conversion ratio for the exchange object.
exchange.SetRate(rate)Examples
javascript
function main(){
Log(exchange.GetTicker())
// 设置汇率转换
exchange.SetRate(7)
Log(exchange.GetTicker())
// 设置为1,不转换
exchange.SetRate(1)
}
python
def main():
Log(exchange.GetTicker())
exchange.SetRate(7)
Log(exchange.GetTicker())
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
After setting the exchange rate value using the exchange.SetRate() function (for example, setting it to 7), all price information of the current exchange object (including market data, depth data, order prices, etc.) will be multiplied by the set exchange rate for conversion.
For example, if exchange is a USD-denominated exchange, after executing exchange.SetRate(7), all price data will be multiplied by 7, converting to prices approximately denominated in CNY.
exchange.IO
The exchange.IO() function is used to call other related interfaces of the exchange object.
exchange.IO(k, ...args)Examples
-
Using
"api"mode to call OKX futures batch order interface, passing JSON order data through 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 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)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 key-value in the
paramsparameter is a string, the parameter value needs to be wrapped with single quotes:javascriptvar amount = 1 var price = 10 var basecurrency = "ltc" function main () { // Note that amount.toString() and price.toString() have a ' character on both left and right sides 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)c++void main() { auto amount = 1.0; auto price = 10.0; auto basecurrency = "ltc"; string message = 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 full URLs: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)c++void main() { auto ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC"); Log(ret); } -
GET request without using 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)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 trading starts, the current trading pair of the exchange object is set to BTC_USDT, print the current trading pair ticker Log(exchange.GetTicker()) // Switch 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())c++void main() { Log(exchange.GetTicker()); exchange.IO("currency", "LTC_BTC"); Log(exchange.GetTicker()); } -
Switch exchange interface base address:
javascriptfunction main () { // exchanges[0] is the first exchange object added when creating the live trading exchanges[0].IO("base", "https://api.huobi.pro") }pythondef main(): exchanges[0].IO("base", "https://api.huobi.pro")c++void main() { exchanges[0].IO("base", "https://api.huobi.pro"); } -
Switch market interface 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")c++void main() { exchange.SetBase("https://api.bitfinex.com"); exchange.IO("mbase", "https://api-pub.bitfinex.com"); } -
Switch between 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)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)c++void main() { exchange.IO("dual", true); exchange.IO("dual", false); exchange.SetContractType("swap"); exchange.IO("cross", true); exchange.IO("cross", false); } -
Switch 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)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")c++void main() { exchange.IO("selfTradePreventionMode", "NONE"); } -
Futures_edgeX calculate order Hash and sign:
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)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 throttling - Limit GetTicker to a maximum of 10 calls per second, returns null when 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")c++// C++ is not supported currently -
Rate mode throttling - Use the
"delay"parameter to automatically wait when limit is exceeded instead of returning null: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"])c++// C++ is not supported currently -
Multiple functions sharing rate limit quota:
javascriptfunction main() { // GetTicker and GetDepth share the limit, 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"))c++// C++ is not supported currently -
Use wildcard to limit the frequency of all API calls:
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)c++// C++ is not supported currently -
quota mode - Strict time window aligned rate limiting:
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)c++// C++ is not supported currently -
quota mode - Daily quota, reset at specified time each day:
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)c++// C++ is not supported currently -
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, limited to 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, limited to 1000 calls Log("Rate limits configured successfully") for i in range(5): exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") Sleep(200)c++// C++ is not supported currently
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, see the sections below for details. |
arg | string / number / bool / object / array / any | Yes | Extended parameters, different parameters are passed according to different |
See Also
Remarks
I. Direct Exchange API Calls ("api" mode)
javascript
exchange.IO("api", httpMethod, resource, params, raw)
Call the exchange's unwrapped raw API interface. 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 | URL-encoded request parameters |
| raw | string | No | Raw request body (JSON, etc.) |
Returns null on failure. Only supported in live trading.
II. Runtime Trading Pair Switching ("currency" mode)
javascript
exchange.IO("currency", "ETH_USDT")
Dynamically switch trading pairs, format is uppercase with underscore separator. Equivalent to exchange.SetCurrency.
Backtesting only supports spot, and can only switch between trading pairs with the same quote currency. After switching futures, you need to call
exchange.SetContractType()again.
III. Switch Base Address ("base" / "mbase" mode)
"base": Switch trading interface base address, equivalent toexchange.SetBase()."mbase": Switch market data interface base address, applicable to exchanges that use different domains for market data and trading.
IV. General Trading Mode Commands
The following commands are common across multiple exchanges. For specific support, please refer to Section V for each exchange's documentation.
| Command | 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 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 | Demo/live trading switch |
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 trading mode, must use cross margin under 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 | Demo/live trading switch |
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 sub-account name |
Poloniex
| Command | Parameter | Description |
|---|---|---|
accountId | string | Set account ID |
Bitfinex
| Command | Parameter | Description |
|---|---|---|
version | None | Get 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 API data source |
vaultAddress | string | Set vault address, empty string to disable |
walletAddress | string | Set wallet address |
expiresAfter | number | Order expiration time (milliseconds), set to 0 to disable |
Futures Exchanges
Futures_Binance
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
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 API response extension fields (comma-separated) |
Futures_OKX
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Demo/live trading switch |
cross | bool | Cross/isolated margin mode, default cross |
dual | bool | Hedge (long_short_mode)/one-way (net_mode) position mode |
Futures_HuobiDM
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode, default isolated. Only XXX_USDT perpetual swaps supported |
dual | bool | Hedge (dual_side)/one-way (single_side) position mode |
unified | bool | Unified account mode |
signHost | string | Set API signature host address, empty string to disable |
Futures_Bybit
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
dual | bool | Hedge/one-way position mode |
Futures_KuCoin
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_GateIO
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
dual | bool | Hedge/one-way position mode |
unified | bool | Unified account mode |
Futures_Bitget
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Demo/live trading switch |
cross | bool | Cross (crossed)/isolated margin mode |
dual | bool | Hedge (hedge_mode)/one-way (one_way_mode) position mode |
Futures_MEXC
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_BitMEX
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_CoinEx
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_WOO
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
dual | bool | Hedge/one-way position mode |
Futures_Kraken
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode (only multi-collateral accounts supported) |
Futures_Aevo
| Command | Parameter | Description |
|---|---|---|
signingKey | string | Set signing key, returns public key. Must be obtained from exchange API KEY page, note expiration restrictions |
Futures_Hyperliquid
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
source | "a"/"b" | Switch API data source |
vaultAddress | string | Set vault address, empty string to disable |
walletAddress | string | Set wallet address |
expiresAfter | number | Order expiration time (milliseconds), set to 0 to disable |
Futures_Deepcoin
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
merge | bool | Merge positions (true)/split positions (false) |
Futures_DigiFinex
| Command | Parameter | Description |
|---|---|---|
simulate | bool | Demo/live trading switch |
cross | bool | Cross/isolated margin mode |
Futures_ApolloX
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_Aster
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
dual | bool | Hedge/one-way position mode |
Futures_CoinW
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
Futures_BitMart
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
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 mode |
expiry | number | Order expiration timestamp (milliseconds), default 29 days, minimum 4 minutes |
Futures_Crypto.com
| Command | Parameter | Description |
|---|---|---|
accountId | string | Set trading account ID |
Futures_Bitfinex
| Command | Parameter | Description |
|---|---|---|
mbase | string | Set market API base address |
Futures_edgeX
| Command | Parameter | Description |
|---|---|---|
calcOrderHashAndSign | string(JSON) | Calculate order hash and sign, returns signature string |
Futures_Bibox
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode, default cross |
Futures_Pionex
| Command | Parameter | Description |
|---|---|---|
cross | bool | Cross/isolated margin mode |
dual | bool | Hedge/one-way position mode |
Futures_Phemex
| Command | Parameter | Description |
|---|---|---|
dual | bool | Hedge/one-way position mode. Cross/isolated margin mode must be set on exchange web interface |
Futures_WooFi
Only supports generic commands
"api"and"currency", no exchange-specific commands.
VI. Special Platform IO Commands
Polymarket (Prediction Market)
| Command | Parameters | Description |
|---|---|---|
nonce | [number] | Get or set order nonce value. Returns current nonce without parameters, sets new nonce when a number is passed |
proxyWalletAddress | None | Get proxy wallet address |
redeem | symbol, [wait] | Redeem settled positions (Gas-free via Relayer), wait defaults to true to wait for transaction confirmation. When wait is false, immediately returns {"transactionID": "..."} |
merge | symbol, [amount], [wait] | Merge YES+NO tokens back to USDC (Gas-free via Relayer). When amount is 0 or not provided, automatically takes the smaller position of the two outcomes. wait defaults to true to wait for transaction confirmation |
l2_credentials | None | Get L2 authentication info, returns {"apiKey":"","secret":"","passphrase":""}, used for WebSocket connections or other scenarios |
batchOrders | array | Batch order placement, parameter is an array of order objects, each object contains symbol, side, price, amount fields, optional option field |
Web3 (Blockchain)
| Command | Parameters | Description |
|---|---|---|
abi | Contract address, ABI string | Register contract ABI |
address | [Private key] | Get wallet address |
encode / pack | Type, Data... | ABI encode data |
encodePacked | Type, Data... | ABI packed encode data |
hash | Param1-4 | Calculate hash value |
decode / unpack | Type, Data... | ABI decode data |
key | string | Switch private key used for operations |
IB (Interactive Brokers)
| Command | Parameters | Description |
|---|---|---|
status | None | Get connection status |
time | None | Get IB server time |
reqId | None | Force get new request ID |
orderId | None | Get next available order ID |
ignore | string(array) | Ignore specified error codes |
scan | string(JSON) | Execute market scanner |
wait | [number] | Wait for market data event, can set 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, after disabling cache the rate limit is max 10 times per 30 seconds |
accounts | None | Get all account list |
status | None | Get connection status |
lock | None | Lock trading |
unlock | None | Unlock trading |
wait | None | Wait for market data event |
VII. API Rate Limit Control ("rate" / "quota" Mode)
javascript
exchange.IO("rate", functionNames, maxCalls, period, [behavior])
exchange.IO("quota", functionNames, maxCalls, period, [behavior])
- rate: Smooth rate limiting, does not strictly align with time windows.
- quota: Quota rate limiting, strictly aligns with time windows.
| Parameter | Type | Description |
|---|---|---|
| functionNames | string | Function name, multiple functions separated by commas, * means all |
| maxCalls | number | Maximum number of calls within the time period |
| period | string | Time period ("1s"/"1m"/"1h") or reset time point ("@0815") |
| behavior | string | Optional, "delay" means wait when limit exceeded, defaults to returning null |
Rate limiting for
Buy/Sellfollows theCreateOrdersettings.Gofollows the settings of the actual concurrent function.IO/apionly applies toexchange.IO("api", ...).
exchange.Log
The exchange.Log() function is used to output order placement and cancellation logs in the log area. When called, it does not actually place orders, but only outputs and records trading logs.
exchange.Log(orderType, price, amount)
exchange.Log(orderType, price, amount, ...args)Examples
Using exchange.Log(orderType, price, amount) can be used for live trading copy testing and simulated order placement, which can help record order operations.
The most common use case is: using the exchange.IO function to access the exchange's conditional order creation interface, but using the exchange.IO() function does not output trading log information in the live trading log records.
In this case, you can use the exchange.Log() function to supplement the output logs to record order information, and the same applies to cancellation operations.
javascript
var id = 123
function main() {
// 下单类型买入,价格999,数量 0.1
exchange.Log(LOG_TYPE_BUY, 999, 0.1)
// 取消订单
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)
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 | Extended parameters that can output additional information to this log entry. Multiple |
See Also
Remarks
When the orderType parameter is LOG_TYPE_CANCEL, the price parameter is the order ID to be cancelled, used for printing cancellation logs when directly cancelling orders using the exchange.IO() function.
The exchange.Log() function is a member function of the exchange exchange object, distinct from the global function Log.
exchange.Encode
The exchange.Encode() function is used for signature encryption calculation.
exchange.Encode(algo, inputFormat, outputFormat, data)
exchange.Encode(algo, inputFormat, outputFormat, data, keyFormat, key)Examples
BitMEX Position Change Push Notification (WebSocket Protocol) Example:
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) {
bitmexData = 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", 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 Supported 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 used within the exchange.Encode() function.
exchange.Go
Multi-threaded asynchronous support function that converts all supported function operations to asynchronous concurrent execution.
exchange.Go(method)
exchange.Go(method, ...args)Examples
-
Example of using
exchange.Go()function. To check forundefined, you need to usetypeof(xx) === "undefined", because in JavaScript the comparisonnull == undefinedevaluates to true.javascriptfunction main(){ // The following four operations are executed asynchronously in concurrent multi-threads, they don't consume 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 wait method to wait for the asynchronous ticker result to return var ticker = a.wait() // Returns depth, it's possible to return null if fetching fails var depth = b.wait() // Returns order ID, with 1 second timeout limit, returns undefined on timeout, this object can continue to call wait if the previous wait timed out var orderId = c.wait(1000) if(typeof(orderId) == "undefined") { // Timeout, fetch 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()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 trigger an error:javascriptfunction main() { var d = exchange.Go("GetRecords", PERIOD_H1) // Wait for K-line result var records = d.wait() // Here wait is called on an async operation that has already been waited and completed, will return null and log error message var ret = d.wait() }pythondef main(): d = exchange.Go("GetRecords", PERIOD_H1) records, ok = d.wait() ret, ok = d.wait()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)c++void main() { while(true) { int length = exchanges.size(); auto beginTS = UnixNano() / 1000000; Ticker arrTicker[length] = {}; string arrName[length] = {}; // Note: Based on the number of exchange objects added, you need to execute the corresponding exchanges[n].Go function. This example requires adding four exchange objects, which can be modified according to actual needs auto r0 = exchanges[0].Go("GetTicker"); auto r1 = exchanges[1].Go("GetTicker"); auto r2 = exchanges[2].Go("GetTicker"); auto r3 = exchanges[3].Go("GetTicker"); GoObj *arrRoutine[length] = {&r0, &r1, &r2, &r3}; for(int i = 0; i < length; i++) { arrName[i] = exchanges[i].GetName(); } for(int i = 0; i < length; i++) { Ticker ticker; arrRoutine[i]->wait(ticker); arrTicker[i] = ticker; } auto endTS = UnixNano() / 1000000; json tbl = R"({ "type": "table", "title": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [] })"_json; for(int i = 0; i < length; i++) { json arr = R"(["", "", ""])"_json; arr[0] = format("%d", i); arr[1] = arrName[i]; arr[2] = format("%f", arrTicker[i].Last); tbl["rows"].push_back(arr); } LogStatus(_D(), "Total time for concurrent ticker retrieval:", format("%d", endTS - beginTS), "ms", "\n", "`" + tbl.dump() + "`"); Sleep(500); } } -
Concurrent calls to the
exchange.IO("api", ...)function:javascriptfunction main() { /* Test using OKX futures order placement interface POST /api/v5/trade/order */ var beginTS = new Date().getTime() var param = {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"} var ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var id1 = ret1.wait() var id2 = ret2.wait() var id3 = ret3.wait() var endTS = new Date().getTime() Log("id1:", id1) Log("id2:", id2) Log("id3:", id3) Log("Concurrent order 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")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 for automatic release mechanism
javascriptfunction main() { var counter = 0 var arr = [] // Used to test continuous reference of concurrent related variables 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 concurrent objects to call r.wait() function to get results, cleared each loop iteration // arr.push(r) // If this line of code is used, it will continuously reference concurrent objects at runtime and cannot be automatically released. When the number of concurrent operations exceeds 2000, an error will be reported: ```InternalError: too many routine wait, max is 2000```. counter++ } // Iterate through arrRoutine to call r.wait() LogStatus(_D(), "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 | Parameters for the concurrent execution function. There may be multiple |
See Also
Mail_Go HttpQuery_Go EventLoop exchange.IO (API Rate Limiting Control)
Remarks
This function only creates multi-threaded execution tasks during live trading. Backtesting does not support multi-threaded concurrent execution tasks (available in backtesting environment but still executes sequentially).
After the exchange.Go() function returns an object, call the wait() method of that object to get the data returned by the thread. When concurrent multi-threaded tasks are completed and related variables are no longer referenced, the system will automatically reclaim resources at the underlying level.
The wait() method supports timeout parameters:
-
Without setting a timeout parameter, i.e.,
wait(), or setting the timeout parameter to 0, i.e.,wait(0). Thewait()function will block and wait until the concurrent thread finishes running and returns the execution result of the concurrent thread. -
Setting the timeout parameter to -1, i.e.,
wait(-1). Thewait()function will return immediately. Return values differ between programming languages; please refer to the calling examples in this section for details. -
Setting a specific timeout parameter, such as
wait(300). Thewait()function will wait for a maximum of 300 milliseconds before returning.
Although the system has an automatic recycling mechanism at the underlying level, if related variables are continuously referenced, 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. These functions are executed based on the current exchange exchange object when called concurrently.
Differences between Python and JavaScript languages: In Python, the wait() function of the concurrent object returns two parameters. 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 will always return True unless the strategy is stopped
ret, ok = d.wait()
# If wait times out, or if waiting on an already finished instance, ok returns False
ret, ok = d.wait(100)