Sumber dimuat naik... memuat...

Jika anda mempunyai simpanan di arah yang sama, bagaimana anda boleh mengubah prosedur penerimaan isyarat jika anda tidak lagi membuat pesanan?

Penulis:Jetter, Dicipta: 2023-01-26 20:31:05, Dikemas kini:

/*Backtest Permulaan: 2022-01-15 00:00:00 Akhir: 2023-01-21 00:00:00 tempoh: 1 jam asasPeriode: 15m Bursa: [{eid:Futures_Binance,currency:ETH_USDT}] */

Struktur isyarat var Template = { Flag: 45M103Buy , // logo, boleh ditentukan Exchange: 1, // Tentukan pasangan dagangan pertukaran Mata wang: ETH_USDT, // Pasangan urus niaga ContractType: swap, // jenis kontrak, swap, quarter, next_quarter, spot pengisian segera Price: -1, // harga pembukaan atau penempatan, -1 sebagai harga pasaran Action: long, // Jenis urus niaga [ beli: beli dengan segera, jual: jual dengan segera, long: berjangka banyak, short: berjangka kosong, closesell: berjangka beli dengan kosong, closebuy: berjangka jual dengan murah ] Amount: 0, // jumlah urus niaga {C:$0000FF}

var BaseUrl = https://www.fmz.com/api/v1Alamat antara muka yang diperluaskan FMZ var RobotId = _G() // ID cakera semasa var Success = #5cb85c // warna berjaya var Danger = #ff0000 // warna berbahaya var Warning = #f0ad4e // Warning warna var buffSignal = []

// Format mesej isyarat pemeriksaan Diff functionObject ((object1, object2) { const keys1 = Object.keys ((object1) const keys2 = Object.keys ((object2)) if (keys1.length!== keys2.length) { return false {C:$0000FF} for (let i = 0; i < keys1.length; i++) { if (keys1[i]!== keys2[i]) { return false {C:$0000FF} {C:$0000FF} return true {C:$0000FF}

Fungsi CheckSignal ((Signal) { Signal.Price = parseFloat ((Signal.Price) Signal.Amount = parseFloat ((Signal.Amount) jika (Signal.ExchangeNombor adalah bulat.Signal.Exchange{) { Log (minimal pertukaran kerucut adalah 1 dan untuk nombor bulat kerucut, bahaya) return {C:$0000FF} if (Signal.Amount <= 0 の の typeof ((Signal.Amount)!= number ) { Log (tidak boleh kurang daripada 0 dan mempunyai jenis angka log, typeof (Signal.Amount, Danger) return {C:$0000FF} if (typeof ((Signal.Price)!= number) { Log (Harga aluminium mestilah bernilai aluminium, Danger) return {C:$0000FF} if (Signal.ContractType == spot && Signal.Action!= buy && Signal.Action!= sell) { Log (Log () adalah arahan untuk mengoperasikan barang sedia ada, Action error, Action: log, Signal.Action, Danger) return {C:$0000FF} if (Signal.ContractType!= spot && Signal.Action!= long && Signal.Action!= short && Signal.Action!= closesell && Signal.Action!= closebuy) { Log (Log () arahan untuk mengendalikan niaga hadapan, Kesalahan Tindakan, Tindakan: Lampu, Isyarat.Tindakan, Bahaya) return {C:$0000FF} return true {C:$0000FF}

perintah fungsiRobot ((url, aksesKey, rahsiaKey, robotId, cmd) { - Tidak.https://www.fmz.com/api/v1?access_key=xxx&secret_key=xxx&method=CommandRobot&args=[xxx+,""] url = url + ?access_key= + accessKey + &secret_key= + secretKey + &method=CommandRobot&args=[ + robotId + +,""] var postData = { method: POST data:cmd {C:$0000FF} var headers = User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 \nContent-Type: application/json var ret = HttpQuery ((url, postData, kursor, tajuk) Log (( meniru permintaan webhook TradingView, menghantar permintaan POST untuk ujian:??, url, body:??, cmd, reply:??, ret) {C:$0000FF}

fungsi createManager() { var sendiri = {} self.tasks = []

self.process = function() {
    var processed = 0
    if (self.tasks.length > 0) {
        _.each(self.tasks, function(task) {
            if (!task.finished) {
                processed++
                self.pollTask(task)
            }
        })
        if (processed == 0) {
            self.tasks = []
        }
    }
}

self.newTask = function(signal) {
    // {"Flag":"45M103Buy","Exchange":1,"Currency":"BTC_USDT","ContractType":"swap","Price":"10000","Action":"buy","Amount":"0"}
    var task = {}
    task.Flag = signal["Flag"]
    task.Exchange = signal["Exchange"]
    task.Currency = signal["Currency"]
    task.ContractType = signal["ContractType"]
    task.Price = signal["Price"]
    task.Action = signal["Action"]
    task.Amount = signal["Amount"]
    task.exchangeIdx = signal["Exchange"] - 1
    task.pricePrecision = null
    task.amountPrecision = null 
    task.error = null 
    task.exchangeLabel = exchanges[task.exchangeIdx].GetLabel()
    task.finished = false 
    
    Log("创建任务:", task)
    self.tasks.push(task)
}

self.getPrecision = function(n) {
    var precision = null 
    var arr = n.toString().split(".")
    if (arr.length == 1) {
        precision = 0
    } else if (arr.length == 2) {
        precision = arr[1].length
    } 
    return precision
}

self.pollTask = function(task) {
    var e = exchanges[task.exchangeIdx]
    var name = e.GetName()
    var isFutures = true
    e.SetCurrency(task.Currency)
    if (task.ContractType != "spot" && name.indexOf("Futures_") != -1) {
        // 非现货,则设置合约
        e.SetContractType(task.ContractType)
    } else if (task.ContractType == "spot" && name.indexOf("Futures_") == -1) {
        isFutures = false 
    } else {
        task.error = "指令中的ContractType与配置的交易所对象类型不匹配"
        return 
    }
    
    var depth = e.GetDepth()
    if (!depth || !depth.Bids || !depth.Asks) {
        task.error = "订单薄数据异常"
        return 
    }
    
    if (depth.Bids.length == 0 && depth.Asks.length == 0) {
        task.error = "盘口无订单"
        return 
    }
    
    _.each([depth.Bids, depth.Asks], function(arr) {
        _.each(arr, function(order) {
            var pricePrecision = self.getPrecision(order.Price)
            var amountPrecision = self.getPrecision(order.Amount)
            if (Number.isInteger(pricePrecision) && !Number.isInteger(self.pricePrecision)) {
                self.pricePrecision = pricePrecision
            } else if (Number.isInteger(self.pricePrecision) && Number.isInteger(pricePrecision) && pricePrecision > self.pricePrecision) {
                self.pricePrecision = pricePrecision
            }
            if (Number.isInteger(amountPrecision) && !Number.isInteger(self.amountPrecision)) {
                self.amountPrecision = amountPrecision
            } else if (Number.isInteger(self.amountPrecision) && Number.isInteger(amountPrecision) && amountPrecision > self.amountPrecision) {
                self.amountPrecision = amountPrecision
            }
        })
    })

    if (!Number.isInteger(self.pricePrecision) || !Number.isInteger(self.amountPrecision)) {
        task.err = "获取精度失败"
        return 
    }
    
    e.SetPrecision(self.pricePrecision, self.amountPrecision)
    
    // buy:现货买入 , sell:现货卖出 , long:期货做多 , short:期货做空 , closesell:期货买入平空 , closebuy:期货卖出平多
    var direction = null 
    var tradeFunc = null 
    if (isFutures) {
        switch (task.Action) {
            case "long": 
                direction = "buy"
                tradeFunc = e.Buy 
                break
            case "short": 
                direction = "sell"
                tradeFunc = e.Sell
                break
            case "closesell": 
                direction = "closesell"
                tradeFunc = e.Buy 
                break
            case "closebuy": 
                direction = "closebuy"
                tradeFunc = e.Sell
                break
        }
        if (!direction || !tradeFunc) {
            task.error = "交易方向错误:" + task.Action
            return 
        }
        e.SetDirection(direction)
    } else {
        if (task.Action == "buy") {
            tradeFunc = e.Buy 
        } else if (task.Action == "sell") {
            tradeFunc = e.Sell 
        } else {
            task.error = "交易方向错误:" + task.Action
            return 
        }
    }
    var id = tradeFunc(task.Price, task.Amount)
    if (!id) {
        task.error = "下单失败"
    }
    
    task.finished = true
}

return self

}

var manager = createManager (dalam bahasa Inggeris) function HandleCommand ((signal) { // Mengesan sama ada arahan interaksi diterima jika (isyarat) { Log (( menerima arahan interaksi:, signal) // Menerima arahan interaksi, cetak arahan interaksi } else { return // tidak menerima, tidak memproses {C:$0000FF}

// 检测交互指令是否是测试指令,测试指令可以由当前策略交互控件发出来进行测试
if (signal.indexOf("TestSignal") != -1) {
    signal = signal.replace("TestSignal:", "")
    // 调用FMZ扩展API接口,模拟Trading View的webhook,交互按钮TestSignal发送的消息:{"Flag":"45M103Buy","Exchange":1,"Currency":"BTC_USDT","ContractType":"swap","Price":"10000","Action":"buy","Amount":"0"}
    commandRobot(BaseUrl, FMZ_AccessKey, FMZ_SecretKey, RobotId, signal)
} else if (signal.indexOf("evalCode") != -1) {
    var js = signal.split(':', 2)[1]
    Log("执行调试代码:", js)
    eval(js)
} else {
    // 处理信号指令
    objSignal = JSON.parse(signal)
    if (DiffObject(Template, objSignal)) {
        Log("接收到交易信号指令:", objSignal)
        buffSignal.push(objSignal)
        
        // 检查交易量、交易所编号
        if (!CheckSignal(objSignal)) {
            return
        }
        
        // 创建任务
        manager.newTask(objSignal)
    } else {
        Log("指令无法识别", signal)
    }
}

}

fungsi utama (() { Log (( WebHook Alamat: ,https://www.fmz.com/api/v1?access_key= + FMZ_AccessKey + &secret_key= + FMZ_SecretKey + &method=CommandRobot&args=[ + RobotId + ,+""], Danger) Log ((jenis urus niaga: [ beli: beli dengan segera, sell: jual dengan segera, long: berjangka lebih, short: berjangka kosong, closesell: berjangka membeli dengan kosong, closebuy: berjangka menjual dengan lebih murah ]??, Danger Log (Templat arahan: log, JSON.stringify (Templat), Danger)

while (true) {
    try {
        // 处理交互
        HandleCommand(GetCommand())
        
        // 处理任务
        manager.process()
        
        if (buffSignal.length > maxBuffSignalRowDisplay) {
            buffSignal.shift()
        }
        var buffSignalTbl = {
            "type" : "table",
            "title" : "信号记录",
            "cols" : ["Flag", "Exchange", "Currency", "ContractType", "Price", "Action", "Amount"],
            "rows" : []
        }
        for (var i = buffSignal.length - 1 ; i >= 0 ; i--) {
            buffSignalTbl.rows.push([buffSignal[i].Flag, buffSignal[i].Exchange, buffSignal[i].Currency, buffSignal[i].ContractType, buffSignal[i].Price, buffSignal[i].Action, buffSignal[i].Amount])
        }
        LogStatus(_D(), "\n", "`" + JSON.stringify(buffSignalTbl) + "`")
        Sleep(1000 *SleePinterval )
    } catch (error) {
        Log("e.name:", error.name, "e.stack:", error.stack, "e.message:", error.message)
        Sleep(1000 * 5)
    }
}

}


Lebih lanjut

Bantuan (klik gambar untuk menghubungi)exchange.GetPosition ((), mendapatkan maklumat pegangan semasa. Jika pegangan lebih besar daripada 0, tidak dipesan.

Pencipta Kuantiti - Impian KecilRancangan strategi ini hanya boleh ditulis mengikut keperluan anda sendiri, anda boleh mencari strategi untuk rujukan di Platform Strategi Square.

JetterBagus. Terima kasih! Adakah ini kodnya? var nowRefPosAmount = getPosAmount ((_C)) var x = owRefPosAmount.long var y = owRefPosAmount.short Saya mahu CT itu.

JetterBagus. Terima kasih!