Kontrak Cryptocurrency Simple Order-Supervising Bot

Penulis:Ninabadass, Dibuat: 2022-04-11 10:47:42, Diperbarui: 2022-04-11 10:53:37

Kontrak Cryptocurrency Simple Order-Supervising Bot

Dalam artikel sebelumnya, kita menerapkan spot order supervising bot sederhana, dan hari ini kita akan menerapkan versi kontrak dari order supervising bot sederhana.

Ide Desain

Ada perbedaan besar antara bot pengawas order dari versi kontrak dan versi spot. pengawasan order spot terutama dapat direalisasikan dengan memantau perubahan aset akun. versi futures perlu memantau perubahan posisi di akun. Oleh karena itu, situasi versi berjangka lebih rumit, karena ada kontrak yang berbeda untuk posisi panjang dan pendek berjangka, yang perlu ditangani dengan serangkaian detail. Ide inti adalah untuk memantau perubahan posisi, dan untuk memicu tindakan pengawasan pesanan berdasarkan perubahan posisi. Awalnya dirancang untuk menangani posisi panjang dan pendek bersama-sama, tetapi kami menemukan akan rumit untuk menangani itu. Setelah menganalisis masalah, diputuskan untuk menangani posisi panjang dan pendek secara terpisah.

Pelaksanaan Strategi

Parameter Strategi:

img

Ini mendukung backtest, dan dapat langsung menggunakan pengaturan default untuk backtest untuk pengamatan.

Kode sumber:

/*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() {
    // test function 
    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), "the reference account tests ordering#FF0000")
        } else if(x < 0.2) {
            exchange.SetDirection("sell")
            exchange.Sell(-1, _N(Math.max(1, x * 10), 0), "the reference account tests ordering#FF0000")
        } else if(x >= 0.2 && x <= 0.5 && longPosAmount > 4) {
            exchange.SetDirection("closebuy")
            exchange.Sell(-1, longPosAmount, "the reference account tests closing positions#FF0000")
        } else if(shortPosAmount > 4) {
            exchange.SetDirection("closesell")
            exchange.Buy(-1, _N(shortPosAmount / 2, 0), "he reference account tests closing position#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) {
        // open position
        var tradeFunc = type == PD_LONG ? e.Buy : e.Sell
        e.SetDirection(type == PD_LONG ? "buy" : "sell")
        tradeFunc(-1, delta)
    } else if (delta < 0) {
        // close position 
        var tradeFunc = type == PD_LONG ? e.Sell : e.Buy
        e.SetDirection(type == PD_LONG ? "closebuy" : "closesell")
        if (nowAmount <= 0) {
            Log("no position detected")
            return 
        }
        tradeFunc(-1, Math.min(nowAmount, Math.abs(delta)))
    } else {
        throw "error"
    }
}

function main() {
    LogReset(1)
    if (exchanges.length < 2) {
        throw "no platform with order supervision"
    }
    var exName = exchange.GetName()
    // detect the platform for reference 
    if (!exName.includes("Futures_")) {
        throw "only support futures order supervising"
    }
    Log("start monitoring", exName, "platform", "#FF0000")
    
    // detect the order supervising platform 
    for (var i = 1 ; i < exchanges.length ; i++) {
        if (exchanges[i].GetName() != exName) {
            throw "The order supervising platform is different from the reference platform!"
        }
    }
    
    // set trading pair and contract 
    _.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()) {    // only simulate during backtest 
            test()            // test function, which simulates a reference account to trade automatically, to trigger the order supervising of the account        
        }
        Sleep(5000)
        var nowRefPosAmount = getPosAmount(_C(exchange.GetPosition), refCt)
        var tbl = {
            type : "table", 
            title : "position",
            cols : ["name", "label", "long", "short", "account asset (Stocks)", "account assest (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) + "`")
        
        // calculate the position amount of change 
        var longPosDelta = nowRefPosAmount.long - initRefPosAmount.long
        var shortPosDelta = nowRefPosAmount.short - initRefPosAmount.short

        // detect the change 
        if (longPosDelta == 0 && shortPosDelta == 0) {
            continue
        } else {
            // detect the position change 
            for (var i = 1 ; i < exchanges.length ; i++) {
                // execute the action of long
                if (longPosDelta != 0) {
                    Log(exchanges[i].GetName(), exchanges[i].GetLabel(), "Execute long order supervising, amount of change:", longPosDelta)
                    trade(exchanges[i], refCt, PD_LONG, longPosDelta)
                }
                // execute the action of short
                if (shortPosDelta != 0) {
                    Log(exchanges[i].GetName(), exchanges[i].GetLabel(), "Execute short order supervising, amount of change:", shortPosDelta)
                    trade(exchanges[i], refCt, PD_SHORT, shortPosDelta)
                }
            }
        }

        // after the operation of order supervising, update
        initRefPosAmount = nowRefPosAmount
    }
}

Tes

Mengingat fakta bahwa setelah OKEX memperbarui antarmuka V5, dan OKEX simulasi bot dapat digunakan, saya menggunakan API KAYs dari dua OKEX simulasi bot untuk menguji, sangat nyaman.

Objek pertukaran pertama yang akan ditambahkan adalah platform referensi, dan platform pengawasan pesanan mengikuti akun platform referensi untuk beroperasi. Pada halaman bot simulasi OKEX, akun platform referensi secara manual menempatkan 3 kontrak crypto-margin triwulanan ETH.

img

Bisa dilihat bahwa bot mendeteksi perubahan posisi, dan operasi berikut.

img

Mari kita coba untuk menutup 2 posisi kontrak yang baru saja kita buka. posisi setelah menutup posisi ditunjukkan pada gambar:

img

Robot mengikuti untuk mengoperasikan dan ditutup 2 kontrak.

img

Strategi ini dirancang dengan cara yang sederhana dan mudah dimengerti tanpa optimasi. Bagian yang ditingkatkan juga perlu menangani detail seperti deteksi aset saat mengawasi pesanan. Untuk menyederhanakan desain, pesanan pasar digunakan untuk mengawasi pesanan. Strategi hanya memberikan ide pembelajaran, dan bot dapat dioptimalkan sesuai dengan kebutuhan Anda.

Alamat strategi:https://www.fmz.com/strategy/270012

Selamat tinggal komentar Anda.


Lebih banyak