Loading ...

均线趋势策略

Author: jcinedc, Date: 2021-10-01 23:45:50
Tags:

  • 判断均线与行情位置关系,确认突破后做多,跌破后做空,到压制或支撑点位做空或做多;
  • 下单后根据轮询间隔和加仓次数决定加仓;回测k线数量越大越准确,默认600根;
  • 止损为确认六根k线突破或跌破后一段波动内实行;
  • 其中杠杆倍数尽量调低,仓位默认为百分之百;
  • 基于均线设定为1000周期,所以无法进行回测。

'''backtest
start: 2021-09-15 00:00:00
end: 2021-09-30 00:00:00
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
'''

import json
import time
line = []
def grid(now_price):
    global line
    line = [now_price+interval*i for i in range(-5,6)]

def main():
    exchange.SetContractType("swap")
    exchange.SetMarginLevel(multiple)
    account = _C(exchange.GetAccount)
    median = 0
    sign = []
    wave = []
    scale = []
    initial = account["Balance"]
    secondary = account["Balance"]
    net_worth = 0
    while True:
        start = time.clock()
        ticker = _C(exchange.GetTicker)
        account = _C(exchange.GetAccount)
        position = exchange.GetPosition()
        r = _C(exchange.GetRecords,PERIOD_H1)
        ma = TA.MA(r, average)
        copies = _N((secondary*multiple)*accuracy/(cishu+1),3)
        tab1 = {
            "type": "table", 
            "title": "账户信息", 
            "cols": ["初始资金", "当前资金", "可用担保资金", "总收益", "循环延时"], 
            "rows": []
        }
        tab2 = {
            "type": "table", 
            "title": "交易信息", 
            "cols": ["币种", "方向", "数量", "持仓均价", "持仓价值", "现价", "未实现盈亏", "补仓次数"], 
            "rows": []
        } 

        if len(position) == 0:
            a=0
            b=0
            c=0
            e="None"
            f=0
            g=0
            h=0
            ii=_N(account["Balance"],2)
            k=_N((account["Balance"]+account["FrozenBalance"])-initial,2)
            LogProfit((account["Balance"]+account["FrozenBalance"])-initial,'&')
        elif len(position) > 0:
            a=_N(position[0]["Price"],2)
            b=_N(position[0]["Profit"],2)
            c=len(scale)
            d=position[0]["Type"]
            f=_N(account["Balance"],2)
            g=position[0]["Amount"]
            h=_N(position[0]["Amount"]*ticker['Last'],2)
            ii=_N(net_worth+position[0]["Profit"],2)
            k=_N((net_worth+position[0]["Profit"])-initial,2)
            LogProfit((net_worth+position[0]["Profit"])-initial,'&')
            if d==1:
                e="做空#FF0000"
            elif d==0:
                e="做多#00FF00"

        i=0
        while i<back_test:
            if r[-i-1]["Close"]>ma[-i-1]:
                wave.append(0)
                i=i+1
            else:
                wave.append(1)
                i=i+1
        if len(sign)==0:
            if wave.count(0)==len(wave) and ticker['Last']>ma[-1]:          
                if r[-2]["Close"]>ma[-2] and r[-3]["Close"]>ma[-3] and r[-4]["Close"]>ma[-4]:
                    if (ma[-3]/r[-3]["Close"])-1>=-0.03:
                        net_worth = account["Balance"]
                        exchange.SetDirection("buy")
                        exchange.Buy(-1,_N(copies/ticker['Last'],3))
                        sign.append(100)
                        grid(_N(ticker['Last'],2))
                        median = line[5]
            elif wave.count(1)==len(wave) and ticker['Last']<ma[-1]:         
                if r[-2]["Close"]<ma[-2] and r[-3]["Close"]<ma[-3] and r[-4]["Close"]<ma[-4]:
                    if (ma[-3]/r[-3]["Close"])-1<=0.03:
                        net_worth = account["Balance"]
                        exchange.SetDirection("sell")
                        exchange.Sell(-1,_N(copies/ticker['Last'],3))
                        sign.append(400)
                        grid(_N(ticker['Last'],2))
                        median = line[5]
            elif wave.count(0)/wave.count(1)>0.65 and wave.count(0)/wave.count(1)<1.5:       
                if (ma[-3]/r[-3]["Close"])-1>=-0.1 and (ma[-3]/r[-3]["Close"])-1<1.1:
                    net_worth = account["Balance"]
                    exchange.SetDirection("sell")
                    exchange.Sell(-1,_N(copies/ticker['Last'],3))
                    sign.append(500)
                    grid(_N(ticker['Last'],2))
                    median = line[5]
            elif wave.count(0)/wave.count(1)>=3.9 and ticker['Last']<ma[-1]:        
                if r[-2]["Close"]<ma[-2] and r[-3]["Close"]<ma[-3] and r[-4]["Close"]<ma[-4]:        
                    if (ma[-3]/r[-3]["Close"])-1<=0.06:  
                        net_worth = account["Balance"]
                        exchange.SetDirection("sell")
                        exchange.Sell(-1,_N(copies/ticker['Last'],3))
                        sign.append(200)
                        grid(_N(ticker['Last'],2))
                        median = line[5]
            elif wave.count(0)/wave.count(1)<=0.26 and ticker['Last']>ma[-1]:         
                if r[-2]["Close"]>ma[-2] and r[-3]["Close"]>ma[-3] and r[-4]["Close"]>ma[-4]:
                    if (ma[-3]/r[-3]["Close"])-1>=-0.06:
                        net_worth = account["Balance"]
                        exchange.SetDirection("buy")
                        exchange.Buy(-1,_N(copies/ticker['Last'],3))
                        sign.append(300)
                        grid(_N(ticker['Last'],2))
                        median = line[5]
        if len(sign)>0 and len(sign)>0 and len(line)>0:
            for i in range(len(line)):
                if len(scale)<cishu:
                    if ticker['Last']>line[i] and i>median:
                        del line[0]
                        line.append(line[-1]+500)
                        if sign[0]==100 or sign[0]==300:
                            exchange.SetDirection("buy")
                            exchange.Buy(-1,_N(copies/ticker['Last'],3))
                            scale.append(1)
                            Log("第%d次加仓#FF0000"%len(scale))
                            LogProfit((net_worth+position[0]["Profit"])-initial)
                        elif sign[0]==200 or sign[0]==400 or sign[0]==500:
                            exchange.SetDirection("sell")
                            exchange.Sell(-1,_N(copies/ticker['Last'],3))
                            scale.append(1)
                            Log("第%d次加仓#FF0000"%len(scale)) 
                    elif ticker['Last']<line[i] and i<median:
                        del line[-1]
                        line.insert(0,line[0]-500)
                        if sign[0]==100 or sign[0]==300:
                            exchange.SetDirection("buy")
                            exchange.Buy(-1,_N(copies/ticker['Last'],3))
                            scale.append(1)
                            Log("第%d次加仓#FF0000"%len(scale))
                        elif sign[0]==200 or sign[0]==400 or sign[0]==500:
                            exchange.SetDirection("sell")
                            exchange.Sell(-1,_N(copies/ticker['Last'],3))
                            scale.append(1)
                            Log("第%d次加仓#FF0000"%len(scale))
                        
                elif sign[0]==200 or sign[0]==400:
                    if r[-2]["Close"]>ma[-2] and r[-3]["Close"]>ma[-3] and r[-4]["Close"]>ma[-4]:
                        if r[-5]["Close"]>ma[-5] and r[-6]["Close"]>ma[-6]:
                            secondary = _N(net_worth+position[0]["Profit"],2)
                            exchange.SetDirection("closesell")
                            exchange.Buy(-1,position[0]["Amount"])
                            net_worth = account["Balance"]
                            sign.clear()
                            scale.clear()
                elif sign[0]==300 or sign[0]==100:
                    if r[-2]["Close"]<ma[-2] and r[-3]["Close"]<ma[-3] and r[-4]["Close"]<ma[-4]:
                        if r[-5]["Close"]<ma[-5] and r[-6]["Close"]<ma[-6]:
                            secondary = _N(net_worth+position[0]["Profit"],2)
                            exchange.SetDirection("closebuy")
                            exchange.Sell(-1,position[0]["Amount"])
                            net_worth = account["Balance"]
                            sign.clear()
                            scale.clear()
                elif sign[0]==500:
                    if r[-2]["Close"]>ma[-2] and r[-3]["Close"]>ma[-3] and r[-4]["Close"]>ma[-4]:
                        if r[-5]["Close"]>ma[-5] and r[-6]["Close"]>ma[-6]:
                            if (ma[-3]/r[-3]["Close"])-1>=-0.12:
                                secondary = _N(net_worth+position[0]["Profit"],2)
                                exchange.SetDirection("closesell")
                                exchange.Buy(-1,position[0]["Amount"])
                                net_worth = account["Balance"]
                                sign.clear()
                                scale.clear()
                
            
        wave.clear()
        end = time.clock()

        tab1["rows"].append([
                initial,
                ii,
                f,
                k,
                '%s ms' % int((end-start)*1000)
            ])
        tab2["rows"].append([
                exchange.GetCurrency(),
                e,
                g,
                a,
                h,
                _N(ticker['Last'],2),
                b,
                c
            ])
        LogStatus("`" + json.dumps(tab1) + "`\n" + 
        "`" + json.dumps(tab2) + "`\n" 
        "" + '最后执行时间:',_D() + "")
        Sleep(10000)

More