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

多品种跨期布林对冲策略

Author: yuzy, Date: 2022-11-27 14:50:42
Tags:


'''backtest
start: 2022-11-01 00:00:00
end: 2022-11-30 23:59:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_CTP","currency":"FUTURES"}]
'''

import json

class Trader:
    def __init__(self,q,e,symbolA,symbolB,N,P,OpAmount):
        self.q = q 
        self.e = e 
        self.symbolA = symbolA
        self.symbolB = symbolB
        self.N = N 
        self.P = P 
        self.OpAmount = OpAmount
        self.status = 0 
        self.isBusy = False
    def onTick(self):
        if (self.isBusy or not exchange.IO("status")) or not ext.IsTrading(self.symbolA) or not ext.IsTrading(self.symbolB):
            Sleep(1000)
            return
        _C(exchange.SetContractType,self.symbolA)
        recordsA = _C(exchange.GetRecords)
        _C(exchange.SetContractType,self.symbolB)
        recordsB = _C(exchange.GetRecords)
        if recordsA[-1]["Time"] != recordsB[-1]["Time"]:
            return
        minL = min(len(recordsA),len(recordsB))
        rA = recordsA.copy()
        rA.reverse()
        rB = recordsB.copy()
        rB.reverse()
        arrDiff = []
        for i in range(minL):
            arrDiff.append(rB[i]["Close"] - rA[i]["Close"])
        arrDiff.reverse()
        if len(arrDiff) < self.N:
            return
        boll = TA.BOLL(arrDiff, self.N, self.P)
        p = 0 
        if self.status == 0 :
            if arrDiff[-1] > boll[0][-1]:
                Log("开仓 A买B卖", ",A最新价格:", recordsA[-1]["Close"], ",B最新价格:", recordsB[-1]["Close"])
                p = 2 
            elif arrDiff[-1] < boll[2][-1] :
                Log("开仓 A卖B买", ",A最新价格:", recordsA[-1]["Close"], ",B最新价格:", recordsB[-1]["Close"])
                p = 1 
        elif self.status == 1 and arrDiff[-1] > boll[1][-1] :
            Log("平仓 A买B卖", ",A最新价格:", recordsA[-1]["Close"], ",B最新价格:", recordsB[-1]["Close"])
            p = 2 
        elif self.status == 2 and arrDiff[-1] < boll[1][-1] :
            Log("平仓 A卖B买", ",A最新价格:", recordsA[-1]["Close"], ",B最新价格:", recordsB[-1]["Close"])
            p = 1 
        if p == 0 :
            return
        self.isBusy = True 
        tasks = []
        if p == 1:
            tasks.append([self.symbolA,"sell" if self.status == 0 else "closebuy"])
            tasks.append([self.symbolB,"buy" if self.status == 0 else "closesell"])
        elif p == 2:
            tasks.append([self.symbolA,"buy" if self.status == 0 else "closesell"])
            tasks.append([self.symbolB,"sell" if self.status == 0 else "closebuy"])
        def callBack(task,ret):
            def callBack(task,ret):
                self.isBusy = False
                if task["action"] == "sell":
                    self.status = 2 
                elif task["action"] == "buy":
                    self.status = 1 
                else :
                    self.status = 0 
            self.q.pushTask(self.e,tasks[1][0],tasks[1][1],self.OpAmount,callBack)
            
        self.q.pushTask(self.e,tasks[0][0],tasks[0][1],self.OpAmount,callBack)


def main():
    SetErrorFilter("ready|login|timeout")
    Log("正在与交易服务器连接...")
    while not exchange.IO("status"):
        Sleep(1000)
    Log("与交易服务器连接成功")
    iniAccount = _C(exchange.GetAccount)
    Log(iniAccount)
    def callBack(task,ret):
        Log(task["desc"], "成功" if ret else "失败")
    q = ext.NewTaskQueue(callBack)
    t_arr = []
    list_1 = Instruments.split("|")
    for i in range(len(list_1)):
        symbols = list_1[i].split("&")
        symbolA = symbols[0]
        symbolB = symbols[1]
        t_arr.append(Trader(q,exchange,symbolA,symbolB,N,P,OpAmount))
    while True:
        q.poll()
        for t in t_arr:
            t.onTick()
        tab = {
                "type" : "table",
                "title" : "持仓信息",
                "cols" :["合约名称" , "持仓方向" , "持仓均价" , "持仓数量" , "持仓盈亏"],
                "rows" :[]
            }
        a = _C(exchange.GetPosition)
        for i in range(len(a)):
            tab["rows"].append([a[i]["ContractType"], "多" if a[i]["Type"]%2 == 0 else "空", a[i]["Price"], a[i]["Amount"], a[i]["Profit"]])
        LogStatus(_D(), "\n`" + json.dumps(tab) +"`")
        
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

更多内容