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

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", ...).