The resource loading... loading...

Cryptocurrency contracts are easy for robots to follow

Author: Inventors quantify - small dreams, Created: 2021-04-07 21:30:05, Updated: 2023-09-24 19:35:33

img

Cryptocurrency contracts are easy for robots to follow

In the previous article, we implemented a simple spot check-in robot, and today we implemented a contract-based easy check-in robot.

Design ideas

There is a big difference between the contract version of the ledger and the spot version. The spot version can be achieved mainly by monitoring the changes in the assets of the account. The futures version requires monitoring the changes in the holdings of the account. So the futures version is a bit more complicated because the futures have multiple holdings, empty holdings, different contracts. The details of this series need to be worked out. The core idea is to monitor the volatility of the holdings. It was originally designed to handle multiple heads and empty heads together, but this was found to be very complicated. The analysis problem was then decided to handle multiple heads and empty heads separately.

Implementation of the strategy

The policy parameters:

img

Support for retesting, which can be used directly to set retest observation by default.

The source code of the strategy:

/*backtest
start: 2021-03-18 00:00:00
end: 2021-04-07 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_OKCoin","currency":"BTC_USD"},{"eid":"Futures_OKCoin","currency":"BTC_USD"},{"eid":"Futures_OKCoin","currency":"BTC_USD"}]
*/

function test() {
    // 测试函数
    var ts = new Date().getTime()    
    if (ts % (1000 * 60 * 60 * 6) > 1000 * 60 * 60 * 5.5) {
        Sleep(1000 * 60 * 10)
        var nowPosAmount = getPosAmount(_C(exchange.GetPosition), refCt)
        var longPosAmount = nowPosAmount.long
        var shortPosAmount = nowPosAmount.short
        var x = Math.random()
        if (x > 0.7) {
            exchange.SetDirection("buy")
            exchange.Buy(-1, _N(Math.max(1, x * 10), 0), "参考账户测试开单#FF0000")
        } else if(x < 0.2) {
            exchange.SetDirection("sell")
            exchange.Sell(-1, _N(Math.max(1, x * 10), 0), "参考账户测试开单#FF0000")
        } else if(x >= 0.2 && x <= 0.5 && longPosAmount > 4) {
            exchange.SetDirection("closebuy")
            exchange.Sell(-1, longPosAmount, "参考账户测试平仓#FF0000")
        } else if(shortPosAmount > 4) {
            exchange.SetDirection("closesell")
            exchange.Buy(-1, _N(shortPosAmount / 2, 0), "参考账户测试平仓#FF0000")
        }
    }
}

function getPosAmount(pos, ct) {
    var longPosAmount = 0
    var shortPosAmount = 0
    _.each(pos, function(ele) {
        if (ele.ContractType == ct && ele.Type == PD_LONG) {
            longPosAmount = ele.Amount
        } else if (ele.ContractType == ct && ele.Type == PD_SHORT) {
            shortPosAmount = ele.Amount
        }
    })
    return {long: longPosAmount, short: shortPosAmount}
}

function trade(e, ct, type, delta) {
    var nowPosAmount = getPosAmount(_C(e.GetPosition), ct)
    var nowAmount = type == PD_LONG ? nowPosAmount.long : nowPosAmount.short
    if (delta > 0) {
        // 开仓
        var tradeFunc = type == PD_LONG ? e.Buy : e.Sell
        e.SetDirection(type == PD_LONG ? "buy" : "sell")
        tradeFunc(-1, delta)
    } else if (delta < 0) {
        // 平仓
        var tradeFunc = type == PD_LONG ? e.Sell : e.Buy
        e.SetDirection(type == PD_LONG ? "closebuy" : "closesell")
        if (nowAmount <= 0) {
            Log("未检测到持仓")
            return 
        }
        tradeFunc(-1, Math.min(nowAmount, Math.abs(delta)))
    } else {
        throw "错误"
    }
}

function main() {
    LogReset(1)
    if (exchanges.length < 2) {
        throw "没有跟单的交易所"
    }
    var exName = exchange.GetName()
    // 检测参考交易所
    if (!exName.includes("Futures_")) {
        throw "仅支持期货跟单"
    }
    Log("开始监控", exName, "交易所", "#FF0000")
    
    // 检测跟单交易所
    for (var i = 1 ; i < exchanges.length ; i++) {
        if (exchanges[i].GetName() != exName) {
            throw "跟单的期货交易所和参考交易所不同!"
        }
    }
    
    // 设置交易对、合约
    _.each(exchanges, function(e) {
        if (!IsVirtual()) {
            e.SetCurrency(refCurrency)
            if (isSimulate) {
                if (e.GetName() == "Futures_OKCoin") {
                    e.IO("simulate", true)
                }
            }
        }
        e.SetContractType(refCt)
    })

    var initRefPosAmount = getPosAmount(_C(exchange.GetPosition), refCt)
    while(true) {
        if (IsVirtual()) {    // 回测时才模拟
            test()            // 测试函数,模拟参考账户主动交易,触发跟单账户跟单        
        }
        Sleep(5000)
        var nowRefPosAmount = getPosAmount(_C(exchange.GetPosition), refCt)
        var tbl = {
            type : "table", 
            title : "持仓",
            cols : ["名称", "标签", "多仓", "空仓", "账户资产(Stocks)", "账户资产(Balance)"],
            rows : []
        }
        _.each(exchanges, function(e) {
            var pos = getPosAmount(_C(e.GetPosition), refCt)
            var acc = _C(e.GetAccount)
            tbl.rows.push([e.GetName(), e.GetLabel(), pos.long, pos.short, acc.Stocks, acc.Balance])
        })
        LogStatus(_D(), "\n`" + JSON.stringify(tbl) + "`")
        
        // 计算仓位变动量
        var longPosDelta = nowRefPosAmount.long - initRefPosAmount.long
        var shortPosDelta = nowRefPosAmount.short - initRefPosAmount.short

        // 检测变动
        if (longPosDelta == 0 && shortPosDelta == 0) {
            continue
        } else {
            // 检测到仓位变动
            for (var i = 1 ; i < exchanges.length ; i++) {
                // 执行多头动作
                if (longPosDelta != 0) {
                    Log(exchanges[i].GetName(), exchanges[i].GetLabel(), "执行多头跟单,变动量:", longPosDelta)
                    trade(exchanges[i], refCt, PD_LONG, longPosDelta)
                }
                // 执行空头动作
                if (shortPosDelta != 0) {
                    Log(exchanges[i].GetName(), exchanges[i].GetLabel(), "执行空头跟单,变动量:", shortPosDelta)
                    trade(exchanges[i], refCt, PD_SHORT, shortPosDelta)
                }
            }
        }

        // 执行跟单操作后,更新
        initRefPosAmount = nowRefPosAmount
    }
}

Testing

Given that OKEX updates V5 to the interface so that OKEX analog drives can be used, I used two OKEX analog drives API KEY for very convenient testing.

The first exchange object to be added is the reference exchange, and the next exchange follows the exchange account. On the OKEX analogue disc page, refer to the exchange account to manually move 3 ETH quarterly spot contracts.

img

You can see that the real disk detects changes in the holdings of the reference exchange account, and then follows the operation.

img

Let's try to even out the two contracts we just opened, and the holdings after the even out are as follows:

img

The real discs follow the operation and tie two contracts.

img

This strategy is designed in a simple and easy to understand way, without optimization, the perfect part also needs to handle details such as asset detection at the time of checkout, for the sake of simplicity, the market price list is used.

The policy address:https://www.fmz.com/strategy/270012

Welcome to the comments section.


Related

More

pw1013Two different exchanges can't match.

mingxi1005When will the inventors be able to pair the coins to win the futures contracts?

aklkcI hope there's a beta version of usdt.

lau99I would like to have a permanent contract version of Bitcoin usdt, the API of the executor?????

zhousoneI hope that there will be a permanent contract version of the token usdt.

qqlove23Thank you for sharing, it's worth learning.

Inventors quantify - small dreamsSince the contract specifications may vary from exchange to exchange, the code of the order may need to be adjusted according to the specific situation.

pw1013The bibox exchange I use, with 80 percent return on commissions, is perfectly supported by FMZ

pw1013If you want to make a change to the bibox futures I'm currently using, where do you need to change it if you want to link to someone else's okx exchange?

Inventors quantify - small dreamsIt is possible to do this by changing the code.

Inventors quantify - small dreamsWe have not yet received any contact from the exchange to evaluate this exchange.