金字塔决策交易系统

 找回密码
 

微信登录

微信扫一扫,快速登录

搜索
查看: 824|回复: 5

随机开仓和持仓管理 python 测试项目

[复制链接]

3

主题

66

帖子

66

积分

等级: 免费版

注册:
2021-7-16
曾用名:
发表于 2025-2-3 09:08 | 显示全部楼层 |阅读模式
本帖最后由 技术006 于 2025-2-3 09:51 编辑

[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




回复

使用道具 举报

3

主题

66

帖子

66

积分

等级: 免费版

注册:
2021-7-16
曾用名:
 楼主| 发表于 2025-2-6 11:10 | 显示全部楼层
<think> 嗯,我现在在看这个Python策略代码,感觉有点复杂。首先,这个策略是用于期货交易的,对吧?它用了多个指标,比如KDJ和MACD,还有布林带。这些指标都是技术分析中常用的,但我不太确定它们是如何被结合起来使用的。
代码一开始定义了一些参数,比如最小订单量、空头和多头的最大仓位,这可能是在风险控制方面的设置。然后初始化了一些变量,包括KDJ线、MACD线和布林带的相关参数。这部分我大概明白,就是设定了一些初始值。

接下来是on_bar_callback函数,每当有新的TICK数据到达时就会触发。这里面计算了最新的收盘价,然后更新了KDJ、MACD和布林带的数据。这里我看到用到了talib库,这个库提供了很多技术分析指标,能很方便地计算出这些值。不过,我不太清楚这些参数的具体含义,比如KDJ中的3, 3, 5是什么意思?是快线、慢线和信号线的周期吗?

然后代码进入了策略逻辑部分。首先看空头仓位是否超过了一定的比例,如果超过了,就平掉一部分空头仓位。这可能是一种风险控制机制,防止仓位过大导致的风险。同样地,对于多头仓位也做了类似处理。

接下来是关于布林带和KDJ的交叉点的判断。当价格触碰到下布林带,并且KDJ的黄金交叉(即J > K)发生时,策略会开多仓;反之,当价格触碰上布林带并且出现死亡交叉(K > J),则开空仓。这里我不太明白为什么黄金交叉和死亡交叉的条件是这样设置的,是不是根据经验或者某种理论来的?

然后是MACD部分,如果MACD在0线之上,并且出现了金叉,就加多仓;如果在0线以下并出现死叉,则加空仓。这里我有点疑惑,为什么只看是否在0线以上或以下,而不是考虑其他情况?比如,信号线和MACD线的交叉点。

接下来是关于仓位管理的部分,如果多头仓位超过了一定比例,就平掉一部分;同样地,如果空头仓位过高,也会平掉一部分。这似乎是在控制仓位风险,防止过大的仓位导致的大幅波动。

然后还有其他条件,比如当价格在布林带中间时,可能会平仓,这取决于当前的仓位方向。这里我不太确定这是否是一个有效的策略,因为有时候价格在中间区域可能意味着趋势不明朗,不应该轻易平仓。

接下来是关于震荡操作的部分,当价格回到均线并且满足某些条件时,会开多或空仓。这可能是在利用均线作为支撑或阻力来进行交易决策。但我觉得这里面的逻辑有点混乱,不知道具体的数据是什么样的。

最后,还有一系列检查和平仓操作,比如检查当前是否有持仓,以及价格是否触发了止损点。这些都是必要的风险控制措施,但可能需要更详细地设置止损位,而不仅仅是基于某个条件。

整体来看,这个策略试图结合多个指标来进行多空操作,包括趋势跟踪和震荡交易。不过,我觉得代码中有些地方可能存在逻辑问题,比如在判断KDJ交叉点的时候,是否正确地捕捉到了买卖...

model: Ollama (deepseek-r1:70b), time: 11:10



补充内容 (2025-2-6 11:25):


以下是针对上述问题的逐步解释和建议:

1. **理解策略逻辑**:
    - 首先,分析代码中的各个指标(KDJ、MACD、布林带)如何被利用来识别买卖信号。例如,黄金交叉通常意味着上涨趋势,而死亡交叉则可能预示下跌。

2. **检查条件判断**:
    - 确保所有的条件判断是否正确捕捉到了所需的市场信号。比如,当价格触碰到布林带且KDJ出现黄金交叉时,确实应该开多仓吗?是否存在其他因素可能干扰这个信号?

3. **优化代码结构**:
    - 将重复使用的代码块封装成函数,如开仓、加仓和平仓操作,这样可以提高代码的可读性和维护性,减少冗余。

4. **完善风险控制**:
    - 除了仓位管理和止损,可以考虑增加止盈机制,以锁定利润。同时,可以设置最大回撤限制,以防止过大的亏损。

5. **参数优化**:
    - 对KDJ、MACD和布林带的参数进行调优,看看是否有更好的组合可以提高策略的表现。这可能需要通过大量历史数据回测来确定最佳参数。

6. **实时交易考虑因素**:
    - 考虑到延迟和滑点,评估这些因素对策略执行的影响。在实际交易中,确保订单能够及时准确地执行,避免由于延迟导致的重大误差。

7. **回测与验证**:
    - 使用历史数据进行详细的回测,分析策略在不同市场环境下的表现。检查策略在多种情况下是否稳定可靠,如牛市、熊市和震荡市。

8. **监控与调整**:
    - 在实盘交易中持续监控策略表现,及时发现并解决出现的问题。根据市场变化,动态调整策略参数或逻辑,以适应不同的市场条件。

通过以上步骤,可以更全面地理解和优化这个期货交易策略,使其在实际应用中更加稳定和有效。
回复

使用道具 举报

3

主题

66

帖子

66

积分

等级: 免费版

注册:
2021-7-16
曾用名:
 楼主| 发表于 2025-2-6 11:36 | 显示全部楼层
<think> 嗯,我看到用户提交了一个Python脚本,似乎是一个交易策略的代码。首先,我需要理解这个代码的大致功能和结构,以便能够有效地帮助他。
从文件内容来看,这个代码是为期货交易设计的,使用了多个函数,比如on_tick、on_bar,以及一些辅助函数,如strategy_position、order_price、get_holding_pnl等。看起来这是一个基于tick数据和bar数据的自动交易系统。

接下来,我注意到用户提到了“exit”函数的问题,并指出系统存在BUG,特别是关于计时器的部分被注释掉了。这可能意味着在策略停止或测评结束时,计时器没有正确终止,导致潜在的资源泄漏或其他问题。

我还注意到代码中有许多被注释掉的print语句,这些可能是在调试过程中使用的,但现在已经不需要了。同时,有一些条件判断和逻辑结构,特别是关于订单的执行、止盈止损的设置,这些都需要仔细检查是否正确。

另外,我看到代码中有一些全局变量,如futa_glo、ftu_glo等,用于存储持仓信息和订单信息。这些在多线程或多函数调用时可能会有问题,需要确保它们的访问是线程安全的。

还有一个重要的问题是,这段代码没有包含任何错误处理机制。如果在执行订单时出现异常,比如网络问题或者其他意外情况,策略可能会崩溃,而不是优雅地处理错误并继续运行。

最后,我注意到用户试图在exit函数中终止计时器,但相关代码被注释了。这部分需要修复,以确保在策略停止时,所有的资源都能正确释放,避免潜在的问题。

综上所述,这段代码虽然结构清晰,但存在一些潜在的问题,比如错误处理、资源管理和多线程安全等。接下来,我应该逐步...

model: Ollama (deepseek-r1:70b), time: 11:36









deepseek-

补充内容 (2025-2-6 11:38):
持仓管理模块 python
回复

使用道具 举报

3

主题

66

帖子

66

积分

等级: 免费版

注册:
2021-7-16
曾用名:
 楼主| 发表于 2025-2-6 11:56 | 显示全部楼层
以下是对您提交的代码的详细分析以及改进建议:

1. 文件结构与命名
问题:文件内容包含多个函数,但整体结构不够清晰,缺乏明确的模块划分。
建议:
将相关功能模块化,如将与订单执行、持仓管理、策略逻辑等分开,便于维护和扩展。
使用更具描述性的函数和变量命名,避免简写,如on_tick可以改为handle_tick_event。
2. 错误处理
问题:代码中缺乏错误处理机制,可能导致策略在出现异常时崩溃。
建议:
在关键操作(如订单执行)周围添加try-except块,捕捉和记录异常。
实现重试机制,处理暂时性的网络或系统错误。
3. 资源管理
问题:exit函数中注释掉的计时器终止代码可能导致资源泄漏。
建议:
移除注释,正确调用killtimer函数,以确保计时器在策略停止时正确终止。
确保所有系统资源(如数据库连接、文件句柄等)在退出时被妥善释放。
4. 全局变量管理
问题:使用全局变量可能导致多线程访问时的竞态条件,影响数据一致性。
建议:
使用线程安全的数据结构或互斥锁来保护对全局变量的访问。
考虑将全局变量替换为类属性,封装在一个策略管理器中,以提高代码的可维护性。
5. 注释与调试信息
问题:代码中存在大量被注释的调试语句,这可能导致代码混乱。
建议:
移除不必要的注释和调试代码,或使用日志系统来记录关键信息。
使用版本控制工具跟踪代码变更,避免在生产代码中保留过多的注释。
6. 逻辑结构
问题:条件判断部分较为复杂,可能影响可读性和维护性。
建议:
将复杂的条件逻辑拆分成小函数,每个函数负责一个特定的判断。
使用设计模式(如策略模式)来管理不同的交易逻辑。
7. 安全与合规
问题:缺乏输入验证和数据有效性检查,可能导致安全漏洞或意外行为。
建议:
在处理用户输入或外部数据时,进行充分的验证和过滤。
确保所有交易操作符合相关法律法规,并遵循合规要求。
回复

使用道具 举报

3

主题

66

帖子

66

积分

等级: 免费版

注册:
2021-7-16
曾用名:
 楼主| 发表于 2025-2-11 16:17 | 显示全部楼层
20250211

无源码KaiCang无源码ChiCang.zip

12.6 KB, 下载次数: 233

回复

使用道具 举报

2

主题

5

帖子

5

积分

Rank: 1

等级: 新手上路

注册:
2025-2-13
曾用名:
发表于 2025-2-22 19:31 | 显示全部楼层
能帮我写个策略吗?用py编写,我可以付薪酬给!


补充内容 (2025-2-22 19:32):
联系方式yesing@126.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 微信登录

本版积分规则

手机版|小黑屋|上海金之塔信息技术有限公司 ( 沪ICP备13035422号 )

GMT+8, 2025-3-14 03:48 , Processed in 0.251343 second(s), 25 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表