Market
exchange.GetTicker
Get the Ticker structure corresponding to the currently set trading pair or contract code, i.e., market data. The GetTicker() function is a member function of the exchange object exchange. The member functions (methods) of the exchange object are only related to exchange, which will not be repeated in subsequent documentation.
exchange.GetTicker()
exchange.GetTicker(symbol)Examples
-
For futures exchange objects (i.e.,
exchangeorexchanges[0]), you need to use theexchange.SetContractType()function to set the contract code before calling market data functions. This will not be repeated in subsequent documentation.javascriptfunction main(){ // If it's a futures exchange object, first set the contract code, for example, set it to perpetual contract // exchange.SetContractType("swap") var ticker = exchange.GetTicker() /* Due to network reasons, the exchange API may not be accessible (even if the device where the bot is hosted can open the exchange website, the API interface may still be inaccessible) In this case, ticker will be null, and accessing ticker.High will cause an error, so when testing this code, ensure that the exchange API 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) }pythondef 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"])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
symbolparameter to request market data for a specific symbol (spot symbol).javascriptfunction main() { var ticker = exchange.GetTicker("BTC_USDT") Log(ticker) }pythondef main(): ticker = exchange.GetTicker("BTC_USDT") Log(ticker)c++void main() { auto ticker = exchange.GetTicker("BTC_USDT"); Log(ticker); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The When calling the When calling the When calling the |
See Also
exchange.GetDepth exchange.GetTrades exchange.GetRecords exchange.GetTickers exchange.IO (API rate limit control)
Remarks
In the backtesting system, the Ticker data returned by the exchange.GetTicker() function has simulated values for High and Low, taken from the best ask and best bid at that time.
In live trading, the Ticker data returned by the exchange.GetTicker() function has High and Low values determined by the data returned from the exchange's encapsulated 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 |
exchange.GetDepth
Get the Depth structure, i.e., order book data, for the spot or futures corresponding to the currently set trading pair and contract code.
exchange.GetDepth()
exchange.GetDepth(symbol)Examples
-
Test the
exchange.GetDepth()function:javascriptfunction main(){ var depth = exchange.GetDepth() /* Due to network issues, the exchange API may be inaccessible (even if the device hosting the bot can open the exchange website, the API interface may still be unreachable) In this case, depth will be null, and accessing depth.Asks[1].Price will cause an error, so when testing this code, ensure that the exchange API is accessible */ var price = depth.Asks[1].Price Log("Second ask price:", price) }pythondef main(): depth = exchange.GetDepth() 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
exchangeobject is a futures exchange object, use thesymbolparameter to request order book data for a specific instrument (futures instrument).javascriptfunction main() { // BTC USDT-margined perpetual contract var depth = exchange.GetDepth("BTC_USDT.swap") Log(depth) }pythondef main(): depth = exchange.GetDepth("BTC_USDT.swap") Log(depth)c++void main() { auto depth = exchange.GetDepth("BTC_USDT.swap"); Log(depth); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The parameter When calling the When calling the When calling the |
See Also
Remarks
In the backtesting system, when using Simulated Tick backtesting, the data returned by the exchange.GetDepth() function has simulated values for each level.
In the backtesting system, when using Real Tick backtesting, the data returned by the exchange.GetDepth() function is a second-level depth snapshot.
exchange.GetTrades
Get the Trade structure array for the currently set trading pair or contract code, i.e., the market transaction data for spot or futures.
exchange.GetTrades()
exchange.GetTrades(symbol)Examples
-
Test the
exchange.GetTrades()function:javascriptfunction main(){ var trades = exchange.GetTrades() /* Due to network issues, the exchange API may be inaccessible (even if the host device can open the exchange website, the API interface may still be unreachable) In this case, trades will be null, and accessing trades[0].Id will cause an error. Therefore, when testing this code, please ensure the exchange API is accessible */ Log("id:", trades[0].Id, "time:", trades[0].Time, "Price:", trades[0].Price, "Amount:", trades[0].Amount, "type:", trades[0].Type) }pythondef 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"])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
exchangeobject is a futures exchange object, use thesymbolparameter to request market trade data for a specific instrument (futures contract).javascriptfunction main() { // BTC USDT-margined perpetual contract var trades = exchange.GetTrades("BTC_USDT.swap") Log(trades) }pythondef main(): trades = exchange.GetTrades("BTC_USDT.swap") Log(trades)c++void main() { auto trades = exchange.GetTrades("BTC_USDT.swap"); Log(trades); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The parameter When calling the When calling the When calling the |
See Also
Remarks
The exchange.GetTrades() function retrieves the market trading history (not your own trades) for the current trading pair or contract. Some exchanges do not support this function, and the specific range of returned data varies by exchange and needs to be handled according to actual circumstances. The returned data is an array, where the time order of each element is consistent with the order of data returned by the exchange.GetRecords() function, meaning the last element of the array is the data closest to the current time.
In the backtesting system, when using simulated-level Tick backtesting, the exchange.GetTrades() function returns an empty array.
In the backtesting system, when using **real-level Tick** backtesting, the data returned by the exchange.GetTrades() function is order flow snapshot data, i.e., a Trade structure array.
Exchanges that do not support the exchange.GetTrades() function:
| Function Name | Unsupported Spot Exchanges | Unsupported Futures Exchanges |
|---|---|---|
| GetTrades | Hyperliquid | Futures_BitMart / Futures_Bibox / Futures_Hyperliquid / Futures_edgeX |
exchange.GetRecords
Get the Record structure array corresponding to the currently set trading pair or contract code for spot or futures, i.e., K-line data.
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 with custom period.
javascriptfunction main() { // Print K-line data with period of 120 seconds (2 minutes) Log(exchange.GetRecords(60 * 2)) // Print K-line data with period of 5 minutes Log(exchange.GetRecords(PERIOD_M5)) }pythondef main(): Log(exchange.GetRecords(60 * 2)) Log(exchange.GetRecords(PERIOD_M5))c++void main() { Log(exchange.GetRecords(60 * 2)[0]); Log(exchange.GetRecords(PERIOD_M5)[0]); } -
Output K-line bar data:
javascriptfunction main() { var records = exchange.GetRecords(PERIOD_H1) /* Due to network issues, the exchange API may be inaccessible (even if the host device can open the exchange website, the API interface may still be unavailable) In this case, records will be null, and accessing records[0].Time will cause an error, so please ensure the exchange API is accessible when testing this code */ 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]) }pythondef 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])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
exchangeobject is a futures exchange object, use thesymbol,period, andlimitparameters to request K-line data for a specific instrument (futures instrument).javascriptfunction main() { var records = exchange.GetRecords("BTC_USDT.swap", 60, 100) Log(records) }pythondef main(): records = exchange.GetRecords("BTC_USDT.swap", 60, 100) Log(records)c++void main() { auto records = exchange.GetRecords("BTC_USDT.swap", 60, 100); Log(records); }
Returns
| Type | Description |
| The |
Arguments
| Name | Type | Required | Description |
symbol | string | No | The When calling the When calling the When calling the |
period | number | No | The |
limit | number | No | The |
See Also
Remarks
The default K-line period can be set in the backtest and live trading pages. If a parameter is specified when calling the exchange.GetRecords() function, it will retrieve K-line data corresponding to that parameter's period. If no parameter is specified during the function call, it will return K-line data according to the K-line period set in the backtest or live trading parameters.
The return value is an array of Record structures. The returned K-line data accumulates over time, with the upper limit of accumulated K-line bars affected by the exchange.SetMaxBarLen() function setting. When not set, the default upper limit is 5000 K-line bars. When the K-line data reaches the accumulation limit, adding a new K-line bar will simultaneously delete the earliest K-line bar (like a queue operation). Some exchanges do not provide K-line interfaces, in which case the docker will collect real-time market trade data (Trade structure array) to generate K-lines.
If the exchange's K-line interface supports pagination queries, when calling the exchange.SetMaxBarLen() function to set a larger K-line length, multiple API requests will be made.
When initially calling the exchange.GetRecords() function, the number of K-line bars obtained differs between backtesting and live trading:
-
In the backtest system, a certain number of K-line bars before the start time of the backtest time range will be pre-fetched (default is 5000, the backtest system settings and data volume will affect the final returned quantity) as initial K-line data.
-
In live trading, the specific number of K-line bars obtained is based on the maximum data volume available from the exchange's K-line interface.
When the period parameter is set to 5, it requests 5-second period K-line data. If the period parameter is not divisible by 60 (meaning the period cannot be expressed in minutes), the underlying system will use the exchange.GetTrades() related interface to obtain trade record data and synthesize the required K-line data. If the period parameter is divisible by 60, it will use at minimum 1-minute K-line data (using larger periods as much as possible to synthesize the required K-line data) to synthesize the required K-line data.
In the backtest system, simulation-level backtesting requires setting the underlying K-line period (during simulation-level backtesting, the backtest system generates tick data based on the K-line data corresponding to the set underlying K-line period). Note that 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, K-line data of various periods in the backtest system are synthesized from the K-line data corresponding to the underlying K-line period.
In C++ language, if you need to construct K-line data yourself, here is a 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 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 |
exchange.GetPeriod
Get the K-line period set on the FMZ Quant Trading Platform website page when running backtesting or live trading strategies, which is the default K-line period used when calling the exchange.GetRecords() function without parameters.
exchange.GetPeriod()Examples
javascript
function main() {
// For example, when 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")
c++
void main() {
auto period = exchange.GetPeriod();
Log("K-line period:", period / (60 * 60.0), "hours");
}Returns
| Type | Description |
number | The number of seconds of the K-line period, integer value, in seconds. |
See Also
exchange.SetMaxBarLen
Set the maximum length of K-line data.
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)
c++
void main() {
exchange.SetMaxBarLen(50);
auto r = exchange.GetRecords();
Log(r.size(), r[0]);
}Arguments
| Name | Type | Required | Description |
len | number | Yes | The parameter |
See Also
Remarks
The exchange.SetMaxBarLen() function has two effects on cryptocurrency strategy runtime:
-
Affects the number of K-line bars obtained on the first call.
-
Affects the upper limit of the number of K-line bars.
exchange.GetRawJSON
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
| Type | Description |
string | Response data from the |
See Also
Remarks
The exchange.GetRawJSON() function only supports live trading. C++ language strategies do not support this function.
exchange.GetRate
Get the current exchange rate value 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())
c++
void main() {
Log(exchange.GetTicker());
exchange.SetRate(7);
Log(exchange.GetTicker());
Log("Current rate:", exchange.GetRate());
}Returns
| Type | Description |
number | The current exchange rate value of the exchange object. |
See Also
Remarks
If exchange.SetRate() has not been called to set the exchange rate conversion, the default rate value returned by exchange.GetRate() function is 1, indicating that the currently displayed quote currency related data has not undergone exchange rate conversion.
If the exchange rate value has been set using exchange.SetRate(), for example exchange.SetRate(7), then all price information such as market data, depth, and order prices obtained through the exchange exchange object will be multiplied by the set exchange rate 7 for conversion.
If the exchange corresponding to exchange uses USD as the quote currency, after calling exchange.SetRate(7), all prices in live trading will be multiplied by 7 to convert to prices close to CNY. At this time, the exchange rate value obtained using exchange.GetRate() is 7.
exchange.SetData
The exchange.SetData() function is used to set data loaded during strategy runtime.
exchange.SetData(key, value)Examples
The data format of the required parameter value is shown 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. After the strategy program runs to this time, before the next data timestamp 1579708800000 (i.e., time 2020-01-23 00:00:00), when calling the exchange.GetData() function to retrieve data, it will always get the content of the data [1579622400000, 123]. As the program continues to run and time progresses, data is retrieved sequentially in this manner.
In the following example, when running (backtesting or live trading), when the current moment reaches or exceeds the timestamp 1579795200000, calling the exchange.GetData() function returns: {"Time":1579795200000,"Data":["abc",123,{"price":123}]}. Where "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)
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
| Type | Description |
number | The string length after JSON encoding of the parameter |
Arguments
| Name | Type | Required | Description |
key | string | Yes | Data collection name. |
value | array | Yes | The data to be loaded by the |
See Also
Remarks
The loaded data can be any economic indicators, industry data, related indices, etc., used for quantitative analysis of all quantifiable information in strategies.
exchange.GetData
The exchange.GetData() function is used to retrieve data loaded by the exchange.SetData() function or data provided by external links.
exchange.GetData(key)
exchange.GetData(key, timeout)Examples
-
Get the calling method for directly writing data.
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)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); } } -
Supports requesting data through external links. The format of the requested data:
json{ "schema":["time","data"], "data":[ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] }Where
schemais the data format for each record in the loaded data body. This format is fixed as["time","data"], corresponding to the format of each data item in thedataattribute. Thedataattribute stores the data body, where each data item consists of a millisecond timestamp and data content (the data content can be any JSON-encodable data).Test service program written in Go:
golangpackage 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) }Response data after the program receives a request:
json{ "schema":["time","data"], "data":[ [1579536000000, "abc"], [1579622400000, 123], [1579708800000, {"price": 123}], [1579795200000, ["abc", 123, {"price": 123}]] ] }Test strategy code:
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)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); } } -
Method for calling external link data.
javascriptfunction main() { Log(exchange.GetData("http://xxx.xx.x.xx:9090/data")) Log(exchange.GetData("https://www.fmz.com/upload/asset/32bf73a69fc12d36e76.json")) }pythondef 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 query data created on the datadata platform, requiring the response data format to be (must include time and data field descriptions in the schema):
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 format agreed upon in the "schema". When calling the
exchange.GetData()function, it returns a JSON object, for example:{"Time":1579795200000, "Data":"..."}.javascriptfunction main() { Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data")) // The xxx part in the link is the encoding of the queried data, xxx here is an example }pythondef main(): Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data"))c++void main() { Log(exchange.GetData("https://www.datadata.com/api/v1/query/xxx/data")); }
Returns
| Type | Description |
object / null | Records in the data collection or data returned by the request. |
Arguments
| Name | Type | Required | Description |
key | string | Yes | Data collection name or request link. |
timeout | number | No | Used to set cache timeout in milliseconds. The default cache timeout for live trading is one minute. |
See Also
Remarks
Data is fetched all at once during backtesting, while data is cached for one minute during live trading. In the backtesting system, when using the API request method to fetch data, the backtesting system will automatically add parameters such as from (timestamp in seconds), to (timestamp in seconds), and period (underlying K-line period, timestamp in milliseconds) to the request to determine the time range of data to be retrieved.
exchange.GetMarkets
The exchange.GetMarkets() function is used to get market information from the exchange.
exchange.GetMarkets()Examples
-
Example of calling futures exchange object:
javascriptfunction main() { var markets = exchange.GetMarkets() var currency = exchange.GetCurrency() // 获取当前合约代码也可以用exchange.GetContractType()函数 var ct = "swap" var key = currency + "." + ct Log(key, ":", markets[key]) }pythondef main(): markets = exchange.GetMarkets() currency = exchange.GetCurrency() ct = "swap" key = currency + "." + ct Log(key, ":", markets[key])c++void main() { auto markets = exchange.GetMarkets(); auto currency = exchange.GetCurrency(); auto ct = "swap"; auto key = currency + "." + ct; Log(key, ":", markets[key]); } -
Using futures exchange object to call
exchange.GetMarkets()function in the backtesting system. Before calling any market data functions, GetMarkets only returns the market data of the current default trading pair; after calling market data functions, it will return the market data of all requested instruments. Please 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]) + "`")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
| Type | Description |
object / null | Dictionary containing |
See Also
Remarks
The exchange.GetMarkets() function returns a dictionary with trading symbol names as keys. For spot trading, the format is fixed as trading pairs, for example:
json
{
"BTC_USDT" : {...}, // Value is Market structure
"LTC_USDT" : {...},
...
}
For futures contract exchanges, since one symbol may contain multiple contracts, for example: BTC_USDT trading pair includes perpetual contracts, quarterly contracts, etc. The exchange.GetMarkets() function returns a dictionary with keys as the combination of trading pair and contract code, for example:
json
{
"BTC_USDT.swap" : {...}, // Value is Market structure
"BTC_USDT.quarter" : {...},
"LTC_USDT.swap" : {...},
...
}
- The
exchange.GetMarkets()function supports both live trading and backtesting systems. - The
exchange.GetMarkets()function only returns market information for symbols that are actively trading on the exchange. exchange.GetMarkets()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 | -- |
exchange.GetTickers
The exchange.GetTickers() function is used to get aggregated market data from the exchange (array of Ticker structures). When exchange is a spot exchange object, it returns market data for all trading pairs; when exchange is a futures exchange object, it returns market data for all contracts.
exchange.GetTickers()Examples
-
Call the
exchange.GetTickers()function to get aggregated market data.javascriptfunction main() { var tickers = exchange.GetTickers() if (tickers && tickers.length > 0) { Log("Number of tradable symbols:", tickers.length) } }pythondef main(): tickers = exchange.GetTickers() if tickers and len(tickers) > 0: Log("Number of tradable symbols:", len(tickers))c++void main() { auto tickers = exchange.GetTickers(); if (tickers.Valid && tickers.size() > 0) { Log("Number of tradable symbols:", tickers.size()); } } -
Using spot exchange object, call the
exchange.GetTickers()function in the backtesting system. Before calling any market data functions, GetTickers only returns the ticker data of the current default trading pair; after calling market data functions, it will return ticker data for all requested symbols. Please 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 other trading pair market data, 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 other trading pair market data 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]) + "`")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
| Type | Description |
| The |
See Also
Remarks
Notes:
-
This function requests the exchange's aggregated market data interface. There is no need to set trading pairs or contract codes before calling. It only returns market data for instruments currently listed on the exchange.
-
The backtesting system supports this function.
-
Exchange objects that do not provide aggregated market data interfaces do not support this function.
-
This function does not support options 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 / Futures_edgeX |