资源加载中... loading...

Market

exchange.GetTicker

Get the {@struct/Ticker Ticker} structure of the spot or contract corresponding to the currently set trading pair, contract code, i.e. the ticker data. GetTicker () function is a member function of the exchange object {@var/EXCHANGE exchange}, the use of exchange object member functions (methods) only related to exchange, and it will not be repeated in the document.

The exchange.GetTicker() function returns the {@struct/Ticker Ticker} structure when the request for data succeeds, and returns null value when the request for data fails. {@struct/Ticker Ticker}, null value

exchange.GetTicker() exchange.GetTicker(symbol)

The parameter symbol is used to specify the specific trading pair and contract code corresponding to the requested {@struct/Ticker Ticker} data. If this parameter is not passed, the market data of the currently set trading pair and contract code will be requested by default. When calling the exchange.GetTicker(symbol) function, exchange is the spot exchange object. If you need to request market data with the denominated currency as USDT and the trading currency as BTC, the parameter symbol is: "BTC_USDT", and the format is the trading pair format defined by the FMZ platform. When calling the exchange.GetTicker(symbol) function, exchange is the futures exchange object. If you need to request the market data of BTC’s U-standard perpetual contract, the parameter symbol is: "BTC_USDT.swap", and the format is a combination of the trading pair and contract code defined by the FMZ platform, separated by the character “.”. When calling the exchange.GetTicker(symbol) function, exchange is the futures exchange object. If you need to request the market data of BTC’s U-standard option contract, the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance Option BTC-240108-40000-C as an example), the format is the combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character “.”.

symbol false string

function main(){
    // If it is a futures exchange object, set the contract code first, e.g. set it as a perpetual contract
    // exchange.SetContractType("swap")

    var ticker = exchange.GetTicker()
    /*
        The exchange interface may not be accessible due to network reasons (even if the docker program's device can open the exchange website, the API interface may not be accessible).
        At this point, the ticker is null, and it will cause an error when accessing ticker.High, so when testing this code, make sure that the exchange interface can be accessed.
    */
    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)
}
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"])
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);
}

For futures exchange objects (i.e., exchange or exchanges[0]), you need to set the contract code using the exchange.SetContractType() function before calling the ticker function, which will not be repeated.

function main() {
    var ticker = exchange.GetTicker("BTC_USDT")
    Log(ticker)
}
def main():
    ticker = exchange.GetTicker("BTC_USDT")
    Log(ticker)
void main() {
    auto ticker = exchange.GetTicker("BTC_USDT");
    Log(ticker);
}

Use the symbol parameter to request market data for a specific symbol (spot symbol).

The Ticker data returned by the exchange.GetTicker() function in the backtesting system. Where High and Low are simulated values, taken from the sell one and buy one of the market at that time. The Ticker data returned by the exchange.GetTicker() function in the real market. Where the High and Low values are based on the data returned by the encapsulated exchange Tick interface, which includes the highest and lowest prices within a certain period (usually a 24-hour period). Exchanges that do not support the exchange.GetTicker() function:

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetTicker Futures_Aevo

{@fun/Market/exchange.GetDepth exchange.GetDepth}, {@fun/Market/exchange.GetTrades exchange.GetTrades}, {@fun/Market/exchange.GetRecords exchange.GetRecords}, {@fun/Market/exchange.GetTickers exchange.GetTickers}

exchange.GetDepth

Get the {@struct/Depth Depth} structure of the spot or contract corresponding to the currently set trading pair, contract code, i.e. order book data.

The exchange.GetDepth() function returns the {@struct/Depth Depth} structure if the request for data succeeds, and it returns null if the request for data fails. {@struct/Depth Depth}, null value

exchange.GetDepth() exchange.GetDepth(symbol)

The parameter symbol is used to specify the specific trading pair and contract code corresponding to the requested {@struct/Depth Depth} data. If this parameter is not passed, the order book data of the currently set trading pair and contract code will be requested by default. When calling the exchange.GetDepth(symbol) function, exchange is the spot exchange object. If you need to request to obtain the order book data with the denominated currency as USDT and the transaction currency as BTC, the parameter symbol is: "BTC_USDT", and the format is the trading pair format defined by the FMZ platform. When calling the exchange.GetDepth(symbol) function, exchange is the futures exchange object. If you need to request the order book data of BTC’s U-standard perpetual contract, the parameter symbol is: "BTC_USDT.swap", and the 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, exchange is the futures exchange object. If you need to request the order book data of the BTC’s U-standard option contract, the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance Option BTC-240108-40000-C as an example), the format is the combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character “.”. symbol false string

function main(){
    var depth = exchange.GetDepth()
    /*
        The exchange interface may not be accessible due to network reasons (even if the docker program's device can open the exchange website, the API interface may not be accessible).
        At this point, the depth is null, which will cause an error when accessing depth.Asks[1].Price, so make sure you can access the exchange interface when testing the code.
    */
    var price = depth.Asks[1].Price
    Log("Sell 2 price is:", price)
}
def main():
    depth = exchange.GetDepth()
    price = depth["Asks"][1]["Price"]
    Log("Sell 2 price is:", price)
void main() {
    auto depth = exchange.GetDepth();
    auto price = depth.Asks[1].Price;
    Log("Sell 2 price is:", price);
}

Test exchange.GetDepth() function:

function main() {
    // BTC U-based perpetual contract
    var depth = exchange.GetDepth("BTC_USDT.swap")
    Log(depth)
}
def main():
    depth = exchange.GetDepth("BTC_USDT.swap")
    Log(depth)
void main() {
    auto depth = exchange.GetDepth("BTC_USDT.swap");
    Log(depth);
}

When the configured exchange object is a futures exchange object, use the symbol parameter to request the order book data of a specific symbol (futures symbol).

In the backtesting system, the data for each grade returned by the exchange.GetDepth() function when using the Simulate Tick backtesting are all simulated values. In the backtesting system, the data returned by the exchange.GetDepth() function when using the Real Tick backtesting is a second level deep snapshot.

{@fun/Market/exchange.GetTicker exchange.GetTicker}, {@fun/Market/exchange.GetTrades exchange.GetTrades}, {@fun/Market/exchange.GetRecords exchange.GetRecords}

exchange.GetTrades

Get the {@struct/Trade Trade} structure array of the spot or contract corresponding to the currently set trading pair, contract code, i.e. the market transaction data.

The exchange.GetTrades() function returns an array of {@struct/Trade Trade} structures if the request for data succeeds, and it returns null values if the request for data fails. {@struct/Trade Trade}arrays, null values

exchange.GetTrades() exchange.GetTrades(symbol)

The parameter symbol is used to specify the specific trading pair and contract code corresponding to the requested {@struct/Trade Trade} array data. If this parameter is not passed, the latest transaction record data of the currently set trading pair and contract code will be requested by default. When calling the exchange.GetTrades(symbol) function, exchange is the spot exchange object. If you need to request to obtain the order book data with the denominated currency as USDT and the trading currency as BTC, the parameter symbol is: "BTC_USDT", and the format is the trading pair format defined by the FMZ platform. When calling the exchange.GetTrades(symbol) function, exchange is the futures exchange object. If you need to request the order book data of BTC’s U-standard perpetual contract, the parameter symbol is: "BTC_USDT.swap", and the 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, exchange is the futures exchange object. If you need to request the order book data of BTC’s U-standard option contract, the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance Option BTC-240108-40000-C as an example), the format is the combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character “.”. symbol false string

function main(){
    var trades = exchange.GetTrades()
    /*
        The exchange interface may not be accessible due to network reasons (even if the docker program's device can open the exchange website, the API interface may not be accessible).
        At this point, trade is null. When accessing trade[0].Id, it will cause an error. Therefore, when testing this code, ensure that you can access the exchange interface.
    */
    Log("id:", trades[0].Id, "time:", trades[0].Time, "Price:", trades[0].Price, "Amount:", trades[0].Amount, "type:", trades[0].Type)
}
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"])
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);
}

Test the exchange.GetTrades() function:

function main() {
    // BTC's U-based perpetual contract
    var trades = exchange.GetTrades("BTC_USDT.swap")
    Log(trades)
}
def main():
    trades = exchange.GetTrades("BTC_USDT.swap")
    Log(trades)
void main() {
    auto trades = exchange.GetTrades("BTC_USDT.swap");
    Log(trades);
}

When the configured exchange object is a futures exchange object, use the symbol parameter to request market transaction record data for a specific symbol (futures symbol).

exchange.GetTrades() function to get the current trading pairs, the market’s transaction history (not their own) corresponding to contracts. Some exchanges do not support this function, and the specific data returned is how much of the range of transaction records depends on the exchange and needs to be handled according to the specific situation. The return data is an array, where each element of the chronological order and exchange.GetRecords () function returns the same order of data, that is, the last element of the array is the data closest to the current time. The exchange.GetTrades() function returns an empty array when using Simulate Tick backtesting in the backtesting system. The data returned by the exchange.GetTrades() function when using Real Tick backtesting in the backtesting system is the order flow snapshot data, i.e. the {@struct/Trade Trade} structure array. Exchanges that do not support the exchange.GetTrades() function:

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetTrades Futures_BitMart / Futures_Bibox

{@fun/Market/exchange.GetTicker exchange.GetTicker}, {@fun/Market/exchange.GetDepth exchange.GetDepth}, {@fun/Market/exchange.GetRecords exchange.GetRecords}

exchange.GetRecords

Get the {@struct/Record Record} structure array of the spot or contract corresponding to the currently set trading pair, contract code, i.e. K-line data.

The exchange.GetRecords() function returns an array of {@struct/Record Record} structures when the request for data succeeds, and it returns null values when the request for data fails. {@struct/Record Record}arrays, null values

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

The parameter symbol is used to specify the specific trading pair and contract code corresponding to the requested {@struct/Record Record} array data. If this parameter is not passed, the K-line data of the currently set trading pair and contract code will be requested by default. When calling the exchange.GetRecords(symbol) function, exchange is the spot exchange object. If you need to request to obtain the data with the denominated currency as USDT and the transaction currency as BTC, the parameter symbol is: "BTC_USDT", and the format is the trading pair format defined by the FMZ platform. When calling the exchange.GetRecords(symbol) function, exchange is the futures exchange object. If you need to request the order book data of BTC’s U-standard perpetual contract, the parameter symbol is: "BTC_USDT.swap", and the format is a combination of the trading pair and contract code defined by the FMZ platform, separated by the character “.”. When calling the exchange.GetRecords(symbol) function, exchange is the futures exchange object. If you need to request the order book data of BTC’s U-standard option contract, the parameter symbol is: "BTC_USDT.BTC-240108-40000-C" (taking Binance Option BTC-240108-40000-C as an example), the format is the combination of the trading pair defined by the FMZ platform and the specific option contract code defined by the exchange, separated by the character “.”. symbol false string The parameter period specifies the period of the requested K-line data, for example: {@var/PERIOD/PERIOD_M1 PERIOD_M1}, {@var/PERIOD/PERIOD_M5 PERIOD_M5}, {@var/PERIOD/PERIOD_M15 PERIOD_M15}, etc. The value of parameter period can be passed not only the defined standard period, but also integer values in seconds. If this parameter is not passed, the period of the K-line data requested by default is the default K-line period of the current strategy real-time/backtest configuration. period false number The parameter limit is used to specify the length of the requested K-line data. If this parameter is not passed, the default request length is the maximum number of K-line bars requested at a time of the exchange K-line interface. This parameter may cause paging to query the exchange K-line data, and the time consumption of the function call will increase during paging query. limit false number

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))      
}
def main():
    Log(exchange.GetRecords(60 * 2))
    Log(exchange.GetRecords(PERIOD_M5))
void main() {
    Log(exchange.GetRecords(60 * 2)[0]);
    Log(exchange.GetRecords(PERIOD_M5)[0]);
}

Get K-line data for a custom period.

function main() {
    var records = exchange.GetRecords(PERIOD_H1)
    /*
        The exchange interface may not be accessible due to network reasons (even if the docker program's device can open the exchange website, the API interface may not be accessible).
        At this point, records is null. When accessing records[0].Time, it will cause an error. Therefore, when testing this code, ensure that you can access the exchange interface.
    */
    Log("The first k-line data is Time:", records[0].Time, "Open:", records[0].Open, "High:", records[0].High)
    Log("The second k-line data is Time:", records[1].Time ,"Close:", records[1].Close)
    Log("Current K-line (latest)", records[records.length-1], "Previous K-line", records[records.length-2])
}
def main():
    records = exchange.GetRecords(PERIOD_H1)
    Log("The first k-line data is Time:", records[0]["Time"], "Open:", records[0]["Open"], "High:", records[0]["High"])
    Log("The second k-line data Time:", records[1]["Time"], "Close:", records[1]["Close"])
    Log("Current K-line (latest)", records[-1], "Previous K-line", records[-2])
void main() {
    auto records = exchange.GetRecords(PERIOD_H1);
    Log("The first k-line data is Time:", records[0].Time, "Open:", records[0].Open, "High:", records[0].High);
    Log("The 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]);
}

Output K-line bar data:

function main() {
    var records = exchange.GetRecords("BTC_USDT.swap", 60, 100)
    Log(records)
}
def main():
    records = exchange.GetRecords("BTC_USDT.swap", 60, 100)
    Log(records)
void main() {
    auto records = exchange.GetRecords("BTC_USDT.swap", 60, 100);
    Log(records);
}

When the configured exchange object is a futures exchange object, use the symbol, period, and limit parameters to request the K-line data of a specific product (futures product).

The default K-line period can be set in the backtest and real trading pages. If you specify a parameter when calling the exchange.GetRecords() function, the K-line data corresponding to that parameter period will be obtained. If no parameter is specified when the function is called, the corresponding K-line data will be returned according to the K-line period set in the backtest and real market parameters. The return value is an array of Record structures, the returned K-line data will be accumulated over time, the upper limit of the accumulated K-line bars is affected by the exchange.SetMaxBarLen() function setting. The default limit is 5000 bars when it’s not set. When the K-line data reaches the K-line bar accumulation limit, it will be updated by adding a K-line bar and deleting the earliest K-line bar (e.g. queue in/out). Some exchanges do not provide a K-line interface, so the docker collects market transaction record data (Trade structured array) in real time to generate K-lines. If the exchange’s K-line interface supports paging queries, multiple API requests will be made when calling the exchange.SetMaxBarLen() function to set a larger K-line length. When the exchange.GetRecords() function is called initially, the number of K-line bars obtained differs between backtesting and real trading: - The backtesting system will obtain a certain number of K-line bars before the start of the backtesting time range in advance (the default is 5000, the settings of the backtesting system and the amount of data will affect the final number returned), as the initial K-line data. - The number of K-line bars obtained during the actual trading is based on the maximum amount of data that can be obtained from the K-line interface of the exchange. The period parameter is set to 5, which is a request to get K-line data with a period of 5 seconds. If the period parameter is not divisible by 60 (i.e., the period represented is not divisible by minutes). The underlying system uses the relevant interface of exchange.GetTrades() to obtain the transaction record data and synthesize the required K-line data. If the period parameter is divisible by 60, then the required K-line data is synthesized using a minimum of 1-minute K-line data (if possible, the required K-line data is synthesized using a larger period). The simulated level backtesting in the backtesting system requires the setting of the underlying K-line period (when the backtesting system simulates level backtesting, the corresponding K-line data is used to generate Tick data according to the set underlying K-line period). It should be noted that the period of the K-line data obtained in the strategy should not be smaller than the underlying K-line period. Because in the simulation level backtesting, the K-line data of each period in the backtesting system is synthesized from the K-line data of the underlying K-line period. The C++ language has the following code example if you need to construct your own K-line data:

#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 display: Records[10]
    Log(r);                      
    auto ma = TA.MA(r,10);       
    // Output display: [nan,nan,nan,nan,nan,nan,nan,nan,nan,450]
    Log(ma);                     
}

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

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetRecords Zaif / Coincheck / BitFlyer Futures_Aevo

{@fun/Market/exchange.GetTicker exchange.GetTicker}, {@fun/Market/exchange.GetDepth exchange.GetDepth}, {@fun/Market/exchange.GetTrades exchange.GetTrades}, {@fun/Market/exchange.SetMaxBarLen exchange.SetMaxBarLen}

exchange.GetPeriod

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

K-line period in seconds, integer value in seconds. number

exchange.GetPeriod()

function main() {
    // For example, the K-line period set on the website page of the FMZ Quant Trading platform during backtesting and live trading is 1 hour.
    var period = exchange.GetPeriod()
    Log("K-line period:", period / (60 * 60), "hours")
}
def main():
    period = exchange.GetPeriod()
    Log("K-line period:", period / (60 * 60), "hours")
void main() {
    auto period = exchange.GetPeriod();
    Log("K-line period:", period / (60 * 60.0), "hours");
}

{@fun/Market/exchange.GetRecords exchange.GetRecords}

exchange.SetMaxBarLen

Set the maximum length of the K-line.

exchange.SetMaxBarLen(n)

The parameter n is used to specify the maximum K-line length. n true number

function main() {
    exchange.SetMaxBarLen(50)
    var records = exchange.GetRecords()
    Log(records.length, records)
}
def main():
    exchange.SetMaxBarLen(50)
    r = exchange.GetRecords()
    Log(len(r), r)
void main() {
    exchange.SetMaxBarLen(50);
    auto r = exchange.GetRecords();
    Log(r.size(), r[0]);
}

The exchange.SetMaxBarLen() function affects two aspects for cryptocurrency strategy runtime:

  • Affects the number of K-line bars (Bars) that are obtained on the first call.
  • Affects the maximum number of K-line bars (Bars).

{@fun/Market/exchange.GetRecords exchange.GetRecords}

exchange.GetRawJSON

Get the original content returned by the last rest request for the current exchange object ({@var/EXCHANGE exchange}, {@var/EXCHANGE/exchanges exchanges}).

The response data for the rest request. string

exchange.GetRawJSON()

function main(){
    exchange.GetAccount(); 
    var obj = JSON.parse(exchange.GetRawJSON());
    Log(obj);
}
import json
def main():
    exchange.GetAccount()
    obj = json.loads(exchange.GetRawJSON())
    Log(obj)
void main() {
    auto obj = exchange.GetAccount();
    // C++ does not support the GetRawJSON function
    Log(obj);
}

The exchange.GetRawJSON() function is only supported for the real trading. The function is not supported by strategies in the C++ language.

{@var/EXCHANGE exchange}

exchange.GetRate

Get the exchange rate currently set for the exchange object.

The current value of the exchange rate of the exchange object. number

exchange.GetRate()

function main(){
    Log(exchange.GetTicker())
    // Set up exchange rate conversion
    exchange.SetRate(7)
    Log(exchange.GetTicker())
    Log("Current exchange rate:", exchange.GetRate())
}
def main():
    Log(exchange.GetTicker())
    exchange.SetRate(7)
    Log(exchange.GetTicker())
    Log("Current exchange rate:", exchange.GetRate())
void main() {
    Log(exchange.GetTicker());
    exchange.SetRate(7);
    Log(exchange.GetTicker());
    Log("Current exchange rate:", exchange.GetRate());
}

If exchange.SetRate() has not been called to set the conversion rate, the exchange.GetRate() function returns a default rate value of 1. That is, the data related to the currently displayed currency (quoteCurrency) has not been converted. If an exchange rate value has been set using exchange.SetRate(), for example, exchange.SetRate(7). Then all price information, such as quotes, depths, and order prices obtained through the exchange exchange object will be converted by multiplying by the set exchange rate 7. If exchange corresponds to an exchange with USD as the denomination currency, after calling exchange.SetRate(7), all prices in the live market will be converted to a price close to CNY by multiplying 7. At this point, the exchange rate value obtained using exchange.GetRate() is 7.

{@fun/Trade/exchange.SetRate exchange.SetRate}

exchange.SetData

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

The length of the string after parameter value JSON encoding. number

exchange.SetData(key, value)

The name of the data collection. key true string The data to be loaded by the exchange.SetData() function has a data structure of an array. The data structure is the same as the data format requested by the exchange.GetData() function when requesting external data, i.e.: "schema": ["time", "data"]. value true array

/*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)
    }
}
'''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)
/*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);
    }
}

It requires that the data for the parameter value be in the same format as the data variable in the following example. You can see that the timestamp 1579622400000 corresponds to the time 2020-01-22 00:00:00, and that when the strategy program is run after this time, call the exchange.GetData() function to get the data before the next data timestamp 1579708800000, that is, time 2020-01-23 00:00:00. What you get are [1579622400000, 123] the contents of that data, as the program continues to run, the time changes, and so on to get the data item by item. In the following example, at runtime (backtesting or live trading), the current moment reaches or exceeds the timestamp 1579795200000, the exchange.GetData() function is called and the return value is: {"Time":1579795200000,"Data":["abc", 123,{"price":123}]}. "Time":1579795200000 corresponds to 1579795200000 in data [1579795200000, ["abc", 123, {"price": 123}]]. "Data":["abc", 123, {"price": 123}] corresponds to data ["abc", 123, {"price": 123}]] in [1579795200000, ["abc", 123, {"price": 123}]].

The loaded data can be any economic indicators, industry data, relevant indicators, etc., used for strategy quantitative assessment of all quantifiable information.

{@fun/Market/exchange.GetData exchange.GetData}

exchange.GetData

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

Records in the data collection. object

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

The name of the data collection. key true string Used to set the cache timeout in milliseconds. Defaults to a one minute cache timeout for live tradings. timeout false number

/*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)
    }
}
'''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)
/*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);
    }
}

The call to get the data written directly.

/*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)
    }
}
'''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)
/*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);
    }
}

It support for requesting data through external links, the format of the data requested to:

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

Where schema is the data format for each record in the body of the loaded data, which is fixed to ["time", "data"] corresponding to the format of the entry-by-entry data in the data attribute. What is stored in the data attribute is the body of the data, with each entry consisting of a millisecond-level timestamp and the data content (which can be any JSON-encodable data). The service program for testing, written in Go:

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 program’s response data upon receipt of the request:

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

Test strategy code:

function main() {
    Log(exchange.GetData("http://xxx.xx.x.xx:9090/data"))
    Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json"))
}
def main():
    Log(exchange.GetData("http://xxx.xx.x.xx:9090/data"))
    Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json"))
void main() {
    Log(exchange.GetData("http://xxx.xx.x.xx:9090/data"));
    Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json"));
}

The call method to get the data of an external link.

function main() {
    Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data"))   // The xxx part of the link is the code of the query data, here xxx is an example.
}
def main():
    Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data"))
void main() {
    Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data"));
}

Request data for a query created on the platform datadata, requesting that the data format of the answer be (must have time, data fields described in schema):

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

The “data” field is the required data content, and the data in the “data” field needs to be the same as what is agreed in the “schema”. When the exchange.GetData() function is called, a JSON object is returned, e.g.: {"Time":1579795200000, "Data":"..."}.

Get the data at once for backtesting and cache one minute of data for live trading. In the backtesting system, when requesting data using the access interface, the backtesting system automatically adds from (timestamped in seconds), to (timestamped in seconds) to the request, parameters such as period (underlying K-line period, timestamped in milliseconds) are used to determine the time frame over which the data is to be acquired.

{@fun/Market/exchange.SetData exchange.SetData}

exchange.GetMarkets

The exchange.GetMarkets() function is used to get exchange market information.

Dictionary containing the {@struct/Market Market} structure. object

exchange.GetMarkets()

function main() {
    var markets = exchange.GetMarkets()
    var currency = exchange.GetCurrency()

    // Get the current contract code can also use exchange.GetContractType() function
    var ct = "swap"

    var key = currency + "." + ct
    Log(key, ":", markets[key])
}
def main():
    markets = exchange.GetMarkets()
    currency = exchange.GetCurrency()
    ct = "swap"

    key = currency + "." + ct
    Log(key, ":", markets[key])
void main() {
    auto markets = exchange.GetMarkets();
    auto currency = exchange.GetCurrency();

    auto ct = "swap";
    auto key = currency + "." + ct;
    Log(key, ":", markets[key]);
}

Example of a call to a futures exchange object:

/*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]) + "`")
}
'''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]) + "`")
/*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() + "`");
}

Use the futures exchange object to call the exchange.GetMarkets() function in the backtesting system. Before calling any market function, GetMarkets only returns the market data of the current default trading pair. After calling the market function, it returns the market data of all requested varieties. You can refer to the following test example:

The exchange.GetMarkets() function returns a dictionary with a key named the name of the trade variety, and for spot fixes formatted as a trading pair, for example:

{
    "BTC_USDT" : {...},  // The key value is the Market structure
    "LTC_USDT" : {...},  
    ...
}

For futures contract exchanges, as there may be multiple contracts for a single variety, e.g. BTC_USDT trading pairs, there are perpetual contracts, quarterly contracts, and so on. The exchange.GetMarkets() function returns a dictionary with the key name of the pair combined with the contract code, for example:

{
    "BTC_USDT.swap" : {...},     // The key value is the Market structure
    "BTC_USDT.quarter" : {...}, 
    "LTC_USDT.swap" : {...},
    ...
}
  • The exchange.GetMarkets() function supports live tradings, backtesting system.
  • The exchange.GetMarkets() function returns market information only for the varieties that are traded on line on the exchange.
  • The exchange.GetMarkets() function does not support options contracts.

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

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetMarkets Coincheck / Bithumb / BitFlyer

{@struct/Market Market}

exchange.GetTickers

The exchange.GetTickers() function is used to get exchange aggregated ticker data (the array of {@struct/Ticker Ticker} structure). exchange returns ticker data for all trading pairs when it is a spot exchange object; exchange returns ticker data for all contracts when it is a futures exchange object.

The exchange.GetTickers() function returns an array of {@struct/Ticker Ticker} structures when it succeeds in requesting data, and null when it fails. {@struct/Ticker Ticker} arrays, null values

exchange.GetTickers()

function main() {
    var tickers = exchange.GetTickers()
    if (tickers && tickers.length > 0) {
        Log("Number of tradable items on the exchange:", tickers.length)
    }
}
def main():
    tickers = exchange.GetTickers()
    if tickers and len(tickers) > 0:
        Log("Number of tradable items on the exchange:", len(tickers))
void main() {
    auto tickers = exchange.GetTickers();
    if (tickers.Valid && tickers.size() > 0) {
        Log("Number of tradable items on the exchange:", tickers.size());
    }
}

Call the exchange.GetTickers() function to obtain aggregated market data.

/*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 other trading pair market data, call Get Tickers
    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 market data for 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]) +  "`")
}
'''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]) +  "`")
/*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() + "`");
}

Use the spot exchange object and call the exchange.GetTickers() function in the backtest system. Before calling any market function, GetTickers only returns the ticker data of the current default trading pair. After calling the market function, it returns the ticker data of all requested varieties. You can refer to the following test example:

  • This function requests the exchange to aggregate tickers interface, no need to set up trading pairs, contract code before calling. It only returns the tickers of the online trading varieties on the exchange.
  • The backtesting system supports this function.
  • Exchange objects that do not provide an aggregated ticker interface do not support this function.
  • This function does not support option contracts.

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

Function Name Unsupported Spot Exchanges Unsupported Futures Exchanges
GetTickers Zaif / WOO / Gemini / Coincheck / BitFlyer / Bibox Futures_WOO / Futures_dYdX / Futures_Deribit / Futures_Bibox / Futures_Aevo

{@struct/Ticker Ticker}, {@fun/Market/exchange.GetTicker exchange.GetTicker}

Log Trade