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

Structures

Trade

Structure of market transaction records.

The market transaction record Id, or if the exchange interface does not provide an Id then use a timestamp to populate it. Id string Millisecond timestamp. Time number Transaction price. Price number Transaction amount. Amount number Order type, refer to {@var/ORDER_TYPE/ORDER_TYPE_BUY ORDER_TYPE_BUY}, {@var/ORDER_TYPE/ORDER_TYPE_SELL ORDER_TYPE_SELL}. Type number

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

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

Ticker

The structure of the market ticker.

The original data returned by the exchange interface, no such attribute is available for backtesting. Info object The Symbol field is the trading variety code defined by the FMZ platform.

  • For the spot exchange object, the format of the Symbol field value (as an example) is: BTC_USDT, indicating the BTC_USDT spot trading pair.
  • For the futures exchange object, the format of the Symbol field value (as an example) is BTC_USDT.swap, which represents the USDT propriety perpetual contract for BTC.
  • For futures exchange objects, the format of the Symbol field value is (for example): BTC_USDT.BTC-240108-40000-C, which represents a call option contract of BTC in USDT with an exercise date of January 8, 2024 and an exercise price of 40,000.

Symbol string The highest price, or if the exchange interface does not provide a 24-hour highest price, then use the sell one price to fill. High number The lowest price, or if the exchange interface does not provide a 24-hour lowest price, then use the buy one price to fill. Low number The current moment’s sell one price. Sell number The current moment’s buy one price. Buy number The latest transaction price. Last number Period open price, if the exchange interface does not provide a 24-hour rolling period open price, then the current price is used to fill. Open number Recent transaction amount, in principle, spot transaction amount is in baseCurrency, and contract transaction amount is in number of contracts. If the exchange interface does not provide such data, it will be populated with the data available in the exchange interface, for example, the transaction amount may be in quoteCurrency. Volume number Millisecond-level timestamp. Time number Positions, most exchange interfaces do not provide this data and the value is 0 when this data is not supported. OpenInterest number

The exchange.GetTicker() function returns a Ticker structure. For option contracts, the exchange.GetTicker() function call is prone to errors. Because option contract market liquidity is usually poor, there are often no pending orders for the first buy or first sell. At this time, when the FMZ bottom layer detects that the Ticker structure field Buy or Sell is 0, an error prompt will be triggered.

{@fun/Market/exchange.GetTicker exchange.GetTicker}, {@fun/Market/exchange.GetTickers exchange.GetTickers}

Record

The structure of K-Line Bar, the standard OHLC structure, is used to draw K-lines and indicators for calculation and analysis.

Millisecond-level timestamp, for a Record structure whose Time attribute value is the start timestamp of the period of this K-line Bar. Time number Opening price. Open number Highest price. High number Lowest price. Low number Closing price. Close number Position amount, most of the exchange interfaces do not provide this data, the value is 0 when this data is not supported. OpenInterest number Transaction amount. In principle, spot transaction amount is in baseCurrency and contract transaction amount is in number of contracts. If the exchange interface does not provide such data, it will be populated with the existing data from the exchange interface, for example, the transaction amount in quoteCurrency. Volume number

The exchange.GetRecords() function returns an array of Records or an empty array. Each Record structure represents a K-line bar, i.e. a K-line bar.

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

Order

The structure of the order.

Teh original data of the exchange interface response, no such attribute is available for backtesting. Info object The Symbol field is the trading product code defined by the FMZ platform, and its format is consistent with the Symbol field of the {@struct/Ticker Ticker} structure.

  • For spot exchange objects, the format of the Symbol field value is (for example): BTC_USDT, indicating the BTC_USDT spot trading pair.
  • For futures exchange objects, the format of the Symbol field value is (for example): BTC_USDT.swap, which represents the USDT-standard perpetual contract of BTC.

Symbol string Order Id, this attribute consists of the exchange product code and the exchange original order ID, separated by English commas. For example, the attribute Id format of the spot trading pair ETH_USDT order of OKX exchange is: ETH-USDT,1547130415509278720. Id string The price of the order, note that this attribute may be 0 or -1 for market orders. Price number The number of orders placed, note that this attribute of a market order may be an amount and not a currency. Amount number The number of transactions, possibly padded with 0 if the exchange interface does not provide this data. DealAmount number Average transaction price, note that some exchanges do not provide this data. This attribute is set to 0 if it is not available and cannot be calculated. AvgPrice number Order status, refer to {@var/ORDER_STATE/ORDER_STATE_PENDING ORDER_STATE_PENDING}, {@var/ORDER_STATE/ORDER_STATE_CLOSED ORDER_STATE_CLOSED}, {@var/ORDER_STATE/ORDER_STATE_CANCELED ORDER_STATE_CANCELED}, {@var/ORDER_STATE/ORDER_STATE_UNKNOWN ORDER_STATE_UNKNOWN}. Status number Order type, refer to {@var/ORDER_TYPE/ORDER_TYPE_BUY ORDER_TYPE_BUY}, {@var/ORDER_TYPE/ORDER_TYPE_SELL ORDER_TYPE_SELL}. Type number For the opening and closing direction of contract orders, refer to {@var/ORDER_OFFSET/ORDER_OFFSET_OPEN ORDER_OFFSET_OPEN}, {@var/ORDER_OFFSET/ORDER_OFFSET_CLOSE ORDER_OFFSET_CLOSE}. Offset number This attribute in spot orders is "", i.e. the empty string. In a contract order, this attribute is the specific contract code. ContractType string

Order order structure can be returned by the exchange.GetOrder(), exchange.GetOrders() functions. GetOrders() function returns an array of Order structures or an empty array, or [[`], that is, an empty array if there are no current outstanding orders. Order order structure status attribute can be directly compared with ORDER_STATE_PENDING and other constants to determine whether they are equal and thus determine the status of the order.

{@fun/Trade/exchange.GetOrder exchange.GetOrder}, {@fun/Trade/exchange.GetOrders exchange.GetOrders}, {@fun/Trade/exchange.GetHistoryOrders exchange.GetHistoryOrders}

OrderBook

Order structure in market depth.

Price. Price number Amount. Amount number

GetDepth() function returns a data structure in which the attribute values of Bids, Asks are OrderBook arrays.

{@fun/Market/exchange.GetDepth exchange.GetDepth}, {@struct/Depth Depth}

Depth

Structure of the market depth.

The sell order array, i.e. OrderBook array, is sorted by price from lowest to highest, and the first OrderBook structure in the array has the lowest Price. Asks array The buy order array, i.e. OrderBook array, is sorted by price from highest to lowest, and the first OrderBook structure in the array has the highest Price. Bids array Millisecond-level timestamp. Time number

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

{@fun/Market/exchange.GetDepth exchange.GetDepth}, {@struct/OrderBook OrderBook}

Account

The structure of the account information.

The original data returned by the exchange interface, no such attribute is available for backtesting. Info object The number of available denominated currencies, in spot, if the trading pair is BTC_USDT, Balance refers to the number of currently available USDT. In the U-standard contract, Balance refers to the amount of available margin (USDT, quoteCurrency). Balance number The value of the frozen assets when the order is not filled. FrozenBalance number The number of available trading currencies, in spot, if the trading pair is BTC_USDT, Stocks refers to the number of currently available BTC. Stocks refers to the number of available margin (currency, baseCurrency) in a currency-based contract. Stocks number The value of the frozen assets when the order is not filled. FrozenStocks number Only futures exchange objects support this field. The Equity field is the total equity of the futures account margin under the current contract setting. If the exchange interface does not provide relevant data, this field is 0.

Equity number This field is only supported by futures exchange objects. The UPnL field is the sum of the unrealized profit and loss of all positions opened by the futures account margin under the current contract settings.

UPnL number

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

{@fun/Account/exchange.GetAccount exchange.GetAccount}

Asset

The structure of specific currency asset information.

Exchange-defined names for cryptocurrency assets, which may vary from exchange to exchange for the same cryptocurrency, e.g. BTC may be called XBT on some exchanges. Currency string Available balance of currency assets. Amount number The number of frozen assets in the currency. FrozenAmount number

The FrozenAmount of currency assets may include assets locked in for unfilled orders, and the margin portion locked in for futures positions.

{@fun/Account/exchange.GetAssets exchange.GetAssets}

Position

Structure of contract position information.

The original data returned by the exchange interface, no such attribute is available for backtesting. Info object The Symbol field is the trading product code defined by the FMZ platform, and its format is consistent with the Symbol field of the {@struct/Ticker Ticker} structure.

  • For spot exchange objects, the format of the Symbol field value is (for example): BTC_USDT, indicating the BTC_USDT spot trading pair.
  • For futures exchange objects, the format of the Symbol field value is (for example): BTC_USDT.swap, which represents the USDT-standard perpetual contract of BTC.

Symbol string Position bar size, filled by calculation if the exchange interface does not provide this data, it may be inaccurate. MarginLevel number Position size, which is usually a positive integer (number of contract numbers). Note that contract specifications such as contract multipliers, values, etc. may differ from one exchange to another. Amount number Position freeze amount, the number of temporarily frozen positions when the closed order is not filled. FrozenAmount number Average price of the position, which in principle is the average price of the position as a whole (does not participate in settlement). If the data is not provided by the exchange interface, it is filled with the average price of positions available on the exchange interface (participating in settlement). Price number The floating profit/loss of the position is in principle the unrealized profit/loss of the position, if the data is not provided by the exchange interface, it will be filled with other profit/loss data of the exchange interface. The unit of profit and loss value is the same as the unit of current contract margin. Profit number Position type, refer to {@var/POSITION_DIRECTION/PD_LONG PD_LONG}, {@var/POSITION_DIRECTION/PD_SHORT PD_SHORT}. Type number Contract code, see the description of the {@fun/Futures/exchange.SetContractType exchange.SetContractType} function for details. ContractType string The margin occupied by the position, filled with 0 if the exchange interface does not provide this data. Margin number

The exchange.GetPositions() function returns an array of Positions or an empty array. For cryptocurrency futures, it is important to note that the Position structure array returned by the exchange.GetPositions() function. For the FrozenAmount, Profit, and Margin attributes in the position data structure, as the data provided by the exchange is not uniform, the GetPositions() interface, the definition of the data returned by the exchange object may be different. For example, some exchanges have no position freeze data in the position data, so the FrozenAmount is 0. If you need to calculate certain data, you can use the original data in the Info attribute to calculate and analysis.

{@fun/Futures/exchange.GetPositions exchange.GetPositions}

Market

Structure of market information on traded varieties.

Taking values such as "btcusdt", the Symbol field records the original name of the traded variety on the exchange. Note that the format and definition of this attribute are different from the Symbol field of the {@struct/Ticker Ticker} structure. Symbol string Taking values such as "BTC", the BaseAsset field records the name of the traded currency (i.e.: baseCurrency), which is uniformly uppercase. BaseAsset string Taking values such as "USDT", the QuoteAsset field records the name of the denominated currency (i.e.: quoteCurrency), which is uniformly uppercase. QuoteAsset string Taking values such as 0.01, the TickSize field records the value of the smallest change in the price of the traded item on the exchange. TickSize number Taking values such as 0.01, the AmountSize field records the value of the minimum change in the volume of orders placed on the exchange for that trade. AmountSize number Taking values such as 2, the PricePrecision field records the precision of the price of the traded item on the exchange, indicating that the price is accurate to 2 decimals. PricePrecision number Taking values such as 3, the AmountPrecision field records the precision of the orders placed on the exchange for the traded variety, indicating that the orders are accurate to 3 decimals. AmountPrecision number Taking values such as 0.001, the MinQty field records the minimum order size on the exchange for that trade. MinQty number Taking values such as 1000, the MaxQty field records the maximum number of orders that can be placed on the exchange for that variety of trade. MaxQty number Taking values such as 5, the MinNotional field records the minimum amount of the order placed on the exchange for that variety of trade. MinNotional number Taking values such as 9999999, the MaxNotional field records the maximum amount of orders placed on the exchange for that variety of trade. MaxNotional number The field CtVal records the value of a contract of the trading product on the exchange, in the currency recorded in the CtValCcy field. For example: CtVal is 0.01, CtValCcy is "BTC", which means that a contract is worth 0.01 BTC. CtVal number The field CtValCcy records the value unit of a contract. The value unit of a contract may be: BTC, USD, ETH, etc. CtValCcy number The field Info records the raw data for the species returned by the exchange’s market information interface. Info object

The exchange.GetMarkets() function returns a dictionary containing this Market structure. Due to the different level of support for market information data by each exchange, fields that are not supported by the exchange will be ignored. The values of the above fields are taken from the raw data of the exchange interface, you can also check the content of the Info field.

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

Funding

The structure of the funding rate information of the trading product. Only cryptocurrency perpetual contracts support funding rates.

The raw data returned when the cryptocurrency futures exchange funding rate interface is called. Info object The Symbol field is the trading product code defined by the FMZ platform. Symbol string Funding rate interval, in milliseconds. 28800000 means 8 hours interval. Interval number The timestamp of the start time of the next funding rate period (the settlement time of this period), in milliseconds. Time number The funding rate that will be used for this period’s settlement. Rate number

The perpetual contract funding rates of different futures exchanges have different calculation methods and mechanisms, and the settlement cycles are 1 hour, 4 hours, 8 hours, and one day. The current funding rate of perpetual contracts on futures exchanges has a fixed value and a floating value calculated in real time. The Rate field is the funding rate value without %. If you want to convert it to a value with %, you can multiply it by 100 and add the % at the end.

{@fun/Futures/exchange.GetFundings exchange.GetFundings}

OtherStruct

HttpQuery-options

This JSON structure is used to configure the parameters of the HttpQuery function and the HttpQuery_Go function to send the Http request.

Request method, for example: GET, POST, etc. method string Request body. For example, in a POST request, the body can contain form data, JSON, text, etc. body string Character set encoding. For example, specify the encoding of text data in the body as: "UTF-8". charset string A cookie is a small piece of data used to store and exchange state information between a client (usually a browser) and a server. cookie string Used to simulate browser tls fingerprint. profile string When set to true, the HttpQuery function call returns the complete response message. When set to false, only the data in the response message Body is returned. debug bool Request header information exists in the form of key-value pairs (JSON structure) and is used to transmit various information, such as content type, authentication information, cache control, etc. headers JSON Timeout setting. Setting 1000 means a timeout of 1 second. timeout number

Example of use:

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

The http message sent when the above code is executed:

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

{@fun/Global/HttpQuery HttpQuery}, {@fun/Global/HttpQuery_Go HttpQuery_Go}

HttpQuery-return

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

http status code StatusCode number Request header information. Header JSON Cookies information. Cookies array The full path information of the request. Trace JSON Message length Length number Message content. Body string

An example of the returned JSON data structure is:

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

{@fun/Global/HttpQuery HttpQuery}, {@fun/Global/HttpQuery_Go HttpQuery_Go}

LogStatus-table

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

Used to set the type of UI and controls to be parsed and displayed. For the status bar table, it is fixedly set to: table. type string Used to set the title of the status bar table. title string Used to set the column titles of the status bar table. The first element of the array is the title of the first column, and so on. cols array Used to set the row data of the status bar table. The first element of the 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 (the elements in the array structure correspond to the table column names one by one), that is, the first row of data in the table. rows array

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

{@fun/Log/LogStatus LogStatus}

LogStatus-btnTypeOne

This JSON structure is used to configure the button control in the status bar. The button control JSON structure can be embedded in the status bar table JSON structure. This structure is an old version structure, and the platform is still compatible. It is recommended to use the latest version of the button JSON structure. Example of constructing a status bar button control (after the button is triggered and clicked, the pop-up box contains a single input control, which is constructed through the input field):

{
    "type": "button", 
    "cmd": "open", 
    "name": "opening a position", 
    "input": {
        "name": "number of opening positions", 
        "type": "number", 
        "defValue": 1
    }
}

The controls in the pop-up box triggered by clicking the status bar button control are set through input or group.

For button controls, the fixed setting is: button. type string Button type settings class string The text on the button control, that is, the button name. name string The interactive command content sent to the strategy when the button control triggers a click operation. cmd string The description of the button control. The description is displayed when the mouse is placed on the button in the status bar. description string Sets the button to disabled (true) / enabled (false). disabled bool When constructing a status bar button for interaction, data input is also supported. The interaction command is ultimately captured by the GetCommand() function. Add the input item to the JSON data structure of the button control in the status bar to configure the input control in the pop-up box displayed when the button is triggered. For example, to set the value of the input field:

{
    "name": "Number of opening positions", 
    "type": "number", 
    "defValue": 1,
    "description": "test",                  
}

Description of each field in the above JSON structure:

  • name The title of the control in the pop-up box that pops up after the status bar button triggers a click operation.
  • description Description of the control in the pop-up box that pops up after the status bar button triggers a click operation.
  • type The type of control in the pop-up box that pops up after the status bar button triggers a click operation. The possible values of the type field are as follows:
    1. "number": numeric input control.
    2. "string": string input control.
    3. "selected": drop-down box control.
    4. "boolean": switch control.
  • defValue The default value of the control in the pop-up box that pops up after the status bar button triggers a click operation. If it is a drop-down box type control (selected), the defValue field is used to set the drop-down box options. For example: "input": {"name": "Opening quantity", "type": "selected", "defValue": "A|B|C"}, the text description of the drop-down box options is set to A, B, C.

For the fields extended by the drop-down box type control:

  • options The drop-down box control in the page triggered by the status bar button control can use the options field to set options. The options in the options field not only support strings, but also support the use of {text: "description", value: "value"} structure. Use the defValue field to set the default option, which can be multiple selections.
  • multiple When this field is set to true, multiple selections in the drop-down box are supported.

input JSON The input field configures a control in the pop-up box that pops up after the status bar button is triggered by clicking. The difference between group and input is that it configures a group of controls. The elements in group have the same data structure as the input field value. Please refer to the relevant description of the input field.

group array

An example of the class value of the JSON structure of a button in the status bar:

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

Example of using the group field with the input field:

function main() {
    // The drop-down box control in the page triggered by the testBtn1 button uses the options field to set options and the defValue field to set the default options. This is different 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 (set input field implementation) testBtn2 button triggered by the page in the drop-down box control using the options field to set the options, options field in the options field not only supports the string,
      it also supports the use of ```{text: "description", value: "value"}``` structure. Use the defValue field to set the default option. The default option can be multiple selection (multiple selection is achieved through an array structure). Multiple selection requires setting the additional field multiple to true.
    */
    var testBtn2 = {
        type: "button", 
        name: "testBtn2",
        cmd: "cmdTestBtn2",
        input: {
            name: "testBtn2MultiComboBox", 
            type: "selected", 
            description: "Implementing multiple selection in drop-down box", 
            options: [{text: "Option A", value: "A"}, {text: "Option B", value: "B"}, {text: "Option C", value: "C"}],
            defValue: ["A", "C"],
            multiple: true
        }
    }
  
    // Status bar grouping button control (set group field implementation) testBtn3 button triggered by the page in the drop-down box control using the options field to set options, also supports the direct use of defValue set options.
    var testBtn3 = {
        type: "button",                     
        name: "testBtn3",
        cmd: "cmdTestBtn3", 
        group: [
            {name: "comboBox1", label: "labelComboBox1", description: "Drop-down box 1", type: "selected", defValue: 1, options: ["A", "B"]}, 
            {name: "comboBox2", label: "labelComboBox2", description: "Drop-down box 2", type: "selected", defValue: "A|B"}, 
            {name: "comboBox3", label: "labelComboBox3", description: "Drop-down box 3", type: "selected", defValue: [0, 2], multiple: true, options: ["A", "B", "C"]}, 
            {
                name: "comboBox4", 
                label: "labelComboBox4", 
                description: "Drop-down 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"}]
            }
        ]
    }
    while (true) {
        LogStatus("`" + JSON.stringify(testBtn1) + "`\n", "`" + JSON.stringify(testBtn2) + "`\n", "`" + JSON.stringify(testBtn3) + "`\n")
        var cmd = GetCommand()
        if (cmd) {
            Log(cmd)
        }
        Sleep(5000)
    }
}

{@fun/Log/LogStatus LogStatus}

LogStatus-btnTypeTwo

This JSON structure is used to configure the button control in the status bar. The button control JSON structure can be embedded in the status bar table JSON structure. The latest version of the button JSON structure. Example of constructing a status bar button control (after the button is triggered and clicked, the pop-up box contains multiple input controls, which are constructed through the group field):

{
    "type": "button",
    "cmd": "open",
    "name": "Open a position and place an order",
    "group": [{
        "type": "selected",
        "name": "tradeType",
        "label": "order type",
        "description": "market order, limit order",
        "default": 0,
        "group": "trading setup",
        "settings": {
            "options": ["market order", "limit order"],
            "required": true,
        }
    }, {
        "type": "selected",
        "name": "direction",
        "label": "trading direction",
        "description": "buy, sell",
        "default": "buy",
        "group": "trading setup",
        "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 setup",
        "filter": "tradeType==1",
        "settings": {
            "required": true,
        }
    }, {
        "type": "number",
        "name": "amount",
        "label": "order quantity",
        "description": "order quantity",
        "group": "trading setup",
        "settings": {
            "required": true,
        }
    }],
}

The controls in the pop-up box triggered by clicking the status bar button control are set through input or group.

For button controls, the fixed setting is: button. type string The text on the button control, that is, the button name. name string The interactive command content sent to the strategy when the button control triggers a click operation. cmd string When constructing a status bar button for interaction, data input is also supported. The interaction command is ultimately captured by the GetCommand() function. Add the input item to the JSON data structure of the button control in the status bar to configure the input control in the pop-up box displayed when the button is triggered. Compared with the old version of the input structure, the new version has some new fields and changes:

{
    "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 the following settings: "number"numeric input box, "string"string input box, "selected"drop-down 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 pop-up box that pops up after the status bar button is clicked. 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 indicate the field name of the control input content. For example, an excerpt of the group field is used as an illustration:

    var testBtn3 = {
        type: "button",                     
        name: "testBtn3",
        cmd: "cmdTestBtn3", 
        group: [
            {name: "comboBox1", label: "labelComboBox1", description: "Drop-down box 1", type: "selected", defValue: 1, options: ["A", "B"]}, 
            {name: "comboBox2", label: "labelComboBox2", description: "Drop-down box 2", type: "selected", defValue: "A|B"}, 
            {name: "comboBox3", label: "labelComboBox3", description: "Drop-down box 3", type: "selected", defValue: [0, 2], multiple: true, options: ["A", "B", "C"]}, 
            {
                name: "comboBox4", 
                label: "labelComboBox4", 
                description: "Drop-down 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 snippet, if the status bar button triggers an interaction, a pop-up box will pop up with 4 controls, all of which are drop-down box 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 value of name in the JSON structure is used as the field name of the returned interactive information, for example: comboBox1, comboBox2, etc.

  • label Used to set the title of the control.

  • description Description of the control. If the current JSON structure is an element in the field value (array structure) of the group field, and the label field is not set, description is the control title in the pop-up box that pops up after the status bar button is clicked.

  • default The default value of the control.

  • filter Selector, used to hide controls. Not setting this field means no filtering (displaying controls); when this field is set, no filtering (displaying controls) occurs when the expression is true. When the expression is false, filtering occurs (no displaying controls)

  • group Used to control the grouping of controls, which can be folded.

  • settings Component configuration, the control has a variety of UI options, use this option to make specific settings. For example:

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

    settings: settings.required: Whether it is required. settings.disabled: Whether to disable. settings.min: Valid when type=number, indicating the minimum value or minimum length of a string. settings.max: Valid when type=number, indicating the maximum value or the maximum length of a string. settings.step: Valid when type=number and render=slider, indicating the step length. settings.multiple: Valid when type=selected, indicating that multiple selections are supported. settings.customizable: It is valid when type=selected, indicating that customization is supported; users can directly edit and add new options in the drop-down box control. If the newly edited option is selected, the name of the option is used instead of the value represented by the option when the interaction is triggered. settings.options: Valid when type=selected, indicating the selector option data format: [“option 1”, “option 2”], [{‘name’:‘xxx’,‘value’:0}, {‘name’:‘xxx’,‘value’:1}]. settings.render: Rendering component type. When type=number, settings.render is not set (default number 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 drop-down box), optional: segment (segment selector). When type=boolean, there is currently only a default checkbox.

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

group array

Support bilingual settings:

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

{@fun/Log/LogStatus LogStatus}

Chart-options

This JSON is used to set the chart configuration information of the custom drawing function Chart(). The chart library used is Highcharts. Only a few basic configuration fields are listed here.

Platform extension field. Set to true to use Highstocks charts; set to false to use Highcharts charts.

__isStock string

{
    layout: 'single', // Not participating in grouping, displayed separately, default is group 'group'
    height: 300,      // Specify height
}

extension JSON Chart title title string X-axis configuration. xAxis JSON Y-axis configuration. yAxis JSON Chart data series. series JSON

A simple drawing example:

// This chart is an object in JavaScript language. Before using the Chart function, we need to declare an object variable chart to configure the chart.
var chart = {                                           
    // This field marks whether the chart is a general chart. If you are interested, you can change it to false and run it.
    __isStock: true,                                    
    // Zoom tool
    tooltip: {xDateFormat: '%Y-%m-%d %H:%M:%S, %A'},    
    // title
    title : { text : 'Price difference analysis chart'},                       
    // Select range
    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
    },
    // The horizontal axis of the coordinate axis is: x-axis, and the current setting type is: time
    xAxis: { type: 'datetime'},                         
    // The vertical axis of the coordinate axis is: the y-axis, the default value is adjusted according to the data size
    yAxis : {                                           
        // title
        title: {text: 'Price difference'},                           
        // Whether to enable the right vertical axis
        opposite: false                                 
    },
    // Data series, this property saves each data series (line, K-line chart, label, etc.)
    series : [                                          
        // The index is 0, and the data array stores the data of the index series.
        {name : "line1", id : "line 1,buy1Price", data : []},                          
        // The index is 1, dashStyle:'shortdash' is set, that is, a dashed line is set
        {name : "line2", id : "line 2,lastPrice", dashStyle : 'shortdash', data : []}  
    ]
}
function main(){
    // Call the Chart function to initialize the chart
    var ObjChart = Chart(chart)         
    // Clear
    ObjChart.reset()                      
    while(true){
        // Get the timestamp of this poll, which is a millisecond timestamp. Used to determine the position of the X-axis written to the chart
        var nowTime = new Date().getTime()
        // Get market data
        var ticker = _C(exchange.GetTicker)
        // Get the buy price from the return value of the market data
        var buy1Price = ticker.Buy    
        // Get the last transaction price. In order to prevent the two lines from overlapping, we add 1.
        var lastPrice = ticker.Last + 1
        // Use the timestamp as the X value and the buy price as the Y value to pass into the data sequence of index 0
        ObjChart.add(0, [nowTime, buy1Price])
        // Same as above
        ObjChart.add(1, [nowTime, lastPrice])
        Sleep(2000)
    }
}

{@fun/Log/Chart Chart}

KLineChart-options

This JSON is used to set the chart configuration information of the custom drawing function KLineChart. Only a few basic configuration fields are listed here.

Whether to draw on the main chart. overlay bool X-axis configuration. xAxis JSON Y-axis configuration. yAxis JSON Candlestick chart configuration. candle JSON

Please refer to Special article on drawing charts using KLineChart function.

{@fun/Log/KLineChart KLineChart}

SetData-data

The JSON is used to set the data to be loaded by the exchange.SetData() function. The JSON data is an array structure, in which each element is also an array, namely [time, data].

The timestamp of the data, marking the time of this data. time number data is a piece of data corresponding to a certain time in the data loaded by the exchange.SetData() function. When the strategy is running, the exchange.GetData() function gets the data with the corresponding timestamp according to the current time.

data string, number, bool, object, array, etc.

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

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

{@fun SetData}, {@fun GetData}

EventLoop-return

This JSON is the data structure returned by the EventLoop() function. The EventLoop() function monitors: 1. Any WebSocket readable data event; 2. Task completion events concurrent with the exchange.Go() and HttpQuery_Go() functions; 3. Message events sent in threads created by the __Thread() function in the JavaScript language strategy.

Event sequence number. Seq number Event name. Event string Event thread Id. ThreadId number Event index. Index number nano timestamp. Nano number

Use the exchange.Go() function to make concurrent requests and the event data structure returned by the EventLoop() function.

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

When a message is sent using __threadPostMessage() in a concurrently executed thread (created by the __Thread() function) in the JavaScript language strategy, the EventLoop() function in the thread receiving the message will monitor the following event data structure:

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

{@fun/Global/EventLoop EventLoop}

DBExec-return

This JSON is the data structure returned by the DBExec() function; it is also returned when executing an SQL statement using the exec() method of the object created by the Dial() function.

The column names of the data to be queried, a string array. columns array The specific data to be queried, where each piece of data corresponds to a column name. The value of the values field is a two-dimensional array, where each element is an array and a data record. values array

Example of querying data in the database:

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

{@fun/Global/DBExec DBExec}, {@fun/Global/Dial Dial}

__threadJoin-return

This JSON is the data structure returned by the __threadJoin() function, which saves some information about concurrent threads in the JavaScript language strategy.

Thread Id. id number Whether the thread is forced to end. terminated bool The running time of the thread in nanoseconds. elapsed number The return value of the thread function. ret number

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

function testFunc() {
    for (var i = 0 ; i < 5 ; i++) {
        Log(i)
        Sleep(300)
    }
}

function main() {
    var id = __Thread(testFunc)    
    
    Log(__threadJoin(id, 1000))
    Log(__threadJoin(id))
}

{@fun/Threads/__threadJoin __threadJoin}

Built-in functions Built-in variables