The resource loading... loading...

Inventors quantify trading platform API upgrades: enhancing the strategic design experience

Author: Inventors quantify - small dreams, Created: 2024-06-28 09:08:29, Updated: 2024-07-24 12:00:40

[TOC]

img

The Foreword

The inventors of the Quantitative Trading Platform underwent a number of redesigns after nine years of technological iterations, although we as users may not have noticed. In the past two years, the platform has undergone a number of optimizations and upgrades in terms of user experience, including a comprehensive upgrade of the UI interface, a wealth of commonly used Quantitative Trading tools, and the addition of more retrieval data support.

In order to make the policy design easier, the trading logic clearer and the API interface easier to use for beginners, the platform upgraded the API interface used by the policy. These new features can be enabled with the latest version of the hosts. The platform remains fully compatible with the old interface calls. Information about the new features of the API interface has been updated in sync with the inventors' API documentation to quantify the trading platform:

The grammar manual:https://www.fmz.com/syntax-guideThe user manual:https://www.fmz.com/user-guide

So let's take a look through this article to see what interface upgrades are available and what changes are needed to make the old policies compatible with the current API.

1st, the new API interface

新增exchange.GetTickers函数

Such aggregated market interfaces are essential for designing multi-variety strategies, market-wide market monitoring strategies. This is to make strategies easier to develop and avoid duplication of the wheel. The inventors of the quantitative trading platform packaged such APIs for exchanges.

If the exchange does not have such an interface (individual exchange), callexchange.GetTickers()In the meantime, I'm going to try to get some answers.

The function has no parameters and returns real-time market data of all varieties in the market interface.

exchange.GetTickers()The function isexchange.GetTicker()The full variation of the requested version of the function (look carefully, the difference between the two function names is only a single plural) ‒

We tested the environment using OKX Live Simulation Disks:

function main() {
    exchange.IO("simulate", true)

    var tickers = exchange.GetTickers()
    if (!tickers) {
        throw "tickers error"
    }

    var tbl = {type: "table", title: "test tickers", cols: ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], rows: []}
    for (var i in tickers) {
        var ticker = tickers[i]
        tbl.rows.push([ticker.Symbol, ticker.High, ticker.Open, ticker.Low, ticker.Last, ticker.Buy, ticker.Sell, ticker.Time, ticker.Volume])
    }

    LogStatus("`" + JSON.stringify(tbl) +  "`")
    return tickers.length
}

img

新增exchange.CreateOrder函数

The Newexchange.CreateOrder()Functions are the focus of this upgrade.exchange.CreateOrder()The biggest function is to specify the order type, direction, etc. directly in the function's parameters. This eliminates the need to depend on the current settings of the system.

In multi-transaction scenario, the design complexity is greatly reduced in the concurrent scenario.exchange.CreateOrder()So the four parameters of the function aresymbolsidepriceamount

Testing the environment using the OKX futures simulation:

function main() {
    exchange.IO("simulate", true)

    var id1 = exchange.CreateOrder("ETH_USDT.swap", "buy", 3300, 1)
    var id2 = exchange.CreateOrder("BTC_USDC.swap", "closebuy", 70000, 1)
    var id3 = exchange.CreateOrder("LTC_USDT.swap", "sell", 110, 1)

    Log("id1:", id1, ", id2:", id2, ", id3:", id3)
}

img

So that's only three times.exchange.CreateOrder()Function calls result in three different types of futures orders, in different directions.

新增exchange.GetHistoryOrders函数

The Newexchange.GetHistoryOrders()The function is used to obtain historical trading orders of a certain variety, which also requires exchange interface support.

The interfaces implemented by exchanges vary greatly when it comes to querying historical orders:

  • Some support split-page queries, some do not.
  • Some deals are not available for all query window periods, i.e. orders that exceed N days.
  • Most exchanges support time-stamped queries, some do not.

For this type of interface to be packaged to the maximum degree of compatibility, it is necessary to consider whether it meets the needs and expectations of the policy in actual use.

For more details on the functions, see the syntax manual in the API documentation:

https://www.fmz.com/syntax-guide#fun_exchange.gethistoryorders

Testing in real-world environments using the Binance spot market:

function main() {
    var orders = exchange.GetHistoryOrders("ETH_USDT")

    // 写入图表
    var tbl = {type: "table", title: "test GetHistoryOrders", cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []}
    for (var order of orders) {
        tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType])
    }
    
    LogStatus("orders.length:", orders.length, "\n", "`" + JSON.stringify(tbl) +  "`")
}

img

新增exchange.GetPositions函数

The old version of the get hold data function wasexchange.GetPosition()The update adds a new access to hold function to better match the semantics of the function name:exchange.GetPositions()│ while still being compatible/upgrading the GetPosition function│

exchange.GetPositions()There are three ways to call a function:

  • Exchange.GetPositions is a free exchange. When no parameters are passed, hold data is requested according to the current transaction pair/contract code setting.
  • exchange.GetPositions ((ETH_USDT.swap button)) When specifying a specific variety (ETH_USDT.swap, as defined by the FMZ platform), hold data for a specific variety is requested.
  • Exchange.GetPositions is a free exchange. Request all holdings data for the current dimensions of the exchange's interfaces available.

Testing the environment using the OKX futures simulation:

function main() {
    exchange.IO("simulate", true)

    exchange.SetCurrency("BTC_USDT")
    exchange.SetContractType("swap")

    var p1 = exchange.GetPositions()
    var p2 = exchange.GetPositions("")

    var tbls = []
    for (var positions of [p1, p2]) {
        var tbl = {type: "table", title: "test GetPosition/GetPositions", cols: ["Symbol", "Amount", "Price", "FrozenAmount", "Type", "Profit", "Margin", "ContractType", "MarginLevel"], rows: []}
        for (var p of positions) {
            tbl.rows.push([p.Symbol, p.Amount, p.Price, p.FrozenAmount, p.Type, p.Profit, p.Margin, p.ContractType, p.MarginLevel])
        } 
        tbls.push(tbl)
    }

    LogStatus("`" + JSON.stringify(tbls) +  "`")
}

img

When transmittedexchange.GetPositions()The parameters of the function areETH_USDT.swapIn this case, you can get the holdings data of ETH's U-bit perpetual contracts.

img

When transmittedexchange.GetPositions()The parameters of the function are empty strings.""In this case, you can get the data on all the contracts in U.S.A.

2 API upgraded

升级exchange.GetTicker函数

Field functionsexchange.GetTicker()This upgrade is mainly due to the addition of symbol parameters. It allows the function to be detached from the current transaction pair, contract code directly according to the parameters specified by the variety information, request market data. It simplifies the code writing process.

ParameterssymbolFor exchange objectsexchangeIt is a spot/future with different formats:

  • The object of the spot exchange The format is:AAA_BBBThe AAA stands for base currency, the BBB stands for quote currency, and the names of the currencies are capitalized. For example: BTC_USDT spot currency pair.
  • Object of the futures exchange The format is:AAA_BBB.XXXAAA stands for base currency, BBB stands for quote currency, and XXX stands for contract code, such as perpetual contract swap. Currency names are capitalized and contract codes are lower case. For example: BTC_USDT.swap, BTC's U-bit perpetual contract.

Testing in real-world environments using the Binance futures:

var symbols = ["BTC_USDT.swap", "BTC_USDT.quarter", "BTC_USD.swap", "BTC_USD.next_quarter", "ETH_USDT.swap"]

function main() {
    exchange.SetCurrency("ETH_USD")
    exchange.SetContractType("swap")

    var arr = []
    var t = exchange.GetTicker()
    arr.push(t)

    for (var symbol of symbols) {
        var ticker = exchange.GetTicker(symbol)
        arr.push(ticker)
    }

    var tbl = {type: "table", title: "test GetTicker", cols: ["Symbol", "High", "Open", "Low", "Last", "Buy", "Sell", "Time", "Volume"], rows: []}
    for (var ticker of arr) {
        tbl.rows.push([ticker.Symbol, ticker.High, ticker.Open, ticker.Low, ticker.Last, ticker.Buy, ticker.Sell, ticker.Time, ticker.Volume])
    }

    LogStatus("`" + JSON.stringify(tbl) +  "`")
    return arr
}

img

The design of market data for a set of specified varieties is simplified.

升级exchange.GetDepth函数

The same as the GetTicker function.exchange.GetDepth()The function also adds symbol parameters. It is possible to specify the variety directly when requesting depth data.

Testing in real-world environments using the Binance futures:

function main() {
    exchange.SetCurrency("LTC_USD")
    exchange.SetContractType("swap")

    Log(exchange.GetDepth())
    Log(exchange.GetDepth("ETH_USDT.quarter"))
    Log(exchange.GetDepth("BTC_USD.swap"))
}

img

升级exchange.GetTrades函数

The same as the GetTicker function.exchange.GetTrades()The function also adds symbol parameters. It is possible to specify the variety directly when requesting market transaction data.

Testing in real-world environments using the Binance futures:

function main() {
    var arr = []
    var arrR = []
    var symbols = ["LTC_USDT.swap", "ETH_USDT.quarter", "BTC_USD.swap"]    

    for (var symbol of symbols) {
        var r = exchange.Go("GetTrades", symbol)
        arrR.push(r)
    }

    for (var r of arrR) {
        arr.push(r.wait())
    }
    
    var tbls = []
    for (var i = 0; i < arr.length; i++) {
        var trades = arr[i]
        var symbol = symbols[i]

        var tbl = {type: "table", title: symbol, cols: ["Time", "Amount", "Price", "Type", "Id"], rows: []}
        for (var trade of trades) {
            tbl.rows.push([trade.Time, trade.Amount, trade.Price, trade.Type, trade.Id])
        }

        tbls.push(tbl)
    }

    LogStatus("`" + JSON.stringify(tbls) +  "`")
}

img

This upgrade is also compatible with the pass.exchange.Go()The function simultaneously invokes the symbol parameter to specify the variety information when the platform API interface is passed.

升级exchange.GetRecords函数

The GetRecords function made a major adjustment this time, in addition to supporting the variety of K-line data that the symbol parameter directly specifies for the request. The original period parameter was retained to specify the period of the K-line, and a limit parameter was added to specify the desired length of the K-line for the period of the request. It is also compatible with the older version of the GetRecords function, which only calls the period parameter.

exchange.GetRecords()How to call the function:

  • exchange.GetRecords When no parameters are specified, the K-line data of the current transaction pair/contract code-corresponding variety is requested, and the K-line cycle is the default K-line cycle set at the time of the policy review interface or real-time.
  • exchange.GetRecords ((60 * 15) is the name of the When only the K-line cycle parameter is specified, the K-line data of the current transaction pair/contract code corresponding to the variety is requested.
  • exchange.GetRecords (((BTC_USDT.swap button))) is a free and open-source exchange. When specifying only the variety information, the K-line data for the specification of the variety is requested, and the K-line cycle is the default K-line cycle set at the time of the policy retrieval interface or the real disk.
  • exchange.GetRecords (( BTC_USDT.swap bar, 60 * 60)) Specify the species information, specify the specific K-line cycle requesting K-line data.
  • exchange.GetRecords (((BTC_USDT.swap, 60, 1000) is a free online exchange that allows users to exchange information on the exchange. Specify the species information, specify the specific K-line cycle, refer to the K-line length requested for the K-line data to be obtained on a regular basis. Note that a page split request (i.e. multiple calls to the exchange's K-line interface) is generated when the limit parameter exceeds the maximum length of the exchange's one request.

Testing in real-world environments using the Binance futures:

function main() {
    exchange.SetCurrency("ETH_USDT")
    exchange.SetContractType("swap")
    
    var r1 = exchange.GetRecords()
    var r2 = exchange.GetRecords(60 * 60)
    var r3 = exchange.GetRecords("BTC_USDT.swap")
    var r4 = exchange.GetRecords("BTC_USDT.swap", 60)
    var r5 = exchange.GetRecords("LTC_USDT.swap", 60, 3000)

    Log("r1相邻Bar时间差值:", r1[1].Time - r1[0].Time, "毫秒, Bar长度:", r1.length)
    Log("r2相邻Bar时间差值:", r2[1].Time - r2[0].Time, "毫秒, Bar长度:", r2.length)
    Log("r3相邻Bar时间差值:", r3[1].Time - r3[0].Time, "毫秒, Bar长度:", r3.length)
    Log("r4相邻Bar时间差值:", r4[1].Time - r4[0].Time, "毫秒, Bar长度:", r4.length)
    Log("r5相邻Bar时间差值:", r5[1].Time - r5[0].Time, "毫秒, Bar长度:", r5.length)
}

img

升级exchange.GetOrders函数

The GetOrders function has also been added.symbolParameters that can be used to directly specify a query for the currently uncompleted ordered varieties; also support query for all pending varieties; compatible with the original call mode.

exchange.GetOrders()The function can be called in the following ways:

  • exchange.GetOrders ((() Check for all outstanding orders with the current trading pair/contract code.
  • exchange.GetOrders ((BTC_USDT.swap button)) All unfinished orders for BTC's USDT local perpetual contract.
  • exchange.GetOrders (("") Inquire about all uncompleted orders in the current dimension segmentation of the exchange ("dimension segmentation according to the API of the exchange").

Testing the environment using the OKX futures simulation:

function main() {
    exchange.IO("simulate", true)

    exchange.SetCurrency("BTC_USDT")
    exchange.SetContractType("swap")

    // 写入图表
    var tbls = []
    for (var symbol of ["null", "ETH_USDT.swap", ""]) {
        var tbl = {type: "table", title: symbol, cols: ["Symbol", "Id", "Price", "Amount", "DealAmount", "AvgPrice", "Status", "Type", "Offset", "ContractType"], rows: []}

        var orders = null
        if (symbol == "null") {
            orders = exchange.GetOrders()
        } else {
            orders = exchange.GetOrders(symbol)
        }

        for (var order of orders) {
            tbl.rows.push([order.Symbol, order.Id, order.Price, order.Amount, order.DealAmount, order.AvgPrice, order.Status, order.Type, order.Offset, order.ContractType])
        }

        tbls.push(tbl)
    }
    
    LogStatus("`" + JSON.stringify(tbls) +  "`")
}

img

When not passing the parameter, the default request for the current BTC_USDT trading pair, all pending pending pending lists for swap perpetuity contracts.

img

Specify parametersETH_USDT.swapWhen the parameter is asked, all unfinished pending contracts in the ETH_USDT trading pair are requested.

img

Passing in a blank string""When requesting all USDT local contracts all unfinished pending lists.

升级exchange.GetPosition函数

It is still compatible with the old stored access function naming, and also adds symbol parameters to specify the variety of stored data that is specifically requested. Function use andexchange.GetPositions()I'm sure you'll agree.

升级exchange.IO函数

For theexchange.IO("api", ...)Function call mode, upgraded to support full direct-to-complete request address functionality for all exchange objects. For example, if you want to call the OKX interface:

// GET https://www.okx.com /api/v5/account/max-withdrawal ccy: BTC

Support for direct data entryhttps://www.okx.com, you don't need to switch the base address to call the IO function again.

Testing the environment using the OKX futures simulation:

function main() {
    exchange.IO("simulate", true)

    return exchange.IO("api", "GET", "https://www.okx.com/api/v5/account/max-withdrawal", "ccy=BTC")
}

img

3 The impact of the API

影响exchange.GetOrder函数

This upgrade has had a major impact.exchange.GetOrder(id)Parameters of the functionidThe id parameter was changed from the original exchange order id to a string format containing the transaction variety. All packaged orders on the FMZ platform are in this format.

For example:

  • The exchange's original order ID is defined in the exchange order as:123456Before this upgrade, if you were to call the GetOrder function, the order ID that was passed was123456
  • The product code of the name of the exchange defined in the exchange order:BTC-USDTI'm not sure. Note that this refers to the exchange-named transaction variety codes, not the FMZ platform-defined pairs.

I'm not sure if this is a good idea, but I'm not sure.exchange.GetOrder(id)The format of the parameter id that the function needs to pass is adjusted to:BTC-USDT,123456

I'll start by explaining why this design was chosen: Because the CreateOrder function has been upgraded to specify the variety of the order directly (the variety of the order and the current set of transaction pairs, the contract code may be different), if the returned order ID does not contain the variety information, then the order ID will not be used. Because it is not known what the order is for at the time of the specific order, most exchange orders and withdrawals require the specification of parameters describing the variety code.

How to combine this influence: If the order is placed using the exchange.IO function, which calls the exchange's order interface directly to place the order, the return value usually contains the exchange's original symbol (variety code) and the original order id. Similarly, if the order is placed using the FMZ platform wrapped in the order sub-interface, since the order ID is the transaction variety code at the beginning, it is enough to remove the variety code and commas if the original ID of the order is needed.

影响exchange.CancelOrder函数

This upgrade is forexchange.CancelOrder()The effect of functionsexchange.GetOrder()The function is the same.

影响exchange.Buy函数

This upgrade is forexchange.Buy()The effect of functionsexchange.GetOrder()The function is the same.exchange.Buy()The function returns an order Id for a new structure, such as the Id returned when the OKX futures exchange placed an order:LTC-USDT-SWAP,1578360858053058560

影响exchange.Sell函数

This upgrade is forexchange.Sell()The effect of functionsexchange.GetOrder()The function is the same.exchange.Sell()The function returns an order Id for a new structure, such as the Id returned when the OKX futures exchange placed an order:ETH-USDT-SWAP,1578360832820125696

4 Structural adjustments

Ticker structure

This update adds a Symbol field to the ticker construct, which records market information for the current ticker structure. The field format isexchange.GetTicker()The symbol parameter format of the function is perfectly consistent.

Order structure

This update to the Order constructor adds a Symbol field, which is formatted with the symbol of the field.exchange.GetTicker()The symbol parameter format of the function is perfectly consistent. The update also changes the Id field of the Order construct to record variety information, original order information, and references in the new Order Id format.exchange.GetOrder()An explanation of the order Id in the function, which is no longer discussed here.

Positioned Structure

This update to the Position constructor adds the Symbol field, which is formatted with theexchange.GetTicker()The symbol parameter format of the function is perfectly consistent.

5, the retesting system

This upgrade is designed to meet the needs of users by first making the disk compatible, and the retesting system will complete the adaptation within a week. If individual policy code is affected, please change the adaptation as described in this article.

Additional updates

1, Account Structure New fields added Equity, UPnL

Member functions for futures exchange objectsGetAccountReturnedAccountThe structure has been extended to fields.

  • Equity Currently, the total equity of the collateralized assets, with the exception of very specific futures exchanges, mostly supports this field. It is mainly used to calculate real-time account collateral gains and losses.

  • UPnL Unrealized gains and losses on all positions currently held in the underlying asset class, with the exception of very specific futures exchanges that do not support the field.

2, SetMarginLevel function upgraded symbols supported

The member function SetMarginLevel for futures exchange objects has been upgraded with the addition of the parameter symbol.

Test example:

function main() {
    exchange.SetCurrency("ETH_USDT")
    exchange.SetContractType("swap")
    
    // 当前交易对为ETH_USDT,合约代码为swap,设置杠杆值为10
    exchange.SetMarginLevel(10)
    
    // 直接指定交易对BTC_USDT,合约代码swap,设置杠杆值20
    exchange.SetMarginLevel("BTC_USDT.swap", 20)
}

More

Wa-emmnn_I said what happened to my new robot, the return ID also has a transaction pair name, I studied it for a long time, and the log information of the post-order box is not showing now, also because of the administrator update?

I'm not going to lie./upload/asset/2ffc0f961149326b78aed.png This page is about the website. Is this problem caused by this interface update?

ecnemuse 希望exchange.Buy函数能增加开止损单的功能。。

NanSegFront row outline

Wa-emmnn_Good for you

Inventors quantify - small dreamsWell, check it out here. Thank you for asking. We'll deal with it as soon as possible.

Wa-emmnn_Yes, extMsg1, extMsg2 is not showing.

Inventors quantify - small dreamsHello, Order ID is a necessary change, because the upgrade to directly specify the variety order, the order ID must contain the variety information, otherwise it is impossible to determine which variety of the order is, and can not be called at the time of withdrawal ((because most exchanges require to specify the variety when withdrawing, and specify the ID)). The message you said after the order is not displayed, which means: exchange.Buy ((price, amount, extMsg1, extMsg2) when called, extMsg1, extMsg2 is not displayed in the log?

Inventors quantify - small dreamsHello, you are sending the current exchange settings, trading pairs, contract code settings.

Inventors quantifiedPlease send the details of the test code and configuration to the form and the engineer will get back to you at the earliest.

Inventors quantify - small dreamsThe exchange's terms and conditions vary widely, and the level of support varies, so we'll see if that's possible.

Inventors quantify - small dreamsThank you for your support, and if you have any problems, please send us a form or a message.