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

Retrieves the Ticker structure (i.e., the market data) corresponding to the spot or contract of the currently configured trading pair and contract code. The GetTicker() function is a member function of the exchange object exchange. The purpose of the member functions (methods) of the exchange object is related only to exchange, which will not be repeated in the subsequent documentation.

exchange.GetTicker()
exchange.GetTicker(symbol)

Examples

  • For a futures exchange object (i.e., exchange or exchanges[0]), you need to first use the exchange.SetContractType() function to set the contract code before calling the market data functions, which will not be repeated in the subsequent documentation.

    javascript
    function main(){ // If it is a futures exchange object, first set the contract code, for example, set it to a perpetual contract // exchange.SetContractType("swap") var ticker = exchange.GetTicker() /* Due to network reasons, the exchange interface may be inaccessible (even if the device where the docker program is located can open the exchange website, the API interface may still be unreachable) In this case, ticker is null, and accessing ticker.High will cause an error, so when testing this code, make sure the exchange interface is accessible */ Log("Symbol:", ticker.Symbol, "High:", ticker.High, "Low:", ticker.Low, "Sell:", ticker.Sell, "Buy:", ticker.Buy, "Last:", ticker.Last, "Open:", ticker.Open, "Volume:", ticker.Volume) }
    python
    def main(): ticker = exchange.GetTicker() Log("Symbol:", ticker["Symbol"], "High:", ticker["High"], "Low:", ticker["Low"], "Sell:", ticker["Sell"], "Buy:", ticker["Buy"], "Last:", ticker["Last"], "Open:", ticker["Open"], "Volume:", ticker["Volume"])
    rust
    fn main() { // If it is a futures exchange object, first set the contract code, for example, set it to a perpetual contract // exchange.SetContractType("swap").unwrap(); let ticker = exchange.GetTicker(None).unwrap(); Log!("Symbol:", ticker.Symbol, "High:", ticker.High, "Low:", ticker.Low, "Sell:", ticker.Sell, "Buy:", ticker.Buy, "Last:", ticker.Last, "Open:", ticker.Open, "Volume:", ticker.Volume); }
    c++
    void main() { auto ticker = exchange.GetTicker(); Log("Symbol:", ticker.Symbol, "High:", ticker.High, "Low:", ticker.Low, "Sell:", ticker.Sell, "Buy:", ticker.Buy, "Last:", ticker.Last, "Open:", ticker.Open, "Volume:", ticker.Volume); }
  • Use the symbol parameter to request market data of a specific instrument (spot instrument).

    javascript
    function main() { var ticker = exchange.GetTicker("BTC_USDT") Log(ticker) }
    python
    def main(): ticker = exchange.GetTicker("BTC_USDT") Log(ticker)
    rust
    fn main() { let ticker = exchange.GetTicker("BTC_USDT").unwrap(); Log!(ticker); }
    c++
    void main() { auto ticker = exchange.GetTicker("BTC_USDT"); Log(ticker); }

Returns

TypeDescription

Ticker / null value

The exchange.GetTicker() function returns the Ticker structure when the data request succeeds, and returns a null value when the data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

The parameter symbol is used to specify the exact trading pair and contract code corresponding to the requested Ticker data. If this parameter is not passed, the market data of the currently configured trading pair and contract code is requested by default.

When calling the exchange.GetTicker(symbol) function and exchange is a spot exchange object, if you need to request market data with USDT as the quote currency and BTC as the trading currency, the parameter symbol is: "BTC_USDT", whose format is the trading pair format defined by the FMZ platform.

When calling the exchange.GetTicker(symbol) function and exchange is a futures exchange object, if you need to request market data of the BTC USDT-margined perpetual contract, the parameter symbol is: "BTC_USDT.swap", whose format is the combination of the trading pair and contract code defined by the FMZ platform, separated by the character ".".

When calling the exchange.GetTicker(symbol) function and exchange is a futures exchange object, if you need to request market data of the BTC USDT-margined options contract, the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example), whose format is the combination of the trading pair defined by the FMZ platform and the specific options contract code defined by the exchange, separated by the character ".".

See Also

Remarks

In the backtesting system, in the Ticker data returned by the exchange.GetTicker() function, High and Low are simulated values, taken from the best ask price and best bid price of the order book at that time.

In live trading, in the Ticker data returned by the exchange.GetTicker() function, the values of High and Low are determined based on the data returned by the wrapped exchange's Tick interface. This data contains the highest price and lowest price within a certain period (usually a 24-hour period).

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

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetTicker--Futures_Aevo

Gets the Depth structure, i.e. the order book data, of the spot or contract corresponding to the currently set trading pair and contract code.

exchange.GetDepth()
exchange.GetDepth(symbol)

Examples

  • Test the exchange.GetDepth() function:

    javascript
    function main(){ var depth = exchange.GetDepth() /* Due to network reasons, the exchange interface may be inaccessible (even if the device where the docker program runs can open the exchange website, the API interface may still be unreachable) In this case depth is null, and accessing depth.Asks[1].Price will cause an error, so when testing this code make sure the exchange interface is accessible */ var price = depth.Asks[1].Price Log("Second ask price:", price) }
    python
    def main(): depth = exchange.GetDepth() price = depth["Asks"][1]["Price"] Log("Second ask price:", price)
    rust
    fn main() { let depth = exchange.GetDepth(None).unwrap(); let price = depth.Asks[1].Price; Log!("Second ask price:", price); }
    c++
    void main() { auto depth = exchange.GetDepth(); auto price = depth.Asks[1].Price; Log("Second ask price:", price); }
  • When the configured exchange object is a futures exchange object, use the symbol parameter to request the order book data of a specified instrument (futures instrument).

    javascript
    function main() { // BTC USDT-margined perpetual contract var depth = exchange.GetDepth("BTC_USDT.swap") Log(depth) }
    python
    def main(): depth = exchange.GetDepth("BTC_USDT.swap") Log(depth)
    rust
    fn main() { // BTC USDT-margined perpetual contract let depth = exchange.GetDepth("BTC_USDT.swap").unwrap(); Log!(depth); }
    c++
    void main() { auto depth = exchange.GetDepth("BTC_USDT.swap"); Log(depth); }

Returns

TypeDescription

Depth / null

The exchange.GetDepth() function returns the Depth structure 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 exact trading pair or contract code corresponding to the requested Depth data. If this parameter is not passed, the order book data of the currently set trading pair and contract code is requested by default.

When calling the exchange.GetDepth(symbol) function, if exchange is a spot exchange object and you need to request the order book data with USDT as the quote currency and BTC as the trading currency, then the symbol parameter should be "BTC_USDT", whose format is the trading pair format defined by the FMZ platform.

When calling the exchange.GetDepth(symbol) function, if exchange is a futures exchange object and you need to request the order book data of the BTC USDT-margined perpetual contract, then the symbol parameter should be "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.GetDepth(symbol) function, if exchange is a futures exchange object and you need to request the order book data of a BTC USDT-margined options contract, then the symbol parameter should be "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 ".".

See Also

Remarks

In the backtesting system, when backtesting with Simulated-level Tick, all levels of the data returned by the exchange.GetDepth() function are simulated values.

In the backtesting system, when backtesting with Live-level Tick, the data returned by the exchange.GetDepth() function is a second-level depth snapshot.

Gets the Trade structure array of the spot or futures corresponding to the currently set trading pair and contract code, i.e. the market's trade (tick) data.

exchange.GetTrades()
exchange.GetTrades(symbol)

Examples

  • Test the exchange.GetTrades() function:

    javascript
    function main(){ var trades = exchange.GetTrades() /* Due to network reasons, the exchange interface may be inaccessible (even if the device where the docker program is located can open the exchange website, the API interface may still be unreachable) In this case trades is null, and accessing trades[0].Id will cause an error, so when testing this code, make sure the exchange interface is accessible */ Log("id:", trades[0].Id, "time:", trades[0].Time, "Price:", trades[0].Price, "Amount:", trades[0].Amount, "type:", trades[0].Type) }
    python
    def main(): trades = exchange.GetTrades() Log("id:", trades[0]["Id"], "time:", trades[0]["Time"], "Price:", trades[0]["Price"], "Amount:", trades[0]["Amount"], "type:", trades[0]["Type"])
    rust
    fn main() { let trades = exchange.GetTrades(None).unwrap(); Log!("id:", trades[0].Id, "time:", trades[0].Time, "Price:", trades[0].Price, "Amount:", trades[0].Amount, "type:", trades[0].Type); }
    c++
    void main() { auto trades = exchange.GetTrades(); Log("id:", trades[0].Id, "time:", trades[0].Time, "Price:", trades[0].Price, "Amount:", trades[0].Amount, "type:", trades[0].Type); }
  • When the configured exchange object is a futures exchange object, use the symbol parameter to request the market trade record data of a specific instrument (futures instrument).

    javascript
    function main() { // BTC's USDT-margined perpetual contract var trades = exchange.GetTrades("BTC_USDT.swap") Log(trades) }
    python
    def main(): trades = exchange.GetTrades("BTC_USDT.swap") Log(trades)
    rust
    fn main() { // BTC's USDT-margined perpetual contract let trades = exchange.GetTrades("BTC_USDT.swap").unwrap(); Log!(trades); }
    c++
    void main() { auto trades = exchange.GetTrades("BTC_USDT.swap"); Log(trades); }

Returns

TypeDescription

Trade array / null

The exchange.GetTrades() function returns the Trade structure array when the data request succeeds, and returns null when the data request fails.

Arguments

NameTypeRequiredDescription

symbol

string

No

The parameter symbol is used to specify the exact trading pair and contract code corresponding to the requested Trade array data. If this parameter is not passed, the most recent trade records of the currently set trading pair and contract code are requested by default.

When calling the exchange.GetTrades(symbol) function, if exchange is a spot exchange object and you need to request the trade data with USDT as the quote currency and BTC as the base currency, then the parameter symbol is: "BTC_USDT", whose format is the trading pair format defined by the FMZ platform.

When calling the exchange.GetTrades(symbol) function, if exchange is a futures exchange object and you need to request the trade data of BTC's USDT-margined perpetual contract, then the parameter symbol 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.GetTrades(symbol) function, if exchange is a futures exchange object and you need to request the trade data of BTC's USDT-margined options contract, then the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking 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 ".".

See Also

Remarks

The exchange.GetTrades() function is used to get the trade history (not your own trades) of the market corresponding to the current trading pair and contract. Some exchanges do not support this function, and the specific range of trade records returned varies from exchange to exchange, which needs to be handled according to the actual situation. The returned data is an array, in which the time order of each element is consistent with the order of the data returned by the exchange.GetRecords() function, i.e. the last element of the array is the data closest to the current time.

In the backtesting system, when backtesting with simulation-level Tick, the exchange.GetTrades() function returns an empty array.

In the backtesting system, when backtesting with **live-trading-level Tick**, the data returned by the exchange.GetTrades() function is order flow snapshot data, i.e. the Trade structure array.

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

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetTradesHyperliquidFutures_BitMart / Futures_Bibox / Futures_Hyperliquid / Futures_edgeX

Get the Record structure array (i.e. K-line data) of the spot or contract corresponding to the currently set trading pair or contract code.

exchange.GetRecords()
exchange.GetRecords(symbol)
exchange.GetRecords(symbol, period)
exchange.GetRecords(symbol, period, limit)
exchange.GetRecords(period)
exchange.GetRecords(period, limit)

Examples

  • Get K-line data for a custom period.

    javascript
    function main() { // Print K-line data with a K-line period of 120 seconds (2 minutes) Log(exchange.GetRecords(60 * 2)) // Print K-line data with a K-line period of 5 minutes Log(exchange.GetRecords(PERIOD_M5)) }
    python
    def main(): Log(exchange.GetRecords(60 * 2)) Log(exchange.GetRecords(PERIOD_M5))
    rust
    fn main() { // Print K-line data with a K-line period of 120 seconds (2 minutes) Log!(exchange.GetRecords(None, 60 * 2, None)); // Print K-line data with a K-line period of 5 minutes Log!(exchange.GetRecords(None, PERIOD_M5, None)); }
    c++
    void main() { Log(exchange.GetRecords(60 * 2)[0]); Log(exchange.GetRecords(PERIOD_M5)[0]); }
  • Output K-line bar data:

    javascript
    function main() { var records = exchange.GetRecords(PERIOD_H1) /* Due to network reasons, it may not be possible to access the exchange interface (even if the device running the docker program can open the exchange website, the API interface may still be inaccessible) In this case, records is null, and accessing records[0].Time will cause an error. Therefore, when testing this code, please make sure you can access the exchange interface normally */ Log("First K-line data: Time:", records[0].Time, "Open:", records[0].Open, "High:", records[0].High) Log("Second K-line data: Time:", records[1].Time ,"Close:", records[1].Close) Log("Current K-line (latest)", records[records.length-1], "Previous K-line", records[records.length-2]) }
    python
    def main(): records = exchange.GetRecords(PERIOD_H1) Log("First K-line data: Time:", records[0]["Time"], "Open:", records[0]["Open"], "High:", records[0]["High"]) Log("Second K-line data: Time:", records[1]["Time"], "Close:", records[1]["Close"]) Log("Current K-line (latest)", records[-1], "Previous K-line", records[-2])
    rust
    fn main() { let records = exchange.GetRecords(None, PERIOD_H1, None).unwrap(); Log!("First K-line data: Time:", records[0].Time, "Open:", records[0].Open, "High:", records[0].High); Log!("Second K-line data: Time:", records[1].Time, "Close:", records[1].Close); Log!("Current K-line (latest)", records[records.len() - 1], "Previous K-line", records[records.len() - 2]); }
    c++
    void main() { auto records = exchange.GetRecords(PERIOD_H1); Log("First K-line data: Time:", records[0].Time, "Open:", records[0].Open, "High:", records[0].High); Log("Second K-line data: Time:", records[1].Time, "Close:", records[1].Close); Log("Current K-line (latest)", records[records.size() - 1], "Previous K-line", records[records.size() - 2]); }
  • When the configured exchange object is a futures exchange object, you can use the symbol, period, and limit parameters to request K-line data for a specified instrument (futures instrument).

    javascript
    function main() { var records = exchange.GetRecords("BTC_USDT.swap", 60, 100) Log(records) }
    python
    def main(): records = exchange.GetRecords("BTC_USDT.swap", 60, 100) Log(records)
    rust
    fn main() { let records = exchange.GetRecords("BTC_USDT.swap", 60, 100).unwrap(); Log!(records); }
    c++
    void main() { auto records = exchange.GetRecords("BTC_USDT.swap", 60, 100); Log(records); }

Returns

TypeDescription

Record array / null value

The exchange.GetRecords() function returns a Record 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 exact trading pair or contract code corresponding to the requested Record array data. If this parameter is not passed, the K-line data of the currently set trading pair or contract code is requested by default.

When calling the exchange.GetRecords(symbol) function, if exchange is a spot exchange object and you need to request K-line data with USDT as the quote currency and BTC as the base currency, then the symbol parameter is: "BTC_USDT", which follows the trading pair format defined by the FMZ platform.

When calling the exchange.GetRecords(symbol) function, if exchange is a futures exchange object and you need to request K-line data for BTC's USDT-margined perpetual contract, then the symbol parameter is: "BTC_USDT.swap", which follows the format defined by the FMZ platform combining the trading pair and the contract code, separated by the character ".".

When calling the exchange.GetRecords(symbol) function, if exchange is a futures exchange object and you need to request K-line data for BTC's USDT-margined options contract, then the symbol parameter is: "BTC_USDT.BTC-240108-40000-C" (taking the Binance option BTC-240108-40000-C as an example), which follows the format defined by the FMZ platform combining the trading pair with the specific option contract code defined by the exchange, separated by the character ".".

period

number

No

The period parameter is used to specify the period of the requested K-line data, for example: PERIOD_M1, PERIOD_M5, PERIOD_M15, etc. In addition to accepting the predefined standard periods, the period parameter can also accept an integer value in seconds. If this parameter is not passed, the requested K-line data period defaults to the default K-line period configured for the current strategy's live trading/backtest.

limit

number

No

The limit parameter is used to specify the length of the requested K-line data. If this parameter is not passed, the default requested length is the maximum number of K-line bars that the exchange's K-line interface can request at once. This parameter may trigger paginated queries of the exchange's K-line data, and the call duration of this function will increase accordingly when paginated queries are performed.

See Also

Remarks

The default K-line period can be set on the backtesting and live trading pages. When calling the exchange.GetRecords() function, if a parameter is specified, it retrieves the K-line data for the period specified by that parameter; if no parameter is specified, it returns the K-line data for the period set in the backtesting or live trading parameters.

The return value is a Record structure array. The returned K-line data accumulates continuously over time, and the upper limit of the accumulated number of K-line bars is affected by the setting of the exchange.SetMaxBarLen() function. When not set, the default upper limit is 5000 K-line bars. Once the K-line data reaches the accumulation limit, each time a new K-line bar is added, the earliest K-line bar is deleted (similar to the first-in-first-out behavior of a queue). Some exchanges do not provide a K-line interface, in which case the docker collects market trade record data (a Trade structure array) in real time to synthesize K-lines.

If the exchange's K-line interface supports paginated queries, when calling the exchange.SetMaxBarLen() function to set a large K-line length, the system will initiate multiple API requests.

When the exchange.GetRecords() function is called for the first time, the number of K-line bars obtained differs between the backtesting and live trading environments:

  • The backtesting system pre-fetches a certain number of K-line bars prior to the start time of the backtesting time range (5000 by default; the relevant settings and data volume of the backtesting system will affect the final returned number) as the initial K-line data.

  • In live trading, the actual number of K-line bars obtained depends on the maximum amount of data that the exchange's K-line interface can provide.

Setting the period parameter to 5 means requesting K-line data with a period of 5 seconds. If the period parameter is not divisible by 60 (i.e., the represented period cannot be expressed in units of minutes), the underlying system will use the relevant interface of exchange.GetTrades() to obtain trade record data in order to synthesize the required K-line data; if the period parameter is divisible by 60, then 1-minute K-line data is used at minimum (using as large a period as possible) to synthesize the required K-line data.

In the simulation-level backtesting of the backtesting system, because the underlying K-line period must be set (during simulation-level backtesting, the system uses the corresponding K-line data to generate Tick data based on the configured underlying K-line period), the following must be noted: the K-line data period obtained in the strategy cannot be smaller than the underlying K-line period. This is because in simulation-level backtesting, the K-line data of each period is synthesized from the K-line data corresponding to the underlying K-line period.

In the C++ language, if you need to construct K-line data yourself, you can refer to the following code example:

c++
#include <sstream> void main() { Records r; r.Valid = true; for (auto i = 0; i < 10; i++) { Record ele; ele.Time = i * 100000; ele.High = i * 10000; ele.Low = i * 1000; ele.Close = i * 100; ele.Open = i * 10; ele.Volume = i * 1; r.push_back(ele); } // Output displays: Records[10] Log(r); auto ma = TA.MA(r,10); // Output displays: [nan,nan,nan,nan,nan,nan,nan,nan,nan,450] Log(ma); }

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

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetRecordsZaif / Coincheck / BitFlyerFutures_Aevo

Retrieves the K-line period configured on the FMZ Quant Trading platform website page when running a strategy in backtesting or live trading, i.e., the default K-line period used when calling the exchange.GetRecords() function without passing any parameters.

exchange.GetPeriod()

Examples

javascript
function main() { // For example, the K-line period set on the FMZ Quant Trading platform website page during backtesting or live trading is 1 hour var period = exchange.GetPeriod() Log("K-line period:", period / (60 * 60), "hours") }
python
def main(): period = exchange.GetPeriod() Log("K-line period:", period / (60 * 60), "hours")
rust
fn main() { // For example, the K-line period set on the FMZ Quant Trading platform website page during backtesting or live trading is 1 hour let period = exchange.GetPeriod(); Log!("K-line period:", period as f64 / (60.0 * 60.0), "hours"); }
c++
void main() { auto period = exchange.GetPeriod(); Log("K-line period:", period / (60 * 60.0), "hours"); }

Returns

TypeDescription

number

The number of seconds of the K-line period, an integer value, in seconds.

See Also

Set the maximum length of the K-line (candlestick chart).

exchange.SetMaxBarLen(len)

Examples

javascript
function main() { exchange.SetMaxBarLen(50) var records = exchange.GetRecords() Log(records.length, records) }
python
def main(): exchange.SetMaxBarLen(50) r = exchange.GetRecords() Log(len(r), r)
rust
fn main() { exchange.SetMaxBarLen(50); let records = exchange.GetRecords(None, None, None).unwrap(); Log!(records.len(), records); }
c++
void main() { exchange.SetMaxBarLen(50); auto r = exchange.GetRecords(); Log(r.size(), r[0]); }

Arguments

NameTypeRequiredDescription

len

number

Yes

The parameter len is used to specify the maximum length of the K-line.

See Also

Remarks

The exchange.SetMaxBarLen() function affects the following two aspects when a cryptocurrency strategy is running:

  • It affects the number of K-line bars (Bar) obtained on the first call.

  • It affects the upper limit on the number of K-line bars (Bar).

Get the raw content returned by the most recent rest request from the current exchange object (exchange, exchanges).

exchange.GetRawJSON()

Examples

javascript
function main(){ exchange.GetAccount(); var obj = JSON.parse(exchange.GetRawJSON()); Log(obj); }
python
import json def main(): exchange.GetAccount() obj = json.loads(exchange.GetRawJSON()) Log(obj)
c++
void main() { auto obj = exchange.GetAccount(); // C++ 不支持GetRawJSON函数 Log(obj); }

Returns

TypeDescription

string

Response data from the rest request.

See Also

Remarks

The exchange.GetRawJSON() function only supports live trading. C++ language strategies do not support this function.

Get the exchange rate currently set for the exchange object.

exchange.GetRate()

Examples

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

Returns

TypeDescription

number

The current exchange rate value of the exchange object.

See Also

Remarks

If the conversion rate has not been set by calling exchange.SetRate(), the exchange.GetRate() function will return the default rate value 1, meaning that the data related to the currently displayed quote currency (quoteCurrency) has not been converted by any exchange rate.

If an exchange rate value has been set using exchange.SetRate(), for example exchange.SetRate(7), then all price information obtained through the exchange exchange object—such as tickers, market depth, and order prices—will be multiplied by the set rate 7 for conversion.

If exchange corresponds to an exchange that uses the US dollar as its quote currency, after calling exchange.SetRate(7), all prices in live trading will be multiplied by 7, converting them to prices close to the Chinese yuan (CNY). At this point, the rate value obtained through exchange.GetRate() is 7.

The exchange.SetData() function is used to set the data loaded when the strategy is running.

exchange.SetData(key, value)

Examples

The data format required by the value parameter is like the data variable in the following example. As you can see, the timestamp 1579622400000 corresponds to the time 2020-01-22 00:00:00. When the running time of the strategy program exceeds this time and is before the timestamp 1579708800000 of the next data entry (i.e. the time 2020-01-23 00:00:00), calling the exchange.GetData() function will always retrieve the content of this data entry [1579622400000, 123]. As the program continues to run and time passes, and so on, the data can be retrieved entry by entry.

In the following example, when the current moment of the runtime (backtesting or live trading) reaches or exceeds the timestamp 1579795200000, calling the exchange.GetData() function returns: {"Time":1579795200000,"Data":["abc",123,{"price":123}]}. Here "Time":1579795200000 corresponds to 1579795200000 in the data [1579795200000, ["abc", 123, {"price": 123}]]; "Data":["abc",123,{"price":123}] corresponds to ["abc", 123, {"price": 123}] in the data [1579795200000, ["abc", 123, {"price": 123}]].

javascript
/*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ function main() { var data = [ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] exchange.SetData("test", data) while(true) { Log(exchange.GetData("test")) Sleep(1000) } }
python
'''backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] ''' def main(): data = [ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] exchange.SetData("test", data) while True: Log(exchange.GetData("test")) Sleep(1000)
rust
/*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ fn main() { // In the Rust SDK, the data argument of SetData is a JSON string let data = r#"[ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ]"#; exchange.SetData("test", data); loop { Log!(exchange.GetData("test")); Sleep(1000); } }
c++
/*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ void main() { json data = R"([ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ])"_json; exchange.SetData("test", data); while(true) { Log(exchange.GetData("test")); Sleep(1000); } }

Returns

TypeDescription

number

The string length of the value parameter after being JSON-encoded.

Arguments

NameTypeRequiredDescription

key

string

Yes

The name of the data collection.

value

array

Yes

The data to be loaded by the exchange.SetData() function, whose data structure is an array. This data structure is the same as the format required by the exchange.GetData() function when requesting external data, namely: "schema": ["time", "data"].

See Also

Remarks

The loaded data can be any economic indicator, industry data, related index, etc., used to quantitatively evaluate various types of quantifiable information within the strategy.

The exchange.GetData() function is used to retrieve data loaded by the exchange.SetData() function, or data provided by an external link.

exchange.GetData(key)
exchange.GetData(key, timeout)

Examples

  • How to call the method for writing data directly.

    javascript
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ function main() { exchange.SetData("test", [[1579536000000, _D(1579536000000)], [1579622400000, _D(1579622400000)], [1579708800000, _D(1579708800000)]]) while(true) { Log(exchange.GetData("test")) Sleep(1000 * 60 * 60 * 24) } }
    python
    '''backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] ''' def main(): exchange.SetData("test", [[1579536000000, _D(1579536000000/1000)], [1579622400000, _D(1579622400000/1000)], [1579708800000, _D(1579708800000/1000)]]) while True: Log(exchange.GetData("test")) Sleep(1000 * 60 * 60 * 24)
    rust
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ fn main() { // In the Rust SDK, the data parameter of SetData is a JSON string; use format! to concatenate the data let data = format!(r#"[[1579536000000, "{}"], [1579622400000, "{}"], [1579708800000, "{}"]]"#, _D(1579536000000), _D(1579622400000), _D(1579708800000)); exchange.SetData("test", &data); loop { Log!(exchange.GetData("test")); Sleep(1000 * 60 * 60 * 24); } }
    c++
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ void main() { json arr = R"([[1579536000000, ""], [1579622400000, ""], [1579708800000, ""]])"_json; arr[0][1] = _D(1579536000000); arr[1][1] = _D(1579622400000); arr[2][1] = _D(1579708800000); exchange.SetData("test", arr); while(true) { Log(exchange.GetData("test")); Sleep(1000 * 60 * 60 * 24); } }
  • Data can be requested through external links. The data format returned by the request is as follows:

    json
    { "schema":["time","data"], "data":[ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] }

    Here schema defines the data format of each record in the data body. This format is fixed as ["time","data"], corresponding one-to-one with the format of each piece of data in the data attribute. The data attribute is used to store the data body, where each piece of data consists of a millisecond-level timestamp and the data content (the data content can be any JSON-encodable data).

    The following is a test service program written in Go:

    golang
    package main import ( "fmt" "net/http" "encoding/json" ) func Handle (w http.ResponseWriter, r *http.Request) { defer func() { fmt.Println("req:", *r) ret := map[string]interface{}{ "schema": []string{"time","data"}, "data": []interface{}{ []interface{}{1579536000000, "abc"}, []interface{}{1579622400000, 123}, []interface{}{1579708800000, map[string]interface{}{"price":123}}, []interface{}{1579795200000, []interface{}{"abc", 123, map[string]interface{}{"price":123}}}, }, } b, _ := json.Marshal(ret) w.Write(b) }() } func main () { fmt.Println("listen http://localhost:9090") http.HandleFunc("/data", Handle) http.ListenAndServe(":9090", nil) }

    The response data returned by the program after receiving the request:

    json
    { "schema":["time","data"], "data":[ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] }

    The test strategy code is as follows:

    javascript
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ function main() { while(true) { Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")) Sleep(1000) } }
    python
    '''backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] ''' def main(): while True: Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")) Sleep(1000)
    rust
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ fn main() { loop { Log!(exchange.GetData("http://xxx.xx.x.xx:9090/data")); Sleep(1000); } }
    c++
    /*backtest start: 2020-01-21 00:00:00 end: 2020-02-12 00:00:00 period: 1d basePeriod: 1d exchanges: [{"eid":"Bitfinex","currency":"BTC_USD"}] */ void main() { while(true) { Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")); Sleep(1000); } }
  • How to call the method for fetching data from external links.

    javascript
    function main() { Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")) Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json")) }
    python
    def main(): Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")) Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json"))
    rust
    fn main() { Log!(exchange.GetData("http://xxx.xx.x.xx:9090/data")); Log!(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json")); }
    c++
    void main() { Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")); Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json")); }
  • Request the query data created on the datadata platform. The response data format must meet the following requirements (the schema must describe the time and data fields):

    json
    { "data": [], "schema": ["time", "data"] }

    The "data" field contains the required data content, and the data in the "data" field must be consistent with the fields defined in the "schema". When calling the exchange.GetData() function, a JSON object is returned, for example: {"Time":1579795200000, "Data":"..."}.

    javascript
    function main() { Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data")) // The xxx part in the link is the code of the query data; xxx here is just an example }
    python
    def main(): Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data"))
    rust
    fn main() { Log!(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data")); // The xxx part in the link is the code of the query data; xxx here is just an example }
    c++
    void main() { Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data")); }

Returns

TypeDescription

object / null value

The records in the dataset, or the data returned by the request.

Arguments

NameTypeRequiredDescription

key

string

Yes

The name of the dataset, or the data request URL.

timeout

number

No

Used to set the cache timeout period, in milliseconds. In live trading, the default cache timeout is one minute.

See Also

Remarks

In backtesting, the data is retrieved all at once; in live trading, the data is cached for one minute. In the backtesting system, when requesting data via an access interface, the backtesting system automatically adds parameters such as from (timestamp, in seconds), to (timestamp, in seconds), and period (the underlying K-line period, timestamp, in milliseconds) to the request, in order to determine the time range of the data to be retrieved.

The exchange.GetMarkets() function is used to retrieve market information from the exchange.

exchange.GetMarkets()

Examples

  • Call example for a futures exchange object:

    javascript
    function main() { var markets = exchange.GetMarkets() var currency = exchange.GetCurrency() // To get the current contract code you can also use the exchange.GetContractType() function var ct = "swap" var key = currency + "." + ct Log(key, ":", markets[key]) }
    python
    def main(): markets = exchange.GetMarkets() currency = exchange.GetCurrency() ct = "swap" key = currency + "." + ct Log(key, ":", markets[key])
    rust
    fn main() { let markets = exchange.GetMarkets(); let currency = exchange.GetCurrency(); // To get the current contract code you can also use the exchange.GetContractType() function let ct = "swap"; let key = format!("{}.{}", currency, ct); Log!(key, ":", format!("{:?}", markets.get(&key))); }
    c++
    void main() { auto markets = exchange.GetMarkets(); auto currency = exchange.GetCurrency(); auto ct = "swap"; auto key = currency + "." + ct; Log(key, ":", markets[key]); }
  • In the backtesting system, use the futures exchange object to call the exchange.GetMarkets() function. Before calling any market data function, GetMarkets only returns the market data of the current default trading pair; after calling a market data function, it returns the market data of all symbols that have already been requested. Refer to the following test example:

    javascript
    /*backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ function main() { var arrSymbol = ["SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] var tbl1 = { type: "table", title: "markets1", cols: ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], rows: [] } var markets1 = exchange.GetMarkets() for (var key in markets1) { var market = markets1[key] tbl1.rows.push([key, market.Symbol, market.BaseAsset, market.QuoteAsset, market.TickSize, market.AmountSize, market.PricePrecision, market.AmountPrecision, market.MinQty, market.MaxQty, market.MinNotional, market.MaxNotional, market.CtVal]) } for (var symbol of arrSymbol) { exchange.GetTicker(symbol) } var tbl2 = { type: "table", title: "markets2", cols: ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], rows: [] } var markets2 = exchange.GetMarkets() for (var key in markets2) { var market = markets2[key] tbl2.rows.push([key, market.Symbol, market.BaseAsset, market.QuoteAsset, market.TickSize, market.AmountSize, market.PricePrecision, market.AmountPrecision, market.MinQty, market.MaxQty, market.MinNotional, market.MaxNotional, market.CtVal]) } LogStatus("`" + JSON.stringify([tbl1, tbl2]) + "`") }
    python
    '''backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] ''' import json def main(): arrSymbol = ["SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"] tbl1 = { "type": "table", "title": "markets1", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] } markets1 = exchange.GetMarkets() for key in markets1: market = markets1[key] tbl1["rows"].append([key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]]) for symbol in arrSymbol: exchange.GetTicker(symbol) tbl2 = { "type": "table", "title": "markets2", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] } markets2 = exchange.GetMarkets() for key in markets2: market = markets2[key] tbl2["rows"].append([key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]]) LogStatus("`" + json.dumps([tbl1, tbl2]) + "`")
    rust
    /*backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ fn marketToJson(key: &str, market: &Market) -> String { format!(r#"["{}", "{}", "{}", "{}", {}, {}, {}, {}, {}, {}, {}, {}, {}]"#, key, market.Symbol, market.BaseAsset, market.QuoteAsset, market.TickSize, market.AmountSize, market.PricePrecision, market.AmountPrecision, market.MinQty, market.MaxQty, market.MinNotional, market.MaxNotional, market.CtVal) } fn main() { let arrSymbol = ["SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"]; // The Rust SDK has no JSON serialization feature; here format! is used to concatenate the table's JSON text let markets1 = exchange.GetMarkets(); let mut rows1: Vec<String> = Vec::new(); for (key, market) in &markets1 { rows1.push(marketToJson(key, market)); } let tbl1 = format!(r#"{{"type": "table", "title": "markets1", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [{}]}}"#, rows1.join(",")); for symbol in arrSymbol { exchange.GetTicker(symbol); } let markets2 = exchange.GetMarkets(); let mut rows2: Vec<String> = Vec::new(); for (key, market) in &markets2 { rows2.push(marketToJson(key, market)); } let tbl2 = format!(r#"{{"type": "table", "title": "markets2", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [{}]}}"#, rows2.join(",")); LogStatus!(format!("`[{},{}]`", tbl1, tbl2)); }
    c++
    /*backtest start: 2023-05-10 00:00:00 end: 2023-05-20 00:00:00 period: 1m basePeriod: 1m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ void main() { auto arrSymbol = {"SOL_USDT.swap", "BTC_USDT.quarter", "ETH_USDT.swap", "ETH_USDT.quarter"}; json tbl1 = R"({ "type": "table", "title": "markets1", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] })"_json; auto markets1 = exchange.GetMarkets(); for (auto& [key, market] : markets1.items()) { json arrJson = {key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]}; tbl1["rows"].push_back(arrJson); } for (const auto& symbol : arrSymbol) { exchange.GetTicker(symbol); } json tbl2 = R"({ "type": "table", "title": "markets2", "cols": ["key", "Symbol", "BaseAsset", "QuoteAsset", "TickSize", "AmountSize", "PricePrecision", "AmountPrecision", "MinQty", "MaxQty", "MinNotional", "MaxNotional", "CtVal"], "rows": [] })"_json; auto markets2 = exchange.GetMarkets(); for (auto& [key, market] : markets2.items()) { json arrJson = {key, market["Symbol"], market["BaseAsset"], market["QuoteAsset"], market["TickSize"], market["AmountSize"], market["PricePrecision"], market["AmountPrecision"], market["MinQty"], market["MaxQty"], market["MinNotional"], market["MaxNotional"], market["CtVal"]}; tbl2["rows"].push_back(arrJson); } json tbls = R"([])"_json; tbls.push_back(tbl1); tbls.push_back(tbl2); LogStatus("`" + tbls.dump() + "`"); }

Returns

TypeDescription

object / null

A dictionary containing Market structures.

See Also

Remarks

The return value of the exchange.GetMarkets() function is a dictionary. For spot exchanges, the key is the trading instrument name, in a fixed trading pair format, for example:

json
{ "BTC_USDT" : {...}, // The value is a Market structure "LTC_USDT" : {...}, ... }

For futures contract exchanges, since the same instrument may have multiple contracts—for example, the BTC_USDT trading pair includes perpetual contracts, quarterly contracts, etc.—the keys in the dictionary returned by the exchange.GetMarkets() function are a combination of the trading pair and the contract code, for example:

json
{ "BTC_USDT.swap" : {...}, // The value is a Market structure "BTC_USDT.quarter" : {...}, "LTC_USDT.swap" : {...}, ... }

  • The exchange.GetMarkets() function is supported by both live trading and the backtesting system.

  • The exchange.GetMarkets() function only returns market information for trading instruments that are already listed on the exchange.

  • The exchange.GetMarkets() function does not support options contracts.

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

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetMarketsCoincheck / Bithumb / BitFlyer--

The exchange.GetTickers() function is used to retrieve aggregated market data from the exchange (an array of Ticker structures). When exchange is a spot exchange object, it returns the ticker market data for all trading pairs; when exchange is a futures exchange object, it returns the ticker market data for all contracts.

exchange.GetTickers()

Examples

  • Call the exchange.GetTickers() function to retrieve aggregated market ticker data.

    javascript
    function main() { var tickers = exchange.GetTickers() if (tickers && tickers.length > 0) { Log("Number of tradable symbols:", tickers.length) } }
    python
    def main(): tickers = exchange.GetTickers() if tickers and len(tickers) > 0: Log("Number of tradable symbols:", len(tickers))
    rust
    fn main() { if let Ok(tickers) = exchange.GetTickers() { if tickers.len() > 0 { Log!("Number of tradable symbols:", tickers.len()); } } }
    c++
    void main() { auto tickers = exchange.GetTickers(); if (tickers.Valid && tickers.size() > 0) { Log("Number of tradable symbols:", tickers.size()); } }
  • Use a spot exchange object and call the exchange.GetTickers() function in the backtesting system. Before calling any market data function, GetTickers only returns the ticker data of the current default trading pair; after calling a market data function, it returns the ticker data of all trading pairs that have been requested. You can refer to the following test example:

    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 = ["ADA_USDT", "LTC_USDT", "ETH_USDT", "SOL_USDT"] // Before requesting the market data of other trading pairs, call GetTickers var tickers1 = exchange.GetTickers() var tbl1 = {type: "table", title: "tickers1", cols: ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], rows: []} for (var ticker of tickers1) { tbl1.rows.push([ticker.Symbol, ticker.High, ticker.Open, ticker.Low, ticker.Last, ticker.Buy, ticker.Sell, ticker.Time, ticker.Volume]) } // Request the market data of other trading pairs for (var symbol of arrSymbol) { exchange.GetTicker(symbol) } // Call GetTickers again var tickers2 = exchange.GetTickers() var tbl2 = {type: "table", title: "tickers2", cols: ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], rows: []} for (var ticker of tickers2) { tbl2.rows.push([ticker.Symbol, ticker.High, ticker.Open, ticker.Low, ticker.Last, ticker.Buy, ticker.Sell, ticker.Time, ticker.Volume]) } LogStatus("`" + JSON.stringify([tbl1, tbl2]) + "`") }
    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 = ["ADA_USDT", "LTC_USDT", "ETH_USDT", "SOL_USDT"] tickers1 = exchange.GetTickers() tbl1 = {"type": "table", "title": "tickers1", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": []} for ticker in tickers1: tbl1["rows"].append([ticker["Symbol"], ticker["High"], ticker["Open"], ticker["Low"], ticker["Last"], ticker["Buy"], ticker["Sell"], ticker["Time"], ticker["Volume"]]) for symbol in arrSymbol: exchange.GetTicker(symbol) tickers2 = exchange.GetTickers() tbl2 = {"type": "table", "title": "tickers2", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": []} for ticker in tickers2: tbl2["rows"].append([ticker["Symbol"], ticker["High"], ticker["Open"], ticker["Low"], ticker["Last"], ticker["Buy"], ticker["Sell"], ticker["Time"], ticker["Volume"]]) LogStatus("`" + json.dumps([tbl1, tbl2]) + "`")
    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 tickerToJson(ticker: &Ticker) -> String { format!(r#"["{}", {}, {}, {}, {}, {}, {}, {}, {}]"#, ticker.Symbol, ticker.High, ticker.Open, ticker.Low, ticker.Last, ticker.Buy, ticker.Sell, ticker.Time, ticker.Volume) } fn main() { let arrSymbol = ["ADA_USDT", "LTC_USDT", "ETH_USDT", "SOL_USDT"]; // Before requesting the market data of other trading pairs, call GetTickers // The Rust SDK has no JSON serialization, so use format! to concatenate the JSON text of the table let tickers1 = exchange.GetTickers().unwrap(); let rows1 = tickers1.iter().map(tickerToJson).collect::<Vec<String>>().join(","); let tbl1 = format!(r#"{{"type": "table", "title": "tickers1", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": [{}]}}"#, rows1); // Request the market data of other trading pairs for symbol in arrSymbol { exchange.GetTicker(symbol); } // Call GetTickers again let tickers2 = exchange.GetTickers().unwrap(); let rows2 = tickers2.iter().map(tickerToJson).collect::<Vec<String>>().join(","); let tbl2 = format!(r#"{{"type": "table", "title": "tickers2", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": [{}]}}"#, rows2); LogStatus!(format!("`[{},{}]`", tbl1, tbl2)); }
    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"}] */ json tickerToJson(const Ticker& ticker) { json arrJson; arrJson.push_back(ticker.Symbol); arrJson.push_back(ticker.High); arrJson.push_back(ticker.Open); arrJson.push_back(ticker.Low); arrJson.push_back(ticker.Last); arrJson.push_back(ticker.Buy); arrJson.push_back(ticker.Sell); arrJson.push_back(ticker.Time); arrJson.push_back(ticker.Volume); return arrJson; } void main() { std::string arrSymbol[] = {"ADA_USDT", "LTC_USDT", "ETH_USDT", "SOL_USDT"}; auto tickers1 = exchange.GetTickers(); json tbl1 = R"({ "type": "table", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": [] })"_json; tbl1["title"] = "tickers1"; for (const auto& ticker : tickers1) { json arrJson = tickerToJson(ticker); tbl1["rows"].push_back(arrJson); } for (const std::string& symbol : arrSymbol) { exchange.GetTicker(symbol); } auto tickers2 = exchange.GetTickers(); json tbl2 = R"({ "type": "table", "cols": ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], "rows": [] })"_json; tbl2["title"] = "tickers2"; for (const auto& ticker : tickers2) { json arrJson = tickerToJson(ticker); tbl2["rows"].push_back(arrJson); } json tbls = R"([])"_json; tbls.push_back(tbl1); tbls.push_back(tbl2); LogStatus("`" + tbls.dump() + "`"); }

Returns

TypeDescription

Ticker array / null

The exchange.GetTickers() function returns an array of Ticker structures when the data request succeeds, and returns null when the data request fails.

See Also

Remarks

Notes:

  • This function requests the exchange's aggregated market data interface. There is no need to set a trading pair or contract code before calling it, and it only returns market data for trading instruments that are already listed on the exchange.

  • The backtesting system supports this function.

  • Exchange objects that do not provide an aggregated market data interface do not support this function.

  • This function does not support options contracts.

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

Function NameUnsupported Spot ExchangesUnsupported Futures Exchanges
GetTickersZaif / WOO / Gemini / Coincheck / BitFlyer / BiboxFutures_WOO / Futures_dYdX / Futures_Deribit / Futures_Bibox / Futures_Aevo / Futures_edgeX