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 the member functions (methods) of the exchange object is only related to exchange, which will not be repeated in the rest of this document.

exchange.Buy(price, amount)
exchange.Buy(price, amount, ...args)

Examples

  • The order number returned by exchange.Buy() can be used to query order information and cancel orders.

    javascript
    function main() { var id = exchange.Buy(100, 1); Log("id:", id); }
    python
    def main(): id = exchange.Buy(100, 1) Log("id:", id)
    rust
    fn main() { let id = exchange.Buy(100, 1).unwrap(); Log!("id:", id); }
    c++
    void main() { auto id = exchange.Buy(100, 1); Log("id:", id); }
  • When placing an order for a cryptocurrency futures contract, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported:

    ```log

    direction is sell, invalid order type Buy

    direction is buy, invalid order type Sell

    direction is closebuy, invalid order type Buy

    direction is closesell, invalid order type Sell

    ```

    javascript
    // The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set the short direction exchange.SetDirection("sell") // Placing a buy order will report an error; shorting can only sell var id = exchange.Buy(50, 1) // Set the long direction exchange.SetDirection("buy") // Placing a sell order will report an error; going long can only buy var id2 = exchange.Sell(60, 1) // Set the close-long direction exchange.SetDirection("closebuy") // Placing a buy order will report an error; closing long can only sell var id3 = exchange.Buy(-1, 1) // Set the close-short direction exchange.SetDirection("closesell") // Placing a sell order will report an error; closing short can only buy var id4 = exchange.Sell(-1, 1) }
    python
    # The following are incorrect calls def main(): exchange.SetContractType("quarter") exchange.SetDirection("sell") id = exchange.Buy(50, 1) exchange.SetDirection("buy") id2 = exchange.Sell(60, 1) exchange.SetDirection("closebuy") id3 = exchange.Buy(-1, 1) exchange.SetDirection("closesell") id4 = exchange.Sell(-1, 1)
    rust
    // The following are incorrect calls fn main() { let _ = exchange.SetContractType("quarter"); // Set the short direction let _ = exchange.SetDirection("sell"); // Placing a buy order will report an error; shorting can only sell let id = exchange.Buy(50, 1); // Set the long direction let _ = exchange.SetDirection("buy"); // Placing a sell order will report an error; going long can only buy let id2 = exchange.Sell(60, 1); // Set the close-long direction let _ = exchange.SetDirection("closebuy"); // Placing a buy order will report an error; closing long can only sell let id3 = exchange.Buy(-1, 1); // Set the close-short direction let _ = exchange.SetDirection("closesell"); // Placing a sell order will report an error; closing short can only buy let id4 = exchange.Sell(-1, 1); }
    c++
    // The following are incorrect calls void main() { exchange.SetContractType("quarter"); exchange.SetDirection("sell"); auto id = exchange.Buy(50, 1); exchange.SetDirection("buy"); auto id2 = exchange.Sell(60, 1); exchange.SetDirection("closebuy"); auto id3 = exchange.Buy(-1, 1); exchange.SetDirection("closesell"); auto id4 = exchange.Sell(-1, 1); }
  • Spot market order.

    javascript
    // For example, trading pair: ETH_BTC, market order buy function main() { // Place a market order to buy, buying ETH worth 0.1 BTC (quote currency) exchange.Buy(-1, 0.1) }
    python
    def main(): exchange.Buy(-1, 0.1)
    rust
    // For example, trading pair: ETH_BTC, market order buy fn main() { // Place a market order to buy, buying ETH worth 0.1 BTC (quote currency) let _ = exchange.Buy(-1, 0.1); }
    c++
    void main() { exchange.Buy(-1, 0.1); }

Returns

TypeDescription

string / null value

Returns the order Id if the order is placed successfully, and returns a null value if the order fails. The Id attribute of the order Order structure on the FMZ platform consists of the exchange symbol code and the exchange's original order Id, separated by an English comma. For example, the Id attribute format of an order for the OKX exchange spot trading pair ETH_USDT is: ETH-USDT,1547130415509278720. When calling the exchange.Buy() function to place an order, the returned order Id is consistent with the Id attribute 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 amount.

arg

string / number / bool / object / array / any (any type supported by the platform)

No

Extension parameter used to output accompanying information to this order log. Multiple arg parameters can be passed in.

See Also

exchange.Sell exchange.SetContractType exchange.SetDirection exchange.IO (API rate limit control; the Buy function is affected by the CreateOrder rate limit setting)

Remarks

When placing an order for a futures contract, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported. Unless otherwise specified, the order amount on cryptocurrency futures contract exchanges is denominated in number of contracts.

When the price parameter is set to -1, it is used to place a market order. This feature requires the exchange's order placement interface to support market orders. When placing a buy order for cryptocurrency spot in the form of a market order, the order amount parameter amount is the amount denominated in the quote currency. When placing an order for a cryptocurrency futures contract in the form of a market order, the unit of the order amount parameter amount is number of contracts. In live trading, a few cryptocurrency exchanges do not support the market order interface. For a few spot exchanges, the order amount of a market buy order is the number of trading coins. For details, please refer to the Exchange Special Notes in the "User Guide".

If you are using an older version of the docker, the order Id returned by the exchange.Buy() function may differ from the return value order Id described in the current document.

It should be noted that the order placement interfaces of the following three exchanges are relatively special. For spot market buy orders, the order amount is the number of coins rather than the amount.

  • AscendEx

  • BitMEX

  • Bitfinex

The exchange.Sell() function is used to place a sell order.

exchange.Sell(price, amount)
exchange.Sell(price, amount, ...args)

Examples

  • The order number returned by exchange.Sell() can be used to query order information and cancel orders.

    javascript
    function main(){ var id = exchange.Sell(100, 1) Log("id:", id) }
    python
    def main(): id = exchange.Sell(100, 1) Log("id:", id)
    rust
    fn main() { let id = exchange.Sell(100, 1).unwrap(); Log!("id:", id); }
    c++
    void main() { auto id = exchange.Sell(100, 1); Log("id:", id); }
  • When placing orders for cryptocurrency futures contracts, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported:

    log
    direction is sell, invalid order type Buy direction is buy, invalid order type Sell direction is closebuy, invalid order type Buy direction is closesell, invalid order type Sell
    javascript
    // The following are incorrect calls function main() { exchange.SetContractType("quarter") // Set the short direction exchange.SetDirection("sell") // Placing a buy order will report an error; shorting can only sell var id = exchange.Buy(50, 1) // Set the long direction exchange.SetDirection("buy") // Placing a sell order will report an error; going long can only buy var id2 = exchange.Sell(60, 1) // Set the close-long direction exchange.SetDirection("closebuy") // Placing a buy order will report an error; closing a long can only sell var id3 = exchange.Buy(-1, 1) // Set the close-short direction exchange.SetDirection("closesell") // Placing a sell order will report an error; closing a short can only buy var id4 = exchange.Sell(-1, 1) }
    python
    # The following are incorrect calls def main(): exchange.SetContractType("quarter") exchange.SetDirection("sell") id = exchange.Buy(50, 1) exchange.SetDirection("buy") id2 = exchange.Sell(60, 1) exchange.SetDirection("closebuy") id3 = exchange.Buy(-1, 1) exchange.SetDirection("closesell") id4 = exchange.Sell(-1, 1)
    rust
    // The following are incorrect calls fn main() { let _ = exchange.SetContractType("quarter"); // Set the short direction let _ = exchange.SetDirection("sell"); // Placing a buy order will report an error; shorting can only sell let id = exchange.Buy(50, 1); // Set the long direction let _ = exchange.SetDirection("buy"); // Placing a sell order will report an error; going long can only buy let id2 = exchange.Sell(60, 1); // Set the close-long direction let _ = exchange.SetDirection("closebuy"); // Placing a buy order will report an error; closing a long can only sell let id3 = exchange.Buy(-1, 1); // Set the close-short direction let _ = exchange.SetDirection("closesell"); // Placing a sell order will report an error; closing a short can only buy let id4 = exchange.Sell(-1, 1); }
    c++
    // The following are incorrect calls void main() { exchange.SetContractType("quarter"); exchange.SetDirection("sell"); auto id = exchange.Buy(50, 1); exchange.SetDirection("buy"); auto id2 = exchange.Sell(60, 1); exchange.SetDirection("closebuy"); auto id3 = exchange.Buy(-1, 1); exchange.SetDirection("closesell"); auto id4 = exchange.Sell(-1, 1); }
  • Spot market order.

    javascript
    // For example, trading pair: ETH_BTC, sell with a market order function main() { // Note: place a market order to sell, selling 0.2 ETH exchange.Sell(-1, 0.2) }
    python
    def main(): exchange.Sell(-1, 0.2)
    rust
    // For example, trading pair: ETH_BTC, sell with a market order fn main() { // Note: place a market order to sell, selling 0.2 ETH let _ = exchange.Sell(-1, 0.2); }
    c++
    void main() { exchange.Sell(-1, 0.2); }

Returns

TypeDescription

string / null value

Returns the order Id when the order is placed successfully, and returns a null value when the order fails. 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 of an order for the spot trading pair ETH_USDT on the OKX exchange is: ETH-USDT,1547130415509278720. When calling the exchange.Sell() function to place an order, the returned 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 size.

arg

string / number / bool / object / array / any (any type supported by the platform)

No

An extension parameter used to output additional information attached to this order log. Multiple arg parameters can be passed in.

See Also

exchange.Buy exchange.SetContractType exchange.SetDirection exchange.IO (API rate limit control; the Sell function is affected by the CreateOrder rate limit setting)

Remarks

When placing orders for futures contracts, you must pay attention to whether the trading direction is set correctly. If the trading direction does not match the trading function, an error will be reported. For cryptocurrency futures contract exchanges, the order size is denominated in number of contracts unless otherwise specified.

When the price parameter is set to -1, it is used to place a market order, which requires the exchange's order interface to support market orders. When trading cryptocurrency spot with market orders, when placing a sell order, the order size parameter amount is denominated in the trading currency. When trading cryptocurrency futures contracts with market orders, the order size parameter amount is denominated in number of contracts. In live trading, a few cryptocurrency exchanges do not support the market order interface.

If you are using an older version of the docker, the order Id returned by the exchange.Sell() function may differ from the returned order Id described in the current documentation.

exchange.CreateOrder() function is used to place orders.

exchange.CreateOrder(symbol, side, price, amount)
exchange.CreateOrder(symbol, side, price, amount, ...args)

Examples

  • Both spot exchange objects and futures exchange objects place orders by calling the exchange.CreateOrder() function.

    javascript
    function main() { var id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) // Spot exchange object places an order, trading the BTC_USDT spot trading pair // var id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id) }
    python
    def main(): id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01) # Spot exchange object places an order, trading the BTC_USDT spot trading pair # id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01) # Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id)
    rust
    fn main() { let id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01); // Spot exchange object places an order, trading the BTC_USDT spot trading pair // let id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01); // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log!("Order Id:", id); }
    c++
    void main() { auto id = exchange.CreateOrder("BTC_USDT", "buy", 60000, 0.01); // Spot exchange object places an order, trading the BTC_USDT spot trading pair // auto id = exchange.CreateOrder("BTC_USDT.swap", "buy", 60000, 0.01); // Futures exchange object places an order, trading BTC's USDT-margined perpetual contract Log("Order Id:", id); }
  • Place an order with additional parameters (option), used to pass exchange-specific parameters.

    javascript
    function main() { // Pass the option parameter in JSON format var option = { "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" } var sideWithOption = "buy;" + JSON.stringify(option) var id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1) Log("Order Id:", id) Sleep(2000) Log(exchange.GetOrder(id)) }
    python
    import json def main(): # Pass the option parameter in JSON format option = { "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" } sideWithOption = "buy;" + json.dumps(option) id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1) Log("Order Id:", id) Sleep(2000) Log(exchange.GetOrder(id))
    rust
    fn main() { // Pass the option parameter in JSON format (Rust does not support JSON.stringify, so construct the JSON text directly using a raw string) let option = r#"{"type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1"}"#; let sideWithOption = format!("buy;{}", option); let id = exchange.CreateOrder("SOL_USDT.swap", &sideWithOption, -1, 1).unwrap(); Log!("Order Id:", id); Sleep(2000); Log!(exchange.GetOrder(&id)); }
    c++
    void main() { // Pass the option parameter in JSON format json option = R"({ "type": "TRAILING_STOP_MARKET", "activationPrice": "2300", "callbackRate": "0.1" })"_json; string sideWithOption = "buy;" + option.dump(); auto id = exchange.CreateOrder("SOL_USDT.swap", sideWithOption, -1, 1); Log("Order Id:", id); Sleep(2000); Log(exchange.GetOrder(id)); }

Returns

TypeDescription

string / null value

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

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

Arguments

NameTypeRequiredDescription

symbol

string

Yes

The symbol parameter is used to specify the trading pair or contract code corresponding to 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 symbol parameter is: "BTC_USDT", using 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 USDT-margined perpetual contract order for BTC, then the symbol parameter is: "BTC_USDT.swap", using the format defined by the FMZ platform that combines the trading pair and contract code, with the two 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 USDT-margined options contract order for BTC, then the symbol parameter is: "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example), using the format that combines the trading pair defined by the FMZ platform and the specific options contract code defined by the exchange, with the two separated by the character ".".

side

string

Yes

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

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

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

Supports additional parameters (option): You can pass additional parameters via 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.); the specific parameters supported depend on the exchange API.

price

number

Yes

The price parameter 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 amount parameter is used to set the order quantity. Note that when the order is a spot market buy order, the order quantity represents the purchase amount; for a few spot exchanges, the order quantity of a market buy order is the quantity of the base currency—please refer to the Exchange Special Notes 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 denominated in number of contracts.

arg

string / number / bool / object / array / any (any type supported by the platform)

No

An extension parameter used to output accompanying information to the log of this order; the arg parameter can be passed in multiple times.

See Also

Remarks

Additional parameters (option) can be passed via the side parameter to specify exchange-specific parameters. The additional parameters must be merged into the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value&key=value" (URL-encoded format). For example: "buy;{\"type\":\"TRAILING_STOP_MARKET\"}".

The option parameters supported by different exchanges vary. The specific supported parameters are subject to the exchange's API documentation. Common parameters include: order type (type), time in force (timeInForce), activation price (activationPrice), callback rate (callbackRate), etc.

When using the option parameters, you still need to provide the price and amount parameters. If certain parameters have already been passed via option, these base parameters may be overridden by the corresponding parameters in option; the specific behavior depends on the exchange's API implementation.

The exchange.CancelOrder() function is used to cancel an order. In the order Order structure of the FMZ platform, the property Id is composed of the exchange's symbol code and the exchange's original order Id, separated by an English comma. For example, for an order of the OKX exchange spot trading pair ETH_USDT, the format of its Id property is: ETH-USDT,1547130415509278720.

When calling the exchange.CancelOrder() function to cancel an order, the passed-in parameter orderId is consistent with the Id property of the order Order structure.

exchange.CancelOrder(orderId)
exchange.CancelOrder(orderId, ...args)

Examples

  • Cancel an order.

    javascript
    function main(){ var id = exchange.Sell(99999, 1) exchange.CancelOrder(id) }
    python
    def main(): id = exchange.Sell(99999, 1) exchange.CancelOrder(id)
    rust
    fn main() { let id = exchange.Sell(99999, 1).unwrap(); let _ = exchange.CancelOrder(&id); }
    c++
    void main() { auto id = exchange.Sell(99999, 1); exchange.CancelOrder(id); }
  • Among FMZ's API functions, functions that can produce log output (such as Log(), exchange.Buy(), exchange.CancelOrder(), etc.) can all be accompanied by some output parameters after the required parameters.

    For example: exchange.CancelOrder(orders[i].Id, orders[i]), that is, when canceling the order with Id orders[i].Id, additionally output the information of that order, 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)
    rust
    fn main() { if exchange.GetName().contains("Futures_") { Log!("Set contract to: perpetual swap, set direction to: open long."); let _ = exchange.SetContractType("swap"); let _ = exchange.SetDirection("buy"); } let ticker = exchange.GetTicker(None).unwrap(); let _ = exchange.Buy(ticker.Last * 0.5, 0.1); let orders = exchange.GetOrders(None).unwrap(); for i in 0..orders.len() { // Rust does not support appending output parameters after the required parameters of CancelOrder; after canceling the order, call the Log! macro separately to output the accompanying information let _ = exchange.CancelOrder(&orders[i].Id); Log!("Canceled order:", orders[i]); Sleep(500); } }
    c++
    void main() { if (exchange.GetName().find("Futures_") != std::string::npos) { Log("Set contract to: perpetual swap, set direction to: open long."); exchange.SetContractType("swap"); exchange.SetDirection("buy"); } auto ticker = exchange.GetTicker(); exchange.Buy(ticker.Last * 0.5, 0.1); auto orders = exchange.GetOrders(); for (int i = 0 ; i < orders.size() ; i++) { exchange.CancelOrder(orders[i].Id, "Canceled order:", orders[i]); Sleep(500); } }

Returns

TypeDescription

bool

The exchange.CancelOrder() function returning a truthy value (e.g. true) indicates that the order-cancellation request was sent successfully, while returning a falsy value (e.g. false) indicates that the order-cancellation request failed to be sent. 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 check.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

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

arg

string / number / bool / object / array / any (any type supported by the platform)

No

An extension parameter used to output accompanying information into this order-cancellation log; multiple arg parameters can be passed in.

See Also

Remarks

If you are using an older version of the docker (hosting agent), the parameter orderId of the exchange.CancelOrder() function may differ from the orderId described in the current documentation.

The exchange.GetOrder() function is used to obtain order information.

exchange.GetOrder(orderId)

Examples

javascript
function main(){ var id = exchange.Sell(1000, 1) // The parameter id is the order number; fill in the number of the order you want to query var order = exchange.GetOrder(id) Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:", order.DealAmount, "Status:", order.Status, "Type:", order.Type) }
python
def main(): id = exchange.Sell(1000, 1) order = exchange.GetOrder(id) Log("Id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:", order["DealAmount"], "Status:", order["Status"], "Type:", order["Type"])
rust
fn main() { let id = exchange.Sell(1000, 1).unwrap(); // The parameter id is the order number; fill in the number of the order you want to query let order = exchange.GetOrder(&id).unwrap(); Log!("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:", order.DealAmount, "Status:", order.Status, "Type:", order.Type); }
c++
void main() { auto id = exchange.Sell(1000, 1); auto order = exchange.GetOrder(id); Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "DealAmount:", order.DealAmount, "Status:", order.Status, "Type:", order.Type); }

Returns

TypeDescription

Order / null value

Queries order details based on the order Id. Returns the Order structure when the query is successful, and returns a null value when the query fails.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

The orderId parameter is used to specify the order to be queried. The Id attribute of the FMZ platform 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 attribute of an order for the spot trading pair ETH_USDT on the OKX exchange has the format: 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 return value Order structure is the average filled price; some exchanges do not support this field, and if it is not supported it will be set to 0.

If you are using an older version of the docker, the orderId parameter of the exchange.GetOrder() function may differ from the orderId described in the current documentation.

Exchanges that do not support the exchange.GetOrder() function:

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetOrderZaif / Coincheck / Bitstamp--

The exchange.GetOrders() function is used to obtain the current unfilled orders.

exchange.GetOrders()
exchange.GetOrders(symbol)

Examples

  • Using a spot exchange object, place buy orders for multiple different trading pairs at half of the current price as the order price, then query the information of unfilled orders.

    javascript
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"] for (var symbol of arrSymbol) { var t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t.Last / 2, 0.01) } var spotOrders = exchange.GetOrders() var tbls = [] for (var orders of [spotOrders]) { var tbl = {type: "table", title: "test GetOrders", cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []} for (var order of orders) { tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) } tbls.push(tbl) } LogStatus("`" + JSON.stringify(tbls) + "`") // Print the information once and then return, to prevent orders from being filled during subsequent backtesting, which would affect data observation return }
    python
    '''backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"] for symbol in arrSymbol: t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t["Last"] / 2, 0.01) spotOrders = exchange.GetOrders() tbls = [] for orders in [spotOrders]: tbl = {"type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": []} for order in orders: tbl["rows"].append([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) tbls.append(tbl) LogStatus("`" + json.dumps(tbls) + "`") return
    rust
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ fn main() { let arrSymbol = ["ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"]; for symbol in arrSymbol { let t = exchange.GetTicker(symbol).unwrap(); let _ = exchange.CreateOrder(symbol, "buy", t.Last / 2.0, 0.01); } let spotOrders = exchange.GetOrders(None).unwrap(); // Rust does not support JSON.stringify, use format! to build the table's JSON text let mut tbls = Vec::new(); for orders in [&spotOrders] { let mut rows = Vec::new(); for order in orders { rows.push(format!(r#"["{}", "{}", {}, {}, {}, {}, {}, {}, {}, "{}"]"#, order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType)); } let tbl = format!(r#"{{"type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [{}]}}"#, rows.join(",")); tbls.push(tbl); } LogStatus!(format!("`[{}]`", tbls.join(","))); // Print the information once and then return, to prevent orders from being filled during subsequent backtesting, which would affect data observation return; }
    c++
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"ETH_USDT", "BTC_USDT", "LTC_USDT", "SOL_USDT"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 0.01); } auto spotOrders = exchange.GetOrders(); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {spotOrders}; for (const auto& orders : arr) { json tbl = R"({ "type": "table", "title": "test GetOrders", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back("Symbol"); arrJson.push_back("Id"); arrJson.push_back(order.Price); arrJson.push_back(order.Amount); arrJson.push_back(order.DealAmount); arrJson.push_back(order.AvgPrice); arrJson.push_back(order.Status); arrJson.push_back(order.Type); arrJson.push_back(order.Offset); arrJson.push_back(order.ContractType); tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); } LogStatus(_D(), "\n", "`" + tbls.dump() + "`"); return; }
  • Use the futures exchange object to place orders on multiple symbols with different trading pairs and contract codes. The order prices are set far away from the counterparty price at the top of the order book, keeping the orders in an unfilled state, and then query the orders in various ways.

    javascript
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] for (var symbol of arrSymbol) { var t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t.Last / 2, 1) exchange.CreateOrder(symbol, "sell", t.Last * 2, 1) } var defaultOrders = exchange.GetOrders() var swapOrders = exchange.GetOrders("USDT.swap") var futuresOrders = exchange.GetOrders("USDT.futures") var btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap") var tbls = [] var arr = [defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders] var tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"] for (var index in arr) { var orders = arr[index] var tbl = {type: "table", title: tblDesc[index], cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []} for (var order of orders) { tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType]) } tbls.push(tbl) } LogStatus("`" + JSON.stringify(tbls) + "`") // Print the output once and then return immediately, to prevent orders from being filled later in the backtest and affecting the data observation return }
    python
    '''backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] for symbol in arrSymbol: t = exchange.GetTicker(symbol) exchange.CreateOrder(symbol, "buy", t["Last"] / 2, 1) exchange.CreateOrder(symbol, "sell", t["Last"] * 2, 1) defaultOrders = exchange.GetOrders() swapOrders = exchange.GetOrders("USDT.swap") futuresOrders = exchange.GetOrders("USDT.futures") btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap") tbls = [] arr = [defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders] tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"] for index in range(len(arr)): orders = arr[index] tbl = {"type": "table", "title": tblDesc[index], "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": []} for order in orders: tbl["rows"].append([order["Symbol"], order["Id"], order["Price"], order["Amount"], order["DealAmount"], order["AvgPrice"], order["Status"], order["Type"], order["Offset"], order["ContractType"]]) tbls.append(tbl) LogStatus("`" + json.dumps(tbls) + "`") return
    rust
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ fn main() { let arrSymbol = ["BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"]; for symbol in arrSymbol { let t = exchange.GetTicker(symbol).unwrap(); let _ = exchange.CreateOrder(symbol, "buy", t.Last / 2.0, 1); let _ = exchange.CreateOrder(symbol, "sell", t.Last * 2.0, 1); } let defaultOrders = exchange.GetOrders(None).unwrap(); let swapOrders = exchange.GetOrders("USDT.swap").unwrap(); let futuresOrders = exchange.GetOrders("USDT.futures").unwrap(); let btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap").unwrap(); // Rust does not support JSON.stringify, so format! is used here to assemble the JSON text of the table let mut tbls = Vec::new(); let arr = [&defaultOrders, &swapOrders, &futuresOrders, &btcUsdtSwapOrders]; let tblDesc = ["defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"]; for index in 0..arr.len() { let orders = arr[index]; let mut rows = Vec::new(); for order in orders { rows.push(format!(r#"["{}", "{}", {}, {}, {}, {}, {}, {}, {}, "{}"]"#, order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType)); } let tbl = format!(r#"{{"type": "table", "title": "{}", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [{}]}}"#, tblDesc[index], rows.join(",")); tbls.push(tbl); } LogStatus!(format!("`[{}]`", tbls.join(","))); // Print the output once and then return immediately, to prevent orders from being filled later in the backtest and affecting the data observation return; }
    c++
    /*backtest start: 2024-05-21 00:00:00 end: 2024-09-05 00:00:00 period: 5m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"BTC_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"}; for (const auto& symbol : arrSymbol) { auto t = exchange.GetTicker(symbol); exchange.CreateOrder(symbol, "buy", t.Last / 2, 1); exchange.CreateOrder(symbol, "sell", t.Last * 2, 1); } auto defaultOrders = exchange.GetOrders(); auto swapOrders = exchange.GetOrders("USDT.swap"); auto futuresOrders = exchange.GetOrders("USDT.futures"); auto btcUsdtSwapOrders = exchange.GetOrders("BTC_USDT.swap"); json tbls = R"([])"_json; std::vector<std::vector<Order>> arr = {defaultOrders, swapOrders, futuresOrders, btcUsdtSwapOrders}; std::string tblDesc[] = {"defaultOrders", "swapOrders", "futuresOrders", "btcUsdtSwapOrders"}; for (int index = 0; index < arr.size(); index++) { auto orders = arr[index]; json tbl = R"({ "type": "table", "cols": ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], "rows": [] })"_json; tbl["title"] = tblDesc[index]; for (const auto& order : orders) { json arrJson = R"([])"_json; arrJson.push_back(order.Symbol); arrJson.push_back(to_string(order.Id)); // The Id attribute in the Order struct is of type TId, so the FMZ platform's built-in C++ function to_string is used here for encoding arrJson.push_back(order.Price); arrJson.push_back(order.Amount); arrJson.push_back(order.DealAmount); arrJson.push_back(order.AvgPrice); arrJson.push_back(order.Status); arrJson.push_back(order.Type); arrJson.push_back(order.Offset); arrJson.push_back(order.ContractType); tbl["rows"].push_back(arrJson); } tbls.push_back(tbl); } LogStatus(_D(), "\n", "`" + tbls.dump() + "`"); return; }
  • When calling the exchange.GetOrders() function, you can pass in the Symbol parameter to request order data for a specific trading pair or contract code.

    javascript
    function main() { var orders = exchange.GetOrders("BTC_USDT") // Spot symbol example // var orders = exchange.GetOrders("BTC_USDT.swap") // Futures symbol example Log("orders:", orders) }
    python
    def main(): orders = exchange.GetOrders("BTC_USDT") # Spot symbol example # orders = exchange.GetOrders("BTC_USDT.swap") # Futures symbol example Log("orders:", orders)
    rust
    fn main() { let orders = exchange.GetOrders("BTC_USDT"); // Spot symbol example // let orders = exchange.GetOrders("BTC_USDT.swap"); // Futures symbol example Log!("orders:", orders); }
    c++
    void main() { auto orders = exchange.GetOrders("BTC_USDT"); // Spot symbol example // auto orders = exchange.GetOrders("BTC_USDT.swap"); // Futures symbol example Log("orders:", orders); }

Returns

TypeDescription

Order array / null value

The exchange.GetOrders() function returns a Order structure array when the data request succeeds, and returns a null value when the data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

The symbol parameter is used to specify the trading instrument or range of trading instruments to be queried.

For a spot exchange object, if the symbol parameter is not passed in, the unfilled order data for all spot instruments is requested.

For a futures exchange object, if the symbol parameter is not passed in, the unfilled order data for all instruments within the dimension range of the current trading pair and contract code is requested by default.

See Also

Remarks

In the GetOrders function, the use cases of the symbol parameter are summarized as follows:

Exchange Object Categorysymbol ParameterQuery RangeRemarks
SpotDo not pass the symbol parameterQuery all spot trading pairsApplicable to all calling scenarios; if the exchange interface does not support it, an error is reported and a null value is returned, which will not be repeated below
SpotSpecify a trading instrument, with the symbol parameter as: "BTC_USDT"Query the specified BTC_USDT trading pairFor a spot exchange object, the format of the symbol parameter is: "BTC_USDT"
FuturesDo not pass the symbol parameterQuery all trading instruments within the dimension range of the current trading pair and contract codeIf 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 a trading instrument, with the symbol parameter as: "BTC_USDT.swap"Query the specified BTC USDT-margined perpetual contractFor a futures exchange object, the format of the symbol parameter is: a combination of the trading pair and contract code defined by the FMZ platform, separated by the character ".".
FuturesSpecify a range of trading instruments, with the symbol parameter as: "USDT.swap"Query all USDT-margined perpetual contracts-
Futures exchange supporting optionsDo not pass the symbol parameterQuery all option contracts within the dimension range of the current trading pairIf the current trading pair is BTC_USDT and the contract is set to an option contract, for example the Binance option contract: BTC-240108-40000-C
Futures exchange supporting optionsSpecify a specific trading instrumentQuery the specified option contractFor example, for the Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C
Futures exchange supporting optionsSpecify a range of trading instruments, with the symbol parameter as: "USDT.option"Query all USDT-margined option contracts-

In the GetOrders function, the query dimension ranges for a futures exchange object are summarized as follows:

symbol ParameterRequest Range DefinitionRemarks
USDT.swapRange of USDT-margined perpetual contracts.For dimensions not supported by the exchange API interface, an error is reported and a null value is returned when called.
USDT.futuresRange of USDT-margined delivery contracts.-
USD.swapRange of coin-margined perpetual contracts.-
USD.futuresRange of coin-margined delivery contracts.-
USDT.optionRange of USDT-margined option contracts.-
USD.optionRange of coin-margined option contracts.-
USDT.futures_comboRange of spread combo contracts.Futures_Deribit exchange
USD.futures_ffRange of multi-collateral delivery contracts.Futures_Kraken exchange
USD.swap_pfRange of multi-collateral perpetual contracts.Futures_Kraken exchange

When the account represented by the exchange object exchange has no open orders (i.e., active orders in an unfilled state) within the query range or on the specified trading instrument, calling this function will return an empty array, that is: [].

The following exchanges require a symbol parameter to be passed in for the interface that queries current unfilled orders. When calling the GetOrders function on these exchanges, if the symbol parameter is not passed in, only the unfilled orders of the current instrument are requested, rather than the unfilled orders of all instruments (because the exchange interface does not support it).

Zaif, MEXC, LBank, Korbit, Coinw, BitMart, Bithumb, BitFlyer, BigONE.

Exchanges that do not support the exchange.GetOrders() function:

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetOrders--Futures_Bibox

exchange.GetHistoryOrders() function is used to retrieve the historical orders of the current trading pair or contract, and supports specifying a particular trading instrument.

exchange.GetHistoryOrders()
exchange.GetHistoryOrders(symbol)
exchange.GetHistoryOrders(symbol, since)
exchange.GetHistoryOrders(symbol, since, limit)
exchange.GetHistoryOrders(since)
exchange.GetHistoryOrders(since, limit)

Examples

javascript
function main() { var historyOrders = exchange.GetHistoryOrders() Log(historyOrders) }
python
def main(): historyOrders = exchange.GetHistoryOrders() Log(historyOrders)
rust
fn main() { let historyOrders = exchange.GetHistoryOrders(None, None, None); Log!(historyOrders); }
c++
void main() { auto historyOrders = exchange.GetHistoryOrders(); Log(historyOrders); }

Returns

TypeDescription

Order array / null

The exchange.GetHistoryOrders() function returns a Order structure array when the data request succeeds, and returns null when the data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

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

If querying order data for an options contract, the symbol parameter should be set to "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example). Its format is a combination of the trading pair defined by the FMZ platform and the specific options contract code defined by the exchange, separated by the character ".". If this parameter is not passed, the order data for the currently set trading pair or contract code is requested by default.

since

number

No

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

limit

number

No

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

See Also

Remarks

  • When the symbol, since, and limit parameters are not specified, the historical orders of the current trading pair or contract are queried by default, i.e., the historical orders within a certain range closest to the current time are queried. The specific query range depends on the single-query range of the exchange's interface.

  • When the symbol parameter is specified, the historical orders of the set trading instrument are queried.

  • When the since parameter is specified, the query starts from the since timestamp and proceeds toward the current time.

  • When the limit parameter is specified, the query returns once a sufficient number of records is reached.

  • This function is only supported by exchanges that provide a historical order query interface.

Exchanges that do not support the exchange.GetHistoryOrders() function:

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetHistoryOrdersZaif / Upbit / Coincheck / Bitstamp / Bithumb / BitFlyer / BigONEFutures_Bibox / Futures_ApolloX

The exchange.CreateConditionOrder() function is used to create a conditional order. A conditional order is a type of order that is automatically executed when specific trigger conditions are met.

exchange.CreateConditionOrder(symbol, side, amount, condition)
exchange.CreateConditionOrder(symbol, side, amount, condition, ...args)

Examples

  • Create a take-profit order (TP): automatically sell when the price rises to the target price.

    javascript
    function main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, // Take-profit order TpTriggerPrice: 65000, // Trigger price TpOrderPrice: 65000 // Execution price, can also be set to -1 for a market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id) }
    python
    def main(): # Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, # Take-profit order "TpTriggerPrice": 65000, # Trigger price "TpOrderPrice": 65000 # Execution price, can also be set to -1 for a market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("TP order Id:", id)
    rust
    fn main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, // Take-profit order TpTriggerPrice: 65000.0, // Trigger price TpOrderPrice: 65000.0, // Execution price, can also be set to -1 for a market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("TP order Id:", id); }
    c++
    void main() { // Create a take-profit order: when the BTC_USDT price rises to 65000, sell 0.01 BTC at the price of 65000 OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("TP order Id:", id); }
  • Create a stop-loss order (SL): when the price drops to the stop-loss trigger price, automatically sell in the configured manner.

    javascript
    function main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price var condition = { ConditionType: ORDER_CONDITION_TYPE_SL, // Stop-loss order SlTriggerPrice: 58000, // Trigger price SlOrderPrice: -1 // -1 indicates a market order } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id) }
    python
    def main(): # Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price condition = { "ConditionType": ORDER_CONDITION_TYPE_SL, # Stop-loss order "SlTriggerPrice": 58000, # Trigger price "SlOrderPrice": -1 # -1 indicates a market order } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("SL order Id:", id)
    rust
    fn main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, // Stop-loss order SlTriggerPrice: 58000.0, // Trigger price SlOrderPrice: -1.0, // -1 indicates a market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("SL order Id:", id); }
    c++
    void main() { // Create a stop-loss order: when the BTC_USDT price drops to 58000, sell 0.01 BTC at market price OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = -1}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("SL order Id:", id); }
  • Create an OCO order: set take-profit and stop-loss simultaneously. Once either one is triggered, the other is automatically canceled.

    javascript
    function main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 var condition = { ConditionType: ORDER_CONDITION_TYPE_OCO, // OCO order TpTriggerPrice: 65000, // Take-profit trigger price TpOrderPrice: 65000, // Take-profit execution price SlTriggerPrice: 58000, // Stop-loss trigger price SlOrderPrice: 58000 // Stop-loss execution price } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("OCO order Id:", id) }
    python
    def main(): # Create an OCO order: take-profit price 65000, stop-loss price 58000 condition = { "ConditionType": ORDER_CONDITION_TYPE_OCO, # OCO order "TpTriggerPrice": 65000, # Take-profit trigger price "TpOrderPrice": 65000, # Take-profit execution price "SlTriggerPrice": 58000, # Stop-loss trigger price "SlOrderPrice": 58000 # Stop-loss execution price } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Log("OCO order Id:", id)
    rust
    fn main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_OCO, // OCO order TpTriggerPrice: 65000.0, // Take-profit trigger price TpOrderPrice: 65000.0, // Take-profit execution price SlTriggerPrice: 58000.0, // Stop-loss trigger price SlOrderPrice: 58000.0 // Stop-loss execution price }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition); Log!("OCO order Id:", id); }
    c++
    void main() { // Create an OCO order: take-profit price 65000, stop-loss price 58000 OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_OCO, .TpTriggerPrice = 65000, .TpOrderPrice = 65000, .SlTriggerPrice = 58000, .SlOrderPrice = 58000}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Log("OCO order Id:", id); }
  • Create a conditional order with an additional parameter (option), used to pass exchange-specific parameters.

    javascript
    function main() { // Pass the option parameter in JSON format var option = { "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" } var sideWithOption = "buy;" + JSON.stringify(option) var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77, TpOrderPrice: 71 } var id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition) Log("Condition Order Id:", id) Sleep(2000) Log(exchange.GetConditionOrder(id)) }
    python
    import json def main(): # Pass the option parameter in JSON format option = { "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" } sideWithOption = "buy;" + json.dumps(option) condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 77, "TpOrderPrice": 71 } id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition) Log("Condition Order Id:", id) Sleep(2000) Log(exchange.GetConditionOrder(id))
    rust
    fn main() { // Pass the option parameter in JSON format (Rust has no JSON serialization capability, so a raw string is used directly here to construct it) let option = r#"{"type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1"}"#; let sideWithOption = format!("buy;{}", option); let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 71.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", &sideWithOption, 1, &condition).unwrap(); Log!("Condition Order Id:", id); Sleep(2000); Log!(exchange.GetConditionOrder(&id)); }
    c++
    void main() { // Pass the option parameter in JSON format json option = R"({ "type": "TRAILING_STOP_MARKET", "activatePrice": "300", "callbackRate": "0.1" })"_json; string sideWithOption = "buy;" + option.dump(); OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 71}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", sideWithOption, 1, condition); Log("Condition Order Id:", id); Sleep(2000); Log(exchange.GetConditionOrder(id)); }

Returns

TypeDescription

string / null value

When the conditional order is created successfully, the conditional order Id is returned; when creation fails, a null value is returned. The format of the conditional order Id is similar to that of an ordinary order Id, consisting of the exchange symbol code and the exchange's original conditional order Id, separated by an English comma.

Arguments

NameTypeRequiredDescription

symbol

string

Yes

The symbol parameter is used to specify the trading pair or contract code corresponding to 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's quote currency is USDT and the base currency is BTC, then the symbol parameter is: "BTC_USDT", whose format is 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 symbol parameter is: "BTC_USDT.swap", whose format is a combination of the 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 symbol parameter is: "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example), whose format is a combination of the 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 side parameter is used to specify the trading direction of the conditional order.

For a spot exchange object, the available values of the side parameter are: buy, sell. buy means buy, and sell means sell.

For a futures exchange object, the available values of the side parameter are: buy, closebuy, sell, closesell. Among them, buy means open long position, closebuy means close long position, sell means open short position, and closesell means close short position.

Additional parameters (option) are supported: 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, effective rules, etc.). The specific supported parameters depend on the exchange API.

amount

number

Yes

The amount parameter is used to set the order size of the conditional order. Note that when the order is a spot market buy order, the order size represents the purchase amount; for some individual spot exchanges, the order size of a market buy order is the quantity of the base currency. For details, please refer to the Exchange Special Notes in the "User Guide". For a futures exchange object, the order size parameter amount is always measured in the number of contracts.

condition

object

Yes

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

arg

string / number / bool / object / array / any (any type supported by the platform)

No

An extension parameter used to output additional information to the log of this conditional order. Multiple arg parameters can be passed in.

See Also

Remarks

Whether conditional orders are supported depends on the specific exchange; some exchanges may not support conditional orders.

A conditional order does not lock up account funds before it is triggered; the order is only actually placed and funds are only committed after it is triggered.

Different exchanges may vary in their level of support for conditional orders and in the specific parameters involved. Please consult the API documentation of the corresponding exchange before use.

Additional parameters (option) can be passed via the side parameter to supply exchange-specific parameters. The additional parameters must be merged into the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value&key=value" (URL-encoded format). For example: "buy;{\"type\":\"TRAILING_STOP_MARKET\"}".

The option parameters supported vary from exchange to exchange; the specific supported parameters depend on the exchange's API documentation. Common parameters include: order type (type), time in force (timeInForce), activation price (activatePrice), callback rate (callbackRate), and so on.

When using option parameters, you still need to provide the amount and condition parameters. If certain parameters in the exchange API have already been passed via option, these base parameters may be overridden by the corresponding parameters in option; the exact behavior depends on the exchange API's implementation.

The exchange.ModifyOrder() function is used to modify an existing regular order, allowing you to modify the order's price and quantity. This function supports modifying other order attributes via additional parameters (depending on the support of the exchange API).

exchange.ModifyOrder(orderId, side, price, amount)

Examples

  • Modify the price and quantity of a regular order.

    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 the original order info var order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) // Modify the order's price and quantity var newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) // Query the modified order info var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel the order exchange.CancelOrder(newId) }
    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 the original order info order = exchange.GetOrder(id) Log("Original Order Info:", order) Sleep(1000) # Modify the order's price and quantity newId = exchange.ModifyOrder(id, "buy", 77, 2) Log("Modified Order ID:", newId) Sleep(2000) # Query the modified order info newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel the order exchange.CancelOrder(newId)
    rust
    fn main() { // Create a limit buy order let id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1).unwrap(); Log!("Original Order ID:", id); Sleep(2000); // Query the original order info let order = exchange.GetOrder(&id).unwrap(); Log!("Original Order Info:", order); Sleep(1000); // Modify the order's price and quantity let newId = exchange.ModifyOrder(&id, "buy", 77, 2).unwrap(); Log!("Modified Order ID:", newId); Sleep(2000); // Query the modified order info let newOrder = exchange.GetOrder(&newId).unwrap(); Log!("Modified Order Info:", newOrder); // Cancel the order let _ = exchange.CancelOrder(&newId); }
    c++
    void main() { // Create a limit buy order auto id = exchange.CreateOrder("SOL_USDT.swap", "buy", 88, 1); Log("Original Order ID:", id); Sleep(2000); // Query the original order info auto order = exchange.GetOrder(id); Log("Original Order Info:", order); Sleep(1000); // Modify the order's price and quantity auto newId = exchange.ModifyOrder(id, "buy", 77, 2); Log("Modified Order ID:", newId); Sleep(2000); // Query the modified order info auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel the order exchange.CancelOrder(newId); }
  • Use the additional parameter (option) to modify the order's price match mode.

    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 the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter var option = {"priceMatch": "QUEUE_20"} var sideWithOption = "buy;" + JSON.stringify(option) var newId = exchange.ModifyOrder(id, sideWithOption, -1, 2) Log("Modified Order ID:", newId) Sleep(2000) // Query the modified order information var newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) // Cancel the order exchange.CancelOrder(newId) }
    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 the order and set the price match mode to QUEUE_20 # Pass the additional parameter (JSON format) via the side parameter option = {"priceMatch": "QUEUE_20"} sideWithOption = "buy;" + json.dumps(option) newId = exchange.ModifyOrder(id, sideWithOption, -1, 2) Log("Modified Order ID:", newId) Sleep(2000) # Query the modified order information newOrder = exchange.GetOrder(newId) Log("Modified Order Info:", newOrder) # Cancel the order exchange.CancelOrder(newId)
    rust
    fn main() { // Create a limit buy order let id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1).unwrap(); Log!("Original Order ID:", id); Sleep(2000); // Modify the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter; Rust does not support JSON.stringify, so construct the JSON text directly using a raw string let option = r#"{"priceMatch": "QUEUE_20"}"#; let sideWithOption = format!("buy;{}", option); let newId = exchange.ModifyOrder(&id, &sideWithOption, -1, 2).unwrap(); Log!("Modified Order ID:", newId); Sleep(2000); // Query the modified order information let newOrder = exchange.GetOrder(&newId).unwrap(); Log!("Modified Order Info:", newOrder); // Cancel the order let _ = exchange.CancelOrder(&newId); }
    c++
    void main() { // Create a limit buy order auto id = exchange.CreateOrder("SOL_USDT.swap", "buy", 77, 1); Log("Original Order ID:", id); Sleep(2000); // Modify the order and set the price match mode to QUEUE_20 // Pass the additional parameter (JSON format) via the side parameter json option = R"({"priceMatch": "QUEUE_20"})"_json; string sideWithOption = "buy;" + option.dump(); auto newId = exchange.ModifyOrder(id, sideWithOption, -1, 2); Log("Modified Order ID:", newId); Sleep(2000); // Query the modified order information auto newOrder = exchange.GetOrder(newId); Log("Modified Order Info:", newOrder); // Cancel the order exchange.CancelOrder(newId); }

Returns

TypeDescription

string / null value

Returns the order ID when the order modification succeeds, and returns a null value when the modification fails. The returned order ID may be the same as the original order ID or different, depending on the exchange API implementation. Some exchanges return a new order ID after modifying the order, while others keep the order ID unchanged.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

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

side

string

Yes

The side parameter is used to specify the order's trade direction.

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

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

Supports additional parameters (option): Additional parameters can be passed via 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 the price match mode, etc.); the specific parameters supported depend on the exchange API.

price

number

Yes

The price parameter is used to set the new price of the order. When the price is -1, it means the price is not modified, or depending on the exchange API implementation, it may be converted to a market order.

amount

number

Yes

The amount parameter is used to set the new order quantity. When the quantity is -1, it means the quantity is not modified. Note that when the order is a spot market buy order, the order quantity represents the buy amount; for the market buy orders of certain spot exchanges, the order quantity is the amount of the trading currency.

See Also

Remarks

The order ID returned by the exchange.ModifyOrder() function may behave differently depending on the exchange API implementation. Some exchange APIs return an updated order ID, while others keep it unchanged. It is recommended to use the returned new order ID for subsequent operations.

The exchange.ModifyOrder() function does not validate the validity of parameters according to the exchange interface rules, but instead submits the parameters directly to the exchange API. When invalid parameters are passed in (such as a price or quantity of -1), the parameters may be ignored by the exchange, and the order will retain its original attributes unchanged.

Supports passing additional parameters (option) via the side parameter to modify other order attributes. Additional parameters must be merged with the side parameter before being passed in, in the format "side;{JSON object}" (recommended) or "side;key=value" (URL-encoded format). For example, to modify the price match mode: "buy;{\"priceMatch\":\"QUEUE_20\"}".

For modifying market orders among regular orders, you need to check specifically whether the exchange API supports it. Some exchanges do not support modifying market orders.

When modifying an order, the order's other attributes (such as order type, position mode, account mode, leverage, order time-in-force rules, etc.) usually retain the settings of the original order. If you need to modify these attributes, they can be passed in via additional parameters (option), provided the exchange API supports it.

Certain exchange APIs may convert an order into a market order when the price parameter is not received (price is -1 or null). For spot market buy orders, note that the unit of the order quantity may be the amount rather than the number of coins.

Support for the order modification feature depends on the specific exchange; some exchanges may not support the order modification feature, or may only support modifying certain parameters. Please consult the API documentation of the corresponding exchange before use.

The exchange.ModifyConditionOrder() function is used to modify an existing conditional order, allowing modification of the order amount, trigger condition, and execution price of the conditional order. It supports modifying other properties of the conditional order through additional parameters (depending on the specific support of the exchange API).

exchange.ModifyConditionOrder(orderId, side, amount, condition)

Examples

  • Modify the quantity and trigger conditions of a conditional order.

    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 the original conditional order information var order = exchange.GetConditionOrder(id) Log("Original Condition Order Info:", order) Sleep(1000) // Modify the quantity and trigger conditions of the conditional order var newCondition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75, TpOrderPrice: 71 } var newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) // Query the modified conditional order information var newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) // Cancel the conditional order exchange.CancelConditionOrder(newId) }
    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 the original conditional order information order = exchange.GetConditionOrder(id) Log("Original Condition Order Info:", order) Sleep(1000) # Modify the quantity and trigger conditions of the conditional order newCondition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 75, "TpOrderPrice": 71 } newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) # Query the modified conditional order information newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) # Cancel the conditional order exchange.CancelConditionOrder(newId)
    rust
    fn main() { // Create a take-profit conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 76.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, &condition).unwrap(); Log!("Original Condition Order ID:", id); Sleep(2000); // Query the original conditional order information let order = exchange.GetConditionOrder(&id); Log!("Original Condition Order Info:", order); Sleep(1000); // Modify the quantity and trigger conditions of the conditional order let newCondition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75.0, TpOrderPrice: 71.0, ..Default::default() }; let newId = exchange.ModifyConditionOrder(&id, "buy", 2, &newCondition).unwrap(); Log!("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information let newOrder = exchange.GetConditionOrder(&newId); Log!("Modified Condition Order Info:", newOrder); // Cancel the conditional order let _ = exchange.CancelConditionOrder(&newId); }
    c++
    void main() { // Create a take-profit conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 76}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition); Log("Original Condition Order ID:", id); Sleep(2000); // Query the original conditional order information auto order = exchange.GetConditionOrder(id); Log("Original Condition Order Info:", order); Sleep(1000); // Modify the quantity and trigger conditions of the conditional order OrderCondition newCondition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 75, .TpOrderPrice = 71}; auto newId = exchange.ModifyConditionOrder(id, "buy", 2, newCondition); Log("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information auto newOrder = exchange.GetConditionOrder(newId); Log("Modified Condition Order Info:", newOrder); // Cancel the conditional order exchange.CancelConditionOrder(newId); }
  • Use the additional parameter (option) to modify the trigger price type of a conditional order.

    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 (index) // Pass the additional parameter via the side parameter (in JSON format) var option = {"newTpTriggerPxType": "index"} var sideWithOption = "buy;" + JSON.stringify(option) var newCondition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75, TpOrderPrice: 71 } var newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) // Query the modified conditional order information var newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) // Cancel the conditional order exchange.CancelConditionOrder(newId) }
    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 (index) # Pass the additional parameter via the side parameter (in JSON format) option = {"newTpTriggerPxType": "index"} sideWithOption = "buy;" + json.dumps(option) newCondition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 75, "TpOrderPrice": 71 } newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition) Log("Modified Condition Order ID:", newId) Sleep(2000) # Query the modified conditional order information newOrder = exchange.GetConditionOrder(newId) Log("Modified Condition Order Info:", newOrder) # Cancel the conditional order exchange.CancelConditionOrder(newId)
    rust
    fn main() { // Create a take-profit conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 77.0, TpOrderPrice: 76.0, ..Default::default() }; let id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, &condition).unwrap(); Log!("Original Condition Order ID:", id); Sleep(2000); // Modify the conditional order and set the trigger price type to index price (index) // Pass the additional parameter via the side parameter (in JSON format; Rust has no JSON serialization here, so a raw string literal is used directly) let sideWithOption = r#"buy;{"newTpTriggerPxType": "index"}"#; let newCondition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 75.0, TpOrderPrice: 71.0, ..Default::default() }; let newId = exchange.ModifyConditionOrder(&id, sideWithOption, 2, &newCondition).unwrap(); Log!("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information let newOrder = exchange.GetConditionOrder(&newId); Log!("Modified Condition Order Info:", newOrder); // Cancel the conditional order let _ = exchange.CancelConditionOrder(&newId); }
    c++
    void main() { // Create a take-profit conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 77, .TpOrderPrice = 76}; auto id = exchange.CreateConditionOrder("SOL_USDT.swap", "buy", 1, condition); Log("Original Condition Order ID:", id); Sleep(2000); // Modify the conditional order and set the trigger price type to index price (index) // Pass the additional parameter via the side parameter (in JSON format) json option = R"({"newTpTriggerPxType": "index"})"_json; string sideWithOption = "buy;" + option.dump(); OrderCondition newCondition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 75, .TpOrderPrice = 71}; auto newId = exchange.ModifyConditionOrder(id, sideWithOption, 2, newCondition); Log("Modified Condition Order ID:", newId); Sleep(2000); // Query the modified conditional order information auto newOrder = exchange.GetConditionOrder(newId); Log("Modified Condition Order Info:", newOrder); // Cancel the conditional order exchange.CancelConditionOrder(newId); }

Returns

TypeDescription

string / null value

When the conditional order is successfully modified, the conditional order ID is returned; when the modification fails, a null value is returned. The returned conditional order ID may be the same as the original conditional order ID, or it may be different, depending on the specific implementation of the exchange API. Some exchanges return a new conditional order ID after modifying the conditional order, while some exchanges keep the conditional order ID unchanged.

Arguments

NameTypeRequiredDescription

orderId

string

Yes

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

side

string

Yes

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

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

For futures exchange objects, the available values for the side parameter are: buy, closebuy, sell, closesell. buy means opening a long position, closebuy means closing a long position, sell means opening a short position, closesell means closing a short position.

Additional parameters (option) supported: 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 properties of the conditional order (such as the trigger price type, etc.), and the specific parameters supported depend on the exchange API.

amount

number

Yes

The amount parameter is used to set the new order amount of the conditional order. When the amount is -1, it indicates that the order amount is not modified. For futures exchange objects, the order amount parameter amount is denominated in the number of contracts.

condition

object

Yes

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

See Also

Remarks

The conditional order ID returned by the exchange.ModifyConditionOrder() function may exhibit different behaviors depending on the exchange API implementation. Some exchange APIs return an updated conditional order ID, while others keep it unchanged. It is recommended to use the returned new conditional order ID for subsequent operations.

The exchange.ModifyConditionOrder() function does not validate the validity of the parameters according to the exchange interface rules, but submits the parameters directly to the exchange API. When invalid parameters are passed in (such as an amount of -1), the parameter may be ignored by the exchange, and the conditional order retains its original properties unchanged.

Passing additional parameters (option) through the side parameter is supported, used to modify other properties of the conditional order. The additional parameters need to be merged with the side parameter, in the format "side;{JSON object}" (recommended) or "side;key=value" (URL-encoded format). For example, to modify the trigger price type: "buy;{\"newTpTriggerPxType\":\"index\"}".

For market order modification of conditional orders, you need to specifically check whether the exchange API supports it. Setting TpOrderPrice or SlOrderPrice in the condition parameter to -1 indicates a market order.

When modifying a conditional order, other properties of the conditional order (such as condition type, position mode, account mode, leverage, etc.) are usually retained from the original conditional order's settings. If you need to modify these properties, you can pass them in through additional parameters (option), provided that the exchange API supports it.

The trigger price type can be modified through additional parameters, for example, changing the trigger price type from the last price (last) to the index price (index) or the mark price (mark). The specific parameter names and support status depend on the exchange API documentation.

The support for the conditional order modification feature depends on the specific exchange. Some exchanges may not support the conditional order modification feature, or may only support modifying some parameters. Please consult the API documentation of the corresponding exchange before use.

exchange.CancelConditionOrder() function is used to cancel a conditional order. The format of the conditional order Id is similar to that of a regular order Id, consisting of the exchange symbol code and the exchange's original conditional order Id, separated by an English comma.

When calling the exchange.CancelConditionOrder() function to cancel a conditional order, the conditionOrderId parameter passed in is consistent with the Id attribute of the conditional order structure.

exchange.CancelConditionOrder(conditionOrderId)
exchange.CancelConditionOrder(conditionOrderId, ...args)

Examples

  • Cancel a conditional order.

    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)
    rust
    fn main() { // Create a stop-loss conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000.0, SlOrderPrice: -1.0, // Market order ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition).unwrap(); Sleep(1000); let _ = exchange.CancelConditionOrder(&id); }
    c++
    void main() { // Create a stop-loss conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = -1}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Sleep(1000); exchange.CancelConditionOrder(id); }
  • Batch cancel condition orders, with condition order information output.

    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)
    rust
    fn main() { // Create several condition orders let condition1 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000.0, TpOrderPrice: 65000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition1); let condition2 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_SL, SlTriggerPrice: 58000.0, SlOrderPrice: 58000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition2); Sleep(1000); let orders = exchange.GetConditionOrders(None).unwrap(); for i in 0..orders.len() { // In Rust, CancelConditionOrder does not support extended parameters; output the accompanying information with Log let _ = exchange.CancelConditionOrder(&orders[i].Id); Log!("Canceled condition order:", orders[i]); Sleep(500); } }
    c++
    void main() { // Create several condition orders OrderCondition condition1 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1); OrderCondition condition2 = {.ConditionType = ORDER_CONDITION_TYPE_SL, .SlTriggerPrice = 58000, .SlOrderPrice = 58000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition2); Sleep(1000); auto orders = exchange.GetConditionOrders(); for (int i = 0 ; i < orders.size() ; i++) { exchange.CancelConditionOrder(orders[i].Id, "Canceled condition order:", orders[i]); Sleep(500); } }

Returns

TypeDescription

bool

The exchange.CancelConditionOrder() function returns a truthy value (e.g. true) to indicate that the request to cancel the conditional order was sent successfully, and returns a falsy value (e.g. false) to indicate that the request to cancel the conditional order 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

An extended parameter used to output additional information to the log of this canceled conditional order. Multiple arg parameters can be passed in.

See Also

Remarks

The return value of the exchange.CancelConditionOrder() function only indicates whether the cancellation request was sent successfully or failed. To determine whether the exchange has actually canceled the conditional order, you can call the exchange.GetConditionOrders() function for confirmation.

Only untriggered conditional orders can be canceled; conditional orders that have already been triggered and converted into regular orders cannot be canceled through this function.

The exchange.GetConditionOrder() function is used to retrieve information about a specified conditional order.

exchange.GetConditionOrder(conditionOrderId)

Examples

javascript
function main(){ // Create a take-profit conditional order var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000, TpOrderPrice: 65000 } var id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Sleep(1000) // The parameter id is the conditional order number; fill in the number of the conditional order you want to query var order = exchange.GetConditionOrder(id) Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "Status:", order.Status, "Type:", order.Type, "Condition:", order.Condition) }
python
def main(): # Create a take-profit conditional order condition = { "ConditionType": ORDER_CONDITION_TYPE_TP, "TpTriggerPrice": 65000, "TpOrderPrice": 65000 } id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition) Sleep(1000) order = exchange.GetConditionOrder(id) Log("Id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "Status:", order["Status"], "Type:", order["Type"], "Condition:", order["Condition"])
rust
fn main() { // Create a take-profit conditional order let condition = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000.0, TpOrderPrice: 65000.0, ..Default::default() }; let id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition).unwrap(); Sleep(1000); // The parameter id is the conditional order number; fill in the number of the conditional order you want to query let order = exchange.GetConditionOrder(&id).unwrap(); Log!("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "Status:", order.Status, "Type:", order.Type, "Condition:", order.Condition); }
c++
void main() { // Create a take-profit conditional order OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; auto id = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition); Sleep(1000); auto order = exchange.GetConditionOrder(id); Log("Id:", order.Id, "Price:", order.Price, "Amount:", order.Amount, "Status:", order.Status, "Type:", order.Type); }

Returns

TypeDescription

Order / null value

Query the details of a conditional order by its conditional order Id. When the query succeeds, the Order structure is returned; when the query fails, a null value is returned.

The returned Order structure contains a Condition field, which holds the 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 format of the conditional order Id is similar to that of a regular order Id, consisting of the exchange symbol code and the exchange's original conditional order Id, separated by an English comma.

The conditionOrderId parameter passed in when calling the exchange.GetConditionOrder() function to query a conditional order is consistent with the Id property 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 the trigger condition, trigger price, and order status.

Conditional order statuses include: not triggered, triggered, canceled, etc. The specific status values are determined by the exchange.

exchange.GetConditionOrders() function is used to obtain unfinished conditional orders (conditional orders that have not yet been triggered or canceled).

exchange.GetConditionOrders()
exchange.GetConditionOrders(symbol)

Examples

  • Use the spot exchange object to create multiple condition orders, then query the pending condition order information.

    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])
    rust
    fn main() { // Create multiple condition orders let condition1 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000.0, TpOrderPrice: 65000.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, &condition1); let condition2 = OrderCondition { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 3200.0, TpOrderPrice: 3200.0, ..Default::default() }; let _ = exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, &condition2); Sleep(1000); // Query all pending condition orders let orders = exchange.GetConditionOrders(None).unwrap(); Log!("Pending condition orders count:", orders.len()); for i in 0..orders.len() { Log!("Condition order", i + 1, ":", orders[i]); } }
    c++
    void main() { // Create multiple condition orders OrderCondition condition1 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000}; exchange.CreateConditionOrder("BTC_USDT", "sell", 0.01, condition1); OrderCondition condition2 = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 3200, .TpOrderPrice = 3200}; exchange.CreateConditionOrder("ETH_USDT", "sell", 0.1, condition2); Sleep(1000); // Query all pending condition orders auto orders = exchange.GetConditionOrders(); Log("Pending condition orders count:", orders.size()); for (int i = 0; i < orders.size(); i++) { Log("Condition order", i+1, ":", orders[i]); } }
  • Query the pending condition orders for a specified trading pair.

    javascript
    function main() { // Query the pending condition orders for the BTC_USDT trading pair var orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders) }
    python
    def main(): # Query the pending condition orders for the BTC_USDT trading pair orders = exchange.GetConditionOrders("BTC_USDT") Log("BTC_USDT pending condition orders:", orders)
    rust
    fn main() { // Query the pending condition orders for the BTC_USDT trading pair let orders = exchange.GetConditionOrders("BTC_USDT"); Log!("BTC_USDT pending condition orders:", orders); }
    c++
    void main() { // Query the pending condition orders for the BTC_USDT trading pair auto orders = exchange.GetConditionOrders("BTC_USDT"); Log("BTC_USDT pending condition orders:", orders); }

Returns

TypeDescription

Order array / null value

The exchange.GetConditionOrders() function returns a Order structure array when the data request is successful, and returns a null value when the data request fails.

The returned Order structure contains a Condition field, which contains the detailed configuration information of 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 or range of trading instruments to be queried.

For spot exchange objects, when the symbol parameter is not passed, the unfinished conditional order data of all spot instruments will be requested.

For futures exchange objects, when the symbol parameter is not passed, by default it requests the unfinished conditional order data of all instruments within the dimension range of the current trading pair and contract code.

See Also

Remarks

In the GetConditionOrders function, the use cases of the symbol parameter are summarized as follows:

Exchange Object Categorysymbol ParameterQuery ScopeRemarks
Spotsymbol parameter not passedQuery all spot trading pairsApplicable to all call scenarios; if the exchange interface does not support it, an error is reported and a null value is returned, which will not be repeated below
SpotSpecify a trading instrument, with symbol parameter as: "BTC_USDT"Query the specified BTC_USDT trading pairFor spot exchange objects, the format of the symbol parameter is: "BTC_USDT"
Futuressymbol parameter not passedQuery all trading instruments within the dimension range of the current trading pair and contract codeAssuming the current trading pair is BTC_USDT and the contract code is swap, this queries all USDT-margined perpetual contracts. Equivalent to calling GetConditionOrders("USDT.swap")
FuturesSpecify a trading instrument, with symbol parameter as: "BTC_USDT.swap"Query the specified BTC USDT-margined perpetual contractFor futures exchange objects, the format of the symbol parameter is: a combination of the trading pair and contract code defined by the FMZ platform, with the two separated by the character ".".
FuturesSpecify a range of trading instruments, with symbol parameter as: "USDT.swap"Query all USDT-margined perpetual contracts-
Futures exchange supporting optionssymbol parameter not passedQuery all option contracts within the dimension range of the current trading pairAssuming the current trading pair is BTC_USDT and the contract is set to an option contract, such as a Binance option contract: BTC-240108-40000-C
Futures exchange supporting optionsSpecify a specific trading instrumentQuery the specified option contractFor example, for the Binance futures exchange, the symbol parameter is: BTC_USDT.BTC-240108-40000-C
Futures exchange supporting optionsSpecify a range of trading instruments, with symbol parameter as: "USDT.option"Query all USDT-margined option contracts-

In the GetConditionOrders function, the query dimension ranges of the futures exchange object are summarized as follows:

symbol ParameterRequest Scope DefinitionRemarks
USDT.swapUSDT-margined perpetual contract range.For dimensions not supported by the exchange API interface, an error is reported and a null value is returned when called.
USDT.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_ffMixed-margin delivery contract range.Futures_Kraken exchange
USD.swap_pfMixed-margin perpetual contract range.Futures_Kraken exchange

When the account represented by the exchange object exchange has no unfinished conditional orders within the query scope or on the specified trading instrument, calling this function will return an empty array, i.e.: [].

Support for the conditional order feature depends on the specific exchange; some exchanges may not support the conditional order feature.

The exchange.GetHistoryConditionOrders() function is used to retrieve the historical conditional orders (including triggered, canceled, and expired conditional orders) for the current trading pair or contract, and supports specifying a particular trading instrument.

exchange.GetHistoryConditionOrders()
exchange.GetHistoryConditionOrders(symbol)
exchange.GetHistoryConditionOrders(symbol, since)
exchange.GetHistoryConditionOrders(symbol, since, limit)
exchange.GetHistoryConditionOrders(since)
exchange.GetHistoryConditionOrders(since, limit)

Examples

  • Query historical conditional orders. The returned results are sorted in ascending order by time.

    javascript
    function main() { var historyConditionOrders = exchange.GetHistoryConditionOrders() Log("Historical condition orders count:", historyConditionOrders.length) // Iterate and display; orders are sorted in ascending order by the Time property for (var i = 0; i < historyConditionOrders.length; i++) { Log("Order", i+1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status) } }
    python
    def main(): historyConditionOrders = exchange.GetHistoryConditionOrders() Log("Historical condition orders count:", len(historyConditionOrders)) # Iterate and display; orders are sorted in ascending order by the Time property for i in range(len(historyConditionOrders)): Log("Order", i+1, "Created at:", historyConditionOrders[i]["Time"], "ID:", historyConditionOrders[i]["Id"], "Status:", historyConditionOrders[i]["Status"])
    rust
    fn main() { let historyConditionOrders = exchange.GetHistoryConditionOrders(None, None, None).unwrap(); Log!("Historical condition orders count:", historyConditionOrders.len()); // Iterate and display; orders are sorted in ascending order by the Time property for i in 0..historyConditionOrders.len() { Log!("Order", i + 1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status); } }
    c++
    void main() { auto historyConditionOrders = exchange.GetHistoryConditionOrders(); Log("Historical condition orders count:", historyConditionOrders.size()); // Iterate and display; orders are sorted in ascending order by the Time property for (int i = 0; i < historyConditionOrders.size(); i++) { Log("Order", i+1, "Created at:", historyConditionOrders[i].Time, "ID:", historyConditionOrders[i].Id, "Status:", historyConditionOrders[i].Status); } }
  • Query the historical conditional orders of a specified trading pair, and limit the number of results returned.

    javascript
    function main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair var historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders) }
    python
    def main(): # Query the 10 most recent historical conditional orders for the BTC_USDT trading pair historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10) Log("BTC_USDT historical condition orders:", historyConditionOrders)
    rust
    fn main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair let historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10); Log!("BTC_USDT historical condition orders:", historyConditionOrders); }
    c++
    void main() { // Query the 10 most recent historical conditional orders for the BTC_USDT trading pair auto historyConditionOrders = exchange.GetHistoryConditionOrders("BTC_USDT", 0, 10); Log("BTC_USDT historical condition orders:", historyConditionOrders); }
  • Query historical conditional orders by time range.

    javascript
    function main() { // Query historical conditional orders starting from the specified timestamp var startTime = new Date("2024-01-01").getTime() var historyConditionOrders = exchange.GetHistoryConditionOrders(startTime, 50) Log("Historical condition orders since:", historyConditionOrders) }
    python
    def main(): # Query historical conditional orders starting from the specified timestamp import time startTime = int(time.mktime(time.strptime("2024-01-01", "%Y-%m-%d")) * 1000) historyConditionOrders = exchange.GetHistoryConditionOrders(startTime, 50) Log("Historical condition orders since:", historyConditionOrders)
    rust
    fn main() { // Query historical conditional orders starting from the specified timestamp let startTime: i64 = 1704067200000; // Timestamp for 2024-01-01 // In Rust, passing None for the symbol parameter means the current trading pair let historyConditionOrders = exchange.GetHistoryConditionOrders(None, startTime, 50); Log!("Historical condition orders since:", historyConditionOrders); }
    c++
    void main() { // Query historical conditional orders starting from the specified timestamp auto startTime = 1704067200000; // Timestamp for 2024-01-01 // In C++, the symbol parameter cannot be omitted; pass "" to indicate the current trading pair auto historyConditionOrders = exchange.GetHistoryConditionOrders("", startTime, 50); Log("Historical condition orders since:", historyConditionOrders); }

Returns

TypeDescription

Order array / null

The exchange.GetHistoryConditionOrders() 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 a Condition field, which holds the detailed configuration information of 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 format of the symbol parameter is: BTC_USDT; if it is a futures exchange object, taking a perpetual contract as an example, the format of the symbol parameter is: BTC_USDT.swap.

If you are querying conditional order data for an options contract, set the symbol parameter to "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example). Its 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 ".". If this parameter is not passed, the conditional order data for the currently set trading pair and contract code is requested by default.

since

number

No

The since parameter is used to specify the starting timestamp of 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 the symbol, since, and limit parameters are not specified, the historical conditional orders of the current trading pair or contract are queried by default, i.e., the historical conditional orders within a certain range closest to the current time are queried. The query range depends on the single-query range of the exchange interface.

  • When the symbol parameter is specified, the historical conditional orders of the set trading instrument are queried.

  • When the since parameter is specified, the query starts from the since timestamp and proceeds toward the current time.

  • When the limit parameter is specified, the query returns after a sufficient number of records has been found.

  • This function is only supported by exchanges that provide a historical conditional order query interface.

Historical conditional orders include conditional orders in states such as triggered (converted to regular orders), canceled, and expired.

The returned array of historical conditional orders is sorted in ascending order by order creation time (the Time attribute), i.e., orders with the earliest time are at the front of the array, and orders with the latest time are at the back.

Support for the conditional order feature depends on the specific exchange. Some exchanges may not support the conditional order feature or the historical conditional order query feature.

The exchange.SetPrecision() function is used to set the precision of the price and order amount for the exchange exchange object. Once set, the system will automatically ignore any excess portion of the data that exceeds the specified precision.

exchange.SetPrecision(pricePrecision, amountPrecision)

Examples

javascript
function main(){ // Set the price decimal precision to 2 digits and the order amount decimal precision to 3 digits exchange.SetPrecision(2, 3) }
python
def main(): exchange.SetPrecision(2, 3)
rust
fn main() { // Set the price decimal precision to 2 digits and the order amount decimal precision to 3 digits exchange.SetPrecision(2, 3); }
c++
void main() { exchange.SetPrecision(2, 3); }

Arguments

NameTypeRequiredDescription

pricePrecision

number

Yes

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

amountPrecision

number

Yes

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

See Also

Remarks

The backtesting system does not support this function; the numerical precision in the backtesting system is handled automatically by the system.

Sets the current exchange rate for the exchange object.

exchange.SetRate(rate)

Examples

javascript
function main(){ Log(exchange.GetTicker()) // Set the exchange rate conversion exchange.SetRate(7) Log(exchange.GetTicker()) // Set to 1, no conversion exchange.SetRate(1) }
python
def main(): Log(exchange.GetTicker()) exchange.SetRate(7) Log(exchange.GetTicker()) exchange.SetRate(1)
rust
fn main() { Log!(exchange.GetTicker(None)); // Set the exchange rate conversion exchange.SetRate(7); Log!(exchange.GetTicker(None)); // Set to 1, no conversion exchange.SetRate(1); }
c++
void main() { Log(exchange.GetTicker()); exchange.SetRate(7); Log(exchange.GetTicker()); exchange.SetRate(1); }

Arguments

NameTypeRequiredDescription

rate

number

Yes

The rate parameter is used to specify the conversion rate.

See Also

Remarks

If you set an exchange rate value using the exchange.SetRate() function (for example, set it to 7), then all price information represented by the current exchange object — such as tickers, depth, order prices, and so on — will be multiplied by the set rate of 7 for conversion.

For example, exchange is an exchange with USD as its quote currency. After executing exchange.SetRate(7), all prices in live trading will be multiplied by 7, converting them to prices close to those quoted in CNY.

exchange.IO() function is used to call other interfaces related to the exchange object.

exchange.IO(k, ...args)

Examples

  • Use the "api" mode to call the OKX futures batch order placement interface, and pass the JSON-formatted order data via 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 placement 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)
    rust
    fn main() { // Rust has no JSON serialization; construct the order array directly using a raw string let arrOrders = r#"[ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ]"#; // Call exchange.IO to directly access the exchange's batch order placement interface; multiple parameters are passed in as a tuple let ret = exchange.IO(("api", "POST", "/api/v5/trade/batch-orders", "", arrOrders)); Log!(ret); }
    c++
    void main() { json arrOrders = R"([ {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}, {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"2","posSide":"long"} ])"_json; auto ret = exchange.IO("api", "POST", "/api/v5/trade/batch-orders", "", arrOrders.dump()); Log(ret); }
  • When the value of a key in the params parameter is of string type, you need to wrap the parameter value with single quotes:

    javascript
    var amount = 1 var price = 10 var basecurrency = "ltc" function main () { // Note that there is a ' character on both the left and right sides of amount.toString() and price.toString() var message = "symbol=" + basecurrency + "&amount='" + amount.toString() + "'&price='" + price.toString() + "'&side=buy" + "&type=limit" var id = exchange.IO("api", "POST", "/v1/order/new", message) }
    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)
    rust
    fn main() { let amount = 1; let price = 10; let basecurrency = "ltc"; // Note that there is a ' character on both the left and right sides of the amount and price parameter values let message = format!("symbol={}&amount='{}'&price='{}'&side=buy&type=limit", basecurrency, amount, price); let id = exchange.IO(("api", "POST", "/v1/order/new", message)); }
    c++
    void main() { auto amount = 1.0; auto price = 10.0; auto basecurrency = "ltc"; string message = str_format("symbol=%s&amount=\"%.1f\"&price=\"%.1f\"&side=buy&type=limit", basecurrency, amount, price); auto id = exchange.IO("api", "POST", "/v1/order/new", message); }
  • The resource parameter supports passing in a complete URL:

    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)
    rust
    fn main() { let ret = exchange.IO(("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC")); Log!(ret); }
    c++
    void main() { auto ret = exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC"); Log(ret); }
  • A GET request that does not use the 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)
    rust
    fn main() { let ret = exchange.IO(("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT")); Log!(ret); }
    c++
    void main() { auto ret = exchange.IO("api", "GET", "/api/v5/trade/orders-pending", "instType=SPOT"); Log(ret); }
  • Switch trading pair at runtime:

    javascript
    function main() { // For example, when the live bot starts, the exchange object's current trading pair is BTC_USDT; print the ticker of the current trading pair Log(exchange.GetTicker()) // Switch the trading pair to LTC_BTC exchange.IO("currency", "LTC_BTC") Log(exchange.GetTicker()) }
    python
    def main(): Log(exchange.GetTicker()) exchange.IO("currency", "LTC_BTC") Log(exchange.GetTicker())
    rust
    fn main() { // For example, when the live bot starts, the exchange object's current trading pair is BTC_USDT; print the ticker of the current trading pair Log!(exchange.GetTicker(None)); // Switch the trading pair to LTC_BTC let _ = exchange.IO(("currency", "LTC_BTC")); Log!(exchange.GetTicker(None)); }
    c++
    void main() { Log(exchange.GetTicker()); exchange.IO("currency", "LTC_BTC"); Log(exchange.GetTicker()); }
  • Switch the exchange API base address:

    javascript
    function main () { // exchanges[0] is the first exchange object added when the live bot was created exchanges[0].IO("base", "https://api.huobi.pro") }
    python
    def main(): exchanges[0].IO("base", "https://api.huobi.pro")
    rust
    fn main() { // exchanges[0] is the first exchange object added when the live bot was created let _ = exchanges[0].IO(("base", "https://api.huobi.pro")); }
    c++
    void main() { exchanges[0].IO("base", "https://api.huobi.pro"); }
  • Switch the market data API base address via "mbase" (using Bitfinex as an example):

    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")
    rust
    fn main() { exchange.SetBase("https://api.bitfinex.com"); let _ = exchange.IO(("mbase", "https://api-pub.bitfinex.com")); }
    c++
    void main() { exchange.SetBase("https://api.bitfinex.com"); exchange.IO("mbase", "https://api-pub.bitfinex.com"); }
  • Switch between the demo/live trading environment (using OKX Futures as an example):

    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)
    rust
    fn main() { let _ = exchange.IO(("simulate", true)); // Switch to demo trading environment // ... trading logic ... let _ = exchange.IO(("simulate", false)); // Switch back to live trading environment }
    c++
    void main() { exchange.IO("simulate", true); // ... trading logic ... exchange.IO("simulate", false); }
  • Switch contract margin mode and position mode (using Binance Futures as an example):

    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)
    rust
    fn main() { let _ = exchange.IO(("dual", true)); // Switch to hedge mode (dual position) let _ = exchange.IO(("dual", false)); // Switch to one-way mode let _ = exchange.SetContractType("swap"); let _ = exchange.IO(("cross", true)); // Switch to cross margin let _ = exchange.IO(("cross", false)); // Switch to isolated margin }
    c++
    void main() { exchange.IO("dual", true); exchange.IO("dual", false); exchange.SetContractType("swap"); exchange.IO("cross", true); exchange.IO("cross", false); }
  • Switch to unified account mode (using Binance Futures as an example):

    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)
    rust
    fn main() { let _ = exchange.IO(("unified", true)); // Switch to unified account mode let _ = exchange.IO(("unified", false)); // Switch to normal mode }
    c++
    void main() { exchange.IO("unified", true); exchange.IO("unified", false); }
  • Set self-trade prevention mode (using Binance as an example):

    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")
    rust
    fn main() { // "NONE" means disable STP mode, other parameters: "EXPIRE_TAKER", "EXPIRE_MAKER", "EXPIRE_BOTH" let _ = exchange.IO(("selfTradePreventionMode", "NONE")); }
    c++
    void main() { exchange.IO("selfTradePreventionMode", "NONE"); }
  • Futures_edgeX calculates the order Hash and signs it:

    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)
    rust
    fn main() { let strJson = r#"{ "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": true, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 }"#; let signature = exchange.IO(("calcOrderHashAndSign", strJson)); Log!(signature); }
    c++
    void main() { json params = R"({ "assetIdSynthetic": "0x4554482d3900000000000000000000", "assetIdCollateral": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "assetIdFee": "0x2ce625e94458d39dd0bf3b45a843544dd4a14b8169045a3a3d15aa564b936c5", "isBuyingSynthetic": true, "amountSynthetic": 10000000, "amountCollateral": 13020000, "amountFee": 6250, "nonce": 676432751, "accountID": 601416704693633632, "expirationTimestamp": 484831 })"_json; auto signature = exchange.IO("calcOrderHashAndSign", params.dump()); Log(signature); }
  • rate mode rate limiting - Limit GetTicker to a maximum of 10 calls per second; returns null when the limit is exceeded:

    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")
    rust
    fn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s")); for _i in 0..20 { // GetTicker returns Err when the limit is exceeded match exchange.GetTicker("BTC_USDT") { Ok(ticker) => Log!("Ticker:", ticker.Last), Err(_) => Log!("Rate limit exceeded"), } } }
    c++
    // C++ is not supported yet
  • rate mode rate limiting - Use the "delay" parameter to automatically wait instead of returning null when the limit is exceeded:

    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"])
    rust
    fn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s", "delay")); for i in 0..20 { let ticker = exchange.GetTicker("BTC_USDT").unwrap(); Log!("Call", i + 1, "Ticker:", ticker.Last); } }
    c++
    // C++ is not supported yet
  • Multiple functions sharing a rate limit quota:

    javascript
    function main() { // GetTicker and GetDepth share the rate limit quota, with a combined maximum of 10 calls per second exchange.IO("rate", "GetTicker,GetDepth", 10, "1s") for (var i = 0; i < 20; i++) { if (i % 2 == 0) { Log("Ticker:", exchange.GetTicker("BTC_USDT")) } else { Log("Depth:", exchange.GetDepth("BTC_USDT")) } } }
    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"))
    rust
    fn main() { // GetTicker and GetDepth share the rate limit quota, with a combined maximum of 10 calls per second let _ = exchange.IO(("rate", "GetTicker,GetDepth", 10, "1s")); for i in 0..20 { if i % 2 == 0 { Log!("Ticker:", exchange.GetTicker("BTC_USDT")); } else { Log!("Depth:", exchange.GetDepth("BTC_USDT")); } } }
    c++
    // C++ is not supported yet
  • Use a wildcard to uniformly limit the call frequency of all APIs:

    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)
    rust
    fn main() { let _ = exchange.IO(("rate", "*", 100, "1m")); for i in 0..10 { let _ = exchange.GetTicker("BTC_USDT"); let _ = exchange.GetDepth("BTC_USDT"); let _ = exchange.GetAccount(); Log!("Round", i + 1, "completed"); Sleep(1000); } }
    c++
    // C++ is not supported yet
  • quota mode - strict rate limiting aligned to time windows:

    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)
    rust
    fn main() { let _ = exchange.IO(("quota", "GetTicker", 3, "1s")); for _i in 0..10 { match exchange.GetTicker("BTC_USDT") { Ok(ticker) => Log!(_D(None), "Ticker:", ticker.Last), Err(_) => Log!(_D(None), "Quota exceeded, waiting for next window"), } Sleep(100); } }
    c++
    // C++ not supported yet
  • quota mode - intraday quota, resets daily at the specified time:

    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)
    rust
    fn main() { let _ = exchange.IO(("quota", "GetTicker", 1000, "@0815")); let mut count = 0; loop { match exchange.GetTicker("BTC_USDT") { Ok(ticker) => { count += 1; Log!("Call count:", count, "Ticker:", ticker.Last); } Err(_) => { Log!("Daily quota exceeded, waiting for reset at 08:15"); Sleep(60000); // Wait 1 minute } } Sleep(1000); } }
    c++
    // C++ not supported yet
  • Combining multiple rate-limiting rules:

    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, cap of 1000 calls Log("Rate limits configured successfully") for (var i = 0; i < 5; i++) { exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") Sleep(200) } }
    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, cap of 1000 calls Log("Rate limits configured successfully") for i in range(5): exchange.GetTicker("BTC_USDT") exchange.GetDepth("BTC_USDT") Sleep(200)
    rust
    fn main() { let _ = exchange.IO(("rate", "GetTicker", 10, "1s")); // GetTicker 10 times per second let _ = exchange.IO(("rate", "GetDepth", 5, "1s")); // GetDepth 5 times per second let _ = exchange.IO(("rate", "CreateOrder", 2, "1s")); // CreateOrder 2 times per second let _ = exchange.IO(("quota", "*", 1000, "@0000")); // All APIs reset daily at 00:00, cap of 1000 calls Log!("Rate limits configured successfully"); for _i in 0..5 { let _ = exchange.GetTicker("BTC_USDT"); let _ = exchange.GetDepth("BTC_USDT"); Sleep(200); } }
    c++
    // C++ is not supported yet

Returns

TypeDescription

string / number / bool / object / array / any

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

Arguments

NameTypeRequiredDescription

k

string

Yes

Call type identifier. Different values correspond to different functions; please refer to the descriptions in each section below for details.

arg

string / number / bool / object / array / any

Yes

Extended parameters. Different parameters need to be passed in according to the different k values, and their number and types are not fixed.

See Also

Remarks

I. Directly Calling Exchange APIs ("api" mode)

javascript
exchange.IO("api", httpMethod, resource, params, raw)

Used to call the exchange's native API endpoints that are not wrapped by FMZ. FMZ automatically handles signature verification; you only need to fill in the request parameters.

ParameterTypeRequiredDescription
httpMethodstringYesGET, POST, etc.
resourcestringYesRequest path or full URL
paramsstringNoRequest parameters in URL-encoded format
rawstringNoRaw request body (JSON, etc.)

Returns a null value on failure, and this mode is only supported in live trading.

II. Switching Trading Pairs at Runtime ("currency" mode)

javascript
exchange.IO("currency", "ETH_USDT")

Used to dynamically switch trading pairs at runtime. The trading pair format is uppercase letters separated by an underscore. This instruction is equivalent to exchange.SetCurrency.

In backtesting mode, only spot is supported, and you can only switch to a trading pair with the same quote currency. After switching trading pairs for futures, you need to call exchange.SetContractType() again.

III. Switching the Base Address ("base" / "mbase" mode)

  • "base": Switches the base address of the trading interface, equivalent to exchange.SetBase().

  • "mbase": Switches the base address of the market data interface, suitable for exchanges that use different domain names for market data and trading.

IV. Common Trading Mode Instructions

The following instructions are common across multiple exchanges. For the specific support of each exchange, please refer to the description in Section V.

InstructionParameterFunction
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 the 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
simulateboolSwitch between demo and live trading
trade_marginNoneIsolated margin (tdMode=isolated)
trade_super_marginNoneCross margin (tdMode=cross)
trade_normalNoneSwitch back to normal spot mode
tdModestringDirectly set the trading mode; cross must be used in 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
simulateboolSwitch between demo and live trading

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 the sub-account name

Poloniex

CommandParameterDescription
accountIdstringSet the account ID

Bitfinex

CommandParameterDescription
versionNoneGet the current API version number

Backpack

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

Hyperliquid (Spot)

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

Futures Exchanges

Futures_Binance (Binance Futures)

CommandParameterDescription
crossboolCross/isolated margin
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 extended fields in the API response (comma-separated)

Futures_OKX (OKX Futures)

CommandParameterDescription
simulateboolSwitch between demo and live trading
crossboolCross/isolated margin; defaults to cross
dualboolHedge (long_short_mode)/one-way (net_mode) position mode

Futures_HuobiDM (Huobi Futures)

CommandParameterDescription
crossboolCross/isolated margin; defaults to isolated. Only supported for XXX_USDT perpetual swaps (swap)
dualboolHedge (dual_side)/one-way (single_side) position mode
unifiedboolUnified account mode
signHoststringSet the API signature Host address; pass an empty string to disable

Futures_Bybit

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

Futures_KuCoin

CommandParameterDescription
crossboolCross/isolated margin

Futures_GateIO

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

Futures_Bitget

CommandParameterDescription
simulateboolSwitch between demo and live trading
crossboolCross (crossed)/isolated (isolated) margin
dualboolHedge (hedge_mode)/one-way (one_way_mode) position mode

Futures_MEXC

CommandParameterDescription
crossboolCross/isolated margin

Futures_BitMEX

CommandParameterDescription
crossboolCross/isolated margin

Futures_CoinEx

CommandParameterDescription
crossboolCross/isolated margin

Futures_WOO

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

Futures_Kraken

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

Futures_Aevo

CommandParameterDescription
signingKeystringSet the signing key and return the public key. Must be obtained from the exchange's API Key page; note that it is time-sensitive

Futures_Hyperliquid

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

Futures_Deepcoin

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

Futures_DigiFinex

CommandParameterDescription
simulateboolSwitch between demo and live trading
crossboolCross/isolated margin

Futures_ApolloX

CommandParameterDescription
crossboolCross/isolated margin

Futures_Aster

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

Futures_CoinW

CommandParameterDescription
crossboolCross/isolated margin

Futures_BitMart

CommandParameterDescription
crossboolCross/isolated margin

Futures_Backpack

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

Futures_Lighter

CommandParameterDescription
crossboolCross/isolated margin
expirynumberOrder expiration timestamp (milliseconds); defaults to 29 days, minimum 4 minutes

Futures_Crypto.com

CommandParameterDescription
accountIdstringSet the trading account ID

Futures_Bitfinex

CommandParameterDescription
mbasestringSet the market data API base address

Futures_edgeX

CommandParameterDescription
calcOrderHashAndSignstring(JSON)Compute the order hash and sign it; returns the signature string

Futures_Bibox

CommandParameterDescription
crossboolCross/isolated margin; defaults to cross

Futures_Pionex

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

Futures_Phemex

CommandParameterDescription
dualboolHedge/one-way position mode. Cross/isolated margin must be set on the exchange's web interface

Futures_WooFi

Only the generic commands "api" and "currency" are supported; no exchange-specific commands.

VI. Special Platform IO Commands

Polymarket (Prediction Market)

CommandParametersDescription
nonce[number]Gets or sets the order's nonce value. Returns the current nonce when no parameter is passed; sets a new nonce when a value is passed
proxyWalletAddressNoneGets the proxy wallet address
redeemsymbol, [wait]Redeems settled positions (gas-free via Relayer). wait defaults to true, waiting for transaction confirmation; when wait is false, returns {"transactionID": "..."} immediately
mergesymbol, [amount], [wait]Merges and redeems YES+NO tokens into USDC (gas-free via Relayer). When amount is 0 or not passed, automatically takes the smaller position size of the two outcomes. wait defaults to true, waiting for transaction confirmation
l2_credentialsNoneGets L2 authentication information, returns {"apiKey":"","secret":"","passphrase":""}, used for scenarios such as WebSocket connections
batchOrdersarrayBatch order placement; the parameter is an array of order objects, each object containing symbol, side, price, amount fields, as well as an optional option field

Web3 (Blockchain)

CommandParametersDescription
abicontract address, ABI stringRegisters a contract ABI
address[private key]Gets the wallet address
encode / packtype, data...ABI-encodes data
encodePackedtype, data...ABI tightly-packed encodes data
hashparam 1-4Computes the hash value
decode / unpacktype, data...ABI-decodes data
keystringSwitches the private key used for operations

IB (Interactive Brokers)

CommandParametersDescription
statusNoneGets the connection status
timeNoneGets the IB server time
reqIdNoneForces retrieval of a new request ID
orderIdNoneGets the next available order ID
ignorestring (array)Ignores the specified error codes
scanstring (JSON)Executes the market scanner
wait[number]Waits for a market data event, with an optional timeout in seconds
debugboolDebug mode
marketDataTypenumberMarket data type (1 real-time / 2 frozen / 3 delayed / 4 delayed frozen)

Futu (Futu Securities)

CommandParametersDescription
refreshboolCache refresh; when caching is disabled, the rate limit is a maximum of 10 times per 30 seconds
accountsNoneGets the list of all accounts
statusNoneGets the connection status
lockNoneLocks trading
unlockNoneUnlocks trading
waitNoneWaits for a market data event

VII. API Rate Limiting Control ("rate" / "quota" modes)

javascript
exchange.IO("rate", functionNames, maxCalls, period, [behavior]) exchange.IO("quota", functionNames, maxCalls, period, [behavior])
  • rate: Smooth rate limiting, not strictly aligned to time windows.
  • quota: Quota-based rate limiting, strictly aligned to time windows.
ParameterTypeDescription
functionNamesstringFunction names, separated by commas for multiple; * means all
maxCallsnumberMaximum number of calls within a single time period
periodstringTime period ("1s"/"1m"/"1h") or reset time point ("@0815")
behaviorstringOptional; "delay" means wait when the limit is exceeded, defaults to returning null

The rate limiting of Buy/Sell follows the settings of CreateOrder; Go follows the settings of the actual concurrent function; IO/api only takes effect for exchange.IO("api", ...).

The exchange.Log() function is used to output order placement and cancellation logs in the log column area. When this function is called, it does not actually place an order; it is only used to output and record trading logs.

exchange.Log(orderType, price, amount)
exchange.Log(orderType, price, amount, ...args)

Examples

Using exchange.Log(orderType, price, amount) allows you to perform live order-following tests and simulated order placement, and it can also assist in recording order information.

The most common use case is: accessing the exchange's conditional order creation interface through the exchange.IO function, but calling the exchange.IO() function does not output trading log information in the live log.

In this case, you can use the exchange.Log() function to supplement the log output in order to record the order information. The same applies to cancellation operations.

javascript
var id = 123 function main() { // Order type buy, price 999, quantity 0.1 exchange.Log(LOG_TYPE_BUY, 999, 0.1) // Cancel order exchange.Log(LOG_TYPE_CANCEL, id) }
python
id = 123 def main(): exchange.Log(LOG_TYPE_BUY, 999, 0.1) exchange.Log(LOG_TYPE_CANCEL, id)
rust
fn main() { let id = 123; // Order type buy, price 999, quantity 0.1 exchange.Log(LOG_TYPE_BUY, 999, 0.1); // Cancel order; when orderType is LOG_TYPE_CANCEL, the price parameter is the order Id to be canceled (in Rust the amount parameter is required and can be passed as 0) exchange.Log(LOG_TYPE_CANCEL, id, 0); }
c++
void main() { auto id = 123; exchange.Log(LOG_TYPE_BUY, 999, 0.1); exchange.Log(LOG_TYPE_CANCEL, id); }

Arguments

NameTypeRequiredDescription

orderType

number

Yes

The orderType parameter is used to set the type of log to output. The available 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 log.

amount

number

Yes

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

arg

string / number / bool / object / array / any (any type supported by the platform)

No

An extension parameter used to output additional information to this log entry. Multiple arg parameters can be passed in.

See Also

Remarks

When the orderType parameter is LOG_TYPE_CANCEL, the price parameter represents the order Id to be canceled, which is used to print the cancellation log when canceling an order by directly calling the exchange.IO() function.

The exchange.Log() function is a member function of the exchange exchange object, which is distinct from the global function Log.

The exchange.Encode() function is used to perform signature and encryption computations.

exchange.Encode(algo, inputFormat, outputFormat, data)
exchange.Encode(algo, inputFormat, outputFormat, data, keyFormat, key)

Examples

Example of BitMEX position change push (wss protocol):

javascript
function main() { var APIKEY = "your Access Key(Bitmex API ID)" var expires = parseInt(Date.now() / 1000) + 10 var signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + expires, "hex", "{{secretkey}}") var client = Dial("wss://www.bitmex.com/realtime", 60) var auth = JSON.stringify({args: [APIKEY, expires, signature], op: "authKeyExpires"}) var pos = 0 client.write(auth) client.write('{"op": "subscribe", "args": "position"}') while (true) { var bitmexData = JSON.parse(client.read()) if(bitmexData.table == 'position' && pos != parseInt(bitmexData.data[0].currentQty)){ Log('position change', pos, parseInt(bitmexData.data[0].currentQty), '@') pos = parseInt(bitmexData.data[0].currentQty) } } }
python
import time def main(): APIKEY = "your Access Key(Bitmex API ID)" expires = int(time.time() + 10) signature = exchange.Encode("sha256", "string", "hex", "GET/realtime" + expires, "hex", "{{secretkey}}") client = Dial("wss://www.bitmex.com/realtime", 60) auth = json.dumps({"args": [APIKEY, expires, signature], "op": "authKeyExpires"}) pos = 0 client.write(auth) client.write('{"op": "subscribe", "args": "position"}') while True: bitmexData = json.loads(client.read()) if "table" in bitmexData and bitmexData["table"] == "position" and len(bitmexData["data"]) != 0 and pos != bitmexData["data"][0]["currentQty"]: Log("position change", pos, bitmexData["data"][0]["currentQty"], "@") pos = bitmexData["data"][0]["currentQty"]
c++
void main() { auto APIKEY = "your Access Key(Bitmex API ID)"; auto expires = Unix() + 10; auto signature = exchange.Encode("sha256", "string", "hex", str_format("GET/realtime%d", expires), "hex", "{{secretkey}}"); auto client = Dial("wss://www.bitmex.com/realtime", 60); json auth = R"({"args": [], "op": "authKeyExpires"})"_json; auth["args"].push_back(APIKEY); auth["args"].push_back(expires); auth["args"].push_back(signature); auto pos = 0; client.write(auth.dump()); client.write("{\"op\": \"subscribe\", \"args\": \"position\"}"); while(true) { auto bitmexData = json::parse(client.read()); if(bitmexData["table"] == "position" && bitmexData["data"][0].find("currentQty") != bitmexData["data"][0].end() && pos != bitmexData["data"][0]["currentQty"]) { Log("Test"); Log("position change", pos, bitmexData["data"][0]["currentQty"], "@"); pos = bitmexData["data"][0]["currentQty"]; } } }

Returns

TypeDescription

string

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

Arguments

NameTypeRequiredDescription

algo

string

Yes

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

It supports the following settings: "raw" (no algorithm), "sign", "signTx", "md4", "md5", "sha256", "sha512", "sha1", "keccak256", "sha3.224", "sha3.256", "sha3.384", "sha3.512", "sha3.keccak256", "sha3.keccak512", "sha512.384", "sha512.256", "sha512.224", "ripemd160", "blake2b.256", "blake2b.512", "blake2s.128", "blake2s.256".

The algo parameter also supports: "text.encoder.utf8", "text.decoder.utf8", "text.encoder.gbk", "text.decoder.gbk", which are used to encode and decode strings.

The algo parameter also supports the "ed25519" algorithm, which can be combined with different hash algorithms. For example, the algo parameter can be written as "ed25519.md5", "ed25519.sha512", etc. The ed25519.seed computation is also supported.

inputFormat

string

Yes

Used to specify the data format of the data parameter. The inputFormat parameter supports being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

outputFormat

string

Yes

Used to specify the output data format. The outputFormat parameter supports being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

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 being set to one of: "raw", "hex", "base64", "string". "raw" represents raw data, "hex" represents hex-encoded data, "base64" represents base64-encoded data, and "string" represents string data.

key

string

No

The key parameter is used to specify the key used in the signature computation. You can use a plaintext string, or you can use "{{accesskey}}" and "{{secretkey}}" to refer respectively to 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 calling the exchange.Encode() function.

Multi-threaded asynchronous support function that can convert the operations of all supported functions into asynchronous concurrent execution.

exchange.Go(method)
exchange.Go(method, ...args)

Examples

  • exchange.Go() function usage example. When checking for undefined, you must use typeof(xx) === "undefined", because null == undefined holds true in JavaScript.

    javascript
    function main(){ // The following four operations execute concurrently in asynchronous multi-threaded mode; they take no time and return immediately var a = exchange.Go("GetTicker") var b = exchange.Go("GetDepth") var c = exchange.Go("Buy", 1000, 0.1) var d = exchange.Go("GetRecords", PERIOD_H1) // Call the wait method to wait for the result of the asynchronous ticker retrieval var ticker = a.wait() // Returns the depth data; it may also return null if the retrieval fails var depth = b.wait() // Returns the order ID with a 1-second timeout; returns undefined on timeout. If the previous wait timed out, this object can continue calling wait var orderId = c.wait(1000) if(typeof(orderId) == "undefined") { // Timed out, retrieve again orderId = c.wait() } var records = d.wait() }
    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()
    rust
    fn main() { // In Rust, exchange.Go uses a typed form: use the Go:: method token to specify the concurrent function; pass () for no arguments and a tuple for arguments // The following four operations execute concurrently in asynchronous multi-threaded mode; they take no time and return immediately let a = exchange.Go(Go::GetTicker, ()); let b = exchange.Go(Go::GetDepth, ()); // There is no Buy token in Rust; it is equivalent to CreateOrder, where the first argument "" indicates the current trading pair let c = exchange.Go(Go::CreateOrder, ("", "buy", 1000, 0.1)); let d = exchange.Go(Go::GetRecords, (PERIOD_H1,)); // Call the wait method to wait for the result of the asynchronous ticker retrieval; wait(0) blocks until the concurrent thread finishes running (corresponding to the parameterless wait() in JS) let ticker = a.wait(0); // Returns the depth data; it may also return Err if the retrieval fails let depth = b.wait(0); // Returns the order ID with a 1-second timeout; returns Err on timeout. If the previous wait timed out, this object can continue calling wait // Note: Err may also indicate that the order placement itself failed (indistinguishable from a timeout); in this case, calling wait again will return Err and log the error message let mut orderId = c.wait(1000); if orderId.is_err() { // Timed out, retrieve again orderId = c.wait(0); } let records = d.wait(0); }
    c++
    void main() { auto a = exchange.Go("GetTicker"); auto b = exchange.Go("GetDepth"); auto c = exchange.Go("Buy", 1000, 0.1); auto d = exchange.Go("GetRecords", PERIOD_H1); Ticker ticker; Depth depth; Records records; TId orderId; a.wait(ticker); b.wait(depth); if(!c.wait(orderId, 300)) { c.wait(orderId); } d.wait(records); }
  • Calling the wait() method on a released concurrent object will raise an error:

    javascript
    function main() { var d = exchange.Go("GetRecords", PERIOD_H1) // Wait for the K-line data results to return var records = d.wait() // Calling wait again here on an asynchronous operation that has already been waited on and finished will return null and log an error message var ret = d.wait() }
    python
    def main(): d = exchange.Go("GetRecords", PERIOD_H1) records, ok = d.wait() ret, ok = d.wait()
    rust
    fn main() { // In Rust, exchange.Go uses a typed syntax: specify the concurrent function via the Go:: method token let d = exchange.Go(Go::GetRecords, (PERIOD_H1,)); // Wait for the K-line data results to return; wait(0) blocks until execution completes (equivalent to JS's parameterless wait()) let records = d.wait(0); // Calling wait again here on an asynchronous operation that has already been waited on and finished will return Err and log an error message let ret = d.wait(0); }
    c++
    void main() { auto d = exchange.Go("GetRecords", PERIOD_H1); Records records; d.wait(records); Records ret; d.wait(ret); }
  • Concurrently retrieve market data from multiple exchanges:

    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)
    rust
    fn main() { loop { let beginTS = UnixNano() / 1000000; let mut arrRoutine = Vec::new(); let mut arrTicker = Vec::new(); let mut arrName = Vec::new(); for e in exchanges.iter() { // In Rust, exchange.Go is a typed form; the token is Go::GetTicker arrRoutine.push(e.Go(Go::GetTicker, ())); arrName.push(e.GetName()); } // On failure, record None as a placeholder to stay index-aligned with arrName for r in arrRoutine.iter() { arrTicker.push(r.wait(0).ok()); } let endTS = UnixNano() / 1000000; // Rust has no built-in JSON serialization; use format! to assemble the table's JSON text let mut rows = String::new(); for i in 0..arrTicker.len() { if let Some(ticker) = &arrTicker[i] { if !rows.is_empty() { rows.push(','); } rows += &format!(r#"[{}, "{}", {}]"#, i, arrName[i], ticker.Last); } } let tbl = format!(r#"{{"type": "table", "title": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [{}]}}"#, rows); LogStatus!(_D(None), "Total time for concurrent ticker retrieval:", endTS - beginTS, "ms", "\n", format!("`{}`", tbl)); Sleep(500); } }
    c++
    void main() { while(true) { int length = exchanges.size(); auto beginTS = UnixNano() / 1000000; vector<Ticker> arrTicker(length); vector<string> arrName(length); // Note: run the exchanges[n].Go function once for each exchange object you add. This example requires adding four exchange objects; adjust as needed auto r0 = exchanges[0].Go("GetTicker"); auto r1 = exchanges[1].Go("GetTicker"); auto r2 = exchanges[2].Go("GetTicker"); auto r3 = exchanges[3].Go("GetTicker"); vector<GoObj*> arrRoutine = {&r0, &r1, &r2, &r3}; for(int i = 0; i < length; i++) { arrName[i] = exchanges[i].GetName(); } for(int i = 0; i < length; i++) { Ticker ticker; arrRoutine[i]->wait(ticker); arrTicker[i] = ticker; } auto endTS = UnixNano() / 1000000; json tbl = R"({ "type": "table", "title": "Market Data", "cols": ["Index", "Name", "Last Price"], "rows": [] })"_json; for(int i = 0; i < length; i++) { json arr = R"(["", "", ""])"_json; arr[0] = str_format("%d", i); arr[1] = arrName[i]; arr[2] = str_format("%f", arrTicker[i].Last); tbl["rows"].push_back(arr); } LogStatus(_D(), "Total time for concurrent ticker retrieval:", str_format("%d", endTS - beginTS), "ms", "\n", "`" + tbl.dump() + "`"); Sleep(500); } }
  • Concurrently call the exchange.IO("api", ...) function:

    javascript
    function main() { /* Test the OKX futures order placement endpoint POST /api/v5/trade/order */ var beginTS = new Date().getTime() var param = {"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"} var ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", JSON.stringify(param)) var id1 = ret1.wait() var id2 = ret2.wait() var id3 = ret3.wait() var endTS = new Date().getTime() Log("id1:", id1) Log("id2:", id2) Log("id3:", id3) Log("Concurrent order time:", endTS - beginTS, "ms") }
    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")
    rust
    fn main() { /* Test the OKX futures order placement endpoint POST /api/v5/trade/order */ let beginTS = UnixNano() / 1000000; // Rust does not support JSON serialization, so construct the parameters directly using a raw string let param = r#"{"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"}"#; // In Rust, exchange.Go uses a typed form: the token is Go::IO, and the parameters are passed as a tuple let ret1 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let ret2 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let ret3 = exchange.Go(Go::IO, ("api", "POST", "/api/v5/trade/order", "", param)); let id1 = ret1.wait(0); let id2 = ret2.wait(0); let id3 = ret3.wait(0); let endTS = UnixNano() / 1000000; Log!("id1:", id1); Log!("id2:", id2); Log!("id3:", id3); Log!("Concurrent order time:", endTS - beginTS, "ms"); }
    c++
    void main() { auto beginTS = UnixNano() / 1000000; json param = R"({"instId":"BTC-USDT-SWAP","tdMode":"cross","side":"buy","ordType":"limit","px":"16000","sz":"1","posSide":"long"})"_json; auto ret1 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump()); auto ret2 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump()); auto ret3 = exchange.Go("IO", "api", "POST", "/api/v5/trade/order", "", param.dump()); json id1 = R"({})"_json; json id2 = R"({})"_json; json id3 = R"({})"_json; ret1.wait(id1); ret2.wait(id2); ret3.wait(id3); auto endTS = UnixNano() / 1000000; Log("id1:", id1); Log("id2:", id2); Log("id3:", id3); Log("Concurrent order time:", endTS - beginTS, "ms"); }
  • Testing the automatic release mechanism

    javascript
    function main() { var counter = 0 var arr = [] // Variables used to test persistently referencing concurrent objects var symbols = ["BTC_USDT", "ETH_USDT", "SOL_USDT", "LTC_USDT", "EOS_USDT"] while (true) { var arrRoutine = [] for (var symbol of symbols) { var r = exchange.Go("GetTicker", symbol) arrRoutine.push(r) // Record the concurrent object, used to call the r.wait() function to get the result; cleared every loop iteration // arr.push(r) // If this line is used, the runtime will persistently reference the concurrent objects, preventing them from being automatically released; when the number of concurrent tasks exceeds 2000, it will report an error: ```InternalError: too many routine wait, max is 2000```. counter++ } // Iterate over arrRoutine and call r.wait() to get the results LogStatus(_D(), "routine number:", counter) Sleep(50) } }
    rust
    fn main() { let mut counter = 0; let mut arr: Vec<TypedRoutine<Go::GetTicker>> = Vec::new(); // Variables used to test persistently referencing concurrent objects let symbols = ["BTC_USDT", "ETH_USDT", "SOL_USDT", "LTC_USDT", "EOS_USDT"]; loop { let mut arrRoutine = Vec::new(); for symbol in symbols { // In Rust, exchange.Go uses a typed form, with the token being Go::GetTicker let r = exchange.Go(Go::GetTicker, (symbol,)); arrRoutine.push(r); // Record the concurrent object, used to call the r.wait(0) function to get the result; cleared every loop iteration // arr.push(r); // If this line is used, the runtime will persistently reference the concurrent objects, preventing them from being automatically released; when the number of concurrent tasks exceeds 2000, it will report an error: InternalError: too many routine wait, max is 2000. counter += 1; } // Iterate over arrRoutine and call r.wait(0) to get the results LogStatus!(_D(None), "routine number:", counter); Sleep(50); } }

Returns

TypeDescription

object

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

Arguments

NameTypeRequiredDescription

method

string

Yes

The method parameter is used to specify the name of the function to be executed concurrently. Please 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

The parameters of the concurrent execution function. The arg parameter can appear multiple times. The type and number of the arg parameters depend on the parameter definition 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 when running in live trading. Backtesting does not support multi-threaded concurrent execution of tasks (it can be used in backtesting, but is still executed sequentially).

After the exchange.Go() function returns an object, you can call its wait() function through that object to obtain the data returned by the thread. When the concurrent multi-threaded tasks have finished executing and the related variables are no longer referenced, the underlying system will automatically handle resource reclamation.

The wait() method supports a timeout parameter:

  1. Do not set the timeout parameter, i.e. wait(), or set the timeout parameter to 0, i.e. wait(0). In this case, the wait() function will block and wait until the concurrent thread finishes running, and return the execution result of the concurrent thread.

  2. Set the timeout parameter to -1, i.e. wait(-1). In this case, the wait() function will return immediately. The return value differs across programming languages; for details, please refer to the call examples in this section.

  3. Set a specific timeout parameter, i.e. wait(300). In this case, the wait() function will wait at most 300 milliseconds before returning.

Although the underlying system has an automatic reclamation mechanism, if the related variables are continuously referenced, the concurrent threads will not be released. When the number of concurrent threads exceeds 2000, an error will be reported: "too many routine wait, max is 2000".

Supported functions: GetTicker, GetDepth, GetTrades, GetRecords, GetAccount, GetOrders, GetOrder, CancelOrder, Buy, Sell, GetPositions, IO, etc. When these functions are called concurrently, they are all executed based on the current exchange exchange object.

The difference between the Python language and the JavaScript language is that in Python, the wait() function of a concurrent object returns two values: the first is the result returned by the asynchronous API call, and the second indicates whether the asynchronous call is completed.

python
def main(): d = exchange.Go("GetRecords", PERIOD_D1) # ok is guaranteed to return True, unless the strategy is stopped ret, ok = d.wait() # If the wait times out, or you wait on an instance that has already finished, ok returns False ret, ok = d.wait(100)