Type/to search
Built-in Functions
Global
Version
Sleep
IsVirtual
Mail
Mail_Go
SetErrorFilter
GetPid
GetLastError
GetCommand
GetMeta
Dial
HttpQuery
HttpQuery_Go
Encode
UnixNano
Unix
GetOS
MD5
DBExec
UUID
EventLoop
__Serve
_G
_D
_N
_C
_Cross
JSON.parse
JSON.stringify
SetChannelData
GetChannelData
Log
Market
Trade
Account
Futures
NetSettings
Threads
threading
Thread
getThread
mainThread
currentThread
Lock
Condition
Event
Dict
pending
Thread
ThreadLock
ThreadEvent
ThreadCondition
ThreadDict
Web3
TA
Talib
talib.CDL2CROWS
talib.CDL3BLACKCROWS
talib.CDL3INSIDE
talib.CDL3LINESTRIKE
talib.CDL3OUTSIDE
talib.CDL3STARSINSOUTH
talib.CDL3WHITESOLDIERS
talib.CDLABANDONEDBABY
talib.CDLADVANCEBLOCK
talib.CDLBELTHOLD
talib.CDLBREAKAWAY
talib.CDLCLOSINGMARUBOZU
talib.CDLCONCEALBABYSWALL
talib.CDLCOUNTERATTACK
talib.CDLDARKCLOUDCOVER
talib.CDLDOJI
talib.CDLDOJISTAR
talib.CDLDRAGONFLYDOJI
talib.CDLENGULFING
talib.CDLEVENINGDOJISTAR
talib.CDLEVENINGSTAR
talib.CDLGAPSIDESIDEWHITE
talib.CDLGRAVESTONEDOJI
talib.CDLHAMMER
talib.CDLHANGINGMAN
talib.CDLHARAMI
talib.CDLHARAMICROSS
talib.CDLHIGHWAVE
talib.CDLHIKKAKE
talib.CDLHIKKAKEMOD
talib.CDLHOMINGPIGEON
talib.CDLIDENTICAL3CROWS
talib.CDLINNECK
talib.CDLINVERTEDHAMMER
talib.CDLKICKING
talib.CDLKICKINGBYLENGTH
talib.CDLLADDERBOTTOM
talib.CDLLONGLEGGEDDOJI
talib.CDLLONGLINE
talib.CDLMARUBOZU
talib.CDLMATCHINGLOW
talib.CDLMATHOLD
talib.CDLMORNINGDOJISTAR
talib.CDLMORNINGSTAR
talib.CDLONNECK
talib.CDLPIERCING
talib.CDLRICKSHAWMAN
talib.CDLRISEFALL3METHODS
talib.CDLSEPARATINGLINES
talib.CDLSHOOTINGSTAR
talib.CDLSHORTLINE
talib.CDLSPINNINGTOP
talib.CDLSTALLEDPATTERN
talib.CDLSTICKSANDWICH
talib.CDLTAKURI
talib.CDLTASUKIGAP
talib.CDLTHRUSTING
talib.CDLTRISTAR
talib.CDLUNIQUE3RIVER
talib.CDLUPSIDEGAP2CROWS
talib.CDLXSIDEGAP3METHODS
talib.AD
talib.ADOSC
talib.OBV
talib.ACOS
talib.ASIN
talib.ATAN
talib.CEIL
talib.COS
talib.COSH
talib.EXP
talib.FLOOR
talib.LN
talib.LOG10
talib.SIN
talib.SINH
talib.SQRT
talib.TAN
talib.TANH
talib.MAX
talib.MAXINDEX
talib.MIN
talib.MININDEX
talib.MINMAX
talib.MINMAXINDEX
talib.SUM
talib.HT_DCPERIOD
talib.HT_DCPHASE
talib.HT_PHASOR
talib.HT_SINE
talib.HT_TRENDMODE
talib.ATR
talib.NATR
talib.TRANGE
talib.BBANDS
talib.DEMA
talib.EMA
talib.HT_TRENDLINE
talib.KAMA
talib.MA
talib.MAMA
talib.MIDPOINT
talib.MIDPRICE
talib.SAR
talib.SAREXT
talib.SMA
talib.T3
talib.TEMA
talib.TRIMA
talib.WMA
talib.LINEARREG
talib.LINEARREG_ANGLE
talib.LINEARREG_INTERCEPT
talib.LINEARREG_SLOPE
talib.STDDEV
talib.TSF
talib.VAR
talib.ADX
talib.ADXR
talib.APO
talib.AROON
talib.AROONOSC
talib.BOP
talib.CCI
talib.CMO
talib.DX
talib.MACD
talib.MACDEXT
talib.MACDFIX
talib.MFI
talib.MINUS_DI
talib.MINUS_DM
talib.MOM
talib.PLUS_DI
talib.PLUS_DM
talib.PPO
talib.ROC
talib.ROCP
talib.ROCR
talib.ROCR100
talib.RSI
talib.STOCH
talib.STOCHF
talib.STOCHRSI
talib.TRIX
talib.ULTOSC
talib.WILLR
talib.AVGPRICE
talib.MEDPRICE
talib.TYPPRICE
talib.WCLPRICE
OS
Structures
Built-in Variables

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.

    javascript
    function main() { var id = exchange.Buy(100, 1); Log("id:", id); }
    python
    def 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:

    log
    direction is sell, invalid order type Buy direction is buy, invalid order type Sell direction is closebuy, invalid order type Buy direction is closesell, invalid order type Sell
    javascript
    // The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set 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) }
    python
    def main(): exchange.Buy(-1, 0.1)
    c++
    void main() { exchange.Buy(-1, 0.1); }

Returns

TypeDescription

string / null

Returns the order Id on successful order placement, returns null on failure. The Id property of the FMZ platform's Order Order structure consists of the exchange symbol code and the exchange's original order Id, separated by an English comma. For example, the Id property format for an order of the spot trading pair ETH_USDT on OKX exchange is: ETH-USDT,1547130415509278720. When calling the exchange.Buy() function to place an order, the return value order Id is consistent with the Id property of the Order Order structure.

Arguments

NameTypeRequiredDescription

price

number

Yes

The price parameter is used to set the order price.

amount

number

Yes

The amount parameter is used to set the order quantity.

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 arg parameters can be passed.

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

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.

    javascript
    function main(){ var id = exchange.Sell(100, 1) Log("id:", id) }
    python
    def 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:

    log
    direction is sell, invalid order type Buy direction is buy, invalid order type Sell direction is closebuy, invalid order type Buy direction is closesell, invalid order type Sell
    javascript
    // The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set 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) }
    python
    def main(): exchange.Sell(-1, 0.2)
    c++
    void main() { exchange.Sell(-1, 0.2); }

Returns

TypeDescription

string / null

Returns the order Id on successful order placement, returns null on failed order placement. The Id property of the FMZ platform's Order structure consists of the exchange symbol code and the exchange's original order Id, separated by an English comma. For example, the Id property format for an order of the spot trading pair ETH_USDT on OKX exchange would be: ETH-USDT,1547130415509278720. When calling the exchange.Sell() function to place an order, the return value order Id is consistent with the Id property of the Order structure.

Arguments

NameTypeRequiredDescription

price

number

Yes

The price parameter is used to set the order price.

amount

number

Yes

The amount parameter is used to set the order quantity.

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 arg parameters can be passed.

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.

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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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)) }
    python
    import 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

TypeDescription

string / null value

Returns the order Id if the order is placed successfully, returns null value if the order fails. 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 a comma. For example, the Id attribute format of an OKX exchange spot trading pair ETH_USDT order is: ETH-USDT,1547130415509278720.

When calling the exchange.CreateOrder(symbol, side, price, amount) function to place an order, the return value order Id is consistent with the Id attribute of the order Order structure.

Arguments

NameTypeRequiredDescription

symbol

string

Yes

The parameter symbol is used to specify the specific trading pair or contract code for the order.

When calling the exchange.CreateOrder(symbol, side, price, amount) function to place an order, if exchange is a spot exchange object, and the order's quote currency is USDT and the base currency is BTC, then the parameter symbol is: "BTC_USDT", in the trading pair format defined by the FMZ platform.

When calling the exchange.CreateOrder(symbol, side, price, amount) function to place an order, if exchange is a futures exchange object, and the order is a BTC USDT-margined perpetual contract order, then the parameter symbol is: "BTC_USDT.swap", in the format of a combination of trading pair and contract code defined by the FMZ platform, separated by the character ".".

When calling the exchange.CreateOrder(symbol, side, price, amount) function to place an order, if exchange is a futures exchange object, and the order is a BTC USDT-margined options contract order, then the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance option BTC-240108-40000-C as an example), in the format of a combination of trading pair defined by the FMZ platform and the specific options contract code defined by the exchange, separated by the character ".".

side

string

Yes

The parameter side is used to specify the trading direction of the order.

For spot exchange objects, the optional values for the side parameter are: buy, sell. buy means buy, sell means sell.

For futures exchange objects, the optional values for the side parameter are: buy, closebuy, sell, closesell. buy means open long position, closebuy means close long position, sell means open short position, closesell means close short position.

Supports additional parameters (option): Additional parameters can be passed through the side parameter, in the format: "side;{JSON object}" or "side;key=value&key=value".

For example: 'buy;{"type":"TRAILING_STOP_MARKET","activationPrice":"2300"}' or "buy;type=TRAILING_STOP_MARKET&activationPrice=2300".

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 price is used to set the price of the order. When the price is -1, it indicates that the order is a market order.

amount

number

Yes

The parameter amount is used to set the order quantity. Note that when the order is a spot market buy order, the order quantity is the buy amount; for some spot exchanges, the market buy order quantity is the number of base currency, please refer to the Exchange Special Instructions in the "User Guide" for details. For futures exchange objects, when using the CreateOrder()/Buy()/Sell() functions to place orders, unless otherwise specified, the order quantity parameter amount is the number of contracts.

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 arg parameter can pass multiple values.

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.

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.

    javascript
    function main(){ var id = exchange.Sell(99999, 1) exchange.CancelOrder(id) }
    python
    def 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 Id orders[i].Id, it will also output the order information, i.e., the Order structure orders[i].

    javascript
    function 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) } }
    python
    def 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

TypeDescription

bool

The exchange.CancelOrder() function returns a true value (e.g., true) indicating that the cancel order request was sent successfully, and returns a false value (e.g., false) indicating that the cancel order request failed to send. The return value only represents whether the request was sent successfully or not. To determine whether the exchange has actually canceled the order, you can call exchange.GetOrders() to confirm.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

The orderId parameter is used to specify the order to be canceled.

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 arg parameters can be passed.

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.

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

TypeDescription

Order / null value

Query order details by order ID. Returns the Order structure on successful query, returns null value on failed query.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

The orderId parameter is used to specify the order to be queried. 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.GetOrder() function to query an order, the orderId parameter passed in is consistent with the Id attribute of the order Order structure.

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 NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetOrderZaif / Coincheck / Bitstamp--

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) + "`") return
    c++
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 0.01); } auto spotOrders = exchange.GetOrders(); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {spotOrders}; for (const auto& orders : arr) { json tbl = R"({ "type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back("Symbol"); arrJson.push_back("Id"); arrJson.push_back(order.Price); arrJson.push_back(order.Amount); arrJson.push_back(order.DealAmount); arrJson.push_back(order.AvgPrice); arrJson.push_back(order.Status); arrJson.push_back(order.Type); arrJson.push_back(order.Offset); arrJson.push_back(order.ContractType); tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); } LogStatus(_D(), "\n", "`" + tbls.dump() + "`"); return; }
  • Use 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) + "`") return
    c++
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 1); exchange.CreateOrder(symbol, "sell", t.Last * 2, 1); } auto defaultOrders = exchange.GetOrders(); auto swapOrders = exchange.GetOrders("USDT.swap"); auto futuresOrders = exchange.GetOrders("USDT.futures"); auto btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap"); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders}; std::string tblDesc[] = {"defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"}; for (int index = 0; index < arr.size(); index++) { auto orders = arr[index]; json tbl = R"({ "type": "table", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; tbl["title"] = tblDesc[index]; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back(order.Symbol); arrJson.push_back(to_string(order.Id)); // 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 the Symbol parameter to specify the order data for the trading pair or contract code to be queried.

    javascript
    function main() { var orders = exchange.GetOrders("BTC_USDT") // 现货品种举例 // var orders = exchange.GetOrders("BTC_USDT.swap") // 期货品种举例 Log("orders:", orders) }
    python
    def 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

TypeDescription

Order array / null value

The exchange.GetOrders() function returns an array of Order structures when data request is successful, and returns null value when data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

The symbol parameter is used to set the trading symbol or trading symbol range to be queried.

For spot exchange objects, when the symbol parameter is not passed, unfilled order data for all spot symbols will be requested.

For futures exchange objects, when the symbol parameter is not passed, unfilled order data for all symbols will be requested by default according to the dimension range of the current trading pair and contract code.

See Also

Remarks

Summary of symbol parameter usage scenarios in the GetOrders function:

Exchange Object Categorysymbol ParameterQuery ScopeNotes
SpotNo symbol parameterQuery all spot trading pairsIn all usage scenarios, if the exchange API does not support it, an error will be reported and null value returned, not repeated hereafter
SpotSpecify trading variety, symbol parameter: "BTC_USDT"Query the specified BTC_USDT trading pairFor spot exchange objects, the symbol parameter format is: "BTC_USDT"
FuturesNo symbol parameterQuery all trading varieties within the current trading pair and contract code dimensionAssuming 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")
FuturesSpecify trading variety, symbol parameter: "BTC_USDT.swap"Query the specified BTC USDT-margined perpetual contractFor 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 "."
FuturesSpecify trading variety range, symbol parameter: "USDT.swap"Query all USDT-margined perpetual contracts-
Futures exchanges supporting optionsNo symbol parameterQuery all option contracts within the current trading pair dimensionAssuming 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 optionsSpecify specific trading varietyQuery the specified option contractFor example, for Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C
Futures exchanges supporting optionsSpecify 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 ParameterRequest Scope DefinitionNotes
USDT.swapUSDT-margined perpetual contract range.For dimensions not supported by the exchange API interface, calling will report an error and return null value.
USDT.futuresUSDT-margined delivery contract range.-
USD.swapCoin-margined perpetual contract range.-
USD.futuresCoin-margined delivery contract range.-
USDT.optionUSDT-margined option contract range.-
USD.optionCoin-margined option contract range.-
USDT.futures_comboSpread combination contract range.Futures_Deribit exchange
USD.futures_ffMulti-collateral delivery contract range.Futures_Kraken exchange
USD.swap_pfMulti-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 NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetOrders--Futures_Bibox

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

TypeDescription

Order array / null

The exchange.GetHistoryOrders() function returns an array of Order structures when the data request is successful, and returns null when the data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

The symbol parameter is used to specify the trading instrument. Taking the BTC_USDT trading pair as an example, when exchange is a spot exchange object, the symbol parameter format is: BTC_USDT; if it is a futures exchange object, taking perpetual contracts as an example, the symbol parameter format is: BTC_USDT.swap.

If querying option contract order data, set the symbol parameter to "BTC_USDT.BTC-240108-40000-C" (using Binance option BTC-240108-40000-C as an example), the format is a combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character ".". When this parameter is not passed, it defaults to requesting order data for the currently set trading pair and contract code.

since

number

No

The since parameter is used to specify the starting timestamp for the query, in milliseconds.

limit

number

No

The limit parameter is used to specify the number of orders to query.

See Also

Remarks

  • When symbol, since, and limit parameters 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 symbol parameter is specified, it queries historical orders for the specified trading instrument.

  • When the since parameter is specified, it queries from the since timestamp towards the current time.

  • When the limit parameter 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 NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetHistoryOrdersZaif / Upbit / Coincheck / Bitstamp / Bithumb / BitFlyer / BigONEFutures_Bibox / Futures_ApolloX

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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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)) }
    python
    import 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

TypeDescription

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

NameTypeRequiredDescription

symbol

string

Yes

The parameter symbol is used to specify the specific trading pair or contract code for the conditional order.

When calling the exchange.CreateConditionOrder(symbol, side, amount, condition) function to place a conditional order, if exchange is a spot exchange object, and the order quote currency is USDT and the trading currency is BTC, then the parameter symbol is: "BTC_USDT", in the trading pair format defined by the FMZ platform.

When calling the exchange.CreateConditionOrder(symbol, side, amount, condition) function to place a conditional order, if exchange is a futures exchange object, and the order is a BTC USDT-margined perpetual contract order, then the parameter symbol is: "BTC_USDT.swap", in the format of a combination of trading pair and contract code defined by the FMZ platform, separated by the character ".".

When calling the exchange.CreateConditionOrder(symbol, side, amount, condition) function to place a conditional order, if exchange is a futures exchange object, and the order is a BTC USDT-margined options contract order, then the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance option BTC-240108-40000-C as an example), in the format of a combination of trading pair defined by the FMZ platform and the specific options contract code defined by the exchange, separated by the character ".".

side

string

Yes

The parameter side is used to specify the trading direction of the conditional order.

For spot exchange objects, the optional values for the side parameter are: buy, sell. buy means buy, sell means sell.

For futures exchange objects, the optional values for the side parameter are: buy, closebuy, sell, closesell. buy means open long position, closebuy means close long position, sell means open short position, closesell means close short position.

Supports additional parameters (option): Additional parameters can be passed through the side parameter, in the format: "side;{JSON object}" or "side;key=value&key=value".

For example: "buy;{\"type\":\"TRAILING_STOP_MARKET\",\"activatePrice\":\"300\"}" or "buy;type=TRAILING_STOP_MARKET&activatePrice=300".

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 amount is used to set the order quantity for the conditional order. Note that when the order is a spot market buy order, the order quantity is the purchase amount; for some spot exchanges, the market buy order quantity is the number of trading coins, please refer to the Exchange Special Instructions in the "User Guide" for details. For futures exchange objects, the order quantity parameter amount is always the number of contracts.

condition

object

Yes

The parameter condition is an object used to set the trigger conditions and execution price for the conditional order. The structure of this object refers to the Condition structure, containing the following properties:

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 arg parameters can be passed.

See Also

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.

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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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) }
    python
    import 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

TypeDescription

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

NameTypeRequiredDescription

orderId

string

Yes

The orderId parameter specifies the original order ID to be modified. The order ID format is consistent with the order ID returned by the exchange.CreateOrder function, composed of the exchange symbol code and the exchange's original order ID, separated by a comma. For example: "ETH-USDT,1547130415509278720".

side

string

Yes

The side parameter specifies the trading direction of the order.

For spot exchange objects, the optional values for the side parameter are: buy, sell. buy means buy, sell means sell.

For futures exchange objects, the optional values for the side parameter are: buy, closebuy, sell, closesell. buy means open long position, closebuy means close long position, sell means open short position, closesell means close short position.

Supports additional parameters (option): Additional parameters can be passed through the side parameter in the format: "side;{JSON object}" or "side;key=value&key=value".

For example: "buy;{\"priceMatch\":\"QUEUE_20\"}" or "buy;priceMatch=QUEUE_20".

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 price parameter sets the new price for the order. When the price is -1, it indicates no price modification, or it may be converted to a market order depending on the exchange API implementation.

amount

number

Yes

The amount parameter sets the new order quantity. When the quantity is -1, it indicates no quantity modification. Note that when the order is a spot market buy order, the order quantity is the purchase amount; for some spot exchanges, the market buy order quantity is the trading coin quantity.

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.

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.

    javascript
    function 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) }
    python
    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) # 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.

    javascript
    function 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) }
    python
    import 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

TypeDescription

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

NameTypeRequiredDescription

orderId

string

Yes

The parameter orderId is used to specify the original conditional order ID to be modified. The conditional order ID format is consistent with the conditional order ID returned by the exchange.CreateConditionOrder function, consisting of the exchange instrument code and the exchange's original conditional order ID, separated by a comma. For example: "SOL-USDT-SWAP,3196255845130256384".

side

string

Yes

The parameter side is used to specify the trading direction of the conditional order.

For spot exchange objects, the optional values for the side parameter are: buy, sell. buy means buy, sell means sell.

For futures exchange objects, the optional values for the side parameter are: buy, closebuy, sell, closesell. buy means open long position, closebuy means close long position, sell means open short position, closesell means close short position.

Supports additional parameters (option): Additional parameters can be passed through the side parameter in the format: "side;{JSON object}" or "side;key=value&key=value".

For example: "buy;{\"newTpTriggerPxType\":\"index\"}" or "buy;newTpTriggerPxType=index".

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 amount is used to set the new order quantity for the conditional order. When the quantity is -1, it means the quantity will not be modified. For futures exchange objects, the order quantity parameter amount is always in contract units.

condition

object

Yes

The parameter condition is an object used to set the new trigger conditions and execution price for the conditional order. The structure of this object refers to the Condition structure, containing the following attributes:

See Also

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.

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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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) } }
    python
    def 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

TypeDescription

bool

The exchange.CancelConditionOrder() function returns a truthy value (e.g., true) indicating that the cancel conditional order request was sent successfully, or returns a falsy value (e.g., false) indicating that the cancel conditional order request failed to send.

Arguments

NameTypeRequiredDescription

conditionOrderId

string

Yes

The conditionOrderId parameter is used to specify the conditional order to be canceled.

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 arg parameters can be passed.

See Also

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.

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

TypeDescription

Order / null value

Queries conditional order details by conditional order ID. Returns an Order structure on successful query, or null value on failure.

The returned Order structure contains a Condition field, which contains detailed configuration information of the conditional order (trigger price, execution price, condition type, etc.).

Arguments

NameTypeRequiredDescription

conditionOrderId

string

Yes

The conditionOrderId parameter is used to specify the conditional order to query. 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.

The conditionOrderId parameter passed when calling the exchange.GetConditionOrder() function should match the Id attribute of the conditional order structure.

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.

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.

    javascript
    function 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]) } }
    python
    def 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.

    javascript
    function main() { // Query pending condition orders for BTC_USDT trading pair var orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders) }
    python
    def 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

TypeDescription

Order array / null value

The exchange.GetConditionOrders() function returns an array of Order structures when the data request is successful, and returns null when the data request fails.
The returned Order structure contains the Condition field, which contains detailed configuration information of the conditional order (trigger price, execution price, condition type, etc.).

Arguments

NameTypeRequiredDescription

symbol

string

No

The parameter symbol is used to set the trading instrument or range of trading instruments to query.
For spot exchange objects, when the symbol parameter is not passed, it requests unfulfilled conditional order data for all spot instruments.
For futures exchange objects, when the symbol parameter is not passed, it requests unfulfilled conditional order data for all instruments within the dimension range of the current trading pair and contract code by default.

See Also

Remarks

Summary of usage scenarios for the symbol parameter in the GetConditionOrders function:

Exchange Object Categorysymbol ParameterQuery RangeRemarks
SpotNo symbol parameter passedQuery all spot trading pairsFor 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
SpotSpecify trading instrument, symbol parameter: "BTC_USDT"Query the specified BTC_USDT trading pairFor spot exchange objects, the symbol parameter format is: "BTC_USDT"
FuturesNo symbol parameter passedQuery all trading instruments within the current trading pair and contract code dimension rangeIf 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")
FuturesSpecify trading instrument, symbol parameter: "BTC_USDT.swap"Query the specified BTC USDT-margined perpetual contractFor 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 "."
FuturesSpecify trading instrument range, symbol parameter: "USDT.swap"Query all USDT-margined perpetual contracts-
Futures exchanges supporting optionsNo symbol parameter passedQuery all option contracts within the current trading pair dimension rangeIf 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 optionsSpecify specific trading instrumentQuery the specified option contractFor example, for Binance Futures exchange, symbol parameter: BTC_USDT.BTC-240108-40000-C
Futures exchanges supporting optionsSpecify 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 ParameterRequest Range DefinitionRemarks
USDT.swapUSDT-margined perpetual contract rangeFor dimensions not supported by the exchange API interface, an error will be reported and null will be returned when called
USDT.futuresUSDT-margined delivery contract range-
USD.swapCoin-margined perpetual contract range-
USD.futuresCoin-margined delivery contract range-
USDT.optionUSDT-margined option contract range-
USD.optionCoin-margined option contract range-
USDT.futures_comboSpread combination contract rangeFutures_Deribit exchange
USD.futures_ffMixed margin delivery contract rangeFutures_Kraken exchange
USD.swap_pfMixed margin perpetual contract rangeFutures_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.

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.

    javascript
    function 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) } }
    python
    def 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.

    javascript
    function 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) }
    python
    def 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.

    javascript
    function 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) }
    python
    def 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

TypeDescription

Order array / null

The exchange.GetHistoryConditionOrders() function returns an array of Order structures when data request is successful, and returns null when data request fails.

The returned Order structure contains a Condition field, which contains detailed configuration information for the conditional order (trigger price, execution price, condition type, etc.).

Arguments

NameTypeRequiredDescription

symbol

string

No

The symbol parameter is used to specify the trading instrument. Taking the BTC_USDT trading pair as an example, when exchange is a spot exchange object, the symbol parameter format is: BTC_USDT; if it is a futures exchange object, taking perpetual contracts as an example, the symbol parameter format is: BTC_USDT.swap.

If querying conditional order data for option contracts, set the symbol parameter to "BTC_USDT.BTC-240108-40000-C" (using Binance option BTC-240108-40000-C as an example), the format is a combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character ".". When this parameter is not passed, it defaults to requesting conditional order data for the currently set trading pair and contract code.

since

number

No

The since parameter is used to specify the starting timestamp for the query, in milliseconds.

limit

number

No

The limit parameter is used to specify the number of conditional orders to query.

See Also

Remarks

  • When symbol, since, and limit parameters 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 symbol parameter is specified, it queries historical conditional orders for the specified trading instrument.

  • When the since parameter is specified, it queries from the since timestamp towards the current time.

  • When the limit parameter 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.

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

NameTypeRequiredDescription

pricePrecision

number

Yes

The pricePrecision parameter is used to control the precision of price data.

amountPrecision

number

Yes

The amountPrecision parameter is used to control the precision of order amount data.

See Also

Remarks

The backtesting system does not support this function. The numerical precision of the backtesting system will be handled automatically.

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

NameTypeRequiredDescription

rate

number

Yes

The rate parameter is used to specify the exchange rate conversion ratio.

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.

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 the raw parameter:

    javascript
    function 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) }
    python
    import 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 params parameter is a string, the parameter value needs to be wrapped with single quotes:

    javascript
    var 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) }
    python
    amount = 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 resource parameter supports full URLs:

    javascript
    function main() { var ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC") Log(ret) }
    python
    def 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 raw parameter:

    javascript
    function main(){ var ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT") Log(ret) }
    python
    def 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:

    javascript
    function 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()) }
    python
    def 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:

    javascript
    function main () { // exchanges[0] is the first exchange object added when creating the live trading exchanges[0].IO("base", "https://api.huobi.pro") }
    python
    def 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):

    javascript
    function main() { exchange.SetBase("https://api.bitfinex.com") exchange.IO("mbase", "https://api-pub.bitfinex.com") }
    python
    def 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):

    javascript
    function main() { exchange.IO("simulate", true) // Switch to demo trading environment // ... trading logic ... exchange.IO("simulate", false) // Switch back to live trading environment }
    python
    def 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):

    javascript
    function 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 }
    python
    def 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):

    javascript
    function main() { exchange.IO("unified", true) // Switch to unified account mode exchange.IO("unified", false) // Switch to normal mode }
    python
    def 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):

    javascript
    function main() { // "NONE" means disable STP mode, other parameters: "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH" exchange.IO("selfTradePreventionMode", "NONE") }
    python
    def main(): exchange.IO("selfTradePreventionMode", "NONE")
    c++
    void main() { exchange.IO("selfTradePreventionMode", "NONE"); }
  • Futures_edgeX calculate order Hash and sign:

    javascript
    function 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) }
    python
    import 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:

    javascript
    function 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") } } }
    python
    def 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:

    javascript
    function 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) } }
    python
    def 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:

    javascript
    function 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")) } } }
    python
    def 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:

    javascript
    function 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) } }
    python
    def 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:

    javascript
    function 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) } }
    python
    def 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:

    javascript
    function 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) } }
    python
    def 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:

    javascript
    function 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) } }
    python
    def 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

TypeDescription

string / number / bool / object / array / any

The exchange.IO() function is used to call other interfaces of the exchange object. It returns the requested response data when the call is successful, and returns a null value when the call fails.

Arguments

NameTypeRequiredDescription

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 k values, the number and type of parameters are not fixed.

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.

ParameterTypeRequiredDescription
httpMethodstringYesGET, POST, etc.
resourcestringYesRequest path or full URL
paramsstringNoURL-encoded request parameters
rawstringNoRaw 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 to exchange.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.

CommandParameterFunction
simulateboolSimulated trading (true) / Live trading (false)
crossboolCross margin (true) / Isolated margin (false)
dualboolHedge mode (true) / One-way mode (false)
unifiedboolUnified account (true) / Standard account (false)
trade_marginNoneSwitch to isolated margin mode
trade_super_marginNoneSwitch to cross margin mode
trade_normalNoneSwitch back to normal spot mode
selfTradePreventionModestringSelf-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

CommandParameterDescription
trade_marginNoneSwitch to isolated margin mode
trade_super_marginNoneSwitch to cross margin mode
trade_normalNoneSwitch back to normal spot mode
unifiedboolUnified account mode
selfTradePreventionModestringSelf-trade prevention, options: EXPIRE_TAKER/EXPIRE_MAKER/EXPIRE_BOTH/NONE

OKX

CommandParameterDescription
simulateboolDemo/live trading switch
trade_marginNoneIsolated margin (tdMode=isolated)
trade_super_marginNoneCross margin (tdMode=cross)
trade_normalNoneSwitch back to normal spot mode
tdModestringDirectly set trading mode, must use cross margin under portfolio margin mode

Huobi

CommandParameterDescription
trade_marginNoneSwitch to isolated margin mode
trade_super_marginNoneSwitch to cross margin mode
trade_normalNoneSwitch back to normal spot mode

Bybit

CommandParameterDescription
trade_marginNoneSwitch to margin mode
trade_normalNoneSwitch back to normal spot mode

Gate.io

CommandParameterDescription
trade_marginNoneSwitch to isolated margin mode
trade_super_marginNoneSwitch to cross margin mode
trade_normalNoneSwitch back to normal spot mode
unifiedboolUnified account mode

Bitget

CommandParameterDescription
simulateboolDemo/live trading switch

CoinEx

CommandParameterDescription
trade_marginNoneSwitch to margin mode
trade_normalNoneSwitch back to normal mode

WOO

CommandParameterDescription
trade_marginNoneSwitch to margin mode
trade_normalNoneSwitch back to normal mode

Crypto.com

CommandParameterDescription
trade_marginNoneSwitch to margin mode
trade_normalNoneSwitch back to normal mode

AscendEx

CommandParameterDescription
trade_marginNoneSwitch to margin mode
trade_normalNoneSwitch back to normal mode

Gemini

CommandParameterDescription
subAccountstringSet sub-account name

Poloniex

CommandParameterDescription
accountIdstringSet account ID

Bitfinex

CommandParameterDescription
versionNoneGet current API version number

Backpack

CommandParameterDescription
selfTradePreventionModestringSelf-trade prevention, options: Allow/RejectTaker/RejectMaker/RejectBoth/Ban

Hyperliquid (Spot)

CommandParameterDescription
source"a"/"b"Switch API data source
vaultAddressstringSet vault address, empty string to disable
walletAddressstringSet wallet address
expiresAfternumberOrder expiration time (milliseconds), set to 0 to disable

Futures Exchanges

Futures_Binance

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode
unifiedboolUnified account (uses papi.binance.com after switching)
selfTradePreventionModestringSelf-trade prevention, options: EXPIRE_TAKER/EXPIRE_MAKER/EXPIRE_BOTH/NONE
extend_keystringSet API response extension fields (comma-separated)

Futures_OKX

CommandParameterDescription
simulateboolDemo/live trading switch
crossboolCross/isolated margin mode, default cross
dualboolHedge (long_short_mode)/one-way (net_mode) position mode

Futures_HuobiDM

CommandParameterDescription
crossboolCross/isolated margin mode, default isolated. Only XXX_USDT perpetual swaps supported
dualboolHedge (dual_side)/one-way (single_side) position mode
unifiedboolUnified account mode
signHoststringSet API signature host address, empty string to disable

Futures_Bybit

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode

Futures_KuCoin

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_GateIO

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode
unifiedboolUnified account mode

Futures_Bitget

CommandParameterDescription
simulateboolDemo/live trading switch
crossboolCross (crossed)/isolated margin mode
dualboolHedge (hedge_mode)/one-way (one_way_mode) position mode

Futures_MEXC

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_BitMEX

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_CoinEx

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_WOO

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode

Futures_Kraken

CommandParameterDescription
crossboolCross/isolated margin mode (only multi-collateral accounts supported)

Futures_Aevo

CommandParameterDescription
signingKeystringSet signing key, returns public key. Must be obtained from exchange API KEY page, note expiration restrictions

Futures_Hyperliquid

CommandParameterDescription
crossboolCross/isolated margin mode
source"a"/"b"Switch API data source
vaultAddressstringSet vault address, empty string to disable
walletAddressstringSet wallet address
expiresAfternumberOrder expiration time (milliseconds), set to 0 to disable

Futures_Deepcoin

CommandParameterDescription
crossboolCross/isolated margin mode
mergeboolMerge positions (true)/split positions (false)

Futures_DigiFinex

CommandParameterDescription
simulateboolDemo/live trading switch
crossboolCross/isolated margin mode

Futures_ApolloX

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_Aster

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode

Futures_CoinW

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_BitMart

CommandParameterDescription
crossboolCross/isolated margin mode

Futures_Backpack

CommandParameterDescription
selfTradePreventionModestringSelf-trade prevention, options: Allow/RejectTaker/RejectMaker/RejectBoth/Ban

Futures_Lighter

CommandParameterDescription
crossboolCross/isolated margin mode
expirynumberOrder expiration timestamp (milliseconds), default 29 days, minimum 4 minutes

Futures_Crypto.com

CommandParameterDescription
accountIdstringSet trading account ID

Futures_Bitfinex

CommandParameterDescription
mbasestringSet market API base address

Futures_edgeX

CommandParameterDescription
calcOrderHashAndSignstring(JSON)Calculate order hash and sign, returns signature string

Futures_Bibox

CommandParameterDescription
crossboolCross/isolated margin mode, default cross

Futures_Pionex

CommandParameterDescription
crossboolCross/isolated margin mode
dualboolHedge/one-way position mode

Futures_Phemex

CommandParameterDescription
dualboolHedge/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)

CommandParametersDescription
nonce[number]Get or set order nonce value. Returns current nonce without parameters, sets new nonce when a number is passed
proxyWalletAddressNoneGet proxy wallet address
redeemsymbol, [wait]Redeem settled positions (Gas-free via Relayer), wait defaults to true to wait for transaction confirmation. When wait is false, immediately returns {"transactionID": "..."}
mergesymbol, [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_credentialsNoneGet L2 authentication info, returns {"apiKey":"","secret":"","passphrase":""}, used for WebSocket connections or other scenarios
batchOrdersarrayBatch order placement, parameter is an array of order objects, each object contains symbol, side, price, amount fields, optional option field

Web3 (Blockchain)

CommandParametersDescription
abiContract address, ABI stringRegister contract ABI
address[Private key]Get wallet address
encode / packType, Data...ABI encode data
encodePackedType, Data...ABI packed encode data
hashParam1-4Calculate hash value
decode / unpackType, Data...ABI decode data
keystringSwitch private key used for operations

IB (Interactive Brokers)

CommandParametersDescription
statusNoneGet connection status
timeNoneGet IB server time
reqIdNoneForce get new request ID
orderIdNoneGet next available order ID
ignorestring(array)Ignore specified error codes
scanstring(JSON)Execute market scanner
wait[number]Wait for market data event, can set timeout in seconds
debugboolDebug mode
marketDataTypenumberMarket data type (1 Real-time/2 Frozen/3 Delayed/4 Delayed Frozen)

Futu (Futu Securities)

CommandParametersDescription
refreshboolCache refresh, after disabling cache the rate limit is max 10 times per 30 seconds
accountsNoneGet all account list
statusNoneGet connection status
lockNoneLock trading
unlockNoneUnlock trading
waitNoneWait 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.
ParameterTypeDescription
functionNamesstringFunction name, multiple functions separated by commas, * means all
maxCallsnumberMaximum number of calls within the time period
periodstringTime period ("1s"/"1m"/"1h") or reset time point ("@0815")
behaviorstringOptional, "delay" means wait when limit exceeded, defaults to returning null

Rate limiting for Buy/Sell follows the CreateOrder settings. Go follows the settings of the actual concurrent function. IO/api only applies to exchange.IO("api", ...).

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

NameTypeRequiredDescription

orderType

number

Yes

The orderType parameter is used to set the output log type. Optional values are LOG_TYPE_BUY, LOG_TYPE_SELL, LOG_TYPE_CANCEL.

price

number

Yes

The price parameter is used to set the price displayed in the output log.

amount

number

Yes

The amount parameter is used to set the order quantity displayed in the output log.

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 arg parameters can be passed.

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.

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

TypeDescription

string

The exchange.Encode() function returns the calculated hash value encoding.

Arguments

NameTypeRequiredDescription

algo

string

Yes

The algo parameter is used to specify the algorithm used in encoding calculation.

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 algo parameter also supports: "text.encoder.utf8", "text.decoder.utf8", "text.encoder.gbk", "text.decoder.gbk" for encoding and decoding strings.

The algo parameter also supports the "ed25519" algorithm. It supports using different hash algorithms, for example, the algo parameter can be written as "ed25519.md5", "ed25519.sha512", etc. Supports ed25519.seed calculation.

inputFormat

string

Yes

Used to specify the data format of the data parameter. The inputFormat parameter supports setting to one of: "raw", "hex", "base64", "string". "raw" means the data is raw data, "hex" means the data is hex encoded, "base64" means the data is base64 encoded, "string" means the data is a string.

outputFormat

string

Yes

Used to specify the output data format. The outputFormat parameter supports setting to one of: "raw", "hex", "base64", "string". "raw" means the data is raw data, "hex" means the data is hex encoded, "base64" means the data is base64 encoded, "string" means the data is a string.

data

string

Yes

The data parameter is the data to be processed.

keyFormat

string

No

Used to specify the data format of the key parameter. The keyFormat parameter supports setting to one of: "raw", "hex", "base64", "string". "raw" means the data is raw data, "hex" means the data is hex encoded, "base64" means the data is base64 encoded, "string" means the data is a string.

key

string

No

The key parameter is used to specify the key used in signature calculation. You can use a plaintext string, or use "{{accesskey}}", "{{secretkey}}" to reference the accessKey and secretKey configured in the exchange exchange object.

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.

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 for undefined, you need to use typeof(xx) === "undefined", because in JavaScript the comparison null == undefined evaluates to true.

    javascript
    function 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() }
    python
    def main(): a = exchange.Go("GetTicker") b = exchange.Go("GetDepth") c = exchange.Go("Buy", 1000, 0.1) d = exchange.Go("GetRecords", PERIOD_H1) ticker, ok = a.wait() depth, ok = b.wait() orderId, ok = c.wait(1000) if ok == False: orderId, ok = c.wait() records, ok = d.wait()
    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:

    javascript
    function 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() }
    python
    def 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:

    javascript
    function main() { while(true) { var beginTS = new Date().getTime() var arrRoutine = [] var arrTicker = [] var arrName = [] for(var i = 0; i < exchanges.length; i++) { arrRoutine.push(exchanges[i].Go("GetTicker")) arrName.push(exchanges[i].GetName()) } for(var i = 0; i < arrRoutine.length; i++) { arrTicker.push(arrRoutine[i].wait()) } var endTS = new Date().getTime() var tbl = { type: "table", title: "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) } }
    python
    import time import json def main(): while True: beginTS = time.time() arrRoutine = [] arrTicker = [] arrName = [] for i in range(len(exchanges)): arrRoutine.append(exchanges[i].Go("GetTicker")) arrName.append(exchanges[i].GetName()) for i in range(len(exchanges)): ticker, ok = arrRoutine[i].wait() arrTicker.append(ticker) endTS = time.time() tbl = { "type": "table", "title": "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:

    javascript
    function 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") }
    python
    import time import json def main(): beginTS = time.time() param = {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"} ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param)) ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param)) ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", json.dumps(param)) id1, ok1 = ret1.wait() id2, ok2 = ret2.wait() id3, ok3 = ret3.wait() endTS = time.time() Log("id1:", id1) Log("id2:", id2) Log("id3:", id3) Log("Concurrent order 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

    javascript
    function 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

TypeDescription

object

The exchange.Go() function immediately returns a concurrent object. You can use the wait() method of this concurrent object to get the result of the concurrent request.

Arguments

NameTypeRequiredDescription

method

string

Yes

The method parameter specifies the name of the concurrent function. Note that this parameter is a function name string, not a function reference.

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 arg parameters. The type and number of arg parameters depend on the parameter requirements of the concurrent execution function.

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:

  1. Without setting a timeout parameter, i.e., wait(), or setting the timeout parameter to 0, i.e., wait(0). The wait() function will block and wait until the concurrent thread finishes running and returns the execution result of the concurrent thread.

  2. Setting the timeout parameter to -1, i.e., wait(-1). The wait() function will return immediately. Return values differ between programming languages; please refer to the calling examples in this section for details.

  3. Setting a specific timeout parameter, such as wait(300). The wait() 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)