标准化套利的使用

交易对象:目前使用郑商所,大商所的spd标准化套利组合进行交易。

交易平台:易盛极星极星产品网

手续费研究:白糖期货手续费和保证金2023年09月更新 - 九期网

本人使用的期货交易公司:中信期货(幸亏资金量大,返还高,不然就是给期货公司打工。套利的间接成本很高,滑点,手续费。)

特点:1.远近月合约,双边收手续费,只收保证金。

2.底层逻辑来自与品种本身的同质性,即5月的交割品种放到下个月一样用。

3.但是,很多品种不是,比如农产品,会变成陈货。交割旺季和淡季的价差会拉大。

4.波动小,是其主要特征,极少情况出现极端行情,风险小使得其成为很多人的热门选择

5.统计学套利和基本面套利,是套利的两大主流方向,如有其他的,欢迎补充。

统计套利,就是根据k线图,选择做多,做空价差

基本面套利,则是更具当前期货价格,现货价格,预测价差是拉大还是缩小。

我上传一段简单的spd合约套利代码,直接使用即可。

思路为:肯特那通道的变种,加入网格系统。做到止盈止损,但黑天鹅我无法保证。

import talib
import talib as ta
import numpy as np

#对价交易
#code1  =  "SPD|s|M|2311|2405"
#code1 = 'M2309-M2407'
spd = 'SPD|s|M|2311|2403'#获取合约数据
code = 'DCE|S|M|2311|2403'#实际下单合约
code1='DCE|F|M|2311'
code2 = 'DCE|F|M|2403'


g_params['n'] = 20 #滚动周期极值
g_params['m'] = 20 #ATR参数
#g_params['p'] = 20 #std周期
g_params['w'] = 'M'
g_params['T'] = 15
g_params['p3'] = 1 #止损线距离
g_params['p1'] = 10
g_params['adx'] = 20
g_params['m2'] =5
# 策略参数,全局变量,各个k线都可以调用
up1 = []
down1 = []
up2 = []
down2 = []
up3 = []
down3 = []
up4 = []
down4 = []
std = []
up_limit1 = []
down_limit1 = []
up_limit2 = []
down_limit2 = []
up_limit3 = []
down_limit3 = []
up_limit4 = []
down_limit4 = []
ran = []

BKDFLG = 0
SKDFLG = 0
BPDFLG = 0
SPDFLG = 0

#开仓委托
BKID = 0
SKID = 0
#平仓委托
BPID = 0
SPID = 0
#开仓标志
BKFLG = 0
SKFLG = 0
#平仓标志 
BPFLG = 0
SPFLG = 0
#开仓撤单标志
BKDEL = 0
SKDEL = 0
#平仓撤单标志
BPDEL = 0
SPDEL = 0
#开仓委托手数
BKM = 0
SKM = 0
#平仓委托手数
BPM = 0
SPM = 0
#开仓委托价格
BKP = 0
SKP = 0
#平仓委托价格
BPP = 0
SPP = 0
#开仓委托时间
BKT = 0
SKT = 0
#平仓委托时间
BPT = 0
SPT = 0

def minprice(price1,price2):
    if price1>price2:
        return price2
    else:
        return price1
def maxprice(price1,price2):
    if price1>price2:
        return price1
    else:
        return price2
# 价格矫正为最小变动价整数倍
def PriceCorrect(src,tick):
    if tick:
        return (int((src+0.5*tick)/tick))*tick
    else:
        src
# 策略开始运行时执行该函数一次
def initialize(context):
    SetBarInterval(spd, g_params['w'], g_params['T'],1000)
    SetBarInterval(code1, g_params['w'], g_params['T'],1000)
    SetBarInterval(code2, g_params['w'], g_params['T'],1000)
    SetBarInterval(code, g_params['w'], g_params['T'],1000)
    SetTriggerType(1)
    SetOrderWay(1)
    SetActual()
    SetAFunUseForHis()
    SetUserNo('Q1010422846')  # 设置交易账号

# 策略触发事件每次触发时都会执行该函数
def handle_data(context):
    #当前k线判断,内部函数
    #出现开平仓信号
    # BKDFLG = 0
    # SKDFLG = 0
    # BPDFLG = 0
    # SPDFLG = 0

    # BKFLG =0
    # SKFLG =0
    # BPFLG =0 
    # SPFLG =0 
    #全局运作,超出k线

    #全局变量,不受时间约束
    global up1
    global down1
    global up2
    global down2
    global up3
    global down3
    global up4
    global down4

    global std
    global up_limit1 
    global down_limit1
    global up_limit2 
    global down_limit2
    global up_limit3 
    global down_limit3
    global up_limit4 
    global down_limit4

    global ran

    global BKDFLG 
    global SKDFLG 
    global BPDFLG 
    global SPDFLG 


    global BKID
    global SKID
    global BPID
    global SPID
    global BKFLG
    global SKFLG
    global BPFLG
    global SPFLG
    global BKDEL
    global SKDEL
    global BPDEL
    global SPDEL
    global BKM
    global SKM
    global BPM
    global SPM
    global BKP
    global SKP
    global BPP
    global SPP
    global BKT
    global SKT
    global BPT
    global SPT

    #确定前面有足够的数据
    if (CurrentBar() >= len(up1)):
        if (len(up1)) < 1:
            up1.append(0)
            down1.append(0)
            up2.append(0)
            down2.append(0)
            up3.append(0)
            down3.append(0)
            up4.append(0)
            down4.append(0)
            std.append(0)
            up_limit1.append(0)
            down_limit1.append(0)
            up_limit2.append(0)
            down_limit2.append(0)
            up_limit3.append(0)
            down_limit3.append(0)
            up_limit4.append(0)
            down_limit4.append(0)
            ran.append(0)
            # preEntryPrice.append(0)
        else:
            up1.append(up1[-1])
            down1.append(down1[-1])
            up2.append(up2[-1])
            down2.append(down2[-1])
            up3.append(up3[-1])
            down3.append(down3[-1])
            up4.append(up4[-1])
            down4.append(down4[-1])
            std.append(std[-1])
            up_limit1.append(up_limit1[-1])
            down_limit1.append(down_limit1[-1])
            up_limit2.append(up_limit2[-1])
            down_limit2.append(down_limit2[-1])
            up_limit3.append(up_limit3[-1])
            down_limit3.append(down_limit3[-1])
            up_limit4.append(up_limit4[-1])
            down_limit4.append(down_limit4[-1])
            ran.append(ran[-1])
    #从第N根k线开始进行程序运行
    if len(Close()) < g_params['p1']:
        return
    m = g_params['m']
    m2 = g_params['m2']
    x = spd
    ran[-1] = ta.ATR(High(x, str(g_params['w'] ), g_params['T'])[:-1], Low(x, str(g_params['w'] ), g_params['T'])[:-1], Close(x, str(g_params['w'] ), g_params['T'])[:-1], m)[
        -1] // PriceTick(x) * PriceTick(x)  # 一个周期前ran
    adx = ta.ADX(High(x, str(g_params['w'] ), g_params['T'])[:-1], Low(x, str(g_params['w'] ), g_params['T'])[:-1], Close(x, str(g_params['w'] ), g_params['T'])[:-1], m2)
    up1[-1] =  Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].max()
    #up_limit1[-1] = up1[-1] + ran[-1]*g_params['p3']
    down1[-1] = Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].min()
    #down_limit1[-1] = down1[-1] - ran[-1]*g_params['p3']

    up2[-1] =  Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].max()
    up_limit2[-1] = up2[-1] - ran[-1]*g_params['p3']
    down2[-1] = Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].min()
    down_limit2[-1] = down2[-1] + ran[-1]*g_params['p3']


    PlotNumeric('up1',up1[-1]+2*PriceTick(spd),RGB_Red(),True)
    PlotNumeric('up_limit2',up_limit2[-1]-2*PriceTick(spd),RGB_Blue(),True)
    PlotNumeric('down1',down1[-1]-2*PriceTick(spd),RGB_Green(),True)
    PlotNumeric('down_limit2',down_limit2[-1]+2*PriceTick(spd),RGB_Yellow(),True)
    #PlotNumeric('adx',adx[-1],RGB_Yellow(),False)
    PlotNumeric('ran',ran[-1],RGB_Red(),False)
    BKDFLG = 0
    SKDFLG = 0
    BPDFLG = 0
    SPDFLG = 0
 
    if Q_Close(spd)>=up1[-1]+2*PriceTick(spd) and A_BuyPosition(code1)==0 and A_SellPosition(code1)==0 :
        if SKDFLG ==0:
            SKDFLG = 1
    elif  Q_Close(spd)<=up_limit2[-1]-2*PriceTick(spd) and  A_BuyPosition(code1)==0 and A_SellPosition(code1)>0 :
        if BPDFLG ==0:
            BPDFLG = 1  # 发出止损信号

    elif  (Q_Close(spd)<=down1[-1]-2*PriceTick(spd)) and A_BuyPosition(code1)==0 and A_SellPosition(code1)==0 :
        if BKDFLG == 0:
            BKDFLG = 1
    elif  (Q_Close(spd)>=down_limit2[-1]+2*PriceTick(spd)) and  A_BuyPosition(code1)>0 and A_SellPosition(code1)==0 :
        if SPDFLG == 0:
            SPDFLG = 1  # 止损信号出现 
    ss = int(A_Assets()*0.005/(Q_Close(code1)*0.1*10))
    ss = 1
    # LogInfo('状态',Q_Close(spd),\
    # A_BuyPosition(code1),A_SellPosition(code1),\
    # A_BuyPosition(spd),A_SellPosition(spd), \
    # BKDFLG ,SKDFLG,BPDFLG,SPDFLG )
    #LogInfo('????',A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code))  
    #//------------------------历史发单------------------------//
    # if context.strategyStatus() != 'C':
    #     if BKDFLG:
    #         Buy(ss, down1[-1], needCover=False) 
    #     elif SKDFLG:
    #         SellShort(ss,up1[-1], needCover=False)
    #     elif SPDFLG:
    #         Sell(ss, down_limit2[-1])
    #     elif BPDFLG:
    #         BuyToCover(ss, up_limit2[-1])
    #     return
    #//------------------------实时处理------------------------//
    # if ExchangeStatus(ExchangeName()) != '3':
    #     return
    #//------------------------变量赋值------------------------//
    #N = int(A_Assets()*0.0005/(Q_Close()*0.1*10))
    #N = 10
    #LogInfo('N',N)
    N = 1
    #N = 1 #下单手数
    T = 5 #时间间隔
    NOW = CurrentTime() #当前时间
    BIDP = 0 if Q_BidPrice(spd) is None else Q_BidPrice(spd) #买一价
    ASKP = 0 if Q_AskPrice(spd) is None else Q_AskPrice(spd) #卖一价
    BRP = A_BuyPositionCanCover(code1) #多头可用持仓
    SRP = A_SellPositionCanCover(code1) #空头可用持仓
    LogInfo('价格',BIDP,ASKP,BRP,SRP)
    # if ExchangeName() == 'SHFE': #如果是上期所合约
    #     SH = Enum_ExitToday() #平仓参数
    # else: #如果非上期所合约
    #     SH = Enum_Exit() #平仓参数
    SH = Enum_ExitToday()
    #//------------------------成交判断------------------------//
    if BKFLG == 1:
        if A_OrderStatus(BKID) == Enum_Filled():
            LogInfo("BK信号:买开委托成交!")
            BKFLG = 0 #买开标志归0
            BKDEL = 0 #买开撤单标志归0
        elif A_OrderStatus(BKID) == Enum_Canceled():
            LogInfo("BK信号:买开委托已撤!")
            if A_OrderFilledLot(BKID) > 0: #如果买开委托部分成交
                BKM = BKM - A_OrderFilledLot(BKID) #买开委托手数
            if BKM > 0: #如果买开委托手数大于0
                BKP = ASKP #买开委托价格
                LogInfo("BK信号:买开委托追价!")
                retCode, BKID = A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code) #发出买开委托
                BKT = NOW #买开委托时间
            BKDEL = 0 #买开撤单标志归0
        elif A_OrderStatus(BKID) == Enum_Suspended() or A_OrderStatus(BKID) == Enum_FillPart():
            if BKDEL == 0: #如果未撤单
               if TimeDiff(BKT, NOW) >= T: #如果时间间隔T秒
                  LogInfo("BK信号:买开委托撤单!")
                  A_DeleteOrder(BKID) #撤掉买开委托挂单
                  BKDEL = 1 #已发出撤掉买开委托挂单
    if SPFLG == 1:
        if A_OrderStatus(SPID) == Enum_Filled():
            LogInfo("SP信号:卖平委托成交!")
            SPFLG = 0 #卖平标志归0
            SPDEL = 0 #卖平撤单标志归0
        elif A_OrderStatus(SPID) == Enum_Canceled():
            LogInfo("SP信号:卖平委托已撤!")
            if A_OrderFilledLot(SPID) > 0: #如果卖平委托部分成交
                SPM = SPM - A_OrderFilledLot(SPID) #卖平委托手数
            if BRP > 0 and SPM > 0 and SPM <= BRP: #如果卖平委托手数不超过多头可用持仓
                SPP = BIDP #卖平委托价格
                LogInfo("SP信号:卖平委托追价!")
                retCode, SPID = A_SendOrder(Enum_Sell(),SH,SPM,SPP,code) #发出卖平委托
                SPT = NOW #卖平委托时间
            SPDEL = 0 #卖平撤单标志归0
        elif A_OrderStatus(SPID) == Enum_Suspended() or A_OrderStatus(SPID) == Enum_FillPart():
            if SPDEL == 0: #如果未撤单
               if TimeDiff(SPT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("SP信号:卖平委托撤单!")
                    A_DeleteOrder(SPID) #撤掉卖平委托挂单
                    SPDEL = 1 #已发出撤掉卖平委托挂单
    if SKFLG == 1:
        if A_OrderStatus(SKID) == Enum_Filled():
            LogInfo("SK信号:卖开委托成交!")
            SKFLG = 0 #卖开标志归0
            SKDEL = 0 #卖开撤单标志归0
        elif A_OrderStatus(SKID) == Enum_Canceled():
            LogInfo("SK信号:卖开委托已撤!")
            if A_OrderFilledLot(SKID) > 0: #如果卖开委托部分成交
                SKM = SKM - A_OrderFilledLot(SKID) #卖开委托手数
            if SKM > 0: #如果卖开委托手数大于0
                SKP = BIDP #卖开委托价格
                LogInfo("SK信号:卖开委托追价!")
                retCode, SKID = A_SendOrder(Enum_Sell(), Enum_Entry(), SKM, SKP,code) #发出卖开委托
                SKT = NOW #卖开委托时间
            SKDEL = 0 #卖开撤单标志归0
        elif A_OrderStatus(SKID) == Enum_Suspended() or A_OrderStatus(SKID) == Enum_FillPart():
            if SKDEL == 0: #如果未撤单
               if TimeDiff(SKT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("SK信号:卖开委托撤单!")
                    A_DeleteOrder(SKID) #撤掉卖开委托挂单
                    SKDEL = 1 #已发出撤掉卖开委托挂单
    if BPFLG == 1:
        if A_OrderStatus(BPID) == Enum_Filled():
            LogInfo("BP信号:买平委托成交!")
            BPFLG = 0 #买平标志归0
            BPDEL = 0 #买平撤单标志归0
        elif A_OrderStatus(BPID) == Enum_Canceled():
            LogInfo("BP信号:买平委托已撤!")
            if A_OrderFilledLot(BPID) > 0:  #如果买平委托部分成交
                BPM = BPM - A_OrderFilledLot(BPID) #买平委托手数
            if SRP > 0 and BPM > 0 and BPM <= SRP: #如果买平委托手数不超过空头可用持仓
                BPP = ASKP #买平委托价格
                LogInfo("BP信号:买平委托追价!")
                retCode, BPID = A_SendOrder(Enum_Buy(),SH,BPM,BPP,code) #发出买平委托
                BPT = NOW #买平委托时间
            BPDEL = 0 #买平撤单标志归0
        elif A_OrderStatus(BPID) == Enum_Suspended() or A_OrderStatus(BPID) == Enum_FillPart():
            if BPDEL == 0: #如果未撤单
               if TimeDiff(BPT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("BP信号:买平委托撤单!")
                    A_DeleteOrder(BPID) #撤掉买平委托挂单
                    BPDEL = 1 #已发出撤掉买平委托挂单
    #//------------------------委托处理------------------------//
    LogInfo('????2',BKDFLG,BKFLG) 
    if BKDFLG == 1:
        LogInfo('????3',BKFLG)
        if BKFLG == 0: #如果没有买开委托
            BKM = N #买开委托手数
            BKP = ASKP #买开委托价格
            LogInfo("BK信号:买开委托发出")
            retCode, BKID = A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code) #发出买开委托
            BKT = NOW #买开委托时间
            BKFLG = 1 #已发出买开委托
            BKDFLG = 0
    if SPDFLG == 1:
        if SPFLG == 0: #如果没有卖平委托
            if BRP > 0: #如果有多头可用持仓
                SPM = BRP #卖平委托手数
                SPP = BIDP #卖平委托价格
                LogInfo("SP信号:卖平委托发出!")
                retCode, SPID = A_SendOrder(Enum_Sell(),SH,SPM,SPP,code) #发出卖平委托
                SPT = NOW #卖平委托时间
                SPFLG = 1 #已发出卖平委托
                SPDFLG = 0           
    if SKDFLG == 1:
        if SKFLG == 0: #如果没有卖开委托
            SKM = N #卖开委托手数
            SKP = BIDP #卖开委托价格
            LogInfo("SK信号:卖开委托发出!")
            retCode, SKID = A_SendOrder(Enum_Sell(),Enum_Entry(),SKM,SKP,code) #发出卖开委托
            SKT = NOW #卖开委托时间
            SKFLG = 1 #已发出卖开委托
            SKDFLG = 0
    if BPDFLG == 1:
        if BPFLG == 0: #如果没有买平委托
            if SRP > 0: #如果有空头可用持仓
                BPM = SRP #买平委托手数
                BPP = ASKP #买平委托价格
                LogInfo("BP信号:买平委托发出!")
                retCode, BPID = A_SendOrder(Enum_Buy(),SH,BPM,BPP,code) #发出买平委托
                BPT = NOW #买平委托时间
                BPFLG = 1 #已发出买平委托
                BPDFLG =0
import talib
import talib as ta
import numpy as np

#对价交易
#code1  =  "SPD|s|M|2311|2405"
#code1 = 'M2309-M2407'
spd = 'SPD|s|M|2311|2403'#获取合约数据
code = 'DCE|S|M|2311|2403'#实际下单合约
code1='DCE|F|M|2311'
code2 = 'DCE|F|M|2403'


g_params['n'] = 20 #滚动周期极值
g_params['m'] = 20 #ATR参数
#g_params['p'] = 20 #std周期
g_params['w'] = 'M'
g_params['T'] = 15
g_params['p3'] = 1 #止损线距离
g_params['p1'] = 10
g_params['adx'] = 20
g_params['m2'] =5
# 策略参数,全局变量,各个k线都可以调用
up1 = []
down1 = []
up2 = []
down2 = []
up3 = []
down3 = []
up4 = []
down4 = []
std = []
up_limit1 = []
down_limit1 = []
up_limit2 = []
down_limit2 = []
up_limit3 = []
down_limit3 = []
up_limit4 = []
down_limit4 = []
ran = []

BKDFLG = 0
SKDFLG = 0
BPDFLG = 0
SPDFLG = 0

#开仓委托
BKID = 0
SKID = 0
#平仓委托
BPID = 0
SPID = 0
#开仓标志
BKFLG = 0
SKFLG = 0
#平仓标志 
BPFLG = 0
SPFLG = 0
#开仓撤单标志
BKDEL = 0
SKDEL = 0
#平仓撤单标志
BPDEL = 0
SPDEL = 0
#开仓委托手数
BKM = 0
SKM = 0
#平仓委托手数
BPM = 0
SPM = 0
#开仓委托价格
BKP = 0
SKP = 0
#平仓委托价格
BPP = 0
SPP = 0
#开仓委托时间
BKT = 0
SKT = 0
#平仓委托时间
BPT = 0
SPT = 0

def minprice(price1,price2):
    if price1>price2:
        return price2
    else:
        return price1
def maxprice(price1,price2):
    if price1>price2:
        return price1
    else:
        return price2
# 价格矫正为最小变动价整数倍
def PriceCorrect(src,tick):
    if tick:
        return (int((src+0.5*tick)/tick))*tick
    else:
        src
# 策略开始运行时执行该函数一次
def initialize(context):
    SetBarInterval(spd, g_params['w'], g_params['T'],1000)
    SetBarInterval(code1, g_params['w'], g_params['T'],1000)
    SetBarInterval(code2, g_params['w'], g_params['T'],1000)
    SetBarInterval(code, g_params['w'], g_params['T'],1000)
    SetTriggerType(1)
    SetOrderWay(1)
    SetActual()
    SetAFunUseForHis()
    SetUserNo('Q1010422846')  # 设置交易账号

# 策略触发事件每次触发时都会执行该函数
def handle_data(context):
    #当前k线判断,内部函数
    #出现开平仓信号
    # BKDFLG = 0
    # SKDFLG = 0
    # BPDFLG = 0
    # SPDFLG = 0

    # BKFLG =0
    # SKFLG =0
    # BPFLG =0 
    # SPFLG =0 
    #全局运作,超出k线

    #全局变量,不受时间约束
    global up1
    global down1
    global up2
    global down2
    global up3
    global down3
    global up4
    global down4

    global std
    global up_limit1 
    global down_limit1
    global up_limit2 
    global down_limit2
    global up_limit3 
    global down_limit3
    global up_limit4 
    global down_limit4

    global ran

    global BKDFLG 
    global SKDFLG 
    global BPDFLG 
    global SPDFLG 


    global BKID
    global SKID
    global BPID
    global SPID
    global BKFLG
    global SKFLG
    global BPFLG
    global SPFLG
    global BKDEL
    global SKDEL
    global BPDEL
    global SPDEL
    global BKM
    global SKM
    global BPM
    global SPM
    global BKP
    global SKP
    global BPP
    global SPP
    global BKT
    global SKT
    global BPT
    global SPT

    #确定前面有足够的数据
    if (CurrentBar() >= len(up1)):
        if (len(up1)) < 1:
            up1.append(0)
            down1.append(0)
            up2.append(0)
            down2.append(0)
            up3.append(0)
            down3.append(0)
            up4.append(0)
            down4.append(0)
            std.append(0)
            up_limit1.append(0)
            down_limit1.append(0)
            up_limit2.append(0)
            down_limit2.append(0)
            up_limit3.append(0)
            down_limit3.append(0)
            up_limit4.append(0)
            down_limit4.append(0)
            ran.append(0)
            # preEntryPrice.append(0)
        else:
            up1.append(up1[-1])
            down1.append(down1[-1])
            up2.append(up2[-1])
            down2.append(down2[-1])
            up3.append(up3[-1])
            down3.append(down3[-1])
            up4.append(up4[-1])
            down4.append(down4[-1])
            std.append(std[-1])
            up_limit1.append(up_limit1[-1])
            down_limit1.append(down_limit1[-1])
            up_limit2.append(up_limit2[-1])
            down_limit2.append(down_limit2[-1])
            up_limit3.append(up_limit3[-1])
            down_limit3.append(down_limit3[-1])
            up_limit4.append(up_limit4[-1])
            down_limit4.append(down_limit4[-1])
            ran.append(ran[-1])
    #从第N根k线开始进行程序运行
    if len(Close()) < g_params['p1']:
        return
    m = g_params['m']
    m2 = g_params['m2']
    x = spd
    ran[-1] = ta.ATR(High(x, str(g_params['w'] ), g_params['T'])[:-1], Low(x, str(g_params['w'] ), g_params['T'])[:-1], Close(x, str(g_params['w'] ), g_params['T'])[:-1], m)[
        -1] // PriceTick(x) * PriceTick(x)  # 一个周期前ran
    adx = ta.ADX(High(x, str(g_params['w'] ), g_params['T'])[:-1], Low(x, str(g_params['w'] ), g_params['T'])[:-1], Close(x, str(g_params['w'] ), g_params['T'])[:-1], m2)
    up1[-1] =  Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].max()
    #up_limit1[-1] = up1[-1] + ran[-1]*g_params['p3']
    down1[-1] = Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].min()
    #down_limit1[-1] = down1[-1] - ran[-1]*g_params['p3']

    up2[-1] =  Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].max()
    up_limit2[-1] = up2[-1] - ran[-1]*g_params['p3']
    down2[-1] = Close(x,str(g_params['w'] ), g_params['T'])[-g_params['n']:-1].min()
    down_limit2[-1] = down2[-1] + ran[-1]*g_params['p3']


    PlotNumeric('up1',up1[-1]+2*PriceTick(spd),RGB_Red(),True)
    PlotNumeric('up_limit2',up_limit2[-1]-2*PriceTick(spd),RGB_Blue(),True)
    PlotNumeric('down1',down1[-1]-2*PriceTick(spd),RGB_Green(),True)
    PlotNumeric('down_limit2',down_limit2[-1]+2*PriceTick(spd),RGB_Yellow(),True)
    #PlotNumeric('adx',adx[-1],RGB_Yellow(),False)
    PlotNumeric('ran',ran[-1],RGB_Red(),False)
    BKDFLG = 0
    SKDFLG = 0
    BPDFLG = 0
    SPDFLG = 0
 
    if Q_Close(spd)>=up1[-1]+2*PriceTick(spd) and A_BuyPosition(code1)==0 and A_SellPosition(code1)==0 :
        if SKDFLG ==0:
            SKDFLG = 1
    elif  Q_Close(spd)<=up_limit2[-1]-2*PriceTick(spd) and  A_BuyPosition(code1)==0 and A_SellPosition(code1)>0 :
        if BPDFLG ==0:
            BPDFLG = 1  # 发出止损信号

    elif  (Q_Close(spd)<=down1[-1]-2*PriceTick(spd)) and A_BuyPosition(code1)==0 and A_SellPosition(code1)==0 :
        if BKDFLG == 0:
            BKDFLG = 1
    elif  (Q_Close(spd)>=down_limit2[-1]+2*PriceTick(spd)) and  A_BuyPosition(code1)>0 and A_SellPosition(code1)==0 :
        if SPDFLG == 0:
            SPDFLG = 1  # 止损信号出现 
    ss = int(A_Assets()*0.005/(Q_Close(code1)*0.1*10))
    ss = 1
    # LogInfo('状态',Q_Close(spd),\
    # A_BuyPosition(code1),A_SellPosition(code1),\
    # A_BuyPosition(spd),A_SellPosition(spd), \
    # BKDFLG ,SKDFLG,BPDFLG,SPDFLG )
    #LogInfo('????',A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code))  
    #//------------------------历史发单------------------------//
    # if context.strategyStatus() != 'C':
    #     if BKDFLG:
    #         Buy(ss, down1[-1], needCover=False) 
    #     elif SKDFLG:
    #         SellShort(ss,up1[-1], needCover=False)
    #     elif SPDFLG:
    #         Sell(ss, down_limit2[-1])
    #     elif BPDFLG:
    #         BuyToCover(ss, up_limit2[-1])
    #     return
    #//------------------------实时处理------------------------//
    # if ExchangeStatus(ExchangeName()) != '3':
    #     return
    #//------------------------变量赋值------------------------//
    #N = int(A_Assets()*0.0005/(Q_Close()*0.1*10))
    #N = 10
    #LogInfo('N',N)
    N = 1
    #N = 1 #下单手数
    T = 5 #时间间隔
    NOW = CurrentTime() #当前时间
    BIDP = 0 if Q_BidPrice(spd) is None else Q_BidPrice(spd) #买一价
    ASKP = 0 if Q_AskPrice(spd) is None else Q_AskPrice(spd) #卖一价
    BRP = A_BuyPositionCanCover(code1) #多头可用持仓
    SRP = A_SellPositionCanCover(code1) #空头可用持仓
    LogInfo('价格',BIDP,ASKP,BRP,SRP)
    # if ExchangeName() == 'SHFE': #如果是上期所合约
    #     SH = Enum_ExitToday() #平仓参数
    # else: #如果非上期所合约
    #     SH = Enum_Exit() #平仓参数
    SH = Enum_ExitToday()
    #//------------------------成交判断------------------------//
    if BKFLG == 1:
        if A_OrderStatus(BKID) == Enum_Filled():
            LogInfo("BK信号:买开委托成交!")
            BKFLG = 0 #买开标志归0
            BKDEL = 0 #买开撤单标志归0
        elif A_OrderStatus(BKID) == Enum_Canceled():
            LogInfo("BK信号:买开委托已撤!")
            if A_OrderFilledLot(BKID) > 0: #如果买开委托部分成交
                BKM = BKM - A_OrderFilledLot(BKID) #买开委托手数
            if BKM > 0: #如果买开委托手数大于0
                BKP = ASKP #买开委托价格
                LogInfo("BK信号:买开委托追价!")
                retCode, BKID = A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code) #发出买开委托
                BKT = NOW #买开委托时间
            BKDEL = 0 #买开撤单标志归0
        elif A_OrderStatus(BKID) == Enum_Suspended() or A_OrderStatus(BKID) == Enum_FillPart():
            if BKDEL == 0: #如果未撤单
               if TimeDiff(BKT, NOW) >= T: #如果时间间隔T秒
                  LogInfo("BK信号:买开委托撤单!")
                  A_DeleteOrder(BKID) #撤掉买开委托挂单
                  BKDEL = 1 #已发出撤掉买开委托挂单
    if SPFLG == 1:
        if A_OrderStatus(SPID) == Enum_Filled():
            LogInfo("SP信号:卖平委托成交!")
            SPFLG = 0 #卖平标志归0
            SPDEL = 0 #卖平撤单标志归0
        elif A_OrderStatus(SPID) == Enum_Canceled():
            LogInfo("SP信号:卖平委托已撤!")
            if A_OrderFilledLot(SPID) > 0: #如果卖平委托部分成交
                SPM = SPM - A_OrderFilledLot(SPID) #卖平委托手数
            if BRP > 0 and SPM > 0 and SPM <= BRP: #如果卖平委托手数不超过多头可用持仓
                SPP = BIDP #卖平委托价格
                LogInfo("SP信号:卖平委托追价!")
                retCode, SPID = A_SendOrder(Enum_Sell(),SH,SPM,SPP,code) #发出卖平委托
                SPT = NOW #卖平委托时间
            SPDEL = 0 #卖平撤单标志归0
        elif A_OrderStatus(SPID) == Enum_Suspended() or A_OrderStatus(SPID) == Enum_FillPart():
            if SPDEL == 0: #如果未撤单
               if TimeDiff(SPT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("SP信号:卖平委托撤单!")
                    A_DeleteOrder(SPID) #撤掉卖平委托挂单
                    SPDEL = 1 #已发出撤掉卖平委托挂单
    if SKFLG == 1:
        if A_OrderStatus(SKID) == Enum_Filled():
            LogInfo("SK信号:卖开委托成交!")
            SKFLG = 0 #卖开标志归0
            SKDEL = 0 #卖开撤单标志归0
        elif A_OrderStatus(SKID) == Enum_Canceled():
            LogInfo("SK信号:卖开委托已撤!")
            if A_OrderFilledLot(SKID) > 0: #如果卖开委托部分成交
                SKM = SKM - A_OrderFilledLot(SKID) #卖开委托手数
            if SKM > 0: #如果卖开委托手数大于0
                SKP = BIDP #卖开委托价格
                LogInfo("SK信号:卖开委托追价!")
                retCode, SKID = A_SendOrder(Enum_Sell(), Enum_Entry(), SKM, SKP,code) #发出卖开委托
                SKT = NOW #卖开委托时间
            SKDEL = 0 #卖开撤单标志归0
        elif A_OrderStatus(SKID) == Enum_Suspended() or A_OrderStatus(SKID) == Enum_FillPart():
            if SKDEL == 0: #如果未撤单
               if TimeDiff(SKT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("SK信号:卖开委托撤单!")
                    A_DeleteOrder(SKID) #撤掉卖开委托挂单
                    SKDEL = 1 #已发出撤掉卖开委托挂单
    if BPFLG == 1:
        if A_OrderStatus(BPID) == Enum_Filled():
            LogInfo("BP信号:买平委托成交!")
            BPFLG = 0 #买平标志归0
            BPDEL = 0 #买平撤单标志归0
        elif A_OrderStatus(BPID) == Enum_Canceled():
            LogInfo("BP信号:买平委托已撤!")
            if A_OrderFilledLot(BPID) > 0:  #如果买平委托部分成交
                BPM = BPM - A_OrderFilledLot(BPID) #买平委托手数
            if SRP > 0 and BPM > 0 and BPM <= SRP: #如果买平委托手数不超过空头可用持仓
                BPP = ASKP #买平委托价格
                LogInfo("BP信号:买平委托追价!")
                retCode, BPID = A_SendOrder(Enum_Buy(),SH,BPM,BPP,code) #发出买平委托
                BPT = NOW #买平委托时间
            BPDEL = 0 #买平撤单标志归0
        elif A_OrderStatus(BPID) == Enum_Suspended() or A_OrderStatus(BPID) == Enum_FillPart():
            if BPDEL == 0: #如果未撤单
               if TimeDiff(BPT, NOW) >= T: #如果时间间隔T秒
                    LogInfo("BP信号:买平委托撤单!")
                    A_DeleteOrder(BPID) #撤掉买平委托挂单
                    BPDEL = 1 #已发出撤掉买平委托挂单
    #//------------------------委托处理------------------------//
    LogInfo('????2',BKDFLG,BKFLG) 
    if BKDFLG == 1:
        LogInfo('????3',BKFLG)
        if BKFLG == 0: #如果没有买开委托
            BKM = N #买开委托手数
            BKP = ASKP #买开委托价格
            LogInfo("BK信号:买开委托发出")
            retCode, BKID = A_SendOrder(Enum_Buy(),Enum_Entry(),BKM,BKP,code) #发出买开委托
            BKT = NOW #买开委托时间
            BKFLG = 1 #已发出买开委托
            BKDFLG = 0
    if SPDFLG == 1:
        if SPFLG == 0: #如果没有卖平委托
            if BRP > 0: #如果有多头可用持仓
                SPM = BRP #卖平委托手数
                SPP = BIDP #卖平委托价格
                LogInfo("SP信号:卖平委托发出!")
                retCode, SPID = A_SendOrder(Enum_Sell(),SH,SPM,SPP,code) #发出卖平委托
                SPT = NOW #卖平委托时间
                SPFLG = 1 #已发出卖平委托
                SPDFLG = 0           
    if SKDFLG == 1:
        if SKFLG == 0: #如果没有卖开委托
            SKM = N #卖开委托手数
            SKP = BIDP #卖开委托价格
            LogInfo("SK信号:卖开委托发出!")
            retCode, SKID = A_SendOrder(Enum_Sell(),Enum_Entry(),SKM,SKP,code) #发出卖开委托
            SKT = NOW #卖开委托时间
            SKFLG = 1 #已发出卖开委托
            SKDFLG = 0
    if BPDFLG == 1:
        if BPFLG == 0: #如果没有买平委托
            if SRP > 0: #如果有空头可用持仓
                BPM = SRP #买平委托手数
                BPP = ASKP #买平委托价格
                LogInfo("BP信号:买平委托发出!")
                retCode, BPID = A_SendOrder(Enum_Buy(),SH,BPM,BPP,code) #发出买平委托
                BPT = NOW #买平委托时间
                BPFLG = 1 #已发出买平委托
                BPDFLG =0

你可能感兴趣的:(极星量化,python,量化学习系列,python)