[Python] 复制代码
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!随机开仓模块!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
##########################################################################################################################################
#import logging #python 原生内置记录调试输出模块
#print(logging)
#from logging.handlers import RotatingFileHandler
#print( RotatingFileHandler)
#########################################################################################################################################
# 设置打印日志的级别,level级别以上的日志会打印出
# level=logging.DEBUG 、INFO 、WARNING、ERROR、CRITICAL
# format参数中可能用到的格式化串
# %(name)s Logger的名字
# %(levelno)s 数字形式的日志级别
# %(levelname)s 文本形式的日志级别
# %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
# %(filename)s 调用日志输出函数的模块的文件名
# %(module)s 调用日志输出函数的模块名
# %(funcName)s 调用日志输出函数的函数名
# %(lineno)d 调用日志输出函数的语句所在的代码行
# %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
# %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
# %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
# %(thread)d 线程ID。可能没有
# %(threadName)s 线程名。可能没有
# %(process)d 进程ID。可能没有
# %(message)s用户输出的消息
#######################################################################################################################################
#def logging_fun():
# # 创建日志的记录等级设
# logging.basicConfig(level=logging.DEBUG)
# # 创建日志记录器,指明日志保存的路径,每个日志文件的最大值,保存的日志文件个数上限
# log_handle = RotatingFileHandler("C://py_ZhangSu_KaiCang_log.txt", maxBytes=1024 * 1024, backupCount=5)
# # 创建日志记录的格式
# formatter = logging.Formatter("format = '%(asctime)s - %(filename)s - %(module)s - %(funcName)s - [line:%(lineno)d] - %(levelname)s - %(thread)d - %(threadName)s - %(process)d - %(message)s',")
# # 为创建的日志记录器设置日志记录格式
# log_handle.setFormatter(formatter)
# # 为全局的日志工具对象添加日志记录器
# logging.getLogger().addHandler(log_handle)
# logging.warning('用来用来打印警告信息')
# logging.error('一般用来打印一些错误信息')
# logging.critical('用来打印一些致命的错误信息,等级最高')
# pass
#logging_fun()
##########################################################################################################################################
#import unittest #python 原生内置测试test模块
#print(unittest)
import datetime #python 原生内置日期模块
print(datetime)
import random #python 原生内置随机模块
print(random)
import time #python 原生内置时间模块
print(time)
#import gc #python原生内存清理模块
#print(gc)
#import threading #python原生等待 不支持
#print(threading)
#event = threading.Event()
#event.wait(SleepS)
SleepS = int(datetime.datetime.now().strftime('%S'))
SleepMin = 0.1 #int(datetime.datetime.now().strftime('%f')[:-3])/1000
#设定启动等待时间 秒
#for i in range(SleepS):
# time.sleep(SleepMin) #time.sleep(SleepS) #python 原生内置暂停
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('启动中!等待账户登录后:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])+"/"+str(SleepS)+'秒 启动')
pass
##########################################################################################################################################
#去掉金字塔 PythonApi 已经强制载入!!!!!!!!!!!!!!!!!!
#from PythonApi import *
#import PythonApi
#print(PythonApi)
########################去掉的模块########################################################################################################
print('import 环境模块加载完成:######################################'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
# 参数定义区,这里定义的参数可以直接在context对象中获取。--(选择实现)
def parameter():
#input_par('ZongFengXian',1,0,1,0.01) #设置总风险度持仓比例
#input_par('DingShiQiS',10,1,60,1) #定时器设置 秒
print('def parameter 模块加载完成:###############################'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
def init(context):
#DingShiQiMs = context.DingShiQiS * 1000 #定时器设置转换毫秒
#settimer(handle_bar_1,DingShiQiMs) #handle_bar 定时执行
#settimer(handle_bar_2,DingShiQiMs) #handle_bar 定时执行
#print(settimer)
#print('####################设置交易模式: 0:自定义品种.1:自选股品种,2:持仓品种=:'+str(context.KC_1_CC_2)+'#################')
print('def init 模块加载完成####################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# before_trading此函数会在每天基准合约的策略交易开始前被调用,当天只会被调用一次。--(选择实现)
def before_trading(context):
print('def before_trading 模块加载完成###########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# after_trading函数会在每天交易结束后被调用,当天只会被调用一次。 --(选择实现)
def after_trading(context):
print('def after_trading 模块加载完成############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# order_status当委托下单,成交,撤单等与下单有关的动作时,该方法就会被调用。---(选择实现)
def order_status(context,order):
#print('def order_status_1 模块加载完成#########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
Orders = get_orders (order_book_id="all", type=1, account="") #合约代码,或者为"all"全部合约,必填项 0:只取未成交订单 1:取全部订单,必须填指定具体的交易帐号,若不指定帐号,则取默认登录帐号
#print(Orders)
#print('全部订单列表:'+str(order.order_book_id))
#判断柜台回报信息,是否为全部成交。
if order.status=='submitted':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/submitted"已报单未成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
if order.status=='tradeing"已成交':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/tradeing"已成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='filled':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/filled"全部成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='cancelled':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/cancelled"已撤单'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='inactive':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/inactive"无效单'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='connected':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/connected"已连接'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='disconnected':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/disconnected"连接断开'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
return
#print('def order_status模块计算完成###########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass #未完成
# order_action当查询交易接口信息时返回的通知---(选择实现)
#注意:该事件函数仅在融资融券、新股申购操作刷新动作时才会触发,一般账户无效。
#def order_action(context,type, account, datas)
pass
#########################################################################################################################################
#
#
#
#########################################################################################################################################
# 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
def handle_bar(context):
#print('def handle_bar_1 模块加载完成>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#获取最近一个订单状态。
id_list=get_orders(order_book_id="all", type=1, account="")
if not(id_list == None):
id_last=get_orders_id (id_list[-1].order_id)
#如果最近一次订单状态为未成交,则进行撤单操作。
if id_last.status =='submitted':
cancel_order (id_last.order_id)
pass
#gc.collect()
#print(str(gc.get_threshold())+'清理内存')
############################################################################## 在context中保存全局变量###################################
Test = 0 #检查模式 0 关闭 1开启
TimeCha = 0 #默认时间差 = 0
ZongFengXianDu = 1 #context.ZongFengXian #总账户风险度%
ZongYingKuiLv = 0.1 #总盈亏率%
ZongHuiCheBiLi = 0.01 #总账户回撤%
ZongChengBenBi = 10 #成本比设置
pass
HuiLuo = 0.02 #品种回落%
ZhangDieFu = 0.02 #品种涨跌幅%
ZhenFu = 0.015 #品种振幅%
YingKuiLv = 0.001 #品种盈亏率%
FengXianDu = 0.09 #品种风险度%
pass
BuyFengXianDu = 0 #品种风险度置零
SellFengXianDu = 0 #品种风险度置零
BuyAvgHoldingPrice = 0 #开仓持仓成本置零
SellAvgHoldingPrice = 0 #开空持仓成本置零
pass
BuyVol = 1 #设置默认每次下单量
SellVol = 1 #设置默认每次下单量
BuyMaxVol = 1 #设置默认买最大持仓量
SellMaxVol = 1 #设置默认卖最大持仓量
FangXiang = 0 #设置默认运行模式方向 = 0: 趋势 = 1,震荡 = 2,风控 = 0
pass
lastbuy = 0 #开多挂单置零
lastbuyping = 0 #平多挂单置零
lastsell = 0 #开空挂单置零
lastsellping = 0 #平空挂单置零
pass
NewAmount = 255 #设置账户断开
OrdAmount = 255 #设置账户断开
KeYongAmount = 255 #设置账户断开
###############################################################################登录账户###################################################
GetAccountBook = len(get_account_book()) #账户列表
#print('账户列表:'+str(GetAccountBook))
AccountBook = (isaccount()) #登录账户
#print('登录账户:'+str(AccountBook))
pass
if 1 == 0 or GetAccountBook != 1:
SleepS = int(datetime.datetime.now().strftime('%S'))
#SleepMin = int(datetime.datetime.now().strftime('%f')[:-3])/1000
#for i in range(SleepS):
# time.sleep(SleepMin)
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('账户列表:'+str(GetAccountBook)+'登录账户:'+str(AccountBook)+'系统错误!账户断开!交易中断!等待'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])+'/'+str(SleepS)+'秒启动')
return
##############################################################################时间判断####################################################
else:
if 1!=0:
DianNaoTime = datetime.datetime.now() ##获得当前时间->这是时间数组格式
DianNaoTime = int(DianNaoTime.strftime("%H%M%S")) #转换为指定的格式:
OpenTime0900_2300 = (90000 <= DianNaoTime <= 101500) or (103000 <= DianNaoTime <= 113000) \
or (133000 <= DianNaoTime <= 150000) or (210000 <= DianNaoTime <= 230000) #交易时间0900-2300
OpenTime2300_0100 = (230000 <= DianNaoTime <= 240000) or (0 <= DianNaoTime <= 10000) #交易时间2300-0100
OpenTime0100_0230 = (10000 <= DianNaoTime <= 23000) #交易时间0100-0230
pass
OpenTimeQuJian = 100 * 5 #设定开盘区间
OpenTime2100 = 210000 <= DianNaoTime <= (210000 + OpenTimeQuJian) #开盘1
OpenTime0900 = 90000 <= DianNaoTime <= (90000 + OpenTimeQuJian) #开盘2-1
OpenTime1030 = 103000 <= DianNaoTime <= (103000 + OpenTimeQuJian) #开盘2-2
OpenTime1330 = 133000 <= DianNaoTime <= (133000 + OpenTimeQuJian) #开盘2-3
pass
CloseTimeQuJian = 100 * 9 #设定收盘区间
CloseTime2300 = (225959 - CloseTimeQuJian) <= DianNaoTime <= 230000 #收盘1-1
CloseTime0100 = (5959 - CloseTimeQuJian) <= DianNaoTime <= 10000 #收盘1-2
CloseTime0230 = (22959 - CloseTimeQuJian) <= DianNaoTime <= 23000 #收盘1-3
CloseTime1015 = (101459 - CloseTimeQuJian) <= DianNaoTime <= 101500 #收盘2-1
CloseTime1130 = (112959 - CloseTimeQuJian) <= DianNaoTime <= 113000 #收盘2-2
CloseTime1500 = (145959 - CloseTimeQuJian) <= DianNaoTime <= 150000 #收盘3
#######################################################################################品种列表###########################################
RunInfoBaseBookId = context.run_info.base_book_id #基准合约代码run_info.base_book_id 合约池连续代码 order_book_id
#print('基准合约代码:'+str(RunInfoBaseBookId))
BaseGetInblocks = get_inblocks(RunInfoBaseBookId) #获取指定品种的所属板块
#print('获取指定品种的所属板块:'+str(BaseGetInblocks))
pass
Universe = context.universe #基准合约代码run_info.base_book_id 合约池连续代码 order_book_id
##print('合约池连续代码:'+str(Universe))
#UniverseGetInblocks=get_inblocks(Universe) #获取指定品种的所属板块
##print('获取指定品种的所属板块:'+str(UniverseGetInblocks))
pass
if 1!=0:#BaseGetInblocks == ['自选:自选股', '系统—指数:连续合约板块']: #'自选股:上海', '系统—指数:连续合约板块':
#GetBlocks2300_0100 = get_blocks ('自选股',1) #['SQAG00','SQAU00','INSC0000'] #夜盘1:00收盘品种
#GetBlocks2300_0230 = ['SQAG00','SQAU00','INSC0000'] #夜盘2:30收盘品种
#GetBlocks0900_2300 = get_blocks ('自选股',1) #日盘交易收盘品种
#print(GetBlocks0) #自设定池 控制策略交易时间是全部时间最长的品种
#GetBlocks1 = get_blocks ('自选股',1) #自选池 1分类板块 #0市场分类 1分类板块 2系统板块
#print(GetBlocks1)
#GetBlocks2 = get_portfolio_book(2,"")
#持仓品种 #投资组合持仓品种 指定查询类型,必填项, 期货 0投机 1保值 ; 股票 0普通 1融资 ; 期权 0非备兑 1备兑; 2全部类型, 该参数对回测无效
#print(GetBlocks2)
OpenCloseTime = CloseTime2300 == 1 or CloseTime0100 == 1 or CloseTime0230 == 1 or CloseTime1015 == 1 \
or CloseTime1130 == 1 or CloseTime1500 == 1 or OpenTime2100 == 1 or OpenTime0900 == 1 or OpenTime1030 == 1 \
or OpenTime1330 == 1 #测试
if OpenCloseTime == 1:
GetBlocks = get_portfolio_book(2,"") #开盘后5分钟和收盘前5分钟 只管理持仓交易!!!!不开新仓!!!!!。
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='KaiCang_10分钟结算持仓'
else:
if OpenTime0900_2300 ==1:
GetBlocks = get_blocks ('主力合约板块',1) #context.universe #get_blocks ('自选股',1) #切换参数设置自动交易模式
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='KaiCang_0900_2300自选股'
else:
if OpenTime2300_0100 ==1:
GetBlocks = ['SQSS00','SQZN00','SQSN00','SQCU00','SQPB00','SQNI00','SQAL00','SQAG00','SQAU00','INSC0000']
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='KaiCang_2300_0100自设股'
else:
if OpenTime0100_0230 ==1:
GetBlocks = ['SQAG00','SQAU00','INSC0000'] #自定义 黄金 白银 原油
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='KaiCang_0100_0230自定义'
else:
GetBlocks = get_portfolio_book(2,"") #非交易时间检查持仓
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='KaiCang_收市检查'
Test = 1
#print(GetBlocks)
#random.shuffle(GetBlocks) #随机打乱列表 更随机性
#print(GetBlocks)
MaxNum = len(GetBlocks) #总数量
if MaxNum == 0:
print(str(BanKuai)+str(MaxNum))
return
#print(str(GetBlocks))
Num = random.randrange(0,MaxNum,1) # random.randint(1,10)/randrange 随机取列表每次列表一个进行交易
FengXianDu = round(ZongFengXianDu / MaxNum,6) #动态风险度=总风险度/最大列表数量
##print(str(BanKuai)+'取合约列表:'+str(Num))
for index in range(len(GetBlocks)): #随机循环合约池
s = GetBlocks[Num]
#print(s)
s1 = get_dynainf(s,210) #品种主力合约代码
Name = get_dynainf(s1,219) #名称
else:
print('获取指定品种的所属板块:'+str(BaseGetInblocks))
print('合约池没有正常设置!自选股必须是连续合约,合约池导入自选股列表,基准合约为空')
return
#print('合约品种列表完成########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
########################################################准备账户刷新#####################################################################
if get_account(6) <= 255 or get_account(26) <= 255 or get_account(19) <= 255:
SleepS = int(datetime.datetime.now().strftime('%S'))
#SleepMin = int(datetime.datetime.now().strftime('%f')[:-3])/1000
#for i in range(SleepS):
# time.sleep(SleepMin)
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('账户异常!未登录!退出交易!''等待'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])\
+'/'+str(SleepS)+'秒启动')
return
###############################################################################################行情刷新####################################
else:
NewZuoShouJia = round(get_dynainf(s1,3),6) #获取最新昨收价
NewOpenJia = round(get_dynainf(s1,4),6) #获取最新今开价
NewHighJia = round(get_dynainf(s1,5),6) #获取最新最高价
NewLowJia = round(get_dynainf(s1,6),6) #获取最新最低价
NewJia = round(get_dynainf(s1,7),6) #获取最新成交价
NewJunJia = round(get_dynainf(s1,11),6) #获取最新均价
NewZhenFu = round(get_dynainf(s1,13),6) #获取最新振幅
NewZhangDieFu = round(get_dynainf(s1,14),6) #获取最新涨跌幅
#NewWeiBi = round(get_dynainf(s1,15),6) #委比
#NewWeiCha = round(get_dynainf(s1,16),6) #委差
NewBuyJia = round(get_dynainf(s1,20),6) #委买价
NewSellJia = round(get_dynainf(s1,21),6) #委卖价
NewZhangSu = round(get_dynainf(s1,24),6) #涨跌速
NewBuyOneVol = round(get_dynainf(s1,25),6) #25 买一量
#print('买一量'+str(NewBuyOneVol))
NewSellOneVol = round(get_dynainf(s1,31),6) #31 卖一量
#print('卖一量'+str(NewSellOneVol))
#NewJunLiang = round(get_dynainf(s1,38),6) #获取最新日均量
NewChiCangLiang = round(get_dynainf(s1,45),6) #获取45 最新持仓量
NewZhangTing = round(get_dynainf(s1,54),6) #获取最新涨停价
NewDieTing = round(get_dynainf(s1,55),6) #获取最新跌停价
NewQianChiCangLiang = round(get_dynainf(s1,60),6) #获取60 昨持仓量
NewJinJieSuan = round(get_dynainf(s1,61),6) #获取最新结算价
NewQianJieSuan = round(get_dynainf(s1,62),6) #获取昨日结算价
#NewUp = round(get_dynainf(s1,204),6) #上升劲道
#NewDn = round(get_dynainf(s1,205),6) #下降劲道
###############################################################################################账户刷新###################################
#print('handle_bar_Stop'+str(datetime.datetime.now()))
NewAmountFuDongYingKui = round(get_account(4),0) #当前交易帐户中的浮动盈亏
NewAmount = round(get_account(6),0) #当前交易帐户中的动态权益/资产值
KeYongAmount = round(get_account(19),0) #当前可用资金
OrdAmount = round(get_account(26),0) #上次结算准备金/期初余额
BaoZhengJinAmount = round(get_account(28),0) #28 占用保证金/证券市值
NewAmountPingCangYingKui = round(get_account(30),0) #平仓盈亏数额/回报卖出金额/融券盈亏
NewAmountShouXuFei = round(get_account(31),0) #当前交易帐户中的手续费
ZongYinKuiAmount = round((NewAmountFuDongYingKui + NewAmountPingCangYingKui - NewAmountShouXuFei),0) #账户总盈亏
if ZongYinKuiAmount==0 or BaoZhengJinAmount==0 or NewAmount==0:
AmountZongYingKuiLV = 0 #总盈亏率
AmountZongFengXianDu = 0 #总风险度
else:
AmountZongYingKuiLV = round(ZongYinKuiAmount / BaoZhengJinAmount,6) #总盈亏率
if AmountZongYingKuiLV == 0:
AmountZongFengXianDu = 0
else:
AmountZongFengXianDu = round(BaoZhengJinAmount / NewAmount,6) #总风险度
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/动态权益:'+str(NewAmount)+'/期初余额:'+str(OrdAmount)\
+'/可用资金:'+str(KeYongAmount)+'/手续费:'+str(NewAmountShouXuFei)+'/平仓盈亏:'+str(NewAmountPingCangYingKui)+'/浮动盈亏:'\
+str(NewAmountFuDongYingKui)+'/总盈亏率:'+str(AmountZongYingKuiLV)+'/总风险度:'+str(AmountZongFengXianDu))
pass
portfolio = get_portfolio (s1, 2) #账户持仓状态
pass
BuyQuantity = round(portfolio.buy_quantity,4) #开多持仓量
BuyMargin = round(portfolio.buy_margin,4) #开多占用保证金
BuyAvgHoldingPrice = round(portfolio.buy_avg_holding_price,4) #开多持仓均价(非结算持仓均价!!!)
BuyPnl = round(portfolio.pnl,4) #开多浮动盈亏
pass
SellQuantity = round(portfolio.sell_quantity,4) #开空持仓量
SellMargin = round(portfolio.sell_margin,4) #开空占用保证金
SellAvgHoldingPrice = round(portfolio.sell_avg_holding_price,4) #开空持仓均价(非结算持仓均价!!!)
SellPnl = round(portfolio.pnl,4) #开空浮动盈亏
pass
if BuyPnl == SellPnl and BuyPnl+SellPnl !=0: #持仓总盈亏
ZongPnl=round((BuyPnl+SellPnl)/2,4)
else:
ZongPnl=0
#print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/总浮动盈亏:'+str(ZongPnl))
pass
instruments = get_instruments(s1) #获取品种的合约基本信息
#instruments = get_instruments('SQRB00') #获取品种的合约基本信息
BuyBaoZhengJinLv = round(instruments.buy_margin_rate,6) #float 多头保证金率
#print(str(BuyBaoZhengJin))
SellBaoZhengJinLv = round(instruments.short_margin_rate,6) #float 空头保证金率
#print(str(SellBaoZhengJin))
HeYueDanWei = round(instruments.multipliter,6) #int 合约单位乘数
#print(str(HeYueDanWei))
MinJia = round(instruments.mintick,6) #float 最小变动价位
#print(str(MinJia))
MeiShouDanWei = round(instruments.round_lot,6) #int 每手单位,例如股票是100
#print(str(MeiShouDanWei))
#print(str(BanKuai)+'合约基本信息'+str(MinJia)+str(DanWei))
#MinJia = round(get_dynainf(s1,208),6) #取得合约最新最小变动价
#ChengShu = round(get_dynainf(s1,209),6) #取得最新合约的单位乘数
#print('合约的单位乘数'+str(ChengShu))
###############################################################################################账户计算###################################
KaiShouXuFei = round(get_charge(s1,get_dynainf(s1,7),1,0),6) #计算开仓所需手续费费用 交易类型,必填项,0开仓 1平仓
PingShouXuFei = round(get_charge(s1,get_dynainf(s1,7),1,1),6) #计算平仓所需手续费费用 交易类型,必填项,0开仓 1平仓
if 1 != 0 and \
MinJia * HeYueDanWei * MeiShouDanWei == 0 or NewQianJieSuan * HeYueDanWei * BuyBaoZhengJinLv * SellBaoZhengJinLv == 0 \
or FengXianDu * OrdAmount == 0 or (KaiShouXuFei + PingShouXuFei) ==0 :
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'!!!!!!!!!!!!!!!合约信息错误!!!更新合约信息!!!!!!!!!!!!!!!!!')
return
else:
MinJiaCha = round(MinJia * HeYueDanWei * MeiShouDanWei,6) #计算最小变动定价
pass
#计算公式:N手某期货合约占用保证金额=当日结算价×交易单位(合约乘数)×期货保证金率×N手。
BuyBaoZhengJin = round(NewQianJieSuan * HeYueDanWei * BuyBaoZhengJinLv * 1 ,0) #昨日多头保证金
#print('多头保证金'+str(BuyBaoZhengJin))
SellBaoZhengJin = round(NewQianJieSuan * HeYueDanWei * SellBaoZhengJinLv * 1 ,0) #昨日空头保证金
#print('空头保证金'+str(SellBaoZhengJin))
MinChenBenBi = round(MinJiaCha / (KaiShouXuFei + PingShouXuFei),6) #最小成本比
OrdBuyMaxVol = round(FengXianDu * OrdAmount / BuyBaoZhengJin ,0) #昨天 多 最大持仓量
OrdSellMaxVol = round(FengXianDu * OrdAmount / SellBaoZhengJin ,0) #昨天 空 最大持仓量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/昨天:'+'最大持仓量:'+str(OrdBuyMaxVol)+':'+str(OrdSellMaxVol)+'/空保证金:'+str(SellBaoZhengJin)+'/空保证金率:'\
+str(SellBaoZhengJinLv)+'/多保证金:'+str(BuyBaoZhengJin)+'/多保证金率:'+str(BuyBaoZhengJinLv)+'/最小成本比'+str(MinChenBenBi)\
+'/开手续费:'+str(KaiShouXuFei)+'/平手续费:'+str(PingShouXuFei)+'/最小单位:'+str(MinJia)+'/最小定价:'+str(MinJiaCha)\
+'/每手单位:'+str(MeiShouDanWei)+'/单位乘数:'+str(HeYueDanWei)+"/")
###############################################################################################多头持仓计算###############################
if BuyQuantity>0:
pass
#print(str(BanKuai)+str(Name)+'/D持仓:'+str(BuyQuantity)+'/均价:'+str(BuyAvgHoldingPrice))
BuyPnl = \
round((NewSellJia - BuyAvgHoldingPrice) / MinJia * MinJiaCha * BuyQuantity - (KaiShouXuFei + PingShouXuFei) * BuyQuantity,4) #开多浮动盈亏 对手价计算减去双向手续费
#print(str(BanKuai)+str(Name)+'/D持仓盈亏:'+str(BuyPnl))
if BuyMargin == 0 or get_account(6) == 0:
BuyFengXianDu = 0
else:
BuyFengXianDu = round(BuyMargin / get_account(6),6)
#print(str(BanKuai)+str(Name)+'/D持仓风险度:'+str(BuyFengXianDu))
pass
if BuyPnl == 0 or BuyMargin == 0 or BuyAvgHoldingPrice == 0:
BuyYingKuiLv = 0
NewBuyBaoZhengJinLv = 0
else:
BuyYingKuiLv = round(BuyPnl / BuyMargin,6)
#print(str(BanKuai)+str(Name)+'/D盈亏率:'+str(BuyYingKuiLv))
NewBuyBaoZhengJinLv = round(BuyMargin / BuyAvgHoldingPrice / HeYueDanWei / BuyQuantity ,6) #反推真实多头保证金率
#print('/D持保证金率:'+str(NewBuyBaoZhengJinLv))
pass
if FengXianDu>0 and KeYongAmount>255 and BuyMargin>0 and BuyQuantity>0:
BuyMaxVol = round((FengXianDu * KeYongAmount) / (BuyMargin / BuyQuantity),0)
#print(str(BanKuai)+str(Name)+'/D最大持仓:'+str(BuyMaxVol))
if 1< MinChenBenBi < BuyMaxVol and BuyVol != BuyMaxVol:
BuyVol = round(int(MinChenBenBi),0) #设置默认每次下单量
#SellVol = round(MinChenBenBi,0) #设置默认每次下单量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/多:最大持:'+str(BuyMaxVol)+'/持:'+str(BuyQuantity)+'/均价:'\
+str(BuyAvgHoldingPrice)+'/总浮盈亏:'+str(ZongPnl)+'/持盈亏:'+str(BuyPnl)+'/盈亏率:'+str(BuyYingKuiLv)+'/持风险度:'\
+str(BuyFengXianDu)+'/持保证金率:'+str(NewBuyBaoZhengJinLv)+'/')
###############################################################################################空头持仓计算##########################
if SellQuantity>0:
pass
#print(str(BanKuai)+str(Name)+'/K持仓:'+str(SellQuantity)+'/均价:'+str(SellAvgHoldingPrice))
SellPnl = \
round((SellAvgHoldingPrice - NewBuyJia) / MinJia * MinJiaCha * SellQuantity - (KaiShouXuFei + PingShouXuFei) * SellQuantity,4) #开空浮动盈亏 对手价计算减去双向手续费
#print(str(BanKuai)+str(Name)+'/K持仓盈亏:'+str(SellPnl))
if SellMargin == 0 or get_account(6) == 0:
SellFengXianDu = 0
else:
SellFengXianDu = round(SellMargin / get_account(6),6)
#print(str(BanKuai)+str(Name)+'/K持仓风险度:'+str(SellFengXianDu))
pass
if SellPnl == 0 or SellMargin == 0 or SellAvgHoldingPrice == 0:
SellYingKuiLv = 0
NewSellBaoZhengJinLv = 0
else:
SellYingKuiLv = round(SellPnl / SellMargin,6)
#print(str(BanKuai)+str(Name)+'/K盈亏率:'+str(SellYingKuiLv))
NewSellBaoZhengJinLv = round(SellMargin / SellAvgHoldingPrice / HeYueDanWei / SellQuantity,6) #反推真实多头保证金率
#print('/K持保证金率:'+str(NewSellBaoZhengJinLv))
pass
if FengXianDu > 0 and KeYongAmount > 255 and SellMargin > 0 and SellQuantity > 0:
SellMaxVol = round((FengXianDu * KeYongAmount) / (SellMargin / SellQuantity),0)
#print(str(BanKuai)+str(Name)+'/K最大持仓:'+str(SellMaxVol))
if 1< MinChenBenBi < SellMaxVol and SellVol != SellMaxVol:
#BuyVol = round(MinChenBenBi,0) #设置默认每次下单量
SellVol = round(int(MinChenBenBi),0) #设置默认每次下单量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/空:最大持:'+str(SellMaxVol)+'/持:'+str(SellQuantity)\
+'/均价:'+str(SellAvgHoldingPrice)+'/总浮盈亏:'+str(ZongPnl)+'/持盈亏:'+str(SellPnl)+'/盈亏率:'+str(SellYingKuiLv)\
+'/持风险度:'+str(SellFengXianDu)+'/持保证金率:'+str(NewSellBaoZhengJinLv)+'/')
##########################################################################################交易条件判断###################################
if not istradertime(s1): #不在交易时间,不进入交易段
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/不在交易时间/不进入交易段")
if Test == 1:
return
else:
return
else:
pass
if 1!=0:
pass
if 1!=0:
DianNaoTime = datetime.datetime.now() ##获得当前时间->这是时间数组格式
DianNaoTime = int(DianNaoTime.strftime("%H%M%S")) #转换为指定的格式:
ChengJIaoTime = int(round(get_dynainf(s1,207),0)) #行情报价最新一笔成交时间
#print(str(BanKuai)+str(Name)+'/电脑时间'+str(DianNaoTime))
#print(str(BanKuai)+str(Name)+'/报价时间'+str(ChengJIaoTime))
DianNaoTimeH = round(DianNaoTime / 10000,0) #取电脑时间小时数
ChengJIaoTimeH = round(ChengJIaoTime / 10000,0) #取交易时间小时数
XiaoShiShiCha = (DianNaoTimeH - ChengJIaoTimeH) #计算小时时间差
if DianNaoTimeH!=ChengJIaoTimeH: #小时数相等
if DianNaoTimeH == ChengJIaoTimeH:
TimeCha = round(DianNaoTime - ChengJIaoTime,0) #计算成交时间差
else:
if DianNaoTimeH > ChengJIaoTimeH: #小时数不相等
#print('交易小时>电脑小时:'+str(XiaoShiShiCha))
TimeCha = round(DianNaoTime - (ChengJIaoTime + abs(XiaoShiShiCha * 10000)),0) #计算成交时间差
pass
if DianNaoTimeH < ChengJIaoTimeH: #小时数不相等
#print('交易小时<电脑小时:'+str(XiaoShiShiCha))
TimeCha = round(DianNaoTime - (ChengJIaoTime - abs(XiaoShiShiCha * 10000)),0) #计算成交时间差
pass
#print('报价不活跃 情况完成######################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
########################################################################################总控 方向 模式 ################################
if NewAmount != 0 or NewAmountShouXuFei != 0 or OrdAmount != 0:
pass
if SellQuantity >= 0 or BuyQuantity >= 0:
AmountHuiCheJinE = round(NewAmount - NewAmountShouXuFei - OrdAmount,0) #最新账户回撤金额
HuiCheJinE = round(OrdAmount * ZongHuiCheBiLi,6) #设定回撤金额
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'+str(ZongHuiCheBiLi)+'/设定回撤金额:'+str(HuiCheJinE) )
if AmountHuiCheJinE < -HuiCheJinE or AmountHuiCheJinE > HuiCheJinE * 9:
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'\
+str(ZongHuiCheBiLi)+'/账户当日回撤:'+str(AmountHuiCheJinE)+'/大于触发阀值:'+str(HuiCheJinE)+'执行风控退出平仓交易!')
else:
if ZongPnl == 0 or BaoZhengJinAmount == 0:
NewZongHuiCheBiLi = 0
else:
NewZongHuiCheBiLi = round(ZongPnl / BaoZhengJinAmount,6)
if NewZongHuiCheBiLi < -ZongHuiCheBiLi: #回撤大于设定盈亏率 test!!!
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'\
+str(ZongHuiCheBiLi)+'/账户当日盈亏率:'+str(NewZongHuiCheBiLi)+'/大于回撤比例:'+str(ZongHuiCheBiLi)\
+'执行风控重启平仓交易!')
else:
if abs(int(TimeCha)) > 10 or NewChiCangLiang < 50000 or NewQianChiCangLiang < 50000 or NewBuyJia >= NewZhangTing or NewSellJia <= NewDieTing:
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/时差:'+str(TimeCha)\
+'秒/######################报价不活跃=======平仓######################')
pass
else:
if 1 != 0 and ( OpenCloseTime == 1 ): #测试
#FangXiang = 0
print(str(BanKuai)+str(Name)+'=====================测试收盘平仓========================')
pass
if 1 != 0:
if NewJia > NewLowJia > NewQianJieSuan: #均价 大于 前均价 趋势多
FangXiang = 1
pass
if NewJia < NewHighJia < NewQianJieSuan: #均价 小于 前均价 趋势空
FangXiang = -1
pass
if NewZhenFu < ZhenFu:
FangXiang = 0
pass
if CloseTime1500 == 1: #收盘平仓
FangXiang = 0
pass
#print('计算持仓 盈亏 账户 情况完成##############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#########################################################################################方向检查########################################
if FangXiang == 0:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"风控:0:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
if FangXiang == 1:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"趋势:1:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
if FangXiang == 2:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"震荡:2:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
#print('检查方向完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
####################################################### 下单时对接盘口 #开仓平仓量大于买卖一量 重新计算修改下单量 ###########################
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'下单对接盘口之前:'+' BuyVol:'+str(BuyVol)+' SellVol:'+str(SellVol))
if BuyVol > NewSellOneVol > 0:
BuyVol = int(NewSellOneVol) #卖一量对接
else:
BuyVol = int(BuyVol) #买开平量(开仓下单)
if SellVol > NewBuyOneVol > 0:
SellVol = int(NewBuyOneVol) #买一量对接
else:
SellVol = int(SellVol) #卖开平量(开仓下单)
if BuyQuantity !=0:
if BuyQuantity > NewSellOneVol > 0:
NewBuyVol = int(NewSellOneVol) #卖一量对接
else:
NewBuyVol = int(BuyQuantity) #买平持仓量(平仓下单)
#print('下单对接盘口之后:'+' NewBuyVol:'+str(NewBuyVol))
if SellQuantity !=0:
if SellQuantity > NewBuyOneVol > 0:
NewSellVol = int(NewBuyOneVol) #买一量对接
else:
NewSellVol = int(SellQuantity) #卖平持仓量(平仓下单)
#print('下单对接盘口之后:'+' NewSellVol:'+str(NewSellVol))
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'下单对接盘口之后:'+' BuyVol:'+str(BuyVol)+' SellVol:'+str(SellVol))
#print('盘口下单置换完成########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
##########################################################总平仓下单#####################################################################
if 1 != 0\
and (FangXiang == 0 ): #开关 1==0 关闭 1 != 0 打开
if BuyQuantity != 0:
sell_close(s1,"ThisClose",volume = NewBuyVol,repeat = 1,serial_id = 1) #账户回撤大于设定值%
pass
if SellQuantity != 0:
buy_close(s1,"ThisClose",volume = NewSellVol,repeat = 1,serial_id = 2) #账户回撤大于设定值%
pass
#print('回撤下单完成#########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
################################################################ 品种结束循环 重启!######################################################
if 1 != 1 \
and ( (BuyMaxVol != BuyVol and SellMaxVol != SellVol) or BuyPnl !=0 or SellPnl !=0 or KaiShouXuFei != 0 \
or PingShouXuFei != 0 or BuyQuantity > BuyVol or SellQuantity > SellVol ): ##构建计算条件
ChengBen = (KaiShouXuFei + PingShouXuFei) * (BuyQuantity + SellQuantity) * ZongChengBenBi #计算总持仓成本比金额
BuyChengBen = (KaiShouXuFei + PingShouXuFei) * BuyQuantity * MinChenBenBi #计算多持仓成本比金额
SellChengBen = (KaiShouXuFei + PingShouXuFei) * SellQuantity * MinChenBenBi #计算空持仓成本比金额
pass
if ZongPnl > ChengBen and (BuyPnl > BuyChengBen and SellPnl > SellChengBen): #多空总持仓都盈利,而且盈利都大于成本比!
pass
if BuyQuantity > 0 and SellQuantity > 0: #多空 同时持仓盈利 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 3)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 4)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 同时持仓盈利 风控趋势震荡对平持仓 结束循环重启!')
pass
#print('同时持仓盈利下单完成#############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
elif ZongPnl > ChengBen and (BuyPnl > BuyChengBen or SellPnl > SellChengBen): #多空总持仓有分别盈亏,总计盈利大于成本比!
pass
if BuyQuantity > 0 or SellQuantity > 0: #多空 分别 (单向或者双向) 持仓盈亏 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 5)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 6)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 分别 (单向或者双向) 持仓合并盈利 风控趋势震荡对平持仓 结束循环重启!')
elif ZongPnl < -ChengBen and (BuyPnl < -BuyChengBen or SellPnl < -SellChengBen): #多空总持仓有分别亏,总计亏大于成本比!
pass
if BuyQuantity > 0 or SellQuantity > 0: #多空 分别 (单向或者双向) 持仓盈亏 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 7)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 8)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 分别 (单向或者双向) 持仓合并亏损 风控趋势震荡对平持仓 结束循环重启!')
else:
pass
#print('分别持仓盈亏下单完成#####################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
######################################################################## 开始构建信号下单 ###############################################
#使用buy_open、sell_close等方法下单
#下单示例:
#buy_open(s1, "Market", volume=100) # 市价开多
pass
######################################################################趋势开多########################################################
if ( NewZhangSu < -(NewZhenFu * ZhenFu) ) and FangXiang == 1: #判断趋势 做多
##print(s1+'趋势多')
if BuyQuantity == 0:
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 9) #开多试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
#sell_open(s1,"ThisClose",volume = SellVol,repeat=0,serial_id = 2)
pass
#if BuyQuantity != 0 and BuyQuantity < BuyMaxVol:
#buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 8)
#####################################################################多止盈止损########################################################
if BuyQuantity > 0 and FangXiang == 1:
##print(s1)
##print(BuyAvgHoldingPrice)
#BuyHuiLuo = (NewJia - BuyAvgHoldingPrice) / BuyAvgHoldingPrice
##print(s1+"/"+str(BuyHuiLuo)+"/"+str(HuiLuo))
if BuyQuantity > BuyMaxVol:
sell_close(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 10) #持仓量大于最大持仓量 平多
pass
#if BuyYingKuiLv < -YingKuiLv and SellQuantity < SellMaxVol:
#sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 10) #多亏阀值止损 反手开空
pass
#####################################################################趋势开空#########################################################
if ( NewZhangSu > (NewZhenFu * ZhenFu) ) and FangXiang == -1: #判断趋势 做空
#print(s1+'趋势空')
if SellQuantity == 0:
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 11) #开空试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
#buy_open(s1,"ThisClose",volume = BuyVol,repeat=0,serial_id = 5)
pass
#if SellQuantity != 0 and SellQuantity < SellMaxVol:
#sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 11)
#####################################################################空止盈止损########################################################
if SellQuantity > 0 and FangXiang == -1:
##print(s1)
##print(SellAvgHoldingPrice)
#SellHuiLuo = (SellAvgHoldingPrice - NewJia) / SellAvgHoldingPrice
##print(s1+"/"+str(SellHuiLuo)+"/"+str(HuiLuo))
if SellQuantity > SellMaxVol:
buy_close(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 12) #持仓量大于最大持仓量 平空
pass
#if SellYingKuiLv < -YingKuiLv and BuyQuantity < BuyMaxVol:
#buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 14) #空亏阀值止损 反手开多
pass
#print('趋势下单完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#####################################################################震荡开仓###########################################################
if BuyQuantity == 0 and FangXiang == 2: #震荡做多
##print(s1+'震荡多')
if NewZhangSu < -(NewZhenFu * ZhenFu):
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 13) #开多试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if BuyQuantity != 0 and FangXiang == 2: #震荡做多
if BuyQuantity < BuyMaxVol and NewZhangSu < -(NewZhenFu * ZhenFu):
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 14) #开多仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if SellQuantity == 0 and FangXiang == 2: #震荡做空
##print(s1+'震荡空')
if NewZhangSu > (NewZhenFu * ZhenFu):
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 15) #开空试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if SellQuantity != 0 and FangXiang == 2: #震荡做空
if SellQuantity < SellMaxVol and NewZhangSu > (NewZhenFu * ZhenFu):
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 16) #开空仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
#print('震荡下单完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#########################################################################################################################################
#
#
#
#
#########################################################################################################################################
#!!!!!!!!!!!!!!!!!!!! 系统有BUG 去掉 !!!!!!!!!!
# exit函数会在测评结束或者停止策略运行时会被调用。---(选择实现)
#def exit(context):
#killtimer(handle_bar_1) #终止计时器
#killtimer(handle_bar_2) #终止计时器
#print("终止计时器/策略手动已退出!")
#gc.collect()
#print(str(gc.get_threshold())+'清理内存')
#return
#print('最后一行完成<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
return
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!持仓管理模块!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!/usr/local/bin/python
# -*- coding:utf-8 -*-
##########################################################################################################################################
#import logging #python 原生内置记录调试输出模块
#print(logging)
#from logging.handlers import RotatingFileHandler
#print( RotatingFileHandler)
#########################################################################################################################################
# 设置打印日志的级别,level级别以上的日志会打印出
# level=logging.DEBUG 、INFO 、WARNING、ERROR、CRITICAL
# format参数中可能用到的格式化串
# %(name)s Logger的名字
# %(levelno)s 数字形式的日志级别
# %(levelname)s 文本形式的日志级别
# %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
# %(filename)s 调用日志输出函数的模块的文件名
# %(module)s 调用日志输出函数的模块名
# %(funcName)s 调用日志输出函数的函数名
# %(lineno)d 调用日志输出函数的语句所在的代码行
# %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
# %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
# %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
# %(thread)d 线程ID。可能没有
# %(threadName)s 线程名。可能没有
# %(process)d 进程ID。可能没有
# %(message)s用户输出的消息
#######################################################################################################################################
#def logging_fun():
# # 创建日志的记录等级设
# logging.basicConfig(level=logging.DEBUG)
# # 创建日志记录器,指明日志保存的路径,每个日志文件的最大值,保存的日志文件个数上限
# log_handle = RotatingFileHandler("C://py_ZhangSu_ChiCang_log.txt", maxBytes=1024 * 1024, backupCount=5)
# # 创建日志记录的格式
# formatter = logging.Formatter("format = '%(asctime)s - %(filename)s - %(module)s - %(funcName)s - [line:%(lineno)d] - %(levelname)s - %(thread)d - %(threadName)s - %(process)d - %(message)s',")
# # 为创建的日志记录器设置日志记录格式
# log_handle.setFormatter(formatter)
# # 为全局的日志工具对象添加日志记录器
# logging.getLogger().addHandler(log_handle)
# logging.warning('用来用来打印警告信息')
# logging.error('一般用来打印一些错误信息')
# logging.critical('用来打印一些致命的错误信息,等级最高')
# pass
#logging_fun()
##########################################################################################################################################
#import unittest #python 原生内置测试test模块
#print(unittest)
import datetime #python 原生内置日期模块
print(datetime)
import random #python 原生内置随机模块
print(random)
import time #python 原生内置时间模块
print(time)
#import gc #python原生内存清理模块
#print(gc)
#import threading #python原生等待 不支持
#print(threading)
#event = threading.Event()
#event.wait(SleepS)
SleepS = int(datetime.datetime.now().strftime('%S'))
SleepMin = 0.1 #int(datetime.datetime.now().strftime('%f')[:-3])/1000
#设定启动等待时间 秒
#for i in range(SleepS):
# time.sleep(SleepMin) #time.sleep(SleepS) #python 原生内置暂停
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('启动中!等待账户登录后:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])+"/"+str(SleepS)+'秒 启动')
pass
##########################################################################################################################################
#去掉金字塔 PythonApi 已经强制载入!!!!!!!!!!!!!!!!!!
#from PythonApi import *
#import PythonApi
#print(PythonApi)
########################去掉的模块########################################################################################################
print('import 环境模块加载完成:######################################'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
# 参数定义区,这里定义的参数可以直接在context对象中获取。--(选择实现)
def parameter():
#input_par('ZongFengXian',1,0,1,0.01) #设置总风险度持仓比例
#input_par('DingShiQiS',10,1,60,1) #定时器设置 秒
print('def parameter 模块加载完成:###############################'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。--(必须实现)
def init(context):
#DingShiQiMs = context.DingShiQiS * 1000 #定时器设置转换毫秒
#settimer(handle_bar_1,DingShiQiMs) #handle_bar 定时执行
#settimer(handle_bar_2,DingShiQiMs) #handle_bar 定时执行
#print(settimer)
#print('####################设置交易模式: 0:自定义品种.1:自选股品种,2:持仓品种=:'+str(context.KC_1_CC_2)+'#################')
print('def init 模块加载完成####################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# before_trading此函数会在每天基准合约的策略交易开始前被调用,当天只会被调用一次。--(选择实现)
def before_trading(context):
print('def before_trading 模块加载完成###########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# after_trading函数会在每天交易结束后被调用,当天只会被调用一次。 --(选择实现)
def after_trading(context):
print('def after_trading 模块加载完成############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
# order_status当委托下单,成交,撤单等与下单有关的动作时,该方法就会被调用。---(选择实现)
def order_status(context,order):
#print('def order_status_1 模块加载完成#########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
Orders = get_orders (order_book_id="all", type=1, account="") #合约代码,或者为"all"全部合约,必填项 0:只取未成交订单 1:取全部订单,必须填指定具体的交易帐号,若不指定帐号,则取默认登录帐号
#print(Orders)
#print('全部订单列表:'+str(order.order_book_id))
#判断柜台回报信息,是否为全部成交。
if order.status=='submitted':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/submitted"已报单未成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
if order.status=='tradeing"已成交':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/tradeing"已成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='filled':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/filled"全部成交'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='cancelled':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/cancelled"已撤单'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='inactive':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/inactive"无效单'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='connected':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/connected"已连接'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass
if order.status=='disconnected':
#订单状态 "submitted"已报单未成交 "tradeing"已成交 "filled"全部成交 "cancelled"已撤单 "inactive"无效单 "connected"已连接 "disconnected"连接断开
print('全部订单列表:'+str(order.order_book_id)+':'+str(order.status)+'/disconnected"连接断开'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
return
#print('def order_status模块计算完成###########################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
pass #未完成
# order_action当查询交易接口信息时返回的通知---(选择实现)
#注意:该事件函数仅在融资融券、新股申购操作刷新动作时才会触发,一般账户无效。
#def order_action(context,type, account, datas)
pass
#########################################################################################################################################
#
#
#
#########################################################################################################################################
#########################################################################################################################################
#
#
#
#
#########################################################################################################################################
# 你选择的品种的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新。--(必须实现)
def handle_bar(context):
#print('def handle_bar_2 模块加载完成:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#print('def handle_bar_1 模块加载完成>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#获取最近一个订单状态。
id_list=get_orders(order_book_id="all", type=1, account="")
if not(id_list == None):
id_last=get_orders_id (id_list[-1].order_id)
#如果最近一次订单状态为未成交,则进行撤单操作。
if id_last.status =='submitted':
cancel_order (id_last.order_id)
pass
#gc.collect()
#print(str(gc.get_threshold())+'清理内存')
############################################################################## 在context中保存全局变量###################################
Test = 0 #检查模式 0 关闭 1开启
TimeCha = 0 #默认时间差 = 0
ZongFengXianDu = 1 #context.ZongFengXian #总账户风险度%
ZongYingKuiLv = 0.1 #总盈亏率%
ZongHuiCheBiLi = 0.01 #总账户回撤%
ZongChengBenBi = 10 #成本比设置
pass
HuiLuo = 0.02 #品种回落%
ZhangDieFu = 0.02 #品种涨跌幅%
ZhenFu = 0.015 #品种振幅%
YingKuiLv = 0.02 #品种盈亏率%
FengXianDu = 0.09 #品种风险度%
pass
BuyFengXianDu = 0 #品种风险度置零
SellFengXianDu = 0 #品种风险度置零
BuyAvgHoldingPrice = 0 #开仓持仓成本置零
SellAvgHoldingPrice = 0 #开空持仓成本置零
pass
BuyVol = 1 #设置默认每次下单量
SellVol = 1 #设置默认每次下单量
BuyMaxVol = 1 #设置默认买最大持仓量
SellMaxVol = 1 #设置默认卖最大持仓量
FangXiang = 0 #设置默认运行模式方向 = 0: 趋势 = 1,震荡 = 2,风控 = 0
pass
lastbuy = 0 #开多挂单置零
lastbuyping = 0 #平多挂单置零
lastsell = 0 #开空挂单置零
lastsellping = 0 #平空挂单置零
pass
NewAmount = 255 #设置账户断开
OrdAmount = 255 #设置账户断开
KeYongAmount = 255 #设置账户断开
###############################################################################登录账户###################################################
GetAccountBook = len(get_account_book()) #账户列表
#print('账户列表:'+str(GetAccountBook))
AccountBook = (isaccount()) #登录账户
#print('登录账户:'+str(AccountBook))
pass
if 1 == 0 or GetAccountBook != 1:
SleepS = int(datetime.datetime.now().strftime('%S'))
#SleepMin = int(datetime.datetime.now().strftime('%f')[:-3])/1000
#for i in range(SleepS):
# time.sleep(SleepMin)
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('账户列表:'+str(GetAccountBook)+'登录账户:'+str(AccountBook)+'系统错误!账户断开!交易中断!等待'\
+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])+'/'+str(SleepS)+'秒启动')
return
##############################################################################时间判断####################################################
else:
if 1!=0:
DianNaoTime = datetime.datetime.now() ##获得当前时间->这是时间数组格式
DianNaoTime = int(DianNaoTime.strftime("%H%M%S")) #转换为指定的格式:
OpenTime0900_2300 = (90000 <= DianNaoTime <= 101500) or (103000 <= DianNaoTime <= 113000) \
or (133000 <= DianNaoTime <= 150000) or (210000 <= DianNaoTime <= 230000) #交易时间0900-2300
OpenTime2300_0100 = (230000 <= DianNaoTime <= 240000) or (0 <= DianNaoTime <= 10000) #交易时间2300-0100
OpenTime0100_0230 = (10000 <= DianNaoTime <= 23000) #交易时间0100-0230
pass
OpenTimeQuJian = 100 * 5 #设定开盘区间
OpenTime2100 = 210000 <= DianNaoTime <= (210000 + OpenTimeQuJian) #开盘1
OpenTime0900 = 90000 <= DianNaoTime <= (90000 + OpenTimeQuJian) #开盘2-1
OpenTime1030 = 103000 <= DianNaoTime <= (103000 + OpenTimeQuJian) #开盘2-2
OpenTime1330 = 133000 <= DianNaoTime <= (133000 + OpenTimeQuJian) #开盘2-3
pass
CloseTimeQuJian = 100 * 9 #设定收盘区间
CloseTime2300 = (225959 - CloseTimeQuJian) <= DianNaoTime <= 230000 #收盘1-1
CloseTime0100 = (5959 - CloseTimeQuJian) <= DianNaoTime <= 10000 #收盘1-2
CloseTime0230 = (22959 - CloseTimeQuJian) <= DianNaoTime <= 23000 #收盘1-3
CloseTime1015 = (101459 - CloseTimeQuJian) <= DianNaoTime <= 101500 #收盘2-1
CloseTime1130 = (112959 - CloseTimeQuJian) <= DianNaoTime <= 113000 #收盘2-2
CloseTime1500 = (145959 - CloseTimeQuJian) <= DianNaoTime <= 150000 #收盘3
#######################################################################################品种列表###########################################
RunInfoBaseBookId = context.run_info.base_book_id #基准合约代码run_info.base_book_id 合约池连续代码 order_book_id
#print('基准合约代码:'+str(RunInfoBaseBookId))
BaseGetInblocks = get_inblocks(RunInfoBaseBookId) #获取指定品种的所属板块
#print('获取指定品种的所属板块:'+str(BaseGetInblocks))
pass
Universe = context.universe #基准合约代码run_info.base_book_id 合约池连续代码 order_book_id
##print('合约池连续代码:'+str(Universe))
#UniverseGetInblocks=get_inblocks(Universe) #获取指定品种的所属板块
##print('获取指定品种的所属板块:'+str(UniverseGetInblocks))
pass
if 1!=0:#BaseGetInblocks == ['自选:自选股', '系统—指数:连续合约板块']: #'自选股:上海', '系统—指数:连续合约板块':
#GetBlocks2300_0100 = get_blocks ('自选股',1) #['SQAG00','SQAU00','INSC0000'] #夜盘1:00收盘品种
#GetBlocks2300_0230 = ['SQAG00','SQAU00','INSC0000'] #夜盘2:30收盘品种
#GetBlocks0900_2300 = get_blocks ('自选股',1) #日盘交易收盘品种
#print(GetBlocks0) #自设定池 控制策略交易时间是全部时间最长的品种
#GetBlocks1 = get_blocks ('自选股',1) #自选池 1分类板块 #0市场分类 1分类板块 2系统板块
#print(GetBlocks1)
#GetBlocks2 = get_portfolio_book(2,"")
#持仓品种 #投资组合持仓品种 指定查询类型,必填项, 期货 0投机 1保值 ; 股票 0普通 1融资 ; 期权 0非备兑 1备兑; 2全部类型, 该参数对回测无效
#print(GetBlocks2)
OpenCloseTime = CloseTime2300 == 1 or CloseTime0100 == 1 or CloseTime0230 == 1 or CloseTime1015 == 1 \
or CloseTime1130 == 1 or CloseTime1500 == 1 or OpenTime2100 == 1 or OpenTime0900 == 1 or OpenTime1030 == 1 \
or OpenTime1330 == 1 #测试
if OpenCloseTime == 1:
GetBlocks = get_portfolio_book(2,"") #开盘后5分钟和收盘前5分钟 只管理持仓交易!!!!不开新仓!!!!!。
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='ChiCang_10分钟结算持仓'
else:
if OpenTime0900_2300 ==1:
GetBlocks = get_portfolio_book(2,"") #get_blocks ('自选股',1) #切换参数设置自动交易模式
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='ChiCang_0900_2300自选股'
else:
if OpenTime2300_0100 ==1:
GetBlocks = get_portfolio_book(2,"") #get_blocks ('自设股',1) #切换参数设置自动交易模式
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='ChiCang_2300_0100自设股'
else:
if OpenTime0100_0230 ==1:
GetBlocks = get_portfolio_book(2,"") #['SQAG00','SQAU00','INSC0000'] #自定义 黄金 白银 原油
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='ChiCang_0100_0230自定义'
else:
GetBlocks = get_portfolio_book(2,"") #非交易时间检查持仓
random.shuffle(GetBlocks) #随机打乱列表 更随机性
BanKuai='ChiCang_收市检查'
Test = 1
#print(GetBlocks)
#random.shuffle(GetBlocks) #随机打乱列表 更随机性
#print(GetBlocks)
MaxNum = len(GetBlocks) #总数量
if MaxNum == 0:
print(str(BanKuai)+str(MaxNum))
return
#print(str(GetBlocks))
Num = random.randrange(0,MaxNum,1) # random.randint(1,10)/randrange 随机取列表每次列表一个进行交易
FengXianDu = round(ZongFengXianDu / MaxNum,6) #动态风险度=总风险度/最大列表数量
##print(str(BanKuai)+'取合约列表:'+str(Num))
for index in range(len(GetBlocks)): #随机循环合约池
s = GetBlocks[Num]
#print(s)
s1 = get_dynainf(s,210) #品种主力合约代码
Name = get_dynainf(s1,219) #名称
else:
print('获取指定品种的所属板块:'+str(BaseGetInblocks))
print('合约池没有正常设置!自选股必须是连续合约,合约池导入自选股列表,基准合约为空')
return
#print('合约品种列表完成########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
########################################################准备账户刷新#####################################################################
if get_account(6) <= 255 or get_account(26) <= 255 or get_account(19) <= 255:
SleepS = int(datetime.datetime.now().strftime('%S'))
#SleepMin = int(datetime.datetime.now().strftime('%f')[:-3])/1000
#for i in range(SleepS):
# time.sleep(SleepMin)
#event.wait(SleepS)
#if int(datetime.datetime.now().strftime('%S')) == int(SleepS):
print('账户异常!未登录!退出交易!''等待'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])\
+'/'+str(SleepS)+'秒启动')
return
###############################################################################################行情刷新####################################
else:
NewZuoShouJia = round(get_dynainf(s1,3),6) #获取最新昨收价
NewOpenJia = round(get_dynainf(s1,4),6) #获取最新今开价
NewHighJia = round(get_dynainf(s1,5),6) #获取最新最高价
NewLowJia = round(get_dynainf(s1,6),6) #获取最新最低价
NewJia = round(get_dynainf(s1,7),6) #获取最新成交价
NewJunJia = round(get_dynainf(s1,11),6) #获取最新均价
NewZhenFu = round(get_dynainf(s1,13),6) #获取最新振幅
NewZhangDieFu = round(get_dynainf(s1,14),6) #获取最新涨跌幅
#NewWeiBi = round(get_dynainf(s1,15),6) #委比
#NewWeiCha = round(get_dynainf(s1,16),6) #委差
NewBuyJia = round(get_dynainf(s1,20),6) #委买价
NewSellJia = round(get_dynainf(s1,21),6) #委卖价
NewZhangSu = round(get_dynainf(s1,24),6) #涨跌速
NewBuyOneVol = round(get_dynainf(s1,25),6) #25 买一量
#print('买一量'+str(NewBuyOneVol))
NewSellOneVol = round(get_dynainf(s1,31),6) #31 卖一量
#print('卖一量'+str(NewSellOneVol))
#NewJunLiang = round(get_dynainf(s1,38),6) #获取最新日均量
NewChiCangLiang = round(get_dynainf(s1,45),6) #获取45 最新持仓量
NewZhangTing = round(get_dynainf(s1,54),6) #获取最新涨停价
NewDieTing = round(get_dynainf(s1,55),6) #获取最新跌停价
NewQianChiCangLiang = round(get_dynainf(s1,60),6) #获取60 昨持仓量
NewJinJieSuan = round(get_dynainf(s1,61),6) #获取最新结算价
NewQianJieSuan = round(get_dynainf(s1,62),6) #获取昨日结算价
#NewUp = round(get_dynainf(s1,204),6) #上升劲道
#NewDn = round(get_dynainf(s1,205),6) #下降劲道
###############################################################################################账户刷新###################################
#print('handle_bar_Stop'+str(datetime.datetime.now()))
NewAmountFuDongYingKui = round(get_account(4),0) #当前交易帐户中的浮动盈亏
NewAmount = round(get_account(6),0) #当前交易帐户中的动态权益/资产值
KeYongAmount = round(get_account(19),0) #当前可用资金
OrdAmount = round(get_account(26),0) #上次结算准备金/期初余额
BaoZhengJinAmount = round(get_account(28),0) #28 占用保证金/证券市值
NewAmountPingCangYingKui = round(get_account(30),0) #平仓盈亏数额/回报卖出金额/融券盈亏
NewAmountShouXuFei = round(get_account(31),0) #当前交易帐户中的手续费
ZongYinKuiAmount = round((NewAmountFuDongYingKui + NewAmountPingCangYingKui - NewAmountShouXuFei),0) #账户总盈亏
if ZongYinKuiAmount==0 or BaoZhengJinAmount==0 or NewAmount==0:
AmountZongYingKuiLV = 0 #总盈亏率
AmountZongFengXianDu = 0 #总风险度
else:
AmountZongYingKuiLV = round(ZongYinKuiAmount / BaoZhengJinAmount,6) #总盈亏率
if AmountZongYingKuiLV == 0:
AmountZongFengXianDu = 0
else:
AmountZongFengXianDu = round(BaoZhengJinAmount / NewAmount,6) #总风险度
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/动态权益:'+str(NewAmount)+'/期初余额:'+str(OrdAmount)\
+'/可用资金:'+str(KeYongAmount)+'/手续费:'+str(NewAmountShouXuFei)+'/平仓盈亏:'+str(NewAmountPingCangYingKui)+'/浮动盈亏:'\
+str(NewAmountFuDongYingKui)+'/总盈亏率:'+str(AmountZongYingKuiLV)+'/总风险度:'+str(AmountZongFengXianDu))
pass
portfolio = get_portfolio (s1, 2) #账户持仓状态
pass
BuyQuantity = round(portfolio.buy_quantity,4) #开多持仓量
BuyMargin = round(portfolio.buy_margin,4) #开多占用保证金
BuyAvgHoldingPrice = round(portfolio.buy_avg_holding_price,4) #开多持仓均价(非结算持仓均价!!!)
BuyPnl = round(portfolio.pnl,4) #开多浮动盈亏
pass
SellQuantity = round(portfolio.sell_quantity,4) #开空持仓量
SellMargin = round(portfolio.sell_margin,4) #开空占用保证金
SellAvgHoldingPrice = round(portfolio.sell_avg_holding_price,4) #开空持仓均价(非结算持仓均价!!!)
SellPnl = round(portfolio.pnl,4) #开空浮动盈亏
pass
if BuyPnl == SellPnl and BuyPnl+SellPnl !=0: #持仓总盈亏
ZongPnl=round((BuyPnl+SellPnl)/2,4)
else:
ZongPnl=0
#print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/总浮动盈亏:'+str(ZongPnl))
pass
instruments = get_instruments(s1) #获取品种的合约基本信息
#instruments = get_instruments('SQRB00') #获取品种的合约基本信息
BuyBaoZhengJinLv = round(instruments.buy_margin_rate,6) #float 多头保证金率
#print(str(BuyBaoZhengJin))
SellBaoZhengJinLv = round(instruments.short_margin_rate,6) #float 空头保证金率
#print(str(SellBaoZhengJin))
HeYueDanWei = round(instruments.multipliter,6) #int 合约单位乘数
#print(str(HeYueDanWei))
MinJia = round(instruments.mintick,6) #float 最小变动价位
#print(str(MinJia))
MeiShouDanWei = round(instruments.round_lot,6) #int 每手单位,例如股票是100
#print(str(MeiShouDanWei))
#print(str(BanKuai)+'合约基本信息'+str(MinJia)+str(DanWei))
#MinJia = round(get_dynainf(s1,208),6) #取得合约最新最小变动价
#ChengShu = round(get_dynainf(s1,209),6) #取得最新合约的单位乘数
#print('合约的单位乘数'+str(ChengShu))
###############################################################################################账户计算###################################
KaiShouXuFei = round(get_charge(s1,get_dynainf(s1,7),1,0),6) #计算开仓所需手续费费用 交易类型,必填项,0开仓 1平仓
PingShouXuFei = round(get_charge(s1,get_dynainf(s1,7),1,1),6) #计算平仓所需手续费费用 交易类型,必填项,0开仓 1平仓
if 1 != 0 and \
MinJia * HeYueDanWei * MeiShouDanWei == 0 or NewQianJieSuan * HeYueDanWei * BuyBaoZhengJinLv * SellBaoZhengJinLv == 0 \
or FengXianDu * OrdAmount == 0 or (KaiShouXuFei + PingShouXuFei) ==0 :
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'!!!!!!!!!!!!!!!合约信息错误!!!更新合约信息!!!!!!!!!!!!!!!!!')
return
else:
MinJiaCha = round(MinJia * HeYueDanWei * MeiShouDanWei,6) #计算最小变动定价
pass
#计算公式:N手某期货合约占用保证金额=当日结算价×交易单位(合约乘数)×期货保证金率×N手。
BuyBaoZhengJin = round(NewQianJieSuan * HeYueDanWei * BuyBaoZhengJinLv * 1 ,0) #昨日多头保证金
#print('多头保证金'+str(BuyBaoZhengJin))
SellBaoZhengJin = round(NewQianJieSuan * HeYueDanWei * SellBaoZhengJinLv * 1 ,0) #昨日空头保证金
#print('空头保证金'+str(SellBaoZhengJin))
MinChenBenBi = round(MinJiaCha / (KaiShouXuFei + PingShouXuFei),6) #最小成本比
OrdBuyMaxVol = round(FengXianDu * OrdAmount / BuyBaoZhengJin ,0) #昨天 多 最大持仓量
OrdSellMaxVol = round(FengXianDu * OrdAmount / SellBaoZhengJin ,0) #昨天 空 最大持仓量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/昨天:'+'最大持仓量:'+str(OrdBuyMaxVol)+':'+str(OrdSellMaxVol)+'/空保证金:'+str(SellBaoZhengJin)+'/空保证金率:'\
+str(SellBaoZhengJinLv)+'/多保证金:'+str(BuyBaoZhengJin)+'/多保证金率:'+str(BuyBaoZhengJinLv)+'/最小成本比'+str(MinChenBenBi)\
+'/开手续费:'+str(KaiShouXuFei)+'/平手续费:'+str(PingShouXuFei)+'/最小单位:'+str(MinJia)+'/最小定价:'+str(MinJiaCha)\
+'/每手单位:'+str(MeiShouDanWei)+'/单位乘数:'+str(HeYueDanWei)+"/")
###############################################################################################多头持仓计算###############################
if BuyQuantity>0:
pass
#print(str(BanKuai)+str(Name)+'/D持仓:'+str(BuyQuantity)+'/均价:'+str(BuyAvgHoldingPrice))
BuyPnl = \
round((NewSellJia - BuyAvgHoldingPrice) / MinJia * MinJiaCha * BuyQuantity - (KaiShouXuFei + PingShouXuFei) * BuyQuantity,4) #开多浮动盈亏 对手价计算减去双向手续费
#print(str(BanKuai)+str(Name)+'/D持仓盈亏:'+str(BuyPnl))
if BuyMargin == 0 or get_account(6) == 0:
BuyFengXianDu = 0
else:
BuyFengXianDu = round(BuyMargin / get_account(6),6)
#print(str(BanKuai)+str(Name)+'/D持仓风险度:'+str(BuyFengXianDu))
pass
if BuyPnl == 0 or BuyMargin == 0 or BuyAvgHoldingPrice == 0:
BuyYingKuiLv = 0
NewBuyBaoZhengJinLv = 0
else:
BuyYingKuiLv = round(BuyPnl / BuyMargin,6)
#print(str(BanKuai)+str(Name)+'/D盈亏率:'+str(BuyYingKuiLv))
NewBuyBaoZhengJinLv = round(BuyMargin / BuyAvgHoldingPrice / HeYueDanWei / BuyQuantity ,6) #反推真实多头保证金率
#print('/D持保证金率:'+str(NewBuyBaoZhengJinLv))
pass
if FengXianDu>0 and KeYongAmount>255 and BuyMargin>0 and BuyQuantity>0:
BuyMaxVol = round((FengXianDu * KeYongAmount) / (BuyMargin / BuyQuantity),0)
#print(str(BanKuai)+str(Name)+'/D最大持仓:'+str(BuyMaxVol))
if 1< MinChenBenBi < BuyMaxVol and BuyVol != BuyMaxVol:
BuyVol = round(int(MinChenBenBi),0) #设置默认每次下单量
#SellVol = round(MinChenBenBi,0) #设置默认每次下单量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/多:最大持:'+str(BuyMaxVol)+'/持:'+str(BuyQuantity)+'/均价:'\
+str(BuyAvgHoldingPrice)+'/总浮盈亏:'+str(ZongPnl)+'/持盈亏:'+str(BuyPnl)+'/盈亏率:'+str(BuyYingKuiLv)+'/持风险度:'\
+str(BuyFengXianDu)+'/持保证金率:'+str(NewBuyBaoZhengJinLv)+'/')
###############################################################################################空头持仓计算##########################
if SellQuantity>0:
pass
#print(str(BanKuai)+str(Name)+'/K持仓:'+str(SellQuantity)+'/均价:'+str(SellAvgHoldingPrice))
SellPnl = \
round((SellAvgHoldingPrice - NewBuyJia) / MinJia * MinJiaCha * SellQuantity - (KaiShouXuFei + PingShouXuFei) * SellQuantity,4) #开空浮动盈亏 对手价计算减去双向手续费
#print(str(BanKuai)+str(Name)+'/K持仓盈亏:'+str(SellPnl))
if SellMargin == 0 or get_account(6) == 0:
SellFengXianDu = 0
else:
SellFengXianDu = round(SellMargin / get_account(6),6)
#print(str(BanKuai)+str(Name)+'/K持仓风险度:'+str(SellFengXianDu))
pass
if SellPnl == 0 or SellMargin == 0 or SellAvgHoldingPrice == 0:
SellYingKuiLv = 0
NewSellBaoZhengJinLv = 0
else:
SellYingKuiLv = round(SellPnl / SellMargin,6)
#print(str(BanKuai)+str(Name)+'/K盈亏率:'+str(SellYingKuiLv))
NewSellBaoZhengJinLv = round(SellMargin / SellAvgHoldingPrice / HeYueDanWei / SellQuantity,6) #反推真实多头保证金率
#print('/K持保证金率:'+str(NewSellBaoZhengJinLv))
pass
if FengXianDu > 0 and KeYongAmount > 255 and SellMargin > 0 and SellQuantity > 0:
SellMaxVol = round((FengXianDu * KeYongAmount) / (SellMargin / SellQuantity),0)
#print(str(BanKuai)+str(Name)+'/K最大持仓:'+str(SellMaxVol))
if 1< MinChenBenBi < SellMaxVol and SellVol != SellMaxVol:
#BuyVol = round(MinChenBenBi,0) #设置默认每次下单量
SellVol = round(int(MinChenBenBi),0) #设置默认每次下单量
pass
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/空:最大持:'+str(SellMaxVol)+'/持:'+str(SellQuantity)\
+'/均价:'+str(SellAvgHoldingPrice)+'/总浮盈亏:'+str(ZongPnl)+'/持盈亏:'+str(SellPnl)+'/盈亏率:'+str(SellYingKuiLv)\
+'/持风险度:'+str(SellFengXianDu)+'/持保证金率:'+str(NewSellBaoZhengJinLv)+'/')
##########################################################################################交易条件判断###################################
if not istradertime(s1): #不在交易时间,不进入交易段
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/不在交易时间/不进入交易段")
if Test == 1:
return
else:
return
else:
pass
if 1!=0:
pass
if 1!=0:
DianNaoTime = datetime.datetime.now() ##获得当前时间->这是时间数组格式
DianNaoTime = int(DianNaoTime.strftime("%H%M%S")) #转换为指定的格式:
ChengJIaoTime = int(round(get_dynainf(s1,207),0)) #行情报价最新一笔成交时间
#print(str(BanKuai)+str(Name)+'/电脑时间'+str(DianNaoTime))
#print(str(BanKuai)+str(Name)+'/报价时间'+str(ChengJIaoTime))
DianNaoTimeH = round(DianNaoTime / 10000,0) #取电脑时间小时数
ChengJIaoTimeH = round(ChengJIaoTime / 10000,0) #取交易时间小时数
XiaoShiShiCha = (DianNaoTimeH - ChengJIaoTimeH) #计算小时时间差
if DianNaoTimeH!=ChengJIaoTimeH: #小时数相等
if DianNaoTimeH == ChengJIaoTimeH:
TimeCha = round(DianNaoTime - ChengJIaoTime,0) #计算成交时间差
else:
if DianNaoTimeH > ChengJIaoTimeH: #小时数不相等
#print('交易小时>电脑小时:'+str(XiaoShiShiCha))
TimeCha = round(DianNaoTime - (ChengJIaoTime + abs(XiaoShiShiCha * 10000)),0) #计算成交时间差
pass
if DianNaoTimeH < ChengJIaoTimeH: #小时数不相等
#print('交易小时<电脑小时:'+str(XiaoShiShiCha))
TimeCha = round(DianNaoTime - (ChengJIaoTime - abs(XiaoShiShiCha * 10000)),0) #计算成交时间差
pass
#print('报价不活跃 情况完成######################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
########################################################################################总控 方向 模式 ################################
if NewAmount != 0 or NewAmountShouXuFei != 0 or OrdAmount != 0:
pass
if SellQuantity >= 0 or BuyQuantity >= 0:
AmountHuiCheJinE = round(NewAmount - NewAmountShouXuFei - OrdAmount,0) #最新账户回撤金额
HuiCheJinE = round(OrdAmount * ZongHuiCheBiLi,6) #设定回撤金额
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'+str(ZongHuiCheBiLi)+'/设定回撤金额:'+str(HuiCheJinE) )
if AmountHuiCheJinE < -HuiCheJinE or AmountHuiCheJinE > HuiCheJinE * 9:
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'\
+str(ZongHuiCheBiLi)+'/账户当日回撤:'+str(AmountHuiCheJinE)+'/大于触发阀值:'+str(HuiCheJinE)+'执行风控退出平仓交易!')
else:
if ZongPnl == 0 or BaoZhengJinAmount == 0:
NewZongHuiCheBiLi = 0
else:
NewZongHuiCheBiLi = round(ZongPnl / BaoZhengJinAmount,6)
if NewZongHuiCheBiLi < -ZongHuiCheBiLi: #回撤大于设定盈亏率 test!!!
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'设定回撤比例:'\
+str(ZongHuiCheBiLi)+'/账户当日盈亏率:'+str(NewZongHuiCheBiLi)+'/大于回撤比例:'+str(ZongHuiCheBiLi)\
+'执行风控重启平仓交易!')
else:
if abs(int(TimeCha)) > 10 or NewChiCangLiang < 50000 or NewQianChiCangLiang < 50000 or NewBuyJia >= NewZhangTing or NewSellJia <= NewDieTing:
FangXiang = 0
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'/时差:'+str(TimeCha)\
+'秒/######################报价不活跃=======平仓######################')
pass
else:
if 1 != 0 and ( OpenCloseTime == 1 ): #测试
#FangXiang = 0
print(str(BanKuai)+str(Name)+'=====================测试收盘平仓========================')
pass
if 1 != 0:
if NewJia > NewLowJia > NewQianJieSuan: #均价 大于 前均价 趋势多
FangXiang = 1
pass
if NewJia < NewHighJia < NewQianJieSuan: #均价 小于 前均价 趋势空
FangXiang = -1
pass
if NewZhenFu < ZhenFu:
FangXiang = 0
pass
if CloseTime1500 == 1: #收盘平仓
FangXiang = 0
pass
#print('计算持仓 盈亏 账户 情况完成##############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#########################################################################################方向检查########################################
if FangXiang == 0:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"风控:0:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
if FangXiang == 1:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"趋势:1:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
if FangXiang == 2:
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+"/"+"震荡:2:"+str(FangXiang)+'/动态盈亏率:'+str(YingKuiLv)) #调试打印输出
pass
#print('检查方向完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
####################################################### 下单时对接盘口 #开仓平仓量大于买卖一量 重新计算下单量 ###########################
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'下单对接盘口之前:'+' BuyVol:'+str(BuyVol)+' SellVol:'+str(SellVol))
if BuyVol > NewSellOneVol > 0:
BuyVol = int(NewSellOneVol) #卖一量对接
else:
BuyVol = int(BuyVol) #买开平量(开仓下单)
if SellVol > NewBuyOneVol > 0:
SellVol = int(NewBuyOneVol) #买一量对接
else:
SellVol = int(SellVol) #卖开平量(开仓下单)
if BuyQuantity !=0:
if BuyQuantity > NewSellOneVol > 0:
NewBuyVol = int(NewSellOneVol) #卖一量对接
else:
NewBuyVol = int(BuyQuantity) #买平持仓量(平仓下单)
#print('下单对接盘口之后:'+' NewBuyVol:'+str(NewBuyVol))
if SellQuantity !=0:
if SellQuantity > NewBuyOneVol > 0:
NewSellVol = int(NewBuyOneVol) #买一量对接
else:
NewSellVol = int(SellQuantity) #卖平持仓量(平仓下单)
#print('下单对接盘口之后:'+' NewSellVol:'+str(NewSellVol))
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'下单对接盘口之后:'+' BuyVol:'+str(BuyVol)+' SellVol:'+str(SellVol))
#print('盘口下单置换完成########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
##########################################################总平仓下单#####################################################################
if 1 != 0\
and (FangXiang == 0 ): #开关 1==0 关闭 1 != 0 打开
if BuyQuantity != 0:
sell_close(s1,"ThisClose",volume = NewBuyVol,repeat = 1,serial_id = 1) #账户回撤大于设定值%
pass
if SellQuantity != 0:
buy_close(s1,"ThisClose",volume = NewSellVol,repeat = 1,serial_id = 2) #账户回撤大于设定值%
pass
#print('回撤下单完成#########################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
################################################################ 品种结束循环 重启!######################################################
if 1 != 1 \
and ( (BuyMaxVol != BuyVol and SellMaxVol != SellVol) or BuyPnl !=0 or SellPnl !=0 or KaiShouXuFei != 0 \
or PingShouXuFei != 0 or BuyQuantity > BuyVol or SellQuantity > SellVol ): ##构建计算条件
ChengBen = (KaiShouXuFei + PingShouXuFei) * (BuyQuantity + SellQuantity) * ZongChengBenBi #计算总持仓成本比金额
BuyChengBen = (KaiShouXuFei + PingShouXuFei) * BuyQuantity * MinChenBenBi #计算多持仓成本比金额
SellChengBen = (KaiShouXuFei + PingShouXuFei) * SellQuantity * MinChenBenBi #计算空持仓成本比金额
pass
if ZongPnl > ChengBen and (BuyPnl > BuyChengBen and SellPnl > SellChengBen): #多空总持仓都盈利,而且盈利都大于成本比!
pass
if BuyQuantity > 0 and SellQuantity > 0: #多空 同时持仓盈利 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 3)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 4)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 同时持仓盈利 风控趋势震荡对平持仓 结束循环重启!')
pass
#print('同时持仓盈利下单完成#############################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
elif ZongPnl > ChengBen and (BuyPnl > BuyChengBen or SellPnl > SellChengBen): #多空总持仓有分别盈亏,总计盈利大于成本比!
pass
if BuyQuantity > 0 or SellQuantity > 0: #多空 分别 (单向或者双向) 持仓盈亏 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 5)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 6)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 分别 (单向或者双向) 持仓合并盈利 风控趋势震荡对平持仓 结束循环重启!')
elif ZongPnl < -ChengBen and (BuyPnl < -BuyChengBen or SellPnl < -SellChengBen): #多空总持仓有分别亏,总计亏大于成本比!
pass
if BuyQuantity > 0 or SellQuantity > 0: #多空 分别 (单向或者双向) 持仓盈亏 总盈利盈利大于成本比 风控、趋势、震荡、 对平持仓 结束循环
if BuyQuantity > 0 :
pass
buy_close(s1,"ThisClose",volume = NewBuyVol,repeat = 0,serial_id = 7)
if SellQuantity > 0:
pass
sell_close(s1,"ThisClose",volume = NewSellVol,repeat = 0,serial_id = 8)
print(str(BanKuai)+':'+str(MaxNum)+':'+str(Num)+':'+str(Name)+'多空 分别 (单向或者双向) 持仓合并亏损 风控趋势震荡对平持仓 结束循环重启!')
else:
pass
#print('分别持仓盈亏下单完成#####################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
######################################################################## 开始构建信号下单 ###############################################
#使用buy_open、sell_close等方法下单
#下单示例:
#buy_open(s1, "Market", volume=100) # 市价开多
pass
######################################################################趋势开多########################################################
if ( NewZhangSu < -(NewZhenFu * ZhenFu) ) and FangXiang == 1: #判断趋势 做多
##print(s1+'趋势多')
if BuyQuantity == 0:
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 9) #开多试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
#sell_open(s1,"ThisClose",volume = SellVol,repeat=0,serial_id = 2)
pass
if BuyQuantity != 0 and BuyQuantity < BuyMaxVol:
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 10)
#####################################################################多止盈止损########################################################
if BuyQuantity > 0 and FangXiang == 1:
##print(s1)
##print(BuyAvgHoldingPrice)
#BuyHuiLuo = (NewJia - BuyAvgHoldingPrice) / BuyAvgHoldingPrice
##print(s1+"/"+str(BuyHuiLuo)+"/"+str(HuiLuo))
if BuyQuantity > BuyMaxVol:
sell_close(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 11) #持仓量大于最大持仓量 平多
pass
#if BuyYingKuiLv < -YingKuiLv and SellQuantity < SellMaxVol:
#sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 10) #多亏阀值止损 反手开空
pass
#####################################################################趋势开空#########################################################
if ( NewZhangSu > (NewZhenFu * ZhenFu) ) and FangXiang == -1: #判断趋势 做空
#print(s1+'趋势空')
if SellQuantity == 0:
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 12) #开空试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
#buy_open(s1,"ThisClose",volume = BuyVol,repeat=0,serial_id = 5)
pass
if SellQuantity != 0 and SellQuantity < SellMaxVol:
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 13)
#####################################################################空止盈止损########################################################
if SellQuantity > 0 and FangXiang == -1:
##print(s1)
##print(SellAvgHoldingPrice)
#SellHuiLuo = (SellAvgHoldingPrice - NewJia) / SellAvgHoldingPrice
##print(s1+"/"+str(SellHuiLuo)+"/"+str(HuiLuo))
if SellQuantity > SellMaxVol:
buy_close(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 14) #持仓量大于最大持仓量 平空
pass
#if SellYingKuiLv < -YingKuiLv and BuyQuantity < BuyMaxVol:
#buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 14) #空亏阀值止损 反手开多
pass
#print('趋势下单完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#####################################################################震荡开仓###########################################################
if BuyQuantity == 0 and FangXiang == 2: #震荡做多
##print(s1+'震荡多')
if NewZhangSu < -(NewZhenFu * ZhenFu):
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 15) #开多试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if BuyQuantity != 0 and FangXiang == 2: #震荡做多
if BuyQuantity < BuyMaxVol and NewZhangSu < -(NewZhenFu * ZhenFu):
buy_open(s1,"ThisClose",volume = BuyVol,repeat = 0,serial_id = 16) #开多仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if SellQuantity == 0 and FangXiang == 2: #震荡做空
##print(s1+'震荡空')
if NewZhangSu > (NewZhenFu * ZhenFu):
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 17) #开空试仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
if SellQuantity != 0 and FangXiang == 2: #震荡做空
if SellQuantity < SellMaxVol and NewZhangSu > (NewZhenFu * ZhenFu):
sell_open(s1,"ThisClose",volume = SellVol,repeat = 0,serial_id = 18) #开空仓 取持仓信息 保证金 杠杆 手续费 风险度 盈亏率
pass
#print('震荡下单完成#############################################:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
#!!!!!!!!!!!!!!!!!!!! 系统有BUG 去掉 !!!!!!!!!!
# exit函数会在测评结束或者停止策略运行时会被调用。---(选择实现)
#def exit(context):
#killtimer(handle_bar_1) #终止计时器
#killtimer(handle_bar_2) #终止计时器
#print("终止计时器/策略手动已退出!")
#gc.collect()
#print(str(gc.get_threshold())+'清理内存')
#return
#print('最后一行完成<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<:'+str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]))
return