Type/to search
Built-in Functions
Structures
Trade
Ticker
Record
Order
Condition
OrderBook
Depth
Account
Asset
Position
Market
Funding
OtherStruct
HttpQuery-options
HttpQuery-return
LogStatus-table
LogStatus-btnTypeOne
LogStatus-btnTypeTwo
Chart-options
KLineChart-options
SetData-data
EventLoop-return
DBExec-return
Thread.join-return
Built-in Variables

Data structure for market trade records.

Attributes

NameTypeDescription

Id

string

Unique identifier for the market trade record. If the exchange API does not provide an Id, it will be filled with a timestamp.

Time

number

Timestamp in milliseconds.

Price

number

Execution price.

Amount

number

Execution quantity.

Type

number

Order type, refer to ORDER_TYPE_BUY, ORDER_TYPE_SELL.

See Also

Remarks

The exchange.GetTrades() function returns an array of Trade or an empty array.

Market data structure.

Attributes

NameTypeDescription

Info

object

Raw data returned by the exchange API, not included in backtesting.

Symbol

string

The Symbol field is the trading symbol code defined by the FMZ platform.

  • For spot exchange objects, the Symbol field value format is (example): BTC_USDT, representing the BTC_USDT spot trading pair.

  • For futures exchange objects, the Symbol field value format is (example): BTC_USDT.swap, representing BTC's USDT-margined perpetual contract.

  • For futures exchange objects (option-related functions are also encapsulated in futures exchange objects), the Symbol field value format is (example): BTC_USDT.BTC-240108-40000-C, representing BTC's USDT-margined option contract with an expiration date of January 8, 2024, and a strike price of 40000 for a call option.

High

number

Highest price. If the exchange API does not provide the 24-hour high, it is filled with the ask price.

Low

number

Lowest price. If the exchange API does not provide the 24-hour low, it is filled with the bid price.

Sell

number

Current best ask price.

Buy

number

Current best bid price.

Last

number

Last traded price.

Open

number

Period opening price. If the exchange API does not provide the opening price for the 24-hour rolling period, it is filled with the current price.

Volume

number

Recent trading volume. In principle, spot trading volume is in base currency units, and contract trading volume is in contract units. If the exchange API does not provide such data, it is filled with available data from the exchange API, for example, it may be trading volume in quote currency units.

Time

number

Timestamp in milliseconds.

OpenInterest

number

Open interest. Most exchange APIs do not provide this data, and the value is 0 when not supported.

See Also

Remarks

The exchange.GetTicker() function returns a Ticker structure.

For option contracts, calling the exchange.GetTicker() function is prone to errors. This is because option contract order books typically have poor liquidity, and there are often situations where there are no orders on the bid or ask side. In such cases, when the FMZ underlying system detects that the Buy or Sell field of the Ticker structure is 0, it will trigger an error message.

Data structure for candlestick bars in standard OHLC format, used for charting candlesticks and calculating technical indicators.

Attributes

NameTypeDescription

Time

number

Millisecond timestamp representing the start time of this candlestick period.

Open

number

Opening price.

High

number

Highest price.

Low

number

Lowest price.

Close

number

Closing price.

OpenInterest

number

Open interest. Most exchange APIs do not provide this data; value is 0 when not supported.

Volume

number

Trading volume. For spot trading, volume is principally in base currency units; for futures, volume is in contract units. If the exchange API does not provide standard data, existing API data is used for filling, which may be volume in quote currency units.

See Also

Remarks

The exchange.GetRecords() function returns an array of Records or an empty array. Each Record structure represents one candlestick bar.

For Python, different versions of pandas packages may require different handling, for example:

python
pandas.DataFrame(records) // May need to be adjusted to: pandas.DataFrame(list(records))

Related error message: in getattr KeyError: 'dtype'.

Order structure.

Attributes

NameTypeDescription

Info

object

Raw data returned by the exchange interface, this attribute is not available during backtesting.

Symbol

string

The Symbol field is the trading symbol code defined by the FMZ platform, with the same format as the Symbol field in the Ticker structure.

  • For spot exchange objects, the format of the Symbol field value (example) is: BTC_USDT, representing the BTC_USDT spot trading pair.

  • For futures exchange objects, the format of the Symbol field value (example) is: BTC_USDT.swap, representing the BTC USDT-margined perpetual contract.

Id

string

Order ID, this attribute consists of the exchange symbol code and the exchange's original order ID, separated by an English comma. For example, the Id attribute format for an ETH_USDT spot trading pair order on OKX exchange is: ETH-USDT,1547130415509278720.

Price

number

Order price, note that this attribute for market orders may be 0 or -1.

Amount

number

Order quantity, note that this attribute for market orders may be the amount value rather than the coin quantity.

DealAmount

number

Filled quantity, if the exchange interface does not provide this data, it may be filled with 0.

AvgPrice

number

Average filled price, note that some exchanges do not provide this data. When not provided and cannot be calculated, this attribute is set to 0.

Status

number

Order status, refer to ORDER_STATE_PENDING, ORDER_STATE_CLOSED, ORDER_STATE_CANCELED, ORDER_STATE_UNKNOWN.

Type

number

Order type, refer to ORDER_TYPE_BUY, ORDER_TYPE_SELL.

Offset

number

Open/close direction for contract orders, refer to ORDER_OFFSET_OPEN, ORDER_OFFSET_CLOSE.

ContractType

string

For spot orders, this attribute is "", i.e., an empty string. For contract orders, this attribute is the specific contract code.

Condition

object

Conditional order configuration information. When the order is a conditional order, this field contains the trigger conditions and execution price configuration for the conditional order. For regular orders, this field is null.

The structure of this field refers to the Condition structure.

Time

number

Order creation time, millisecond timestamp.

See Also

Remarks

The Order structure can be returned by exchange.GetOrder() and exchange.GetOrders() functions. The exchange.GetOrders() function returns an array of Order structures or an empty array. If there are no pending orders currently, it returns [], i.e., an empty array. The Status attribute of the Order structure can be directly compared with constants like ORDER_STATE_PENDING to determine if they are equal and thus confirm the order status.

For one-way position mode, when it cannot be determined whether an order is for closing (reducing) a position, the Offset field is set to the opening direction by default, i.e., ORDER_OFFSET_OPEN.

The Time field represents the order creation time as a millisecond timestamp. Some exchanges may also include time information in the Info field, but the Time field provides a standardized timestamp format.

Conditional order configuration structure, used to set trigger conditions and execution prices for conditional orders.

Attributes

NameTypeDescription

ConditionType

number

Conditional order type, available values:

TpTriggerPrice

number

Take profit trigger price. Used when the conditional order type is TP or OCO, the take profit order is triggered when the market price reaches this price.

TpOrderPrice

number

Take profit order execution price, i.e., the actual order price after take profit is triggered. A price of -1 indicates execution as a market order.

SlTriggerPrice

number

Stop loss trigger price. Used when the conditional order type is SL or OCO, the stop loss order is triggered when the market price reaches this price.

SlOrderPrice

number

Stop loss order execution price, i.e., the actual order price after stop loss is triggered. A price of -1 indicates execution as a market order.

See Also

Remarks

  • OCO orders (ConditionType=ORDER_CONDITION_TYPE_OCO) set both take profit and stop loss conditions simultaneously. When one condition is triggered, the other is automatically canceled.
  • TP orders (ConditionType=ORDER_CONDITION_TYPE_TP) only use the TpTriggerPrice and TpOrderPrice fields.
  • SL orders (ConditionType=ORDER_CONDITION_TYPE_SL) only use the SlTriggerPrice and SlOrderPrice fields.
  • GENERIC orders (ConditionType=ORDER_CONDITION_TYPE_GENERIC) are generic conditional orders, and the specific fields used depend on the exchange implementation.

Support for conditional order functionality depends on the specific exchange. Some exchanges may not support certain types of conditional orders.

Special usage of Condition structure in C++ language:
In C++ strategies, the Condition structure needs to use the OrderCondition struct type instead of a JSON object.

JavaScript/Python example (using object/dictionary):

javascript
var condition = { ConditionType: ORDER_CONDITION_TYPE_TP, TpTriggerPrice: 65000, TpOrderPrice: 65000 }

C++ example (using OrderCondition struct):

c++
OrderCondition condition = {.ConditionType = ORDER_CONDITION_TYPE_TP, .TpTriggerPrice = 65000, .TpOrderPrice = 65000};

Note: In C++, you should not use the JSON string approach json condition = R"({...})"_json;. Instead, use the OrderCondition struct initialization syntax directly.

Order structure in market depth.

Attributes

NameTypeDescription

Price

number

Order price.

Amount

number

Order quantity.

See Also

Remarks

In the data structure returned by the exchange.GetDepth() function, the attribute values of Bids and Asks are OrderBook arrays.

Market depth data structure.

Attributes

NameTypeDescription

Asks

array

Ask orders array, i.e., OrderBook array, sorted by price from low to high, with the first OrderBook structure in the array having the lowest price.

Bids

array

Bid orders array, i.e., OrderBook array, sorted by price from high to low, with the first OrderBook structure in the array having the highest price.

Time

number

Timestamp in milliseconds.

See Also

Remarks

The exchange.GetDepth() function returns a Depth structure.

Data structure for account information.

Attributes

NameTypeDescription

Info

object

Raw data returned by the exchange API. This property does not exist in backtesting mode.

Balance

number

Available amount of quote currency. In spot trading, if the trading pair is BTC_USDT, Balance represents the current available USDT amount. In USDT-margined contracts, Balance represents the available margin (USDT, quoteCurrency) amount.

FrozenBalance

number

Asset value frozen when orders are pending.

Stocks

number

Available amount of base currency. In spot trading, if the trading pair is BTC_USDT, Stocks represents the current available BTC amount. In coin-margined contracts, Stocks represents the available margin (coin, baseCurrency) amount.

FrozenStocks

number

Asset value frozen when orders are pending.

Equity

number

Only supported by futures exchange objects. The Equity field represents the total equity of the futures account margin under the current contract settings. If the exchange API does not provide relevant data, this field value is 0.

UPnL

number

Only supported by futures exchange objects. The UPnL field represents the total unrealized profit and loss of all open positions in the futures account margin under the current contract settings.

See Also

Remarks

The exchange.GetAccount() function returns an Account structure. The data in the returned structure depends on the currently set trading pair and contract code.

Data structure for specific currency asset information.

Attributes

NameTypeDescription

Currency

string

Currency asset name defined by the exchange. Due to potential differences in naming conventions across exchanges, the same currency may use different identifiers on different exchanges, for example BTC may be identified as XBT on some exchanges.

Amount

number

Available balance amount of the currency asset.

FrozenAmount

number

Frozen amount of the currency asset.

See Also

Remarks

The frozen amount FrozenAmount of currency assets typically includes assets locked by open orders and margin required for futures positions.

Data structure for contract position information.

Attributes

NameTypeDescription

Info

object

Raw data returned by the exchange interface. This attribute does not exist in backtesting mode.

Symbol

string

The Symbol field is the trading symbol code defined by the FMZ platform, with a format consistent with the Symbol field of the Ticker structure.

  • For spot exchange objects, the format of the Symbol field value (example) is: BTC_USDT, representing the BTC_USDT spot trading pair.

  • For futures exchange objects, the format of the Symbol field value (example) is: BTC_USDT.swap, representing the BTC USDT-margined perpetual contract.

MarginLevel

number

Position leverage multiplier. If the exchange interface does not provide this data, it will be filled through calculation and may contain errors.

Amount

number

Position quantity, usually a positive integer (number of contracts). Note that contract multipliers, values, and other contract specifications may differ between exchanges.

FrozenAmount

number

Frozen position quantity, temporarily frozen position quantity when close orders are not filled.

Price

number

Average position price. In principle, this attribute is the overall average price of the position (not involved in settlement). If the exchange interface does not provide this data, it will be filled with the existing average position price from the exchange interface (involved in settlement).

Profit

number

Floating profit and loss of the position. In principle, this is the unrealized profit and loss of the position. If the exchange interface does not provide this data, it will be filled with other profit and loss data from the exchange interface. The unit of the profit and loss value is the same as the unit of the current contract margin.

Type

number

Position type, refer to PD_LONG, PD_SHORT.

ContractType

string

Contract code. For specific content, please refer to the description of the exchange.SetContractType function.

Margin

number

Margin occupied by the position. If the exchange interface does not provide this data, it will be filled with 0.

See Also

Remarks

The exchange.GetPositions() function returns a Position array or an empty array.

For cryptocurrency futures, it should be noted that in the Position structure array returned by the exchange.GetPositions() function, the FrozenAmount, Profit, and Margin attributes of the position data structure may have different definitions when calling the exchange.GetPositions() interface for different exchange objects, as the data provided by exchanges is not unified.

For example, some exchanges do not have frozen position data in their position data, in which case FrozenAmount is 0. If specific data needs to be calculated, the raw data in the Info attribute can be used for calculation and analysis.

Data structure for trading symbol market information.

Attributes

NameTypeDescription

Symbol

string

Example value: "btcusdt", the Symbol field records the original name of this trading symbol on the exchange. Note that the format and definition of this attribute differs from the Symbol field in the Ticker structure.

BaseAsset

string

Example value: "BTC", the BaseAsset field records the base currency name (i.e., baseCurrency), uniformly in uppercase letters.

QuoteAsset

string

Example value: "USDT", the QuoteAsset field records the quote currency name (i.e., quoteCurrency), uniformly in uppercase letters.

TickSize

number

Example value: 0.01, the TickSize field records the minimum price increment for this trading symbol on the exchange.

AmountSize

number

Example value: 0.01, the AmountSize field records the minimum order quantity increment for this trading symbol on the exchange.

PricePrecision

number

Example value: 2, the PricePrecision field records the price precision for this trading symbol on the exchange, indicating the price is accurate to 2 decimal places.

AmountPrecision

number

Example value: 3, the AmountPrecision field records the order quantity precision for this trading symbol on the exchange, indicating the order quantity is accurate to 3 decimal places.

MinQty

number

Example value: 0.001, the MinQty field records the minimum order quantity for this trading symbol on the exchange.

MaxQty

number

Example value: 1000, the MaxQty field records the maximum order quantity for this trading symbol on the exchange.

MinNotional

number

Example value: 5, the MinNotional field records the minimum order value for this trading symbol on the exchange.

MaxNotional

number

Example value: 9999999, the MaxNotional field records the maximum order value for this trading symbol on the exchange.

CtVal

number

The CtVal field records the value corresponding to a single contract for this trading symbol on the exchange, with the unit specified in the CtValCcy field. For example: CtVal of 0.01 and CtValCcy of "BTC" means a single contract is worth 0.01 BTC.

CtValCcy

number

The CtValCcy field records the value unit of a single contract. The value unit of a single contract can be: BTC, USD, ETH, etc.

Info

object

The Info field records the raw data of this symbol returned by the exchange's market information interface.

See Also

Remarks

The exchange.GetMarkets() function returns a dictionary containing this Market structure.

Due to varying levels of support for market information data across different exchanges, fields not supported by an exchange will be ignored. All field values above are derived from the exchange interface's raw data, and specific details can also be found in the Info field content.

Data structure for trading instrument funding rate information, only cryptocurrency perpetual contracts support funding rate functionality.

Attributes

NameTypeDescription

Info

object

Raw data object returned from cryptocurrency futures exchange funding rate API calls.

Symbol

string

The Symbol field is the standardized trading instrument code defined by the FMZ platform.

Interval

number

Funding rate settlement interval period, unit: milliseconds. For example, 28800000 represents an 8-hour interval.

Time

number

Timestamp of the next funding rate period start time (current period settlement time), unit: milliseconds.

Rate

number

Funding rate value to be applied at the current period settlement.

See Also

Remarks

Different futures exchanges use different calculation methods and mechanisms for perpetual contract funding rates, with settlement periods including 1 hour, 4 hours, 8 hours, 24 hours, etc.

The current funding rate for futures exchange perpetual contracts may be a fixed value or a real-time calculated floating value.

The Rate field is the funding rate value without the % symbol. To convert to percentage format, multiply the value by 100 and add the % symbol.

This JSON structure is used to configure various parameters for HTTP requests sent by HttpQuery and HttpQuery_Go functions.

Attributes

NameTypeDescription

method

string

HTTP request method, for example: GET, POST, etc.

body

string

Request body content. For example, in POST requests, body can contain form data, JSON data, text, etc.

charset

string

Character set encoding. Used to specify the encoding method for text data in the request body, for example: "UTF-8".

cookie

string

Cookie is a small piece of data used to store and exchange state information between the client (usually a browser) and the server.

debug

bool

Debug mode switch. When set to true, the HttpQuery function call will return the complete HTTP response message; when set to false, it only returns the data in the response message Body.

headers

JSON

HTTP request header information, existing as key-value pairs (JSON structure), used to pass various information such as content type, authentication information, cache control, etc.

timeout

number

Timeout setting in milliseconds. Setting 1000 means 1 second timeout.

See Also

Remarks

Usage example:

javascript
function main() { var options = { method: "POST", body: "a=10&b=20&c=30", charset: "UTF-8", cookie: "session_id=12345; lang=en", debug: false, headers: {"TEST-HTTP-QUERY": "123"}, timeout: 1000 } var ret = HttpQuery("http://127.0.0.1:8080", options) Log(ret) }

HTTP message sent when the above code is executed:

log
POST / HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cookie: session_id=12345; lang=en Host: 127.0.0.1:8080 Test-Http-Query: 123 Transfer-Encoding: chunked User-Agent: Mozilla/5.0 (Macintosh; ... Accept-Encoding: gzip, deflate, br e a=10&b=20&c=30 0

This JSON structure is the data structure returned by the HttpQuery function in debug mode when the debug field is specified as true in the parameter options structure.

Attributes

NameTypeDescription

StatusCode

number

HTTP status code

Header

JSON

Request header information

Cookies

array

Cookie information

Trace

JSON

Complete path information of the request

Length

number

Message length

Body

string

Message content

See Also

Remarks

Example of returned JSON data structure:

json
{ "StatusCode": 302, "Header": { "Content-Type": ["text/html"], // ... }, "Cookies": [{ // ... }], "Trace": {}, "Length": 154, "Body": "..." }

This JSON structure is used to configure the table content displayed in the strategy status bar.

Attributes

NameTypeDescription

type

string

Used to set the type of UI control to be parsed and displayed. For status bar tables, it is fixed as: table.

title

string

Used to set the title of the status bar table.

cols

array

Used to set the column headers of the status bar table. The first element of the array is the title of the first column, and so on.

rows

array

Used to set the row data of the status bar table. The first element of this rows array (two-dimensional array) is also an array structure. The length of this array structure should be consistent with the number of table columns (elements in the array correspond one-to-one with table column names), representing the first row of data in the table.

See Also

Remarks

javascript
function main() { var tbl = { type: "table", title: "标题", cols: ["列1", "列2", "列3"], rows: [ ["行1列1", "行1列2", "行1列3"], ["行2列1", "行2列2", "行2列3"], ["行3列1", "行3列2", "行3列3"], ] } LogStatus("`" + JSON.stringify(tbl) + "`") }

This JSON structure is used to configure button controls in the status bar. The button control JSON structure can be embedded into the status bar table JSON structure. This is a legacy version structure that the platform still supports for compatibility, but it is recommended to use the latest version of the button JSON structure.
Status bar button control construction example (after button click trigger, the popup contains a single input control, constructed through the input field):

json
{ "type": "button", "cmd": "open", "name": "Open Position", "input": { "name": "Position Size", "type": "number", "defValue": 1 } }

The controls in the popup triggered by clicking the status bar button are configured through the input or group fields.

Attributes

NameTypeDescription

type

string

For button controls, fixed as: button.

class

string

Button type setting.

name

string

The text displayed on the button control, i.e., the button name.

cmd

string

The interactive command content sent to the strategy when the button control triggers a click operation.

description

string

Description information for the button control. This description is displayed when the mouse hovers over the button in the status bar.

disabled

bool

Set the button as disabled (true) or enabled (false).

input

JSON

When constructing status bar buttons for interaction, data input is supported. The interaction command is ultimately captured by the GetCommand() function. Add an input item to the JSON data structure of the status bar button control to configure the input control in the popup displayed when the button is triggered.
For example, set the input field value to:

json
{ "name": "Position Size", "type": "number", "defValue": 1, "description": "test" }

Description of each field in the above JSON structure:

  • name
    The title of the control in the popup that appears after the status bar button is clicked.
  • description
    The description information of the control in the popup that appears after the status bar button is clicked.
  • type
    The type of control in the popup that appears after the status bar button is clicked. The type field can take the following values:
    1. "number": Numeric input control.
    2. "string": String input control.
    3. "selected": Dropdown control.
    4. "boolean": Switch control.
  • defValue
    The default value of the control in the popup that appears after the status bar button is clicked.
    For dropdown type controls (selected), the defValue field is used to set dropdown options, for example: "input": {"name": "Position Size", "type": "selected", "defValue": "A|B|C"}, the text descriptions of the dropdown options are set to A, B, C.

Extended fields for dropdown type controls:

  • options
    For dropdown controls in the page triggered by status bar button controls, the options field can be used to set options. Options in the options field support not only strings but also the {text: "description", value: "value"} structure. Use the defValue field to set default options, which can be multiple selections.
  • multiple
    When this field is set to true, the dropdown supports multiple selections.

group

array

The input field configures a single control in the popup that appears after the status bar button is clicked, while the group field is used to configure a group of controls. The data structure of elements in group is consistent with the value of the input field. Please refer to the related description of the input field.

See Also

Remarks

Example of class attribute values for button JSON structure in status bar:

javascript
function main() { var table = { type: "table", title: "Status Bar Button Styles", cols: ["Default", "Primary", "Success", "Info", "Warning", "Danger"], rows: [ [ {"type":"button", "class": "btn btn-xs btn-default", "name": "Default"}, {"type":"button", "class": "btn btn-xs btn-primary", "name": "Primary"}, {"type":"button", "class": "btn btn-xs btn-success", "name": "Success"}, {"type":"button", "class": "btn btn-xs btn-info", "name": "Info"}, {"type":"button", "class": "btn btn-xs btn-warning", "name": "Warning"}, {"type":"button", "class": "btn btn-xs btn-danger", "name": "Danger"} ] ] } LogStatus("`" + JSON.stringify(table) + "`") }

group field and input field usage example:

javascript
function main() { // Status bar button control (implemented with input field) - The dropdown control on the page triggered by testBtn1 button uses options field to set options and defValue field to set default option. This differs from other examples in this chapter that directly use defValue to set options. var testBtn1 = { type: "button", name: "testBtn1", cmd: "cmdTestBtn1", input: {name: "testBtn1ComboBox", type: "selected", options: ["A", "B"], defValue: 1} } /* Status bar button control (implemented with input field) - The dropdown control on the page triggered by testBtn2 button uses options field to set options. The options field supports not only strings, but also ```{text: "description", value: "value"}``` structure. Use defValue field to set default option, which can be multiple selections (implemented through array structure). Multiple selection requires setting additional field multiple to true. */ var testBtn2 = { type: "button", name: "testBtn2", cmd: "cmdTestBtn2", input: { name: "testBtn2MultiComboBox", type: "selected", description: "Implement dropdown multi-select", options: [{text: "Option A", value: "A"}, {text: "Option B", value: "B"}, {text: "Option C", value: "C"}], defValue: ["A", "C"], multiple: true } } // Status bar grouped button control (implemented with group field) - The dropdown control on the page triggered by testBtn3 button uses options field to set options, and also supports directly using defValue to set options. var testBtn3 = { type: "button", name: "testBtn3", cmd: "cmdTestBtn3", group: [ {name: "comboBox1", label: "labelComboBox1", description: "Dropdown 1", type: "selected", defValue: 1, options: ["A", "B"]}, {name: "comboBox2", label: "labelComboBox2", description: "Dropdown 2", type: "selected", defValue: "A|B"}, {name: "comboBox3", label: "labelComboBox3", description: "Dropdown 3", type: "selected", defValue: [0, 2], multiple: true, options: ["A", "B", "C"]}, { name: "comboBox4", label: "labelComboBox4", description: "Dropdown 4", type: "selected", defValue: ["A", "C"], multiple: true, options: [{text: "Option A", value: "A"}, {text: "Option B", value: "B"}, {text: "Option C", value: "C"}, {text: "Option D", value: "D"}] } ] } while (true) { LogStatus("`" + JSON.stringify(testBtn1) + "`\n", "`" + JSON.stringify(testBtn2) + "`\n", "`" + JSON.stringify(testBtn3) + "`\n") var cmd = GetCommand() if (cmd) { Log(cmd) } Sleep(5000) } }

This JSON structure is used to configure button controls in the status bar. The button control JSON structure can be embedded into the status bar table JSON structure. This is the latest version of the button JSON structure.
Status bar button control construction example (after the button is clicked, a popup contains multiple input controls, constructed through the group field):

json
{ "type": "button", "cmd": "open", "name": "Open Position", "group": [{ "type": "selected", "name": "tradeType", "label": "Order Type", "description": "Market order, Limit order", "default": 0, "group": "Trading Settings", "settings": { "options": ["Market Order", "Limit Order"], "required": true, } }, { "type": "selected", "name": "direction", "label": "Trade Direction", "description": "Buy, Sell", "default": "buy", "group": "Trading Settings", "settings": { "render": "segment", "required": true, "options": [{"name": "Buy", "value": "buy"}, {"name": "Sell", "value": "sell"}], } }, { "type": "number", "name": "price", "label": "Price", "description": "Order price", "group": "Trading Settings", "filter": "tradeType==1", "settings": { "required": true, } }, { "type": "number", "name": "amount", "label": "Order Amount", "description": "Order quantity", "group": "Trading Settings", "settings": { "required": true, } }], }

The controls in the popup triggered by clicking the status bar button control are set through the input or group field.

Attributes

NameTypeDescription

type

string

For button controls, this field is fixed as: button.

name

string

The text displayed on the button control, i.e., the button name.

cmd

string

The interactive command content sent to the strategy when the button control triggers a click action.

input

JSON

When constructing status bar buttons for interaction, input data is also supported. The interaction commands are ultimately captured by the GetCommand() function. Add an input item to the JSON data structure of the status bar button control to configure the input controls displayed in the popup when the button is triggered.

Compared to the old version of the input structure, the new version adds some new fields and changes:

json
{ "type": "selected", "name": "test", "label": "topic", "description": "desc", "default": 1, "filter": "a>1", "group": "group1", "settings": { ... }, // Component configuration }

Description and explanation of each field in the above JSON structure:

  • type
    Control type (required field), supports setting to: "number" numeric input box, "string" string input box, "selected" dropdown box, "boolean" switch control.

  • name
    If the current JSON structure is the field value of the input field, when the label field is not set, name is the control title in the popup that appears after clicking the status bar button.
    If the current JSON structure is an element in the field value (array structure) of the group field, name is not used as the control title, the name field is used to represent the field name of the control input content. For example, the following code snippet of the group field explains:

    json
    var testBtn3 = { type: "button", name: "testBtn3", cmd: "cmdTestBtn3", group: [ {name: "comboBox1", label: "labelComboBox1", description: "Dropdown box 1", type: "selected", defValue: 1, options: ["A", "B"]}, {name: "comboBox2", label: "labelComboBox2", description: "Dropdown box 2", type: "selected", defValue: "A|B"}, {name: "comboBox3", label: "labelComboBox3", description: "Dropdown box 3", type: "selected", defValue: [0, 2], multiple: true, options: ["A", "B", "C"]}, { name: "comboBox4", label: "labelComboBox4", description: "Dropdown box 4", type: "selected", defValue: ["A", "C"], multiple: true, options: [{text: "Option A", value: "A"}, {text: "Option B", value: "B"}, {text: "Option C", value: "C"}, {text: "Option D", value: "D"}] } ] }

    According to this code snippet, if the status bar button triggers interaction, a popup will appear with 4 controls, all of which are dropdown controls. After setting the options for each control and clicking OK to send the interaction message, the GetCommand function in the strategy will receive cmdTestBtn3:{"comboBox1":1,"comboBox2":0,"comboBox3":[0,2],"comboBox4":["A","C"]}.
    The values of name in the JSON structure are all used as field names for the returned interaction information, for example: comboBox1, comboBox2, etc.

  • label
    Used to set the control title.

  • description
    Description information of the control. If the current JSON structure is an element in the field value (array structure) of the group field, when the label field is not set, description is the control title in the popup that appears after clicking the status bar button.

  • default
    The default value of the control.

  • filter
    Selector, used to hide controls. Not setting this field means no filtering (display control); when this field is set, when the expression is true, no filtering (display control), when the expression is false, filtering (do not display control).

  • group
    Used to control control grouping, collapsible.

  • settings
    Component configuration, controls have multiple UI options to choose from, this option can be used for specific settings. For example:

    json
    settings:{ multiple:true, customizable:true, options:[{name:'xxx|yyy',value:0}] }

    Settings related configurations:
    settings.required: Whether required.
    settings.disabled: Whether disabled.
    settings.min: Valid when type=number, indicates minimum value or minimum string length.
    settings.max: Valid when type=number, indicates maximum value or maximum string length.
    settings.step: Valid when type=number, render=slider, indicates step size.
    settings.multiple: Valid when type=selected, indicates support for multiple selection.
    settings.customizable: Valid when type=selected, indicates support for customization; users can directly edit and add new options in the dropdown control, if a newly edited option is selected, the name of the option is used instead of the value it represents when triggering interaction.
    settings.options: Valid when type=selected, indicates the option data format of the selector: ["Option 1", "Option 2"], [{'name':'xxx','value':0}, {'name':'xxx','value':1}].
    settings.render: Render component type.
    When type=number, settings.render is not set (default numeric input box), optional: slider (slider bar), date (time selector returns timestamp).
    When type=string, settings.render is not set (default single-line input box), optional: textarea (multi-line input), date (time selector returns yyyy-MM-dd hh:mm:ss), color (color selector returns #FF00FF).
    When type=selected, settings.render is not set (default dropdown box), optional: segment (segment selector).
    When type=boolean, currently only default checkbox.

group

array

The input field configures a control in the dialog box that pops up after clicking the status bar button. The difference between group and input is that group configures a group of controls. The elements in group have the same data structure as the input field values. Please refer to the above input field description.

See Also

Remarks

Supports bilingual settings:

json
{ type:'selected', name:'test', label:'选项|options', description:'描述|description', default:0, // Here default value is set to 0, representing the value in {name:'xxx|yyy',value:0} option filter:'a>1&&a<10', group:'分组|group', settings:{ multiple:true, customizable:true, options:[{name:'xxx|yyy',value:0}] } }

This JSON is used to configure chart settings for the custom plotting function Chart(). The chart library uses Highcharts. The following lists several basic configuration fields.

Attributes

NameTypeDescription

__isStock

string

Platform extension field. When set to true, uses Highstocks chart; when set to false, uses Highcharts chart.

extension

JSON

json
{ layout: 'single', // Not grouped, displayed separately, default is grouped 'group' height: 300, // Specify height }

title

string

Chart title

xAxis

JSON

X-axis configuration.

yAxis

JSON

Y-axis configuration.

series

JSON

Chart data series.

See Also

Remarks

Simple plotting example:

javascript
// This chart is an object in JavaScript. Before using the Chart function, you need to declare an object variable chart for configuring the chart var chart = { // This field marks whether the chart is a stock chart. Interested users can change it to false and run to see the effect __isStock: true, // Zoom tool tooltip: {xDateFormat: '%Y-%m-%d %H:%M:%S, %A'}, // Title title : { text : 'Spread Analysis Chart'}, // Range selector rangeSelector: { buttons: [{type: 'hour',count: 1, text: '1h'}, {type: 'hour',count: 3, text: '3h'}, {type: 'hour', count: 8, text: '8h'}, {type: 'all',text: 'All'}], selected: 0, inputEnabled: false }, // Horizontal axis (X-axis), currently set type is datetime xAxis: { type: 'datetime'}, // Vertical axis (Y-axis), default values adjust with data size yAxis : { // Title title: {text: 'Spread'}, // Whether to enable right-side Y-axis opposite: false }, // Data series, this property stores various data series (lines, candlestick charts, labels, etc.) series : [ // Index 0, data array stores data for this index series {name : "line1", id : "Line1,buy1Price", data : []}, // Index 1, dashStyle:'shortdash' is set to display as dashed line {name : "line2", id : "Line2,lastPrice", dashStyle : 'shortdash', data : []} ] } function main(){ // Call Chart function to initialize the chart var ObjChart = Chart(chart) // Clear ObjChart.reset() while(true){ // Get the timestamp of this polling cycle, i.e., millisecond timestamp, used to determine the position on the chart's X-axis var nowTime = new Date().getTime() // Get market data var ticker = _C(exchange.GetTicker) // Get the best bid price from the market data return value var buy1Price = ticker.Buy // Get the last traded price. To prevent the two lines from overlapping, we add 1 var lastPrice = ticker.Last + 1 // Pass timestamp as X value and best bid price as Y value to data series at index 0 ObjChart.add(0, [nowTime, buy1Price]) // Same as above ObjChart.add(1, [nowTime, lastPrice]) Sleep(2000) } }

This JSON is used to configure the chart settings for the custom drawing function KLineChart. Only a few basic configuration fields are listed below.

Attributes

NameTypeDescription

overlay

bool

Whether to draw on the main chart.

xAxis

JSON

X-axis configuration parameters.

yAxis

JSON

Y-axis configuration parameters.

candle

JSON

Candlestick chart configuration parameters.

See Also

Remarks

Refer to Topic article on drawing with KLineChart function.

This JSON is used to set the data to be loaded by the exchange.SetData() function. This JSON data uses an array structure, where each element is also an array with the format [time, data].

Attributes

NameTypeDescription

time

number

The timestamp of the data, used to mark the time corresponding to this data entry.

data

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

data is the specific data content corresponding to a certain time in the data loaded by the exchange.SetData() function. When the strategy is running, the exchange.GetData() function retrieves the data with the corresponding timestamp based on the current time.

See Also

Remarks

Example of loading data in the backtesting system and retrieving data when the strategy backtest is running:

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) } }

This JSON is the data structure returned by the EventLoop() function. The EventLoop() function monitors the following events: 1. Any WebSocket readable data events; 2. Completion events of concurrent tasks from exchange.Go() and HttpQuery_Go() functions; 3. Message events sent by threads created using the threading.Thread() function in JavaScript language strategies.

Attributes

NameTypeDescription

Seq

number

Event sequence number.

Event

string

Event name.

ThreadId

number

Event thread ID.

Index

number

Event index.

Nano

number

Nanosecond timestamp.

See Also

Remarks

When using the exchange.Go() function for concurrent requests, the event data structure returned by the EventLoop() function.

json
{ "Seq":1, "Event":"Exchange_GetTrades", "ThreadId":0, "Index":3, "Nano":1682068771309583400 }

When concurrent execution threads in JavaScript language strategies (created by the threading.Thread() function) use the thread object's postMessage() function to send messages, the EventLoop() function in the receiving thread will monitor the following event data structure:

json
{ "Seq":4, "Event":"thread", "ThreadId":1, "Index":0, "Nano":1727592066508674000 }

This JSON is the data structure returned by the DBExec() function; this JSON data structure is also returned when executing SQL statements using the exec() method of objects created by the Dial() function.

Attributes

NameTypeDescription

columns

array

Column names of the queried data, string array.

values

array

The specific data queried, where each data item corresponds to the column names. The values field is a two-dimensional array, with each element being an array representing one data record.

See Also

Remarks

Example of querying data from database:

json
{ "columns":["TS","HIGH","OPEN","LOW","CLOSE","VOLUME"], "values":[ [1518970320000,100,99.1,90,100,12345.6], [1518960320000,100,99.1,90,100,12345.6] ] }

This JSON is the data structure returned by the join() member function of the Thread object, used to store information related to concurrent threads in JavaScript language strategies. The Thread object refers to a thread object created via threading.Thread().

Attributes

NameTypeDescription

id

number

Thread ID.

terminated

bool

Whether the thread was forcibly terminated.

elapsed

number

Thread execution time (nanoseconds).

ret

number

Return value of the thread function.

See Also

Remarks

The following code tests the timeout mechanism of the join() function of the Thread object and prints the return value of the join() function.

javascript
function testFunc() { for (var i = 0; i < 5; i++) { Log(i) Sleep(300) } } function main() { var t1 = threading.Thread(testFunc) Log(t1.join(1000)) // undefined Log(t1.join()) // {"id":1,"terminated":false,"elapsed":1506864000} }