8 Star 29 Fork 11

小果量化 / qmt_trader

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
LGPL-2.1

qmt_trader

####快速安装 如果感觉设置太麻烦可以找我直接获取文件,直接联系我 xtquant文件太大上传不了,可以加我微信直接获取qmt_trader 微信 下载链接https://mp.weixin.qq.com/s/_AZh7PNclMgW4iHXa6uHIQ 输入图片说明 公众号 https://mp.weixin.qq.com/s/_SYpBLNr4dtZtvj8ydtBrw 输入图片说明 知识星球,更多的内容在知识星球,链接 https://t.zsxq.com/19VzjjXNi 输入图片说明

介绍

QMT系统是专门为国内量化私募、个人高净值客户、活跃交易客户以及量化爱好者研发的一款集行情显示、 策略研究、交易执行和风控管理于一体的策略量化交易终端。QMT系统具有高速行情、极速交易、策略交易、 多维度风控等专业功能,能够满足专业投资者的特殊交易需求

软件架构

文件的核心在qmt_data,qmt_trader

安装教程

  1. 因为xtquant太大了,上次不了去官网下载就可以 官网http://dict.thinktrader.net/nativeApi/download_xtquant.html 随便选择一个版本 输入图片说明

2.下载后面解压放在qmt——tarder下面就可以了不然 输入图片说明

使用说明

1第一步把程序当第三方库使用参考公众号教程https://mp.weixin.qq.com/s/_SYpBLNr4dtZtvj8ydtBrw 2我们还是先用官网原来的xtquant当教程写后面在写封装的库教程

一qmt_trader的使用教程

1实盘框架参考模板

from qmt_trader.qmt_trader import qmt_trader
from qmt_trader.qmt_data import qmt_data
from qmt_trader.trader_tool import tdx_indicator
import schedule
from datetime import datetime
import time
import pandas as pd
class my_trader:
    def __init__(self,path= r'D:/国金QMT交易端模拟/userdata_mini',
                  session_id = 123456,account='55011917',account_type='STOCK',
                  is_slippage=True,slippage=0.01,test=True):
        '''
        实时分钟T0策略利用实盘交易框架2.0
        均线金叉买入死差卖出
        '''
        self.path=path
        self.session_id=session_id
        self.account=account
        self.account_type=account_type
        self.is_slippage=is_slippage
        self.slippage=slippage
        self.test=test
        #买入的目标金额
        self.buy_max_value=10000
        #卖出的目标金额
        self.sell_max_value=0
        #股票列表
        self.code_list=['159937','159980','159985','159981']
        #5分,特别提醒这个参数和获取数据的速度有关系默认是3秒一次数据,
        # 如果是3秒5分钟就等于3*20*5,short_line=100,这个我后面检验一下
        self.short_line=5
        #10分钟
        self.long_line=10
        self.trader=qmt_trader(path=self.path,account=self.account,account_type=self.account_type,
                            is_slippage=self.is_slippage,slippage=self.slippage)
        self.data=qmt_data()
        #调整股票代码
        self.stock_list=[]
        for stock in self.code_list:
            self.stock_list.append(self.trader.adjust_stock(stock=stock))
        #订阅一分钟的数据,需要更快的话可以订阅tick数据
        for stock in self.stock_list:
            self.data.subscribe_quote(stock_code=stock,period='1m',start_time='20240101',
                                      end_time='20500101',count=-1)
    def connact(self):
        '''
        链接qmt
        '''
        try:
            self.trader.connect()
            print(self.trader.balance())
            print(self.trader.position())
            return True
        except Exception as e:
            print("运行错误:",e)
            print('{}连接失败'.format('qmt'))
            return False
    def trader_func(self):
        '''
        交易函数
        '''
        #检查是否是交易时间
        if self.trader.check_is_trader_date_1(trader_time=4,start_date=9,end_date=14,start_mi=0,jhjj='否'):
            #读取订阅数据
            df=self.data.get_market_data_ex(stock_list=self.stock_list,period='1m',
                                            start_time='20240101',end_time='20500101',count=-1)
            #解析数据
            for stock in self.stock_list:
                data=pd.DataFrame()
                hist=df[stock]
                data['date']=hist.index
                data['close']=hist['close'].tolist()
                data['short_line']=data['close'].rolling(self.short_line).mean()
                data['long_line']=data['close'].rolling(self.long_line).mean()
                #测试函数
                data['test']=data['short_line']>data['long_line']
                #金叉
                if self.test:
                    #测试交易
                    gold_fork=data['test'].tolist()[-1]
                else:
                    gold_fork=tdx_indicator.CROSS_UP(S1=data['short_line'],S2=data['long_line'])[-1]
                
                #死叉
                if self.test:
                    dead_fork=data['test'].tolist()[-1]
                else:
                    dead_fork=tdx_indicator.CROSS_DOWN(S1=data['short_line'],S2=data['long_line'])[-1]
                
                #买入
                if gold_fork==True:
                    #买入
                    stock=self.trader.adjust_stock(stock=stock)
                    price=self.data.get_full_tick(code_list=[stock])[stock]['lastPrice']
                    stock=stock[:6]
                    trader_type,trader_amount,price=self.trader.order_target_value(stock=stock,price=price,value=self.buy_max_value)
                    if trader_type=='buy' and trader_amount>=10:
                        self.trader.buy(security=stock,amount=trader_amount,price=price)
                        print('{} 死叉 买入 股票{} 数量{} 价格{}'.format(datetime.now(),stock,trader_amount,price))
                    elif trader_type=='sell' and trader_amount>=10:
                        self.trader.sell(security=stock,amount=trader_amount,price=price)
                        print('持有买多了平部分{} 卖出 股票{} 数量{} 价格{}'.format(datetime.now(),stock,trader_amount,price))
                    else:
                        print('{} 触发金叉{}执行买入不了'.format(datetime.now(),stock))
                else:
                    print('{} 没有触发金叉{}'.format(datetime.now(),stock))
                if dead_fork==True:
                    #卖出
                    stock=self.trader.adjust_stock(stock=stock)
                    price=self.data.get_full_tick(code_list=[stock])[stock]['lastPrice']
                    stock=stock[:6]
                    trader_type,trader_amount,price=self.trader.order_target_value(stock=stock,price=price,value=self.sell_max_value)
                    if trader_type=='sell' and trader_amount>=10:
                        self.trader.sell(security=stock,amount=trader_amount,price=price)
                        print('{} 死叉 卖出 股票{} 数量{} 价格{}'.format(datetime.now(),stock,trader_amount,price))
                    else:
                        print('{} 触发死叉{}执行卖出不了'.format(datetime.now(),stock))
                else:
                    print('{} 没有触发死叉{}'.format(datetime.now(),stock))
        else:
            print('{}目前不少交易时间'.format(datetime.now()))
if __name__=='__main__':
    trader=my_trader(path= r'D:/国金QMT交易端模拟/userdata_mini',
                  session_id = 123456,account='55011917',account_type='STOCK',
                  is_slippage=True,slippage=0.01,test=False)
    trader.connact()
    #3秒
    schedule.every(0.05).minutes.do(trader.trader_func)
    while True:
        schedule.run_pending()
        time.sleep(1)

2qmt_tarder的全部函数使用教程,1导入交易框架

from qmt_trader.qmt_trader import qmt_trader
from qmt_trader.xtquant.xttype import StockAccount
from qmt_trader.xtquant import xtconstant
trader=qmt_trader(path= r'D:/国金QMT交易端模拟/userdata_mini',
                  session_id = 123456,account='55011917',account_type='STOCK',
                  is_slippage=True,slippage=0.01)
#链接
trader.connect()

操作方式,登录qmt,选择行情加交易选,择极简模式 作者:小果 作者微信:15117320079 作者微信公众号:数据分析与运用 公众号链接:https://mp.weixin.qq.com/s/rxGJpZYxdUIHitjvI-US1A 作者知识星球:金融量化交易研究院 id:51340043 链接qmt 0

2随机id

#随机id
trader.random_session_id()

底层的代码,至少需要是整数就可以

 def random_session_id(self):
        '''
        随机id
        '''
        session_id=''
        for i in range(0,9):
            session_id+=str(random.randint(1,9))
        return session_id

#3设置滑点

#设置滑点
trader.select_slippage(stock='600031',price=17.01,trader_type='buy')

滑动价格的最好一位底层的源代码

def select_slippage(self,stock='600031',price=15.01,trader_type='buy'):
        '''
        选择滑点
        安价格来滑点,比如0.01就是一块
        etf3位数,股票可转债2位数
        '''
        stock=self.adjust_stock(stock=stock)
        data_type=self.select_data_type(stock=stock)
        if data_type=='fund' or data_type=='bond':
            slippage=self.slippage/10
            if trader_type=='buy' or trader_type==23:
                price=price+slippage
            else:
                price=price-slippage
        else:
            slippage=self.slippage
            if trader_type=='buy' or trader_type==23:
                price=price+slippage
            else:
                price=price-slippage
        return price

#4检查是否是交易时间

和交易所保持一样,代码

#检查是否是交易时间
trader.check_is_trader_date_1()

输出的结果

周末

底层的代码

def check_is_trader_date_1(self,trader_time=4,start_date=9,end_date=14,start_mi=0,jhjj='否'):
        '''
        检测是不是交易时间
        '''
        if jhjj=='是':
            jhjj_time=15
        else:
            jhjj_time=30
        loc=time.localtime()
        tm_hour=loc.tm_hour
        tm_min=loc.tm_min
        wo=loc.tm_wday
        if wo<=trader_time:
            if tm_hour>=start_date and tm_hour<=end_date:
                if tm_hour==9 and tm_min<jhjj_time:
                    return False
                elif tm_min>=start_mi:
                    return True
                else:
                    return False
            else:
                return False    
        else:
            print('周末')
            return False

5#检查数据类型

代码调用

#检查数据类型
trader.select_data_type(stock='600031')

输出

stock

底层的源代码

def select_data_type(self,stock='600031'):
        '''
        选择数据类型
        '''
        if stock[:3] in ['110','113','123','127','128','111','118'] or stock[:2] in ['11','12']:
            return 'bond'
        elif stock[:3] in ['510','511','512','513','514','515','516','517','518','588','159','501','164'] or stock[:2] in ['16']:
            return 'fund'
        else:
            return 'stock'

6#调整股票代码

源代码调用

#调整股票代码
trader.adjust_stock(stock='600031')

输出

'600031.SH'

底层的源代码

def adjust_stock(self,stock='600031.SH'):
        '''
        调整代码
        '''
        if stock[-2:]=='SH' or stock[-2:]=='SZ' or stock[-2:]=='sh' or stock[-2:]=='sz':
            stock=stock.upper()
        else:
            if stock[:3] in ['600','601','603','688','510','511',
                             '512','513','515','113','110','118','501'] or stock[:2] in ['11']:
                stock=stock+'.SH'
            else:
                stock=stock+'.SZ'
        return stock

7#检查是否可以买入

调用源代码

#检查是否可以买入
trader.check_stock_is_av_buy(stock='600031',price=17.01,amount=1000)

输入的结果

持仓数量: 9
允许买入600031 可用现金19919535.36大于买入金额17010.0 价格17.01 数量1000
True

底层的代码

def check_stock_is_av_buy(self,stock='128036',price='156.700',amount=10,hold_limit=100000):
        '''
        检查是否可以买入
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        #买入是价值
        value=price*amount
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        if cash>=value:
            print('允许买入{} 可用现金{}大于买入金额{} 价格{} 数量{}'.format(stock,cash,value,price,amount))
            return True
        else:
            print('不允许买入{} 可用现金{}小于买入金额{} 价格{} 数量{}'.format(stock,cash,value,price,amount))
            return False

8#检查是否可以卖出

调用的代码

#检查是否可以卖出
trader.check_stock_is_av_sell(stock='600031',amount=1000)

输入的结果

#检查是否可以卖出
trader.check_stock_is_av_sell(stock='600031',amount=1000)

底层的源代码

def check_stock_is_av_sell(self,stock='128036',amount=10):
        '''
        检查是否可以卖出
        '''
        #stock=self.adjust_stock(stock=stock)
        hold_data=self.position()
        try:
            del hold_data['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        #买入是价值
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        stock_list=hold_data['证券代码'].tolist()
        if stock in stock_list:
            hold_num=hold_data[hold_data['证券代码']==stock]['可用余额'].tolist()[-1]
            if hold_num>=amount:
                print('允许卖出:{} 持股{} 卖出{}'.format(stock,hold_num,amount))
                return True
            else:
                print('不允许卖出持股不足:{} 持股{} 卖出{}'.format(stock,hold_num,amount))
                return False
        else:
            print('不允许卖出没有持股:{} 持股{} 卖出{}'.format(stock,0,amount))
            return False

10链接qmt函数

ef connect(self):
        '''
        连接
        path qmt userdata_min是路径
        session_id 账户的标志,随便
        account账户,
        account_type账户内类型
        '''
        print('链接qmt')
        # path为mini qmt客户端安装目录下userdata_mini路径
        path = self.path
        # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号
        session_id = self.session_id
        xt_trader = XtQuantTrader(path, session_id)
        # 创建资金账号为1000000365的证券账号对象
        account=self.account
        account_type=self.account_type
        acc = StockAccount(account_id=account,account_type=account_type)
        # 创建交易回调类对象,并声明接收回调
        callback = MyXtQuantTraderCallback()
        xt_trader.register_callback(callback)
        # 启动交易线程
        xt_trader.start()
        # 建立交易连接,返回0表示连接成功
        connect_result = xt_trader.connect()
        if connect_result==0:
            # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
            subscribe_result = xt_trader.subscribe(acc)
            print(subscribe_result)
            self.xt_trader=xt_trader
            self.acc=acc
            return xt_trader,acc
        else:
            print('qmt连接失败')

11#买入函数

调用的源代码

#买入
trader.order_stock(stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
     order_volume=100,price_type=xtconstant.FIX_PRICE,price=17.01,strategy_name='',order_remark='')

输出的结果

None
交易类型23 代码600031.SH 价格17.020000000000003 数量100 订单编号1082133507
1082133507
on order_error callback
1082133507 -61 限价买入 [SH600031] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的源代码

 def order_stock(self,stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
            '''
            下单,统一接口
            :param account: 证券账号
                :param stock_code: 证券代码, 例如"600000.SH"
                :param order_type: 委托类型, 23:买, 24:卖
                :param order_volume: 委托数量, 股票以'股'为单位, 债券以'张'为单位
                :param price_type: 报价类型, 详见帮助手册
                :param price: 报价价格, 如果price_type为指定价, 那price为指定的价格, 否则填0
                :param strategy_name: 策略名称
                :param order_remark: 委托备注
                :return: 返回下单请求序号, 成功委托后的下单请求序号为大于0的正整数, 如果为-1表示委托失败
            '''
        
            # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
            subscribe_result = self.xt_trader.subscribe(self.acc)
            print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
            #print(subscribe_result)
            stock_code = self.adjust_stock(stock=stock_code)
            price=self.select_slippage(stock=stock_code,price=price,trader_type=order_type)
            # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
            fix_result_order_id = self.xt_trader.order_stock(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                            order_volume=order_volume, price_type=price_type,
                                                            price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id

12#兼容同花顺的买入函数

调用代码

#兼容同花顺的买入函数
trader.buy(security='600031.SH', order_type=xtconstant.STOCK_BUY,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=17.01,strategy_name='',order_remark='')

输出的结果

None
交易类型23 代码600031.SH 价格17.020000000000003 数量100 订单编号2037
2037
on_order_stock_async_response
55011917 1082133508 2037
on order_error callback
1082133508 -61 限价买入 [SH600031] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的源代码

def buy(self,security='600031.SH', order_type=xtconstant.STOCK_BUY,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
        单独独立股票买入函数
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code =self.adjust_stock(stock=security)
        price=self.select_slippage(stock=security,price=price,trader_type='buy')
        order_volume=amount
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        if order_volume>0:
            fix_result_order_id = self.xt_trader.order_stock_async(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                                order_volume=order_volume, price_type=price_type,
                                                                price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id
        else:
            print('买入 标的{} 价格{} 委托数量{}小于0有问题'.format(stock_code,price,order_volume))

13#兼容同花顺的卖出函数

调用代码

#兼容同花顺的卖出函数
trader.sell(security='600031.SH', order_type=xtconstant.STOCK_SELL,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark='')

输入的结果

None
交易类型24 代码600031.SH 价格19.99 数量100 订单编号1082133509
1082133509
on order_error callback
1082133509 -61 限价卖出 [SH600031] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的源代码

def sell(self,security='600031.SH', order_type=xtconstant.STOCK_SELL,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
        单独独立股票卖出函数
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code =self.adjust_stock(stock=security)
        price=self.select_slippage(stock=security,price=price,trader_type='sell')
        order_volume=amount
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        if order_volume>0:
            fix_result_order_id = self.xt_trader.order_stock(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                                order_volume=order_volume, price_type=price_type,
                                                                price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id
        else:
            print('卖出 标的{} 价格{} 委托数量{}小于0有问题'.format(stock_code,price,order_volume))

14#国债逆回购

调用的代码

#国债逆回购
trader.reverse_repurchase_of_treasury_bonds(security='131810.SZ',buy_ratio=0.005, order_type=xtconstant.STOCK_SELL
                                             ,price_type=xtconstant.FIX_PRICE,strategy_name='',order_remark='')

输入的结果

('交易成功', '国债逆回购交易类型24 代码131810.SZ 价格1.82 数量99000 订单编号1082130433')
on order_error callback
1082130433 -61 限价卖出 [SZ131810] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的代码

def reverse_repurchase_of_treasury_bonds(self,security='131810.SZ',buy_ratio=0.005, order_type=xtconstant.STOCK_SELL
                                             ,price_type=xtconstant.FIX_PRICE,strategy_name='',order_remark=''):
        '''
        国债逆回购
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        account=self.balance()
        av_cash=account['可用金额'].tolist()[-1]
        av_cash=float(av_cash)
        av_cash=av_cash*buy_ratio
        spot_data=self.data.get_full_tick(code_list=[security])
        print('{}实时数据'.format(security),spot_data)
        price=spot_data[security]['bidPrice'][0]
        price=float(price)
        amount=math.floor((av_cash)/1000)*1000
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code =self.adjust_stock(stock=security)
        #price=self.select_slippage(stock=security,price=price,trader_type='sell')
        order_volume=amount
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        if order_volume>0:
            fix_result_order_id = self.xt_trader.order_stock(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                                order_volume=order_volume, price_type=price_type,
                                                                price=price, strategy_name=strategy_name, order_remark=order_remark)
            text='国债逆回购交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id)
            return '交易成功',text
        else:
            text='国债逆回购卖出 标的{} 价格{} 委托数量{}小于0有问题'.format(stock_code,price,order_volume)
            return '交易失败',text

15国债逆回购1

调用的代码

#国债逆回购1
trader.reverse_repurchase_of_treasury_bonds_1(buy_ratio=0.5)

输出的结果

('交易成功', '国债逆回购交易类型 代码131810.SZ 价格1.82 数量9000 订单编号1082130434')
on order_error callback
1082130434 -61 限价卖出 [SZ131810] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的源代码

def reverse_repurchase_of_treasury_bonds_1(self,buy_ratio=0.5):
        '''
        国债逆回购1,新的函数
        购买比例buy_ratio
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        account=self.balance()
        av_cash=account['可用金额'].tolist()[-1]
        av_cash=float(av_cash)
        av_cash=av_cash*buy_ratio
        stock_code_sh = '204001.SH'
        stock_code_sz = '131810.SZ'
        price_sh = self.get_bidPrice1(stock_code_sh)
        price_sz = self.get_bidPrice1(stock_code_sz)
        bidPrice1 = max(price_sh,price_sz)
        if price_sh > price_sz:
            stock_code = stock_code_sh
        else:
            stock_code = stock_code_sz
        print(stock_code,bidPrice1)
        price=bidPrice1
        stock=stock_code
        #下单的数量要是1000
        amount = int(av_cash/1000)
        #想下取整1000的倍数
        amount=math.floor(amount/1000)*1000
        #借出钱sell
        if amount>0:
            fix_result_order_id =self.sell(security=stock,amount=amount,price=price)
            text='国债逆回购交易类型 代码{} 价格{} 数量{} 订单编号{}'.format(stock,price,amount,fix_result_order_id)
            return '交易成功',text
        else:
            text='国债逆回购卖出 标的{} 价格{} 委托数量{}小于0有问题'.format(stock,price,amount)
            return '交易失败',text

16异步下单操作

调用代码

#对股票进行异步下单操作,异步下单接口如果正常返回了下单请求序号seq,会收到on_order_stock_async_response的委托反馈
trader.order_stock_async(stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark='')

输出的结果

None
交易类型23 代码600031.SH 价格20.01 数量100 订单编号4006
4006
on_order_stock_async_response
55011917 1082137305 4006
on order_error callback
1082137305 -61 限价买入 [SH600031] [AGENT] [COUNTER] [120141][证券交易未初始化]
[init_date=20240614,curr_date=20240616]

底层的代码

def order_stock_async(self,stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
         释义 
        - 对股票进行异步下单操作,异步下单接口如果正常返回了下单请求序号seq,会收到on_order_stock_async_response的委托反馈
        * 参数
        - account - StockAccount 资金账号
        - stock_code - str 证券代码, 如'600000.SH'
        - order_type - int 委托类型
        - order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
        - price_type - int 报价类型
        - price - float 委托价格
        - strategy_name - str 策略名称
        - order_remark - str 委托备注
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code = self.adjust_stock(stock=stock_code)
        price=self.select_slippage(stock=stock_code,price=price,trader_type=order_type)
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        fix_result_order_id = self.xt_trader.order_stock_async(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                            order_volume=order_volume, price_type=price_type,
                                                            price=price, strategy_name=strategy_name, order_remark=order_remark)
        print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
        return fix_result_order_id

17撤单

调用代码

'''
:param account: 证券账号
:param order_id: 委托编号, 报单时返回的编号
:return: 返回撤单成功或者失败, 0:成功,  -1:委托已完成撤单失败, -2:未找到对应委托编号撤单失败, -3:账号未登陆撤单失败
'''
trader.cancel_order_stock(order_id=12)

输出

委托已完成撤单失败
-1

底层源代码

def cancel_order_stock(self,order_id=12):
        '''
        :param account: 证券账号
            :param order_id: 委托编号, 报单时返回的编号
            :return: 返回撤单成功或者失败, 0:成功,  -1:委托已完成撤单失败, -2:未找到对应委托编号撤单失败, -3:账号未登陆撤单失败
        '''
        # 使用订单编号撤单
        cancel_order_result = self.xt_trader.cancel_order_stock(account=self.acc,order_id=order_id)
        if cancel_order_result==0:
            print('成功')
        elif cancel_order_result==-1:
            print('委托已完成撤单失败')
        elif cancel_order_result==-2:
            print('找到对应委托编号撤单失败')
        elif cancel_order_result==-3:
            print('账号未登陆撤单失败')
        else:
            pass
        return cancel_order_result

18异步撤单操作

调用代码

'''
        * 释义 
        - 根据订单编号对委托进行异步撤单操作
        * 参数
        - account - StockAccount  资金账号 
        - order_id - int 下单接口返回的订单编号
        * 返回 
        - 返回撤单请求序号, 成功委托后的撤单请求序号为大于0的正整数, 如果为-1表示委托失败
        * 备注
        - 如果失败,则通过撤单失败主推接口返回撤单失败信息
        '''
trader.cancel_order_stock_async(order_id=12)

输出的结果

4028

底层的代码

 def cancel_order_stock_async(self,order_id=12):
        '''
        * 释义 
        - 根据订单编号对委托进行异步撤单操作
        * 参数
        - account - StockAccount  资金账号 
        - order_id - int 下单接口返回的订单编号
        * 返回 
        - 返回撤单请求序号, 成功委托后的撤单请求序号为大于0的正整数, 如果为-1表示委托失败
        * 备注
        - 如果失败,则通过撤单失败主推接口返回撤单失败信息
        '''
        # 使用订单编号撤单
        cancel_order_result = self.xt_trader.cancel_order_stock_async(account=self.acc,order_id=order_id)
        if cancel_order_result==0:
            print('成功')
        elif cancel_order_result==-1:
            print('委托已完成撤单失败')
        elif cancel_order_result==-2:
            print('找到对应委托编号撤单失败')
        elif cancel_order_result==-3:
            print('账号未登陆撤单失败')
        else:
            pass
        return cancel_order_result

19 获取证券账号的资产

调用代码

'''
        :param account: 证券账号
            :return: 返回当前证券账号的资产数据
        '''
trader.query_stock_asset()

输出的结果

{'账号类型': 2,
 '资金账户': '55011917',
 '可用金额': 19919535.36,
 '冻结金额': 0.0,
 '持仓市值': 75983.4,
 '总资产': 19995883.76}

底层代码

def query_stock_asset(self):
        '''
        :param account: 证券账号
            :return: 返回当前证券账号的资产数据
        '''
        # 查询证券资产
        
        asset = self.xt_trader.query_stock_asset(account=self.acc)
        data_dict={}
        if asset:
            data_dict['账号类型']=asset.account_type
            data_dict['资金账户']=asset.account_id
            data_dict['可用金额']=asset.cash
            data_dict['冻结金额']=asset.frozen_cash
            data_dict['持仓市值']=asset.market_value
            data_dict['总资产']=asset.total_asset
            return data_dict
        else:
            print('获取失败资金')
            data_dict['账号类型']=[None]
            data_dict['资金账户']=[None]
            data_dict['可用金额']=[None]
            data_dict['冻结金额']=[None]
            data_dict['持仓市值']=[None]
            data_dict['总资产']=[None]
            return  data_dict

20 获取资产对接同花顺

调用代码

'''
对接同花顺
'''
trader.balance()

输入的结果

'''
对接同花顺
'''
trader.balance()

底层的源代码

 def balance(self):
        '''
        对接同花顺
        '''
        try:
            asset = self.xt_trader.query_stock_asset(account=self.acc)
            df=pd.DataFrame()
            if asset:
                df['账号类型']=[asset.account_type]
                df['资金账户']=[asset.account_id]
                df['可用金额']=[asset.cash]
                df['冻结金额']=[asset.frozen_cash]
                df['持仓市值']=[asset.market_value]
                df['总资产']=[asset.total_asset]
                return df
        except:
            print('获取账户失败,读取上次数据,谨慎使用')
            df=pd.DataFrame()
            return df

21当日委托

调用源代码

'''
        当日委托
         :param account: 证券账号
        :param cancelable_only: 仅查询可撤委托
        :return: 返回当日所有委托的委托对象组成的list
        '''
trader.query_stock_orders()

输入的结果

委托数量 0
目前没有委托

底层的代码

 def query_stock_orders(self):
        '''
        当日委托
         :param account: 证券账号
        :param cancelable_only: 仅查询可撤委托
        :return: 返回当日所有委托的委托对象组成的list
        '''
        orders = self.xt_trader.query_stock_orders(self.acc)
        print("委托数量", len(orders))
        data=pd.DataFrame()
        if len(orders) != 0:
            for i in range(len(orders)):
                df=pd.DataFrame()
                df['账号类型']=[orders[i].account_type]
                df['资金账号']=[orders[i].account_id]
                df['证券代码']=[orders[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['订单编号']=[orders[i].order_id]
                df['柜台合同编号']=[orders[i].order_sysid]
                df['报单时间']=[orders[i].order_time]
                df['委托类型']=[orders[i].order_type]
                df['委托数量']=[orders[i].order_volume]
                df['报价类型']=[orders[i].price_type]
                df['委托价格']=[orders[i].price]
                df['成交数量']=[orders[i].traded_volume]
                df['成交均价']=[orders[i].traded_price]
                df['委托状态']=[orders[i].order_status]
                df['委托状态描述']=[orders[i].status_msg]
                df['策略名称']=[orders[i].strategy_name]
                df['委托备注']=[orders[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['报单时间']=pd.to_datetime(data['报单时间'],unit='s')
            return data
        else:
            print('目前没有委托')
            return data

22对接同花顺今天委托

调用源代码

'''
        对接同花顺
        今天委托
        '''
trader.today_entrusts()

输入的结果

'''
        对接同花顺
        今天委托
        '''
trader.today_entrusts()

底层源代码

def today_entrusts(self):
        '''
        对接同花顺
        今天委托
        '''
        def select_data(x):
            if x==48:
                return '未报'
            elif x==49:
                return '待报'
            elif x==50:
                return '已报'
            elif x==51:
                return '已报待撤'
            elif x==52:
                return '部分待撤'
            elif x==53:
                return '部撤'
            elif x==54:
                return '已撤'
            elif x==55:
                return '部成'
            elif x==56:
                return '已成'
            elif x==57:
                return '废单'
            else:
                return '废单'
        orders = self.xt_trader.query_stock_orders(self.acc)
        print("委托数量", len(orders))
        data=pd.DataFrame()
        if len(orders) != 0:
            for i in range(len(orders)):
                df=pd.DataFrame()
                df['账号类型']=[orders[i].account_type]
                df['资金账号']=[orders[i].account_id]
                df['证券代码']=[orders[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['订单编号']=[orders[i].order_id]
                df['柜台合同编号']=[orders[i].order_sysid]
                df['报单时间']=[orders[i].order_time]
                df['委托类型']=[orders[i].order_type]
                df['委托数量']=[orders[i].order_volume]
                df['报价类型']=[orders[i].price_type]
                df['委托价格']=[orders[i].price]
                df['成交数量']=[orders[i].traded_volume]
                df['成交均价']=[orders[i].traded_price]
                df['委托状态']=[orders[i].order_status]
                df['委托状态描述']=[orders[i].status_msg]
                df['策略名称']=[orders[i].strategy_name]
                df['委托备注']=[orders[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['报单时间']=df['报单时间'].apply(conv_time)
            data['委托状态翻译']=data['委托状态'].apply(select_data)
            data['未成交数量']=data['委托数量']-data['成交数量']
            data['未成交价值']=data['未成交数量']*data['委托价格']
            return data
        else:
            print('目前没有委托')
            return data

23检查股票是否涨停跌停

调用源代码

'''
        检查股票是否涨停跌停
        '''
trader.get_check_stock_is_limit_down(stock='600031')

输入的结果

'正常'

底层源代码

def get_check_stock_is_limit_down(self,stock='600031'):
        '''
        检查股票是否涨停跌停
        '''
        stock=self.adjust_stock(stock=stock)
        instrument=self.data.get_instrument_detail(stock_code=stock)
        spot_data=self.data.get_full_tick(code_list=[stock])
        last_price=spot_data[stock]['lastPrice']
        UpStopPrice=instrument['UpStopPrice']
        DownStopPrice=instrument['DownStopPrice']
        if last_price>=UpStopPrice:
            return '涨停'
        elif last_price<=DownStopPrice:
            return '跌停'
        else:
            return '正常'

24 检查没有成交的当日委托

调用源代码

'''
检查没有成交的当日委托
'''
trader.get_check_not_trader_today_entrusts(stock='600031',trader_type='buy',data_type='数量')

输出的结果

委托数量 0
目前没有委托
今天没有委托3/委托已经成交
(0, '没有委托/委托已经成交')

底层的源代码

 def get_check_not_trader_today_entrusts(self,stock='600031',trader_type='buy',data_type='数量'):
        '''
        检查没有成交的当日委托
        '''
        stock=self.adjust_stock(stock=stock)
        df=self.today_entrusts()
        stock=str(stock)[:6]
        if df.shape[0]>0:
            df1=df[df['委托状态']<=53]
            if df1.shape[0]>0:
                df2=df1[df1['证券代码']==stock]
                if df2.shape[0]>0:
                    if trader_type=='buy':
                        df2=df2[df['委托类型']==23]
                        if data_type=='数量':
                            amount=df2['未成交数量'].sum()
                            print('{}委托买入数量{}'.format(stock,amount))
                            return amount,df2
                        else:
                            value=df2['未成交价值'].sum()
                            print('{}委托买入价值{}'.format(stock,value))
                            return value,df2
                    else:
                        df2=df2[df['委托类型']==24]
                        if data_type=='数量':
                            amount=df2['未成交数量'].sum()
                            print('{}委托卖出数量{}'.format(stock,amount))
                            return amount,df2
                        else:
                            value=df2['未成交价值'].sum()
                            print('{}价值{}'.format(stock,value))
                            return value,df2
                   
                else:
                    print('{}没有委托1/委托已经成交'.format(stock))
                    return 0,'没有委托1/委托已经成交'
            else:
                print('没有委托2/委托已经成交')
                return 0,'没有委托2/委托已经成交'
        else:
            print('今天没有委托3/委托已经成交')
            return 0,'没有委托/委托已经成交'

25 检查没有成交的当日委托金额

底层源代码

 def get_check_not_trader_today_entrusts(self,stock='600031',trader_type='buy',data_type='数量'):
        '''
        检查没有成交的当日委托
        '''
        stock=self.adjust_stock(stock=stock)
        df=self.today_entrusts()
        stock=str(stock)[:6]
        if df.shape[0]>0:
            df1=df[df['委托状态']<=53]
            if df1.shape[0]>0:
                df2=df1[df1['证券代码']==stock]
                if df2.shape[0]>0:
                    if trader_type=='buy':
                        df2=df2[df['委托类型']==23]
                        if data_type=='数量':
                            amount=df2['未成交数量'].sum()
                            print('{}委托买入数量{}'.format(stock,amount))
                            return amount,df2
                        else:
                            value=df2['未成交价值'].sum()
                            print('{}委托买入价值{}'.format(stock,value))
                            return value,df2
                    else:
                        df2=df2[df['委托类型']==24]
                        if data_type=='数量':
                            amount=df2['未成交数量'].sum()
                            print('{}委托卖出数量{}'.format(stock,amount))
                            return amount,df2
                        else:
                            value=df2['未成交价值'].sum()
                            print('{}价值{}'.format(stock,value))
                            return value,df2
                   
                else:
                    print('{}没有委托1/委托已经成交'.format(stock))
                    return 0,'没有委托1/委托已经成交'
            else:
                print('没有委托2/委托已经成交')
                return 0,'没有委托2/委托已经成交'
        else:
            print('今天没有委托3/委托已经成交')
            return 0,'没有委托/委托已经成交'

26 通过证券代码来撤单

调用源代码

'''
        通过证券代码来撤单
        类型cancel_type=all/buy/sell/one
        在有多个单时候选择怎么样撤单num=0/all
        '''
try:
    trader.cancel_order_stock_async_by_code(cancel_type='all',stock='600031',num='all')
except:
    pass

输入的结果

委托数量 0
目前没有委托

底层源代码

def cancel_order_stock_async_by_code(self,cancel_type='all',stock='600031',num='all'):
        '''
        通过证券代码来撤单
        类型cancel_type=all/buy/sell/one
        在有多个单时候选择怎么样撤单num=0/all
        '''
        # 使用订单编号撤单
        entrusts=self.today_entrusts()
        entrusts=entrusts[entrusts['委托状态']<=48]
        entrusts=entrusts[entrusts['委托状态']<=53]
        if entrusts.shape[0]>0:
            #stock=self.adjust_stock(stock=stock)
            entrusts['证券代码']=entrusts['证券代码'].astype(str)
            stock_list=entrusts['证券代码'].tolist()
            if stock in stock_list:
                if cancel_type=='all':
                    order_id_list=entrusts['订单编号'].tolist()
                    for order_id in order_id_list:
                        self.cancel_order_stock_async(order_id=order_id)
                elif cancel_type=='buy':
                    entrusts_buy=entrusts[entrusts['委托类型']==xtconstant.STOCK_BUY]
                    order_id_list=entrusts_buy['订单编号'].tolist()
                    for order_id in order_id_list:
                        self.cancel_order_stock_async(order_id=order_id)
                elif cancel_type=='sell':
                    entrusts_sell=entrusts[entrusts['委托类型']==xtconstant.STOCK_SELL]
                    order_id_list=entrusts_sell['订单编号'].tolist()
                    for order_id in order_id_list:
                        self.cancel_order_stock_async(order_id=order_id)
                else:
                    entrusts_on=entrusts[entrusts['证券代码']==stock]
                    if num=='all':
                        order_id_list=entrusts_on['订单编号'].tolist()
                        for order_id in order_id_list:
                            self.cancel_order_stock_async(order_id=order_id)
                    else:
                        order_id_list=entrusts_on['订单编号'].tolist()
                        self.cancel_order_stock_async(order_id=order_id_list[num])

27当日成交

调用代码

'''
        当日成交
        '''
trader.query_stock_trades()

输出结果

成交数量: 0
今日没有成交

底层源代码

def query_stock_trades(self):
        '''
        当日成交
        '''
        trades = self.xt_trader.query_stock_trades(self.acc)
        print("成交数量:", len(trades))
        data=pd.DataFrame()
        if len(trades) != 0:
            for i in range(len(trades)):
                df=pd.DataFrame()
                df['账号类型']=[trades[i].account_type]
                df['资金账号']=[trades[i].account_id]
                df['证券代码']=[trades[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['委托类型']=[trades[i].order_type]
                df['成交编号']=[trades[i].traded_id]
                df['成交时间']=[trades[i].traded_time]
                df['成交均价']=[trades[i].traded_price]
                df['成交数量']=[trades[i].traded_volume]
                df['成交金额']=[trades[i].traded_amount]
                df['订单编号']=[trades[i].order_id]
                df['柜台合同编号']=[trades[i].order_sysid]
                df['策略名称']=[trades[i].strategy_name]
                df['委托备注']=[trades[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['成交时间']=pd.to_datetime(data['成交时间'],unit='s')
            return data
        else:
            print('今日没有成交')     
            return data

28 对接同花顺今日成交

调用源代码

'''
        对接同花顺
        今日成交
        '''
trader.today_trades()

输出的结果

成交数量: 0
今日没有成交

底层源代码

def today_trades(self):
        '''
        对接同花顺
        今日成交
        '''
        trades = self.xt_trader.query_stock_trades(self.acc)
        print("成交数量:", len(trades))
        data=pd.DataFrame()
        if len(trades) != 0:
            for i in range(len(trades)):
                df=pd.DataFrame()
                df['账号类型']=[trades[i].account_type]
                df['资金账号']=[trades[i].account_id]
                df['证券代码']=[trades[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['委托类型']=[trades[i].order_type]
                df['成交编号']=[trades[i].traded_id]
                df['成交时间']=[trades[i].traded_time]
                df['成交均价']=[trades[i].traded_price]
                df['成交数量']=[trades[i].traded_volume]
                df['成交金额']=[trades[i].traded_amount]
                df['订单编号']=[trades[i].order_id]
                df['柜台合同编号']=[trades[i].order_sysid]
                df['策略名称']=[trades[i].strategy_name]
                df['委托备注']=[trades[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            def select_data(x):
                if x==xtconstant.STOCK_BUY:
                    return '证券买入'
                elif x==xtconstant.STOCK_SELL:
                    return '证券卖出'
                else:
                    return '无'
            df['操作']=df['委托类型'].apply(select_data)
            data['成交时间']=pd.to_datetime(data['成交时间'],unit='s')
            return data
        else:
            print('今日没有成交')     
            return data

29查询账户所有的持仓

调用代码

'''
        查询账户所有的持仓
        '''
trader.query_stock_positions()

输入的结果

	账号类型	资金账号	证券代码	持仓数量	可用数量	平均建仓成本	市值
0	2	55011917	513100	8400	8400	1.381	12054.0
1	2	55011917	600031	500	500	19.411	7840.0
2	2	55011917	000001	1700	1700	11.433	17306.0
3	2	55011917	159502	100	100	1.122	102.1
4	2	55011917	159509	4300	4300	1.521	7125.1
5	2	55011917	159937	300	300	5.418	1579.8
6	2	55011917	159980	5400	5400	1.862	9412.2
7	2	55011917	159981	5900	5900	1.712	9711.4
8	2	55011917	161128	2100	2100	4.883	10852.8

底层的源代码

def query_stock_positions(self):
        '''
        查询账户所有的持仓
        '''
        positions = self.xt_trader.query_stock_positions(self.acc)
        print("持仓数量:", len(positions))
        data=pd.DataFrame()
        if len(positions) != 0:
            for i in range(len(positions)):
                df=pd.DataFrame()
                df['账号类型']=[positions[i].account_type]
                df['资金账号']=[positions[i].account_id]
                df['证券代码']=[positions[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['持仓数量']=[positions[i].volume]
                df['可用数量']=[positions[i].can_use_volume]
                df['平均建仓成本']=[positions[i].open_price]
                df['市值']=[positions[i].market_value]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有持股')
            df=pd.DataFrame()
            df['账号类型']=[None]
            df['资金账号']=[None]
            df['证券代码']=[None]
            df['持仓数量']=[None]
            df['可用数量']=[None]
            df['平均建仓成本']=[None]
            df['市值']=[None]
            return df

30对接同花顺持股

调用源代码

'''
        对接同花顺
        持股
        '''
trader.position()

输出的结果

持仓数量: 9
账号类型	资金账号	证券代码	股票余额	可用余额	成本价	参考成本价	市值
0	2	55011917	513100	8400	8400	1.381	1.381	12054.0
1	2	55011917	600031	500	500	19.411	19.411	7840.0
2	2	55011917	000001	1700	1700	11.433	11.433	17306.0
3	2	55011917	159502	100	100	1.122	1.122	102.1
4	2	55011917	159509	4300	4300	1.521	1.521	7125.1
5	2	55011917	159937	300	300	5.418	5.418	1579.8
6	2	55011917	159980	5400	5400	1.862	1.862	9412.2
7	2	55011917	159981	5900	5900	1.712	1.712	9711.4
8	2	55011917	161128	2100	2100	4.883	4.883	10852.8

底层源代码

def position(self):
        '''
        对接同花顺
        持股
        '''
        try:
            positions = self.xt_trader.query_stock_positions(self.acc)
            print("持仓数量:", len(positions))
            data=pd.DataFrame()
            if len(positions) != 0:
                for i in range(len(positions)):
                    df=pd.DataFrame()
                    df['账号类型']=[positions[i].account_type]
                    df['资金账号']=[positions[i].account_id]
                    df['证券代码']=[positions[i].stock_code]
                    df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                    df['股票余额']=[positions[i].volume]
                    df['可用余额']=[positions[i].can_use_volume]
                    df['成本价']=[positions[i].open_price]
                    df['参考成本价']=[positions[i].open_price]
                    df['市值']=[positions[i].market_value]
                    data=pd.concat([data,df],ignore_index=True)
                return data
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                return df
                
        except:
            df=pd.DataFrame()
            return df

31获取个股的持股

调用源代码

trader.query_stock_position(stock_code='600031')

输出的结果

没有持股
{}

源代码

def query_stock_position(self,stock_code='600031.SH'):
        '''
        通过证券代码查持股
        '''
        position = self.xt_trader.query_stock_position(self.acc, stock_code)
        df={}
        if position:
            df['账号类型']=position.account_type
            df['资金账号']=position.account_id
            df['证券代码']=position.stock_code
            df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
            df['持仓数量']=position.volume
            df['可用数量']=position.can_use_volume
            df['平均建仓成本']=position.open_price
            df['市值']=position.market_value
            return df
        else:
            print('没有持股')
            return {}

32 获取股票新可转债ipo数据

调用源代码

'''
        获取股票新可转债ipo数据
        dict 新股新债信息数据集

        { stock1: info1, stock2: info2, ... }

        stock - str 品种代码,例如 '301208.SZ'
        info - dict 新股信息
        name - str 品种名称
        type - str 品种类型
        STOCK - 股票,BOND - 债券
        minPurchaseNum / maxPurchaseNum - int 最小 / 最大申购额度
        单位为股(股票)/ 张(债券)
        purchaseDate - str 申购日期
        issue
'''
trader.query_stock_ipo_data()

输出的结果

没有数据/处理出现错误
品种名称	品种类型	最小申购额度	最大申购额度	申购日期	发行价	证券代码

底层源代码

 def query_stock_ipo_data(self):
        '''
        获取股票新可转债ipo数据
        dict 新股新债信息数据集

        { stock1: info1, stock2: info2, ... }

        stock - str 品种代码,例如 '301208.SZ'
        info - dict 新股信息
        name - str 品种名称
        type - str 品种类型
        STOCK - 股票,BOND - 债券
        minPurchaseNum / maxPurchaseNum - int 最小 / 最大申购额度
        单位为股(股票)/ 张(债券)
        purchaseDate - str 申购日期
        issuePrice - float 发行价
        '''
        try:
            data=self.xt_trader.query_ipo_data()
            df=pd.DataFrame(data).T
            df['证券代码']=df.index
            df.columns=['品种名称','品种类型','最大申购额度','最小申购额度','申购日期','发行价','证券代码']
            return df
        except:
            print('没有数据/处理出现错误')
            df=pd.DataFrame()
            df['品种名称']=None
            df['品种类型']=None
            df['最小申购额度']=None
            df['最大申购额度']=None
            df['申购日期']=None
            df['发行价']=None
            df['证券代码']=None
            return df

33 目标数量下单

调用代码

'''
        目标数量下单
        stock: 标的代码
        amount: 期望的最终数量
        price:价格
        trader_type针对买入账户没有持股的股票,一般不改动
'''
trader.order_target_volume(stock='501018',amount=1000,price=12)

输出的结果

持仓数量: 9
目标数量下单501018 目标数量1000 持有数量0 可以用数量0 需要买入数量1000
('buy', 1000, 12)

底层代码

def order_target_volume(self,stock='501018',amount=1000,price=12):
        '''
        目标数量下单
        stock: 标的代码
        amount: 期望的最终数量
        price:价格
        trader_type针对买入账户没有持股的股票,一般不改动
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        if hold_stock.shape[0]>0:
            stock=str(stock)
            df1=hold_stock[hold_stock['证券代码']==stock]
            if df1.shape[0]>0:
                #可以使用的数量兼容t0
                av_num=df1['可用余额'].tolist()[-1]
                #持有数量
                hold_num=df1['股票余额'].tolist()[-1]
                #持有的价值
                hold_value=df1['市值'].tolist()[-1]
            else:
                av_num=0
                hold_num=0
                hold_value=0
        else:
            av_num=0
            hold_num=0
            hold_value=0
        buy_sell_num=amount-float(hold_num)
        buy_sell_value=buy_sell_num*price
        #存在买入差额
        if buy_sell_num>0:
            buy_sell_num=self.adjust_amount(stock=stock,amount=buy_sell_num)
            #可以资金大于买卖的差额
            if buy_sell_num>=10:
                #可以资金大于买卖差额
                if cash>=buy_sell_value:
                    print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 需要买入数量{}'.format(stock,amount,hold_num,av_num,buy_sell_num))
                    return 'buy',buy_sell_num,price
                else:
                    print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 需要买入数量{} 可用金额{}小于下单金额{} 不交易'.format(stock,amount,hold_num,av_num,buy_sell_num,cash,buy_sell_value))
                    return '',0,price

            else:
                print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 需要买入数量{}小于10不交易'.format(stock,amount,hold_num,av_num,buy_sell_num))
                return '',0,price        
        #存在卖出空间:
        elif buy_sell_num <0:
            #可以卖出的数量多
            buy_sell_num=abs(buy_sell_num)
            buy_sell_num=self.adjust_amount(stock=stock,amount=buy_sell_num)
            if av_num>=buy_sell_num:
                print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 需要卖出数量{}'.format(stock,amount,hold_num,av_num,buy_sell_num))
                return 'sell',buy_sell_num,price
            else:
                #可以卖出的不足卖出全部可以卖出的
                print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 小于需要卖出数量{} 直接卖出'.format(stock,amount,hold_num,av_num,buy_sell_num))
                return 'sell',buy_sell_num,price       
        else:
           print('目标数量下单{} 目标数量{} 持有数量{} 可以用数量{} 需要卖出数量{}等于0不交易'.format(stock,amount,hold_num,av_num,buy_sell_num))
           return '',0,price

34按金额下单

调用代码

'''
        按金额下单
        stock: 证券代码
        value下单金额
        value大于0买入,小0卖出
        prive交易的的价格
        '''
trader.order_value(stock='501018',value=1000,price=1.33,trader_type='buy')
        

输出的结果

持仓数量: 9
按金额下单501018 交易类型buy 可用资金19919535.36大于 下单金额1000  下单数量700
('buy', 700, 1.33)

底层源代码

def order_value(self,stock='501018',value=1000,price=1.33,trader_type='buy'):
        '''
        按金额下单
        stock: 证券代码
        value下单金额
        value大于0买入,小0卖出
        prive交易的的价格
        '''
        hold_stock=self.position()
        account=self.balance()
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        amount=value/price
        amount=self.adjust_amount(stock=stock,amount=amount)
        if trader_type=='buy':
            #这里按道理需要考虑手续费,看隔日资金
            if cash>=value:
                if amount>=10:
                    print('按金额下单{} 交易类型{} 可用资金{}大于 下单金额{}  下单数量{}'.format(stock,trader_type,cash,value,amount))
                    return 'buy',amount,price
                else:
                    print('按金额下单{} 交易类型{} 可用资金{}大于 下单金额{}  下单数量{}小于最小下单单位不交易'.format(stock,trader_type,cash,value,amount))
                    return '',0,price
            else:
                print('按金额下单{} 交易类型{} 可用资金{}小于 下单金额{}  下单数量{} 不交易'.format(stock,trader_type,cash,value,amount))
                return '',0,price
        elif trader_type=='sell':
            df1=hold_stock[hold_stock['证券代码']==stock]
            if df1.shape[0]>0:
                #可以使用的数量兼容t0
                av_num=df1['可用余额'].tolist()[-1]
                #持有数量
                hold_num=df1['股票余额'].tolist()[-1]
                #可用余额大于下单数量
                if av_num>=amount:
                    print('按金额下单{} 交易类型{} 持有数量{} 可用数量{}大于 下单数量{}  下单数量{}'.format(stock,trader_type,hold_num,av_num,amount,amount))
                    return 'sell',amount,price
                else:
                    if av_num>=10:
                        print('按金额下单{} 交易类型{} 持有数量{} 可用数量{}小于 下单数量{}  直接卖出全部下单数量{}'.format(stock,trader_type,hold_num,av_num,amount,av_num))
                        return 'sell',av_num,price
                    else:
                        print('按金额下单{} 交易类型{} 持有数量{} 可用数量{}小于 下单数量{}  下单数量{}小于最小单位不交易'.format(stock,trader_type,hold_num,av_num,amount,av_num))
                        return '',0,price
        else:
            print('按金额下单{} 交易类型{}未知道 不交易'.format(stock,trader_type))
            return '',0,price

35调整数量

调用代码

'''
        调整数量
        '''
trader.adjust_amount(stock='600031',amount=110)
        

输出的结果

100

底层源代码

def adjust_amount(self,stock='',amount=''):
        '''
        调整数量
        '''           
        if stock[:3] in ['110','113','123','127','128','111'] or stock[:2] in ['11','12']:
            amount=math.floor(amount/10)*10
        else:
            amount=math.floor(amount/100)*100
        return amount

36 目标价值下单

调用代码

'''
        目标价值下单
        stock: 股票名字
        value: 股票价值,value = 最新价 * 手数 * 保证金率(股票为1) * 乘数(股票为100)
        prive交易的的价格
        '''
trader.order_target_value(stock='501018',value=1000,price=1.33)
        

输出的结果

'''
        目标价值下单
        stock: 股票名字
        value: 股票价值,value = 最新价 * 手数 * 保证金率(股票为1) * 乘数(股票为100)
        prive交易的的价格
        '''
trader.order_target_value(stock='501018',value=1000,price=1.33)
        

底层源代码

def order_target_value(self,stock='501018',value=1000,price=1.33):
        '''
        目标价值下单
        stock: 股票名字
        value: 股票价值,value = 最新价 * 手数 * 保证金率(股票为1) * 乘数(股票为100)
        prive交易的的价格
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        amount=math.floor(value/price)
        if hold_stock.shape[0]>0:
            stock=str(stock)
            df1=hold_stock[hold_stock['证券代码']==stock]
            if df1.shape[0]>0:
                #可以使用的数量兼容t0
                av_num=df1['可用余额'].tolist()[-1]
                #持有数量
                hold_num=df1['股票余额'].tolist()[-1]
                #持有的价值
                hold_value=df1['市值'].tolist()[-1]
            else:
                av_num=0
                hold_num=0
                hold_value=0
        else:
            av_num=0
            hold_num=0
            hold_value=0
        #买卖价值差转成数量
        #可转债最新10
        amount=self.adjust_amount(stock=stock,amount=amount)
        #买卖的差额
        buy_sell_num=math.floor(amount-float(hold_num))
        buy_sell_num=self.adjust_amount(stock=stock,amount=buy_sell_num)
        buy_sell_value=buy_sell_num*price
        #存在买入差额,买入的大于持有的
        if buy_sell_num>0:
            if buy_sell_num>=10:
                #可用现金大于买卖的差额
                if cash>=buy_sell_value:
                    print('目标价值下单{} 目标价值{} 可用资金{}大于买卖资金{} 目标数量{} 持有数量{} 可用数量{} 买入差额{}'.format(stock,value,cash,buy_sell_value,amount,hold_num,av_num,buy_sell_num))
                    return 'buy',buy_sell_num,price
                else:
                    print('目标价值下单{} 目标价值{} 可用资金{}小于买卖资金{} 目标数量{} 持有数量{} 可用数量{} 买入差额{}不下单'.format(stock,value,cash,buy_sell_value,amount,hold_num,av_num,buy_sell_num))
                    return '',0,price
            else:
                print('目标价值下单{} 目标价值{} 可用资金{} 买卖资金{} 目标数量{} 持有数量{} 可用数量{} 买入差额{}不下单小于最小单位去10'.format(stock,value,cash,buy_sell_value,amount,hold_num,av_num,buy_sell_num))
                return '',0,price
        #存在卖出空间,目标数量小于持有数量卖出:
        elif buy_sell_num <0:
            #可以卖出的数量多
            if av_num>=buy_sell_num:
                buy_sell_num=abs(buy_sell_num)
                buy_sell_num=self.adjust_amount(stock=stock,amount=buy_sell_num)
                print('目标价值下单{} 目标价值{} 目标数量{} 持有数量{} 可用数量{} 卖出差额{}'.format(stock,value,amount,hold_num,av_num,buy_sell_num))
                return 'sell',buy_sell_num,price
            else:
                #可以卖出的不足卖出全部可以卖出的
                print('目标价值下单{} 目标价值{} 目标数量{} 持有数量{} 可用数量{}小于卖出数量 卖出差额{}'.format(stock,value,amount,hold_num,av_num,buy_sell_num))
                return 'sell',av_num,price
        else:
            print('目标价值下单{} 目标价值{} 目标数量{} 等于持有数量{} 可用数量{} 卖出差额{}不下单'.format(stock,value,amount,hold_num,av_num,buy_sell_num))
            return '',0,price

37百分比交易

调用代码

'''
        百分比交易
        percent下单百分比
        '''
trader.order_percent(stock='501018',percent=0.1,price=1.33,trader_type='buy')
        

输出的结果

持仓数量: 9
委托数量 0
目前没有委托
今天没有委托3/委托已经成交
百分比交易501018 下单类型buy 百分比0.1 下单数量1503400 可以资金19919535.36大于目标资金1999588.3760000002 买入数量1503400
('buy', 1503400, 1.33)

底层源代码

def order_percent(self,stock='501018',percent=0.1,price=1.33,trader_type='buy'):
        '''
        百分比交易
        percent下单百分比
        '''
        hold_stock=self.position()
        account=self.balance()
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type='金额')
        #目标金额=目标百分比-委托金额
        target_value=total_asset*percent-entrusts_amount
        #数量
        amount=target_value/price
        amount=self.adjust_amount(stock=stock,amount=amount)
        if trader_type=='buy':
            #这里按道理要考虑手续费看个资金
            if cash>=target_value:
                if amount>=10:
                    print('百分比交易{} 下单类型{} 百分比{} 下单数量{} 可以资金{}大于目标资金{} 买入数量{}'.format(stock,trader_type,percent,amount,cash,target_value,amount))
                    return 'buy',amount,price
                else:
                    print('百分比交易{} 下单类型{} 百分比{} 下单数量{} 可以资金{}大于目标资金{} 买入数量{}小于10不下单'.format(stock,trader_type,percent,amount,cash,target_value,amount))
                    return '',0,price
            else:
                print('百分比交易{} 下单类型{} 百分比{} 下单数量{} 可以资金{}小于目标资金{} 买入数量{}'.format(stock,trader_type,percent,amount,cash,target_value,amount))
                return '',0,price
        elif trader_type=='sell':
            if hold_stock.shape[0]>0:
                stock=str(stock)
                df1=hold_stock[hold_stock['证券代码']==stock]
                if df1.shape[0]>0:
                    #可以使用的数量兼容t0
                    av_num=df1['可用余额'].tolist()[-1]
                    #持有数量
                    hold_num=df1['股票余额'].tolist()[-1]
                    #持有的价值
                    hold_value=df1['市值'].tolist()[-1]
                    #可用数量大于卖出数量
                    if av_num>=amount:
                        print('百分比交易{} 下单类型{} 百分比{} 持有数量{} 可以数量{} 大于等于下单数量{} 下单{}'.format(stock,trader_type,percent,hold_num,cash,amount,amount))
                        return 'sell',amount,price
                    else:
                        print('百分比交易{} 下单类型{} 百分比{} 持有数量{} 可以数量{} 小于下单数量{} 下单{}'.format(stock,trader_type,percent,hold_num,cash,amount,av_num))
                        return 'sell',av_num,price
                else:
                    print('{}账户没有持股不支持交易类型{}'.format(stock,trader_type))
                    return '',0,price
            else:
                print('账户没有持股不支持交易类型{}'.format(trader_type))
                return '',0,price
        else:
            print('未知的交易类型{}'.format(trader_type))
            return '',0,price

38 百分比交易sell

调用源代码

'''
        百分比交易
        percent下单百分比
        '''
trader.order_percent(stock='501018',percent=0.1,price=1.33,trader_type='sell')
        

输出的结果

持仓数量: 9
委托数量 0
目前没有委托
今天没有委托3/委托已经成交
501018账户没有持股不支持交易类型sell
('', 0, 1.33)

39目标百分比下单

调用的代码

'''
        目标百分比下单
        '''
trader.order_target_percent(stock='501018',target_percent=0.1,price=1.33)
       

输出的结果

持仓数量: 9
目标百分比下单501018 目标百分比0.1 目标数量1503449.9067669173 可以资金19919535.36大于目标资金1999588.3760000002 持有数量0 可用数量0 买入差额1503400
('buy', 1503400, 1.33)

底层源代码

 def order_target_percent(self,stock='501018',target_percent=0.1,price=1.33):
        '''
        目标百分比下单
        '''
        hold_stock=self.position()
        account=self.balance()
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        #entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type='金额')
        #目标金额
        target_value=total_asset*target_percent
        #目标数量
        target_amount=target_value/price
        amount=self.adjust_amount(stock=stock,amount=target_amount)
        if hold_stock.shape[0]>0:
            stock=str(stock)
            df1=hold_stock[hold_stock['证券代码']==stock]
            if df1.shape[0]>0:
                #可以使用的数量兼容t0
                av_num=df1['可用余额'].tolist()[-1]
                #持有数量
                hold_num=df1['股票余额'].tolist()[-1]
                #持有的价值
                hold_value=df1['市值'].tolist()[-1]
            else:
                av_num=0
                hold_num=0
                hold_value=0
        else:
            av_num=0
            hold_num=0
            hold_value=0
        #没有买入数量,目标数量-持有数量
        buy_sell_amount=amount-hold_num
        #大于0 存在买入的差额
        if buy_sell_amount>=10:
            #可以现金大于目标金额 这里要考虑手续看个人资金
            if cash>=target_value:
                print('目标百分比下单{} 目标百分比{} 目标数量{} 可以资金{}大于目标资金{} 持有数量{} 可用数量{} 买入差额{}'.format(stock,target_percent,target_amount,cash,target_value,hold_num,av_num,buy_sell_amount))
                return 'buy',buy_sell_amount,price
            else:
                print('目标百分比下单{} 目标百分比{} 目标数量{} 可以资金{}小于目标资金{} 持有数量{} 可用数量{} 买入差额{}不下单'.format(stock,target_percent,target_amount,cash,target_value,hold_num,av_num,buy_sell_amount))
                return '',0,price
        elif buy_sell_amount<=10 and buy_sell_amount>=0:
            print('目标百分比下单{} 目标百分比{} 目标数量{} 可以资金{}目标资金{} 持有数量{} 可用数量{} 买入差额{}小于10不下单'.format(stock,target_percent,target_amount,cash,target_value,hold_num,av_num,buy_sell_amount))
            return '',0,price
        else:
            #可用买入的差额小于0 卖出
            buy_sell_amount=abs(buy_sell_amount)
            #可用数量大于差额
            if av_num>=buy_sell_amount:
                print('目标百分比下单{} 目标百分比{} 目标数量{} 持有数量{} 可用数量{} 大于差额{} 卖出差额{}'.format(stock,target_percent,target_amount,hold_num,av_num,buy_sell_amount,buy_sell_amount))
                return 'sell',buy_sell_amount,price
            else:
                print('目标百分比下单{} 目标百分比{} 目标数量{} 持有数量{} 可用数量{} 小于差额{} 卖出全部{}'.format(stock,target_percent,target_amount,hold_num,av_num,buy_sell_amount,av_num))
                return 'sell',av_num,price

40 目标百分比下单卖

调用函数

'''
        目标百分比下单
        '''
trader.order_target_percent(stock='501018',target_percent=0,price=1.33)
       

输出的结果

持仓数量: 9
目标百分比下单501018 目标百分比0 目标数量0.0 可以资金19919535.36目标资金0.0 持有数量0 可用数量0 买入差额0小于10不下单
('', 0, 1.33)

41 目标百分比下单数量模式

调用源代码

'''
        目标百分比下单数量模式
        '''
trader.order_target_percent_volume(stock='501018',target_percent=0.1,price=1.33)
        

输出的结果

'''
        目标百分比下单数量模式
        '''
trader.order_target_percent_volume(stock='501018',target_percent=0.1,price=1.33)
        

底层源代码

def order_target_percent_volume(self,stock='501018',target_percent=0.1,price=1.33):
        '''
        目标百分比下单数量模式
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        #entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type='金额')
        #目标金额
        target_value=total_asset*target_percent
        #目标数量
        target_amount=target_value/price
        trader_type,trader_amount,price=self.order_target_volume(stock=stock,amount=target_amount,price=price)
        return trader_type,trader_amount,price

42目标百分比下单数量模式sell

调用函数

'''
        目标百分比下单数量模式
        '''
trader.order_target_percent_volume(stock='501018',target_percent=0,price=1.33)
        

输出的结果

'''
        目标百分比下单数量模式
        '''
trader.order_target_percent_volume(stock='501018',target_percent=0,price=1.33)
        
        

43 目标百分比下单金额模式

调用源代码

'''
        目标百分比下单金额模式
        '''
trader.order_target_percent_value(stock='501018',target_percent=0.1,price=1.33)
        

输出的结果

持仓数量: 9
持仓数量: 9
目标价值下单501018 目标价值1999588.3760000002 可用资金19919535.36大于买卖资金1999522.0 目标数量1503400 持有数量0 可用数量0 买入差额1503400
('buy', 1503400, 1.33)

底层源代码

 def order_target_percent_value(self,stock='501018',target_percent=0.1,price=1.33):
        '''
        目标百分比下单金额模式
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        #entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type='金额')
        #目标金额
        target_value=total_asset*target_percent
        #目标数量
        target_amount=target_value/price
        trader_type,trader_amount,price=self.order_target_value(stock=stock,value=target_value,price=price)
        return trader_type,trader_amount,price

44检查模块资金分配

底层源代码

def check_av_target_trader(self,data_type='数量',trader_type='buy',amount=1000,limit_volume=2000,
                value=2000,limit_value=4000,stock='501018',price=2.475):
        '''
        检查模块资金分配
        data_type='数量'/资金,
        trader_type='buy',交易类型
        amount=1000,每次交易的数量股
        limit_volume=2000,单一标的持股限制
        value=2000,每次交易金额
        limit_value=4000,单一标的金额限制
        stock='501018',代码
        price=2.475交易的价格
        '''
        self.get_check_not_trader_today_entrusts()
        #stock=self.adjust_stock(stock=stock)
        stock=str(stock)[:6]
        self.open_set=''
        try:
            hold_stock=self.position()
        except:
            hold_stock=pd.read_excel(r'持股数据\持股数据.xlsx',dtype='object')
        if data_type=='数量':
            if hold_stock.shape[0]>0:
                stock=str(stock)
                if trader_type=='buy':
                    df1=hold_stock[hold_stock['证券代码']==stock]
                    #标的有持股
                    if df1.shape[0]>0:
                        #可以使用的数量兼容t0
                        av_num=df1['可用余额'].tolist()[-1]
                        #持有数量
                        hold_num=df1['股票余额'].tolist()[-1]
                        #委托数量
                        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type=data_type)
                        #买卖的差额
                        av_buy_sell=limit_volume-hold_num-entrusts_amount
                        #持股限制大于现在的持有数量
                        #可以买入的数量大于每次交易的数量
                        if av_buy_sell>=amount:
                            amount=self.adjust_amount(stock=stock,amount=amount)
                            if amount<=0:
                                print('数量模块1{} 可以买入的数量{} 小于0'.format(stock,amount))
                                return '','',''
                            else:
                                return 'buy',amount,price
                        else:
                            #可以买入的数量小于每次交易的数量
                            msg='数量模块2{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                            print(msg)
                            return '',amount,price
                    else:
                        #如果没有持股,直接买入,
                        #持有数量为0
                        #委托数量
                        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='buy',data_type=data_type)
                        av_buy_sell=limit_volume-0-entrusts_amount
                        #持股限制大于现在的持有数量
                        #可以买入的数量大于每次交易的数量
                        if av_buy_sell>=amount:
                            amount=self.adjust_amount(stock=stock,amount=amount)
                            if amount<=0:
                                print('数量模块3{} 可以买入的数量{} 小于0'.format(stock,amount))
                                return '',amount,price
                            else:
                                return 'buy',amount,price
                        else:
                            #可以买入的数量小于每次交易的数量
                            msg='数量模块4{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                            print(msg)
                            return '',amount,price
                #单一标的有持股卖出
                else:
                    #卖
                    df1=hold_stock[hold_stock['证券代码']==stock]
                    #有持股
                    if df1.shape[0]>0:
                        #可以使用的数量兼容t0
                        av_num=df1['可用余额'].tolist()[-1]
                        #持有数量
                        hold_num=df1['股票余额'].tolist()[-1]
                        #可以卖出的数量
                        #委托数量
                        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='sell',data_type=data_type)
                        av_buy_sell=hold_num-amount-entrusts_amount
                        av_num=self.adjust_amount(stock,amount=av_num)
                        if av_buy_sell>=amount:
                            return 'sell',amount,price
                        else:
                            if av_num>0:
                                return 'sell',av_num,price
                            else:
                                print('数量模块5不卖出 可以数量0 小于固定交易数量{} '.format(amount))
                                return '',amount,price
                    else:
                        print('数量模块6持股卖出没有持股 可以数量0 小于固定交易数量{} '.format(amount))
                        return '',amount,price
                        
            #账户没有持股,为空
            else:
                if trader_type=='buy':
                    #委托数量
                    entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type=trader_type,data_type=data_type)
                    av_buy_sell=limit_volume-0-entrusts_amount
                    #持股限制大于现在的持有数量
                    #可以买入的数量大于每次交易的数量
                    if av_buy_sell>=amount:
                        amount=self.adjust_amount(stock=stock,amount=amount)
                        if amount<=0:
                            print('数量模块7{} 可以买入的数量{} 小于0'.format(stock,amount))
                            return '',amount,price
                        else:
                            return 'buy',amount,price
                    else:
                        #可以买入的数量小于每次交易的数量
                        msg='数量模块8{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                        print(msg)
                        return '',amount,price 
                else:
                    print('数量模块9{} 账户持股为空不能卖出'.format(stock))
                    return '',amount,price
        else:
            #金额
            amount=value/price
            amount=self.adjust_amount(stock=stock,amount=amount)
            limit_volume=limit_value/price
            limit_volume=self.adjust_amount(stock=stock,amount=limit_volume)
            if hold_stock.shape[0]>0:
                stock=str(stock)
                df1=hold_stock[hold_stock['证券代码']==stock]
                stock=str(stock)
                if trader_type=='buy':
                    df1=hold_stock[hold_stock['证券代码']==stock]
                    #单一标的有持股
                    if df1.shape[0]>0:
                        #可以使用的数量兼容t0
                        av_num=df1['可用余额'].tolist()[-1]
                        #持有数量
                        hold_num=df1['股票余额'].tolist()[-1]
                        hold_value=df1['市值'].tolist()[-1]
                        hold_num=self.adjust_amount(stock=stock,amount=hold_value/price)
                        if hold_value>=limit_value:
                            print('资金模块1{} 持股的价值{}大于持股价值{}限制不交易'.format(stock,hold_value,limit_value))
                            return '',price,''
                        else:
                            #买卖的差额
                            #委托数量
                            entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type=trader_type,data_type='金额')
                            av_buy_sell=limit_volume-hold_num-entrusts_amount
                            if av_buy_sell>=amount:
                                amount=self.adjust_amount(stock=stock,amount=amount)
                                if amount<=0:
                                    print('资金模块2{} 可以买入的数量{} 小于0'.format(stock,amount))
                                    return '','',''
                                else:
                                    return 'buy',amount,price
                            else:
                                #可以买入的数量小于每次交易的数量
                                msg='资金模块3{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                                print(msg)
                                return '',amount,price
                    #单一标的账户没有持股买入
                    else:
                        amount=value/price
                        amount=self.adjust_amount(stock=stock,amount=amount)
                        limit_volume=limit_value/price
                        limit_volume=self.adjust_amount(stock=stock,amount=limit_volume)
                        #委托数量
                        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type=trader_type,data_type='金额')
                        av_buy_sell=limit_volume-0-entrusts_amount
                        if av_buy_sell>=amount:
                            if amount<=0:
                                    print('资金模块4{} 可以买入的数量{} 小于0'.format(stock,av_buy_sell))
                                    return '',amount,price
                            else:
                                return 'buy',amount,price
                        else:
                            #可以买入的数量小于每次交易的数量
                            msg='资金模块5{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                            print(msg)
                            return '',amount,price
                #单一有持股卖出
                else:
                    #卖
                    df1=hold_stock[hold_stock['证券代码']==stock]
                    if df1.shape[0]>0:
                        #可以使用的数量兼容t0
                        amount=value/price
                        amount=self.adjust_amount(stock=stock,amount=amount)
                        limit_volume=limit_value/price
                        limit_volume=self.adjust_amount(stock=stock,amount=limit_volume)
                        stock=str(stock)
                        av_num=df1['可用余额'].tolist()[-1]
                        #持有数量
                        hold_num=df1['股票余额'].tolist()[-1]
                        hold_value=df1['市值'].tolist()[-1]
                        hold_num=self.adjust_amount(stock=stock,amount=hold_value/price)
                        #委托数量
                        entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type='sell',data_type='金额')
                        #可以卖出的数量
                        av_buy_sell=hold_num-amount-entrusts_amount
                        if av_buy_sell>=amount:
                            return 'sell',amount,price
                        else:
                            if av_num>0:
                                return 'sell',av_num,price
                            else:
                                #可以买入的数量小于每次交易的数量
                                msg='资金模块6持股卖出{} 可用数量{}小于0'.format(stock,av_num)
                                print(msg)
                                return '',amount,price
                    else:
                        msg='资金模块7有持股卖出{} 可用数量小于0'.format(stock)
                        print(msg)
                        return '',amount,price
            #账户没有持股买入
            else:
                if trader_type=='buy':
                    amount=value/price
                    amount=self.adjust_amount(stock,amount=amount)
                    limit_volume=limit_value/price
                    limit_volume=self.adjust_amount(stock=stock,amount=limit_volume)
                    #委托数量
                    entrusts_amount,entrusts_df=self.get_check_not_trader_today_entrusts(stock=stock,trader_type=trader_type,data_type='金额')
                    av_buy_sell=limit_volume-0-entrusts_amount
                    if av_buy_sell>=amount:
                        if amount<=0:
                            print('资金模块8{} 可以买入的数量{} 小于0'.format(stock,av_buy_sell))
                            return '',amount,price
                        else:
                            return 'buy',amount,price
                    else:
                        #可以买入的数量小于每次交易的数量
                        msg='资金模块9持股买入{} 可以买入的数量{} 小于每次交易数量{}不交易'.format(stock,av_buy_sell,amount)
                        print(msg)
                        return '',amount,price
                else:
                    print('资金模块10持股为空{}不卖出'.format(stock))
                    return '','','' 

45 一键清仓

调用源代码

'''
        一键清仓
        '''
trader.one_click_clearance()

输出数据

持仓数量: 9
一键清仓513100 持有数量8400 可用数量8400 卖出数量8400
None
交易类型24 代码513100.SH 价格1.4340000000000002 数量8400 订单编号1082182751
一键清仓600031 持有数量500 可用数量500 卖出数量500
on order_error callback
1082182751 1003 限价卖出 [SH513100] [BROKER] convert request error, none value of field [client_id], account: [55011917], func: [order], fi
None
交易类型24 代码600031.SH 价格15.67 数量500 订单编号1082182752
一键清仓000001 持有数量1700 可用数量1700 卖出数量1700
None
on order_error callback
1082182752 1003 限价卖出 [SH600031] [BROKER] convert request error, none value of field [client_id], account: [55011917], func: [order], fi
交易类型24 代码000001.SZ 价格10.17 数量1700 订单编号1082182753
一键清仓159502 持有数量100 可用数量100 卖出数量100
None
on order_error callback
1082182753 1003 限价卖出 [SZ000001] [BROKER] convert request error, none value of field [client_id], account: [55011917], func: [order], fi
交易类型24 代码159502.SZ 价格1.02 数量100 订单编号1082182754
一键清仓159509 持有数量4300 可用数量4300 卖出数量4300

底层源代码

def one_click_clearance(self):
        '''
        一键清仓
        '''
        hold_stock=self.position()
        if hold_stock.shape[0]>0:
            for stock,hold_num,av_num in zip(hold_stock["证券代码"].tolist(),
                hold_stock['可用余额'].tolist(),hold_stock['股票余额'].tolist()):
                try:
                    stock_1=self.adjust_stock(stock=stock)
                    price=self.data.get_full_tick(code_list=[stock_1])[stock_1]['lastPrice']
                    if av_num>=10:
                        print('一键清仓{} 持有数量{} 可用数量{} 卖出数量{}'.format(stock,hold_num,av_num,av_num))
                        self.sell(security=stock,amount=av_num,price=price)
                    else:
                        print('一键清仓{} 持有数量{} 可用数量{}小于0 卖出数量{} 不交易'.format(stock,hold_num,av_num,av_num))
                except Exception as e:
                    print(e)
        else:
            print("一键清仓 账户没有持股,清仓不了")

46一键撤单全部

调用源代码

"""
        一键撤单全部
        """
trader.one_click_cancel_order_all()
        

输出的结果

委托数量 0
目前没有委托
一键撤单 没有委托

底层源代码

def one_click_cancel_order_all(self):
        """
        一键撤单全部
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                    #撤单
                    cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                    if cancel_order_result>=0:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                    else:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

47 一键撤单全部买入委托

调用的代码

"""
        一键撤单全部买入委托
        """
trader.one_click_cancel_order_buy()
        

输出的结果

委托数量 0
目前没有委托
一键撤单 没有委托

底层源代码

def one_click_cancel_order_all(self):
        """
        一键撤单全部
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                    #撤单
                    cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                    if cancel_order_result>=0:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                    else:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

49一键撤单全部卖出委托

调用的代码

"""
        一键撤单全部卖出委托
        """
trader.one_click_cancel_order_sell()
        

输出结果

委托数量 0
目前没有委托
一键撤单 没有委托

底层源代码

def one_click_cancel_order_sell(self):
        """
        一键撤单全部卖出委托
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                    if data_type==24 or data_type=='卖出':
                        #撤单
                        cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                        if cancel_order_result>=0:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                        else:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
                    else:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{}不是卖出 撤单失败'.format(stock,amount,order_id,data_type))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

50一键撤单全部买入委

调用代码

"""
        一键撤单全部买入委托
        """
trader.one_click_cancel_order_buy()
        

输出的结果

委托数量 0
目前没有委托
一键撤单 没有委托

底层源代码

def one_click_cancel_order_buy(self):
        """
        一键撤单全部买入委托
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                    if data_type==23 or data_type=='买入':
                        #撤单
                        cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                        if cancel_order_result>=0:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                        else:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
                    else:
                        print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{}不是买入 撤单失败'.format(stock,amount,order_id,data_type))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

51一键撤单个股全部买入委托

调用源代码

"""
        一键撤单个股全部买入委托
        """
trader.one_click_cancel_order_buy_by_stock(stock='600031')
        

输出的结果

委托数量 0
目前没有委托
一键撤单 没有委托

底层源代码

def one_click_cancel_order_buy_by_stock(self,stock='600031'):
        """
        一键撤单个股全部买入委托
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                df=df[df['证券代码']==stock]
                if df.shape[0]>0:
                    for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                        if data_type==23 or data_type=='买入':
                            #撤单
                            cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                            if cancel_order_result>=0:
                                print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                            else:
                                print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
                        else:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{}不是买入 撤单失败'.format(stock,amount,order_id,data_type))
                else:
                    print('一键撤单{} 没有可以撤单的内容'.format(stock))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

52 一键撤单个股全部卖出委托

底层源代码

def one_click_cancel_order_sell_by_stock(self,stock='600031'):
        """
        一键撤单个股全部卖出委托
        """
        df=self.today_entrusts()
        if df.shape[0]>0:
            df=df[df['委托状态']>=48]
            df=df[df['委托状态']<=53]
            if df.shape[0]>0:
                df=df[df['证券代码']==stock]
                if df.shape[0]>0:
                    for stock,amount,order_id,data_type,in zip(df['证券代码'],df['未成交数量'],df['订单编号'],df['委托类型']):
                        if data_type==24 or data_type=='卖出':
                            #撤单
                            cancel_order_result=self.cancel_order_stock_async(order_id=int(order_id))
                            if cancel_order_result>=0:
                                print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单成功'.format(stock,amount,order_id,data_type))
                            else:
                                print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{} 撤单失败'.format(stock,amount,order_id,data_type))
                        else:
                            print('一键撤单{} 未成交数量{} 订单编号{} 委托类型{}不是卖出 撤单失败'.format(stock,amount,order_id,data_type))
                else:
                    print('一键撤单{} 没有可以撤单的内容'.format(stock))
            else:
                print("一键撤单 没有可以撤的单")
        else:
            print("一键撤单 没有委托")

53 查询信用资金账号对应的资产

调用源代码

'''
        账户数据
        释义
        查询信用资金账号对应的资产
        参数
        account - StockAccount 资金账号
        返回
        该信用账户对应的资产对象XtCreditDetail组成的list或者None
        备注
        None表示查询失败
        通常情况下一个资金账号只有一个详细信息数据
        示例
        查询信用资金账号1208970161对应的资产信息
        '''
trader.query_credit_detail()

输出结果

没有数据

底层源代码

def query_credit_detail(self):
        '''
        账户数据
        释义
        查询信用资金账号对应的资产
        参数
        account - StockAccount 资金账号
        返回
        该信用账户对应的资产对象XtCreditDetail组成的list或者None
        备注
        None表示查询失败
        通常情况下一个资金账号只有一个详细信息数据
        示例
        查询信用资金账号1208970161对应的资产信息
        '''
        account = StockAccount(self.account, self.account_type)
        positions=self.xt_trader.query_credit_detail(account)
        data=pd.DataFrame()
        if len(positions) != 0:
            for i in range(len(positions)):
                df=pd.DataFrame()
                df['账号类型']=[positions[i].account_type]
                df['资金账号']=[positions[i].account_id]
                df['账号状态']=[positions[i].m_nStatus]
                df['更新时间']=[positions[i].m_nUpdateTime]
                df['计算参数']=[positions[i].m_nCalcConfig]
                df['冻结金额']=[positions[i].m_dFrozenCash]
                df['总资产']=[positions[i].m_dBalance]
                df['可用金额']=[positions[i].m_dAvailable]
                df['持仓盈亏']=[positions[i].m_dPositionProfit]
                df['总市值']=[positions[i].m_dMarketValue]
                df['可取金额']=[positions[i].m_dFetchBalance]
                df['股票市值']=[positions[i].m_dStockValue]
                df['基金市值']=[positions[i].m_dFundValue]
                df['总负债']=[positions[i].m_dTotalDebt]
                df['可用保证金']=[positions[i].m_dEnableBailBalance]
                df['维持担保比例']=[positions[i].m_dPerAssurescaleValue]
                df['净资产']=[positions[i].m_dAssureAsset]
                df['融资负债']=[positions[i].m_dFinDebt]
                df['融资本金']=[positions[i].m_dFinDealAvl]
                df['融资息费']=[positions[i].m_dFinFee]
                df['融券负债']=[positions[i].m_dSloDebt]
                df['融券市值']=[positions[i].m_dSloMarketValue]
                df['融券息费']=[positions[i].m_dSloFee]
                df['其它费用']=[positions[i].m_dOtherFare]
                df['融资授信额度']=[positions[i].m_dFinMaxQuota]
                df['融资可用额度']=[positions[i].m_dFinEnableQuota]
                df['融资冻结额度']=[positions[i].m_dFinUsedQuota]
                df['融券授信额度']=[positions[i].m_dSloMaxQuota]
                df['融券可用额度']=[positions[i].m_dSloEnableQuota]
                df['融券冻结额度']=[positions[i].m_dSloUsedQuota]
                df['融券卖出资金']=[positions[i].m_dSloSellBalance]
                df['已用融券卖出资金']=[positions[i].m_dUsedSloSellBalance]
                df['剩余融券卖出资金']=[positions[i].m_dSurplusSloSellBalance]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有数据')
            df=pd.DataFrame()
            return df

54 查询资金账号对应的负债合约

调用源代码

'''
        释义
        查询资金账号对应的负债合约
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的负债合约对象StkCompacts组成的list或者None
        备注
        None表示查询失败或者负债合约列表为空
        示例
        查询信用资金账号1208970161对应的负债合约
        '''
trader.query_stk_compacts()
        

输出结果

0
没有负债合约

底层源代码

def query_stk_compacts(self):
        '''
        释义
        查询资金账号对应的负债合约
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的负债合约对象StkCompacts组成的list或者None
        备注
        None表示查询失败或者负债合约列表为空
        示例
        查询信用资金账号1208970161对应的负债合约
        '''
        account = StockAccount(self.account, self.account_type)
        compacts=self.xt_trader.query_stk_compacts(account)
        print(len(compacts))
        data=pd.DataFrame()
        if len(compacts) != 0:
            for i in range(len(compacts)):
                df=pd.DataFrame()   
                df['账号类型']=[compacts[i].account_type]
                df['资金账号']=[compacts[i].account_id]
                df['合约类型']=[compacts[i].compact_type]
                df['头寸来源']=[compacts[i].cashgroup_prop]
                df['证券市场']=[compacts[i].exchange_id]
                df['开仓日期']=[compacts[i].open_date]
                df['合约证券数量']=[compacts[i].business_vol]
                df['未还合约数量']=[compacts[i].real_compact_vol]
                df['到期日']=[compacts[i].ret_end_date]
                df['合约金额']=[compacts[i].business_balance]
                df['合约息费']=[compacts[i].businessFare]
                df['未还合约金额']=[compacts[i].real_compact_balance]
                df['未还合约息费']=[compacts[i].real_compact_fare]
                df['已还息费']=[compacts[i].repaid_fare]
                df['已还金额']=[compacts[i].repaid_balance]
                df['证券代码']=[compacts[i].instrument_id]
                df['合约编号']=[compacts[i].compact_id]
                df['定位串']=[compacts[i].position_str]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有负债合约')
            df=pd.DataFrame()
            return df

55 查询资金账号对应的融资融券标的

调用源代码

'''
        释义
        查询资金账号对应的负债合约
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的负债合约对象StkCompacts组成的list或者None
        备注
        None表示查询失败或者负债合约列表为空
        示例
        查询信用资金账号1208970161对应的负债合约
        '''
trader.query_stk_compacts()
        

输出的结果

0
没有负债合约

底层源代码

def query_stk_compacts(self):
        '''
        释义
        查询资金账号对应的负债合约
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的负债合约对象StkCompacts组成的list或者None
        备注
        None表示查询失败或者负债合约列表为空
        示例
        查询信用资金账号1208970161对应的负债合约
        '''
        account = StockAccount(self.account, self.account_type)
        compacts=self.xt_trader.query_stk_compacts(account)
        print(len(compacts))
        data=pd.DataFrame()
        if len(compacts) != 0:
            for i in range(len(compacts)):
                df=pd.DataFrame()   
                df['账号类型']=[compacts[i].account_type]
                df['资金账号']=[compacts[i].account_id]
                df['合约类型']=[compacts[i].compact_type]
                df['头寸来源']=[compacts[i].cashgroup_prop]
                df['证券市场']=[compacts[i].exchange_id]
                df['开仓日期']=[compacts[i].open_date]
                df['合约证券数量']=[compacts[i].business_vol]
                df['未还合约数量']=[compacts[i].real_compact_vol]
                df['到期日']=[compacts[i].ret_end_date]
                df['合约金额']=[compacts[i].business_balance]
                df['合约息费']=[compacts[i].businessFare]
                df['未还合约金额']=[compacts[i].real_compact_balance]
                df['未还合约息费']=[compacts[i].real_compact_fare]
                df['已还息费']=[compacts[i].repaid_fare]
                df['已还金额']=[compacts[i].repaid_balance]
                df['证券代码']=[compacts[i].instrument_id]
                df['合约编号']=[compacts[i].compact_id]
                df['定位串']=[compacts[i].position_str]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有负债合约')
            df=pd.DataFrame()
            return df

56查询资金账号对应的融资融券标的

调用源代码

'''
        释义
        查询资金账号对应的融资融券标的
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的融资融券标的对象CreditSubjects组成的list或者None
        备注
        None表示查询失败或者融资融券标的列表为空
        示例
        查询信用资金账号1208970161对应的融资融券标的
        '''
trader.query_credit_subjects()
        

输出的结果

0
没有融资融券标的
        

底层源代码

 def query_credit_subjects(self):
        '''
        释义
        查询资金账号对应的融资融券标的
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的融资融券标的对象CreditSubjects组成的list或者None
        备注
        None表示查询失败或者融资融券标的列表为空
        示例
        查询信用资金账号1208970161对应的融资融券标的
        '''
        account = StockAccount(self.account, self.account_type)
        compacts=self.xt_trader.query_credit_subjects(account)
        print(len(compacts))
        data=pd.DataFrame()
        if len(compacts) != 0:
            for i in range(len(compacts)):
                df=pd.DataFrame()   
                df['账号类型']=[compacts[i].account_type]
                df['资金账号']=[compacts[i].account_id]
                df['融券状态']=[compacts[i].slo_status]
                df['证券市场']=[compacts[i].exchange_id]
                df['融券保证金比例']=[compacts[i].slo_ratio]
                df['融资保证金比例']=[compacts[i].fin_ratio]
                df['证券代码']=[compacts[i].instrument_id]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有融资融券标的')
            df=pd.DataFrame()
            return df

57查询资金账号对应的可融券数据

调用源代码

'''
        释义
        查询资金账号对应的可融券数据
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的可融券数据对象CreditSloCode组成的list或者None
        备注
        None表示查询失败或者可融券数据列表为空
        示例
        查询
'''
trader.query_credit_slo_code()
        

输出的结果

0
没有可融券数据

底层源代码

def query_credit_slo_code(self):
        '''
        释义
        查询资金账号对应的可融券数据
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的可融券数据对象CreditSloCode组成的list或者None
        备注
        None表示查询失败或者可融券数据列表为空
        示例
        查询信用资金账号1208970161对应的可融券数据
        '''
        account = StockAccount(self.account, self.account_type)
        compacts=self.xt_trader.query_credit_slo_code(account)
        print(len(compacts))
        data=pd.DataFrame()
        if len(compacts) != 0:
            for i in range(len(compacts)):
                df=pd.DataFrame()   
                df['账号类型']=[compacts[i].account_type]
                df['资金账号']=[compacts[i].account_id]
                df['头寸来源']=[compacts[i].cashgroup_prop]
                df['证券市场']=[compacts[i].exchange_id]
                df['融券可融数量']=[compacts[i].enable_amount]
                df['证券代码']=[compacts[i].instrument_id]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有可融券数据')
            df=pd.DataFrame()
            return df

58查询资金账号对应的标的担保品

调用源代码

'''
        释义
        查询资金账号对应的标的担保品
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的标的担保品对象CreditAssure组成的list或者None
        备注
        None表示查询失败或者标的担保品列表为空
        示例
        查询信用资金账号1208970161对应的标的担保品
        '''
trader.query_credit_assure()
        

输出的结果

0
没有对应的标的担保品

底层源代码

def query_credit_assure(self):
        '''
        释义
        查询资金账号对应的标的担保品
        参数
        account - StockAccount 资金账号
        返回
        该账户对应的标的担保品对象CreditAssure组成的list或者None
        备注
        None表示查询失败或者标的担保品列表为空
        示例
        查询信用资金账号1208970161对应的标的担保品
        '''
        account = StockAccount(self.account, self.account_type)
        compacts=self.xt_trader.query_credit_assure(account)
        print(len(compacts))
        data=pd.DataFrame()
        if len(compacts) != 0:
            for i in range(len(compacts)):
                df=pd.DataFrame()   
                df['账号类型']=[compacts[i].account_type]
                df['资金账号']=[compacts[i].account_id]
                df['是否可做担保']=[compacts[i].assure_status]
                df['证券市场']=[compacts[i].exchange_id]
                df['担保品折算比例']=[compacts[i].assure_ratio]
                df['证券代码']=[compacts[i].instrument_id]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有对应的标的担保品')
            df=pd.DataFrame()
            return df

59检查个股的权重

底层源代码

def check_stock_weight(self,stock='600031',user_ratio=0.1):
        '''
        检查个股的权重
        '''
        account=self.balance()
        position=self.position()
        total_cash=account['总资产'].tolist()
        total_cash=total_cash*user_ratio
        if position.shape[0]>0:
            df=position[position['证券代码']==stock]
            if df.shape[0]>0:
                market_value=df['市值'].tolist()[-1]
                return market_value/total_cash
            else:
                return 0
        else:
            return 0

二qmt_trader实盘例子

可以加我微信获取,加入知识星球可以直接下载使用

1通达信预警系统

源代码

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.analysis_models import analysis_models
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from qmt_trader.qmt_trader_ths import qmt_trader_ths
from xgtrader.xgtrader import xgtrader
from trader_tool.ths_rq import ths_rq
from trader_tool.ths_board_concept_data import ths_board_concept_data
from trader_tool.unification_data import unification_data
import os
import pandas as pd
from trader_tool.dfcf_etf_data import dfcf_etf_data
from datetime import datetime
from .user_def_models import user_def_moels
class tongda_letter_early_warning_trading_system:
    def __init__(self,trader_tool='qmt',exe='C:/同花顺软件/同花顺/xiadan.exe',tesseract_cmd='C:/Program Files/Tesseract-OCR/tesseract',
                qq='1029762153@qq.com',open_set='否',qmt_path='D:/国金QMT交易端模拟/userdata_mini',
                qmt_account='55009640',qmt_account_type='STOCK',name='customize_trading_strategies'):
        '''
        分析模型
        '''
        self.exe=exe
        self.tesseract_cmd=tesseract_cmd
        self.qq=qq
        self.trader_tool=trader_tool
        self.open_set=open_set
        self.qmt_path=qmt_path
        self.qmt_account=qmt_account
        self.qmt_account_type=qmt_account_type
        if trader_tool=='ths':
            self.trader=xgtrader(exe=self.exe,tesseract_cmd=self.tesseract_cmd,open_set=open_set)
        else:
            self.trader=qmt_trader_ths(path=qmt_path,account=qmt_account,account_type=qmt_account_type)
        self.stock_data=stock_data()
        self.bond_cov_data=bond_cov_data()
        self.ths_rq=ths_rq()
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.ths_board_concept_data=ths_board_concept_data()
        self.name=name
        self.data=unification_data(trader_tool=self.trader_tool)
        self.data=self.data.get_unification_data()
        self.dfcf_etf_data=dfcf_etf_data()
        self.user_def_moels=user_def_moels(trader_tool=self.trader_tool,exe=self.exe,
                                        tesseract_cmd=self.tesseract_cmd,qq=self.qq,
                                        open_set=self.open_set,qmt_path=self.qmt_path,qmt_account=self.qmt_account,
                                        qmt_account_type=self.qmt_account_type,name=self.name)
        self.trader.connect()
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        trader_type=text['交易品种']
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        df=self.trader.position()
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                if trader_type=='全部':
                    df=df
                else:
                    df['选择']=df['证券代码'].apply(self.trader.select_data_type)
                    df=df[df['选择']==trader_type]
                print(df)
                df=df[df['可用余额']>=10]
                df['黑名单']=df['证券代码'].apply(select_del_stock_list)
                df=df[df['黑名单']=='否']
                print('剔除黑名单**********')
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def save_balance(self):
        '''
        保持账户数据
        '''
        try:
            df=self.trader.balance()
            df.to_excel(r'账户数据\账户数据.xlsx')
            return df
        except Exception as e:
            print(e)
    def params_tdx_text(self):
        '''
        分析通达信内容
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        path=text['通达信警告保存路径']
        columns=text['通达信警告列名称']
        with open(r'{}'.format(path),'r+') as f:
            com=f.readlines()
        result_list=[]
        if len(com)<0:
            df=pd.DataFrame()
            df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
            print('没有警告内容****')
        else:
            for i in com:
                result_list.append(str(i).strip().split('\t'))
            df=pd.DataFrame(result_list)
            print('原始的数据*********************')
            print(df)
            df.columns=columns
            print('请仔细核对名称*************************')
            print(df)
            now_date=str(datetime.now())[:10]
            try:
                df['时间']=df['时间'].apply(lambda x:str(x)[:10])
                df=df[df['时间']==now_date]
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
            except Exception as e:
                print(e)
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
    def get_dea_buy_sell_data(self):
        '''
        处理买卖数据
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        maker_list=text['订单唯一的标识行']
        log_df=pd.read_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        try:
            del log_df['Unnamed: 0']
        except:
            pass
        log_columns=log_df.columns.tolist()
        if len(log_columns)>0:
            log_columns=log_columns
        else:
            log_columns=[]
        df=pd.read_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        if df.shape[0]>0:
            df1=df
            df_columns=df.columns.tolist()
            alike_list=[]
            for i in maker_list:
                if i in df_columns and len(log_columns)==0:
                    df['{}_选择'.format(i)]='不是'
                    print('表格记录为空**********8')
                elif i in df_columns and i in log_columns:
                    df['{}_选择'.format(i)]=df[i].apply(lambda x: '是' if x in log_df[i].tolist() else '不是')
                    alike_list.append('{}_选择'.format(i))
                else:
                    print('{}标记不在2个表中'.format(i))
            for i in alike_list:
                df=df[df[i]=='不是']
            if df.shape[0]>0:
                print('下单的内容************************8')
                print(df)
                df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            else:
                print('没有下单的内容))))))))))))))))))')
                df=pd.DataFrame()
                df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            #log_df=pd.concat([log_df,df],ignore_index=True)
            #log_df.to_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        else:
            print('通达信没有预警内容********************')
    def run_user_def_models(self):
        '''
        运行自定义模型
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        is_open=text['是否开启自定义模型']
        user_func_list=text['自定义模型']
        df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        log_df=pd.read_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        try:
            del log_df['Unnamed: 0']
        except:
            pass
        select_stock_list=[]
        if is_open=='是':
            if len(user_func_list)>0:
                if df.shape[0]>0:
                    for stock in df['证券代码'].tolist():
                        df['证券代码']=df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
                        for func in user_func_list:
                            try:
                                text='self.user_def_moels.{}'.format(func)
                                stats=eval(text)
                                if stats==True:
                                    select_stock_list.append(stock)
                            except Exception as e:
                                print(e)
                        df['自定义分析']=df['证券代码'].apply(lambda x: '是' if x in select_stock_list else '不是')
                        df=df[df['自定义分析']=='是']
                        df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
                        try:
                            del df['macd分析']
                        except Exception as e:
                            print(e)
                        log_df=pd.concat([log_df,df],ignore_index=True)
                        log_df.to_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
                    else:
                        print('没有交易数据*************************')
            else:
                print('没有自定义函数****************8')
        else:
            print('不开启自定义函数***********88')
    def get_params_taredr_stock(self):
        '''
        拆分买卖数据
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        try:
            df['证券代码']=df['证券代码'].apply(lambda x : '0'*(6-len(str(x)))+str(x))
        except Exception as e:
            print(e)
        try:
            del df['Unnamed: 0']
        except:
            pass
        buy_list=text['买入警告条件']
        sell_list=text['卖出警告条件']
        if df.shape[0]>0:
            df['buy']=df['买卖条件'].apply(lambda x: '是' if x in buy_list else '不是')
            df['sell']=df['买卖条件'].apply(lambda x: '是' if x in sell_list else '不是')
            buy_df=df[df['buy']=='是']
            print('买入股票***************************')
            print(buy_df)
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            sell_df=df[df['sell']=='是']
            print('卖出股票*****************')
            print(sell_df)
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
        else:
            print('没有交易数据*****************************')
            buy_df=pd.DataFrame()
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            sell_df=pd.DataFrame()
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))

    def get_del_not_trader_stock(self):
        '''
        剔除黑名单
        '''
        print('剔除黑名单______________*************************_______________________')
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        buy_df=pd.read_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path),dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            buy_df['黑名单']=buy_df['证券代码'].apply(select_del_stock_list)
            buy_df=buy_df[buy_df['黑名单']=='否']
            #隔离策略
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            buy_df['品种']=buy_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            print(buy_df)
        else:
            buy_df=pd.DataFrame()
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
        #卖出
        sell_df=pd.read_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path),dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            sell_df['黑名单']=sell_df['证券代码'].apply(select_del_stock_list)
            sell_df=sell_df[sell_df['黑名单']=='否']
            #隔离策略
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            sell_df['品种']=sell_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
            print(sell_df)
        else:
            sell_df=pd.DataFrame()
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
        return buy_df,sell_df
    def trader_data(self):
        '''
        开始下单
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        trader_models=text['交易模式']
        fix_amount=text['固定交易数量']
        fix_cash=text['固定交易金额']

        #先卖在买入
        sell_df=pd.read_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path),dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            for stock,condi in zip(sell_df['证券代码'].tolist(),sell_df['买卖条件'].tolist()):
                try:
                    price=self.data.get_spot_data(stock=stock)['最新价']
                    if trader_models=='数量':
                       
                        #检查是否可以卖出
                        if self.trader.check_stock_is_av_sell(stock=stock,amount=fix_amount):
                            self.trader.sell(security=stock,price=price,amount=fix_amount)
                            print('交易模式{}卖出条件{} 卖出 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,fix_amount,price))
                        else:
                            print('交易模式{}卖出条件{} {} 不能卖出'.format(trader_models,condi,stock))
                    elif trader_models=='金额':
                        trader_type,amount,price=self.trader.order_value(stock=stock,value=fix_cash,price=price,trader_type='sell')
                        if trader_type=='sell' and amount>=10:
                            self.trader.sell(security=stock,price=price,amount=amount)
                            print('交易模式{}卖出条件{} 卖出 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,amount,price))
                        else:
                            print('交易模式{}卖出条件{} {} 不能卖出'.format(trader_models,condi,stock))
                    else:
                        print('{} 未知的交易模式{}'.format(stock,trader_models))
                except Exception as e:
                    print('{}卖出有问题'.format(stock))
                    print(e)
        else:
            print('没有卖出的数据********************')
        #买入
        buy_df=pd.read_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path),dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            for stock,condi in zip(buy_df['证券代码'].tolist(),buy_df['买卖条件'].tolist()):
                try:
                    price=self.data.get_spot_data(stock=stock)['最新价']
                    if trader_models=='数量':
                        print(fix_amount,'******************')
                        #检查是否可以买入
                        if self.trader.check_stock_is_av_buy(stock=stock,amount=fix_amount,price=price):
                            self.trader.buy(security=stock,price=price,amount=fix_amount)
                            print('交易模式{}买入条件{} 买入 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,fix_amount,price))
                        else:
                            print('交易模式{}买入条件{} {} 不能买入'.format(trader_models,condi,stock))
                    elif trader_models=='金额':
                        trader_type,amount,price=self.trader.order_value(stock=stock,value=fix_cash,price=price,trader_type='buy')
                        if trader_type=='buy' and amount>=10:
                            self.trader.buy(security=stock,price=price,amount=amount)
                            print('交易模式{}买入条件{} 买入 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,amount,price))
                        else:
                            print('交易模式{}买入条件{} {} 不能买入'.format(trader_models,condi,stock))
                    else:
                        print('{} 未知的交易模式{}'.format(stock,trader_models))
                except Exception as e:
                    print('{}买入有问题'.format(stock))
                    print(e)
    def update_all_data(self):
        '''
        更新策略数据
        '''
        print(self.save_position())
        print(self.save_balance())
        self.params_tdx_text()
        self.get_dea_buy_sell_data()
        self.run_user_def_models()
        self.get_params_taredr_stock()
        self.get_del_not_trader_stock()
        self.trader_data()

2禄得可转债自定义因子

源代码

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.analysis_models import analysis_models
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from qmt_trader.qmt_trader_ths import qmt_trader_ths
from xgtrader.xgtrader import xgtrader
from trader_tool.ths_rq import ths_rq
from trader_tool.ths_board_concept_data import ths_board_concept_data
from trader_tool.unification_data import unification_data
import os
import pandas as pd
from trader_tool.dfcf_etf_data import dfcf_etf_data
from datetime import datetime
from .user_def_models import user_def_moels
class tongda_letter_early_warning_trading_system:
    def __init__(self,trader_tool='qmt',exe='C:/同花顺软件/同花顺/xiadan.exe',tesseract_cmd='C:/Program Files/Tesseract-OCR/tesseract',
                qq='1029762153@qq.com',open_set='否',qmt_path='D:/国金QMT交易端模拟/userdata_mini',
                qmt_account='55009640',qmt_account_type='STOCK',name='customize_trading_strategies'):
        '''
        分析模型
        '''
        self.exe=exe
        self.tesseract_cmd=tesseract_cmd
        self.qq=qq
        self.trader_tool=trader_tool
        self.open_set=open_set
        self.qmt_path=qmt_path
        self.qmt_account=qmt_account
        self.qmt_account_type=qmt_account_type
        if trader_tool=='ths':
            self.trader=xgtrader(exe=self.exe,tesseract_cmd=self.tesseract_cmd,open_set=open_set)
        else:
            self.trader=qmt_trader_ths(path=qmt_path,account=qmt_account,account_type=qmt_account_type)
        self.stock_data=stock_data()
        self.bond_cov_data=bond_cov_data()
        self.ths_rq=ths_rq()
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.ths_board_concept_data=ths_board_concept_data()
        self.name=name
        self.data=unification_data(trader_tool=self.trader_tool)
        self.data=self.data.get_unification_data()
        self.dfcf_etf_data=dfcf_etf_data()
        self.user_def_moels=user_def_moels(trader_tool=self.trader_tool,exe=self.exe,
                                        tesseract_cmd=self.tesseract_cmd,qq=self.qq,
                                        open_set=self.open_set,qmt_path=self.qmt_path,qmt_account=self.qmt_account,
                                        qmt_account_type=self.qmt_account_type,name=self.name)
        self.trader.connect()
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        trader_type=text['交易品种']
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        df=self.trader.position()
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                if trader_type=='全部':
                    df=df
                else:
                    df['选择']=df['证券代码'].apply(self.trader.select_data_type)
                    df=df[df['选择']==trader_type]
                print(df)
                df=df[df['可用余额']>=10]
                df['黑名单']=df['证券代码'].apply(select_del_stock_list)
                df=df[df['黑名单']=='否']
                print('剔除黑名单**********')
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def save_balance(self):
        '''
        保持账户数据
        '''
        try:
            df=self.trader.balance()
            df.to_excel(r'账户数据\账户数据.xlsx')
            return df
        except Exception as e:
            print(e)
    def params_tdx_text(self):
        '''
        分析通达信内容
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        path=text['通达信警告保存路径']
        columns=text['通达信警告列名称']
        with open(r'{}'.format(path),'r+') as f:
            com=f.readlines()
        result_list=[]
        if len(com)<0:
            df=pd.DataFrame()
            df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
            print('没有警告内容****')
        else:
            for i in com:
                result_list.append(str(i).strip().split('\t'))
            df=pd.DataFrame(result_list)
            print('原始的数据*********************')
            print(df)
            df.columns=columns
            print('请仔细核对名称*************************')
            print(df)
            now_date=str(datetime.now())[:10]
            try:
                df['时间']=df['时间'].apply(lambda x:str(x)[:10])
                df=df[df['时间']==now_date]
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
            except Exception as e:
                print(e)
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
    def get_dea_buy_sell_data(self):
        '''
        处理买卖数据
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        maker_list=text['订单唯一的标识行']
        log_df=pd.read_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        try:
            del log_df['Unnamed: 0']
        except:
            pass
        log_columns=log_df.columns.tolist()
        if len(log_columns)>0:
            log_columns=log_columns
        else:
            log_columns=[]
        df=pd.read_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        if df.shape[0]>0:
            df1=df
            df_columns=df.columns.tolist()
            alike_list=[]
            for i in maker_list:
                if i in df_columns and len(log_columns)==0:
                    df['{}_选择'.format(i)]='不是'
                    print('表格记录为空**********8')
                elif i in df_columns and i in log_columns:
                    df['{}_选择'.format(i)]=df[i].apply(lambda x: '是' if x in log_df[i].tolist() else '不是')
                    alike_list.append('{}_选择'.format(i))
                else:
                    print('{}标记不在2个表中'.format(i))
            for i in alike_list:
                df=df[df[i]=='不是']
            if df.shape[0]>0:
                print('下单的内容************************8')
                print(df)
                df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            else:
                print('没有下单的内容))))))))))))))))))')
                df=pd.DataFrame()
                df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            #log_df=pd.concat([log_df,df],ignore_index=True)
            #log_df.to_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        else:
            print('通达信没有预警内容********************')
    def run_user_def_models(self):
        '''
        运行自定义模型
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        is_open=text['是否开启自定义模型']
        user_func_list=text['自定义模型']
        df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        log_df=pd.read_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
        try:
            del log_df['Unnamed: 0']
        except:
            pass
        select_stock_list=[]
        if is_open=='是':
            if len(user_func_list)>0:
                if df.shape[0]>0:
                    for stock in df['证券代码'].tolist():
                        df['证券代码']=df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
                        for func in user_func_list:
                            try:
                                text='self.user_def_moels.{}'.format(func)
                                stats=eval(text)
                                if stats==True:
                                    select_stock_list.append(stock)
                            except Exception as e:
                                print(e)
                        df['自定义分析']=df['证券代码'].apply(lambda x: '是' if x in select_stock_list else '不是')
                        df=df[df['自定义分析']=='是']
                        df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
                        try:
                            del df['macd分析']
                        except Exception as e:
                            print(e)
                        log_df=pd.concat([log_df,df],ignore_index=True)
                        log_df.to_excel(r'{}\下单记录\下单记录.xlsx'.format(self.path))
                    else:
                        print('没有交易数据*************************')
            else:
                print('没有自定义函数****************8')
        else:
            print('不开启自定义函数***********88')
    def get_params_taredr_stock(self):
        '''
        拆分买卖数据
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        try:
            df['证券代码']=df['证券代码'].apply(lambda x : '0'*(6-len(str(x)))+str(x))
        except Exception as e:
            print(e)
        try:
            del df['Unnamed: 0']
        except:
            pass
        buy_list=text['买入警告条件']
        sell_list=text['卖出警告条件']
        if df.shape[0]>0:
            df['buy']=df['买卖条件'].apply(lambda x: '是' if x in buy_list else '不是')
            df['sell']=df['买卖条件'].apply(lambda x: '是' if x in sell_list else '不是')
            buy_df=df[df['buy']=='是']
            print('买入股票***************************')
            print(buy_df)
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            sell_df=df[df['sell']=='是']
            print('卖出股票*****************')
            print(sell_df)
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
        else:
            print('没有交易数据*****************************')
            buy_df=pd.DataFrame()
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            sell_df=pd.DataFrame()
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))

    def get_del_not_trader_stock(self):
        '''
        剔除黑名单
        '''
        print('剔除黑名单______________*************************_______________________')
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        buy_df=pd.read_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path),dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            buy_df['黑名单']=buy_df['证券代码'].apply(select_del_stock_list)
            buy_df=buy_df[buy_df['黑名单']=='否']
            #隔离策略
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            buy_df['品种']=buy_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
            print(buy_df)
        else:
            buy_df=pd.DataFrame()
            buy_df.to_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path))
        #卖出
        sell_df=pd.read_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path),dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            sell_df['黑名单']=sell_df['证券代码'].apply(select_del_stock_list)
            sell_df=sell_df[sell_df['黑名单']=='否']
            #隔离策略
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            sell_df['品种']=sell_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
            print(sell_df)
        else:
            sell_df=pd.DataFrame()
            sell_df.to_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path))
        return buy_df,sell_df
    def trader_data(self):
        '''
        开始下单
        '''
        with open(r'{}\通达信预警系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        trader_models=text['交易模式']
        fix_amount=text['固定交易数量']
        fix_cash=text['固定交易金额']

        #先卖在买入
        sell_df=pd.read_excel(r'{}\卖出股票\卖出股票.xlsx'.format(self.path),dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            for stock,condi in zip(sell_df['证券代码'].tolist(),sell_df['买卖条件'].tolist()):
                try:
                    price=self.data.get_spot_data(stock=stock)['最新价']
                    if trader_models=='数量':
                       
                        #检查是否可以卖出
                        if self.trader.check_stock_is_av_sell(stock=stock,amount=fix_amount):
                            self.trader.sell(security=stock,price=price,amount=fix_amount)
                            print('交易模式{}卖出条件{} 卖出 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,fix_amount,price))
                        else:
                            print('交易模式{}卖出条件{} {} 不能卖出'.format(trader_models,condi,stock))
                    elif trader_models=='金额':
                        trader_type,amount,price=self.trader.order_value(stock=stock,value=fix_cash,price=price,trader_type='sell')
                        if trader_type=='sell' and amount>=10:
                            self.trader.sell(security=stock,price=price,amount=amount)
                            print('交易模式{}卖出条件{} 卖出 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,amount,price))
                        else:
                            print('交易模式{}卖出条件{} {} 不能卖出'.format(trader_models,condi,stock))
                    else:
                        print('{} 未知的交易模式{}'.format(stock,trader_models))
                except Exception as e:
                    print('{}卖出有问题'.format(stock))
                    print(e)
        else:
            print('没有卖出的数据********************')
        #买入
        buy_df=pd.read_excel(r'{}\买入股票\买入股票.xlsx'.format(self.path),dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            for stock,condi in zip(buy_df['证券代码'].tolist(),buy_df['买卖条件'].tolist()):
                try:
                    price=self.data.get_spot_data(stock=stock)['最新价']
                    if trader_models=='数量':
                        print(fix_amount,'******************')
                        #检查是否可以买入
                        if self.trader.check_stock_is_av_buy(stock=stock,amount=fix_amount,price=price):
                            self.trader.buy(security=stock,price=price,amount=fix_amount)
                            print('交易模式{}买入条件{} 买入 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,fix_amount,price))
                        else:
                            print('交易模式{}买入条件{} {} 不能买入'.format(trader_models,condi,stock))
                    elif trader_models=='金额':
                        trader_type,amount,price=self.trader.order_value(stock=stock,value=fix_cash,price=price,trader_type='buy')
                        if trader_type=='buy' and amount>=10:
                            self.trader.buy(security=stock,price=price,amount=amount)
                            print('交易模式{}买入条件{} 买入 股票{} 数量{} 价格{}'.format(trader_models,condi,stock,amount,price))
                        else:
                            print('交易模式{}买入条件{} {} 不能买入'.format(trader_models,condi,stock))
                    else:
                        print('{} 未知的交易模式{}'.format(stock,trader_models))
                except Exception as e:
                    print('{}买入有问题'.format(stock))
                    print(e)
    def update_all_data(self):
        '''
        更新策略数据
        '''
        print(self.save_position())
        print(self.save_balance())
        self.params_tdx_text()
        self.get_dea_buy_sell_data()
        self.run_user_def_models()
        self.get_params_taredr_stock()
        self.get_del_not_trader_stock()
        self.trader_data()

        

3雪球跟单系统

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.analysis_models import analysis_models
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from qmt_trader.qmt_trader_ths import qmt_trader_ths
from xgtrader.xgtrader import xgtrader
from trader_tool.ths_rq import ths_rq
from trader_tool.ths_board_concept_data import ths_board_concept_data
from trader_tool.unification_data import unification_data
import os
import pandas as pd
from trader_tool.dfcf_etf_data import dfcf_etf_data
from trader_tool.xueqie_data import xueqie_data
from datetime import datetime
from trader_tool.base_func import base_func
class xueqie_trader:
    def __init__(self,trader_tool='qmt',exe='C:/同花顺软件/同花顺/xiadan.exe',tesseract_cmd='C:/Program Files/Tesseract-OCR/tesseract',
                qq='1029762153@qq.com',open_set='否',qmt_path='D:/国金QMT交易端模拟/userdata_mini',
                qmt_account='55009640',qmt_account_type='STOCK',name='customize_trading_strategies'):
        '''
        雪球跟单模型
        '''
        self.exe=exe
        self.tesseract_cmd=tesseract_cmd
        self.qq=qq
        self.trader_tool=trader_tool
        self.open_set=open_set
        self.qmt_path=qmt_path
        self.qmt_account=qmt_account
        self.qmt_account_type=qmt_account_type
        if trader_tool=='ths':
            self.trader=xgtrader(exe=self.exe,tesseract_cmd=self.tesseract_cmd,open_set=open_set)
        else:
            self.trader=qmt_trader_ths(path=qmt_path,account=qmt_account,account_type=qmt_account_type)
        self.stock_data=stock_data()
        self.bond_cov_data=bond_cov_data()
        self.ths_rq=ths_rq()
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.ths_board_concept_data=ths_board_concept_data()
        self.name=name
        self.data=unification_data(trader_tool=self.trader_tool)
        self.data=self.data.get_unification_data()
        self.dfcf_etf_data=dfcf_etf_data()
        self.trader.connect()
        self.base_func=base_func()
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        trader_type=text['交易品种']
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        df=self.trader.position()
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                if trader_type=='全部':
                    df=df
                else:
                    df['选择']=df['证券代码'].apply(self.trader.select_data_type)
                    df=df[df['选择']==trader_type]
                print(df)
                df=df[df['可用余额']>=10]
                df['黑名单']=df['证券代码'].apply(select_del_stock_list)
                df=df[df['黑名单']=='否']
                print('剔除黑名单**********')
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def save_balance(self):
        '''
        保持账户数据
        '''
        df=self.trader.balance()
        df.to_excel(r'账户数据\账户数据.xlsx')
        return df
    def get_del_buy_sell_data(self,name='',assembly_id='ZH3223683'):
        '''
        处理交易数据
        '''
        with open(r'{}\雪球跟单设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        cookie=text['雪球cookie']
        models=xueqie_data(cookie=cookie,assembly_id=assembly_id)
        df=pd.read_excel(r'持股数据\持股数据.xlsx',dtype='object')
        df1=df[df['股票余额']>=10]
        df1['证券代码']=df1['证券代码'].astype(str)
        hold_stock_list=df1['证券代码'].tolist()
        df=models.get_hist_move()
        try:
            trader_time=self.stock_data.get_trader_date_list()
            now_date=trader_time[-1]
        except Exception as e:
            print(e)
            now_date==str(datetime.now())[:10]
        if df.shape[0]>0:
            print('不开同步持股')
            df['updated_at']=pd.to_datetime(df['updated_at'],unit='ms')
            df['created_at']=pd.to_datetime(df['created_at'],unit='ms')
            df['updated_at']=df['updated_at'].apply(lambda x:str(x)[:10])
            df1=df[df['updated_at']==now_date]
            if df1.shape[0]>0:
                print('策略{} {}今天有交易数据'.format(name,now_date))
                print(df1)
                df=df1
                df['证券代码']=df['stock_symbol'].apply(lambda x:str(x)[2:])
                df['证券代码']=df['证券代码'].astype(str)
                df['prev_weight']=df['prev_weight'].fillna(0)
                df['adjust']=df['target_weight']-df['prev_weight']
                df=df.sort_values(by='created_at',ascending=True)
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
            else:
                print('策略{} {}今天没有交易数据'.format(name,now_date))
                df=pd.DataFrame()
                df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))

        else:
            print('策略{} {}今天没有交易数据'.format(name,now_date))
            df=pd.DataFrame()
            df.to_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path))
    def get_del_not_trader_stock(self):
        '''
        剔除黑名单
        '''
        print('剔除黑名单______________*************************_______________________')
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        df=pd.read_excel(r'{}\原始数据\原始数据.xlsx'.format(self.path),dtype='object')
        if df.shape[0]>0:
            df['证券代码']=df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del df['Unnamed: 0']
            except:
                pass
            df['黑名单']=df['证券代码'].apply(select_del_stock_list)
            df=df[df['黑名单']=='否']
            #隔离策略
            df['证券代码']=df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            df['品种']=df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            print(df)
        else:
            df=pd.DataFrame()
            df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
    def get_trader_data(self):
        '''
        获取交易数据
        '''
        with open(r'{}\雪球跟单设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        adjust_ratio=text['账户跟单比例']
        df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        trader_log=pd.read_excel(r'{}\跟单记录\跟单记录.xlsx'.format(self.path))
        try:
            del trader_log['Unnamed: 0']
        except:
            pass
        if df.shape[0]>0:
            if trader_log.shape[0]>0:
                trader_id_list=trader_log['id'].tolist()
            else:
                trader_id_list=[]
            df['交易情况']=df['id'].apply(lambda x : '已经下单' if x in trader_id_list else '没有下单')
            df=df[df['交易情况']=='没有下单']
            print('没有下单的交易*****************************')
            print(df)
            if df.shape[0]>0:
                df['证券名称']=df['stock_name']
                df['自动价格']='是'
                df['价格']=df['price']
                df['交易类型']='数量'
                df['交易方向']=df['adjust'].apply(lambda x : 'buy' if x>=0 else 'sell')
                df['交易状态']=df['交易方向'].apply(lambda x :'未买' if x=='buy' else '未卖')
                amount_list=[]
                for stock ,trader,adjust, in zip(df['证券代码'],df['交易方向'],df['adjust']):
                    try:
                        stock=str(stock)
                        price=self.data.get_spot_data(stock=stock)['最新价']
                        adjust=(adjust*adjust_ratio)/100
                        if trader=='buy':
                            trader_type,amount,price=self.trader.order_percent(stock=stock,price=price,percent=adjust,trader_type=trader)
                            amount_list.append(amount)
                        elif trader=='sell':
                            adjust=abs(adjust)
                            trader_type,amount,price=self.trader.order_percent(stock=stock,price=price,percent=adjust,trader_type=trader)
                            amount_list.append(amount)
                        else:
                            amount_list.append(0)
                    except Exception as e:
                        print(e)
                        amount_list.append(0)
                df['数量']=amount_list
                print('下单股票池))))))))))))))))))))))))')
                print(df)
                df.to_excel(r'{}\下单股票池\下单股票池.xlsx'.format(self.path))
                trader_log=pd.concat([trader_log,df],ignore_index=True)
                trader_log.to_excel(r'{}\跟单记录\跟单记录.xlsx'.format(self.path))
            else:
                print('没有需要下单标度******************')
                df=pd.DataFrame()
                df.to_excel(r'{}\下单股票池\下单股票池.xlsx'.format(self.path))
        else:
            print('没有交易股票池*************')
            df=pd.DataFrame()
            df.to_excel(r'{}\下单股票池\下单股票池.xlsx'.format(self.path))
    def start_trader_on(self):
        '''
        开始下单
        '''
        with open(r'{}\雪球跟单设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        df=pd.read_excel(r'{}\下单股票池\下单股票池.xlsx'.format(self.path))
        try:
            del df['Unnamed: 0']
        except:
            pass
        #资金模式
        cash_models=text['资金模式']
        #下单模式
        trader_models=text['下单交易模式']
        #自定义资金设置
        data_type=text['交易模式']
        value=text['固定交易资金']
        limit_value=text['持有金额限制']
        amount1=text['固定交易数量']
        limit_amount=text['持股限制']
        if df.shape[0]>0:
            df['证券代码']=df['证券代码'].astype(str)
            #print(df['证券代码'])
            df['证券代码']=df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            if cash_models=='雪球' and trader_models=='通过综合交易模型':
                buy_df=df[df['交易方向']=='buy']
                if buy_df.shape[0]>0:
                    buy_df=buy_df[['证券代码','证券名称','自动价格','价格','交易类型','数量','交易状态']]
                    buy_df.to_excel(r'自定义买入股票\自定义买入股票.xlsx')
                else:
                    print('{} {} 没有买入股票'.format(cash_models,trader_models))
                sell_df=df[df['交易方向']=='sell']
                if sell_df.shape[0]>0:
                    sell_df=sell_df[['证券代码','证券名称','自动价格','价格','交易类型','数量','交易状态']]
                    sell_df.to_excel(r'自定义卖出股票\自定义卖出股票.xlsx')
                else:
                    print('{} {} 没有卖出股票'.format(cash_models,trader_models))
            elif cash_models=='自定义' and trader_models=='通过综合交易模型':
                buy_df=df[df['交易方向']=='buy']
                if buy_df.shape[0]>0:
                    buy_df=buy_df[['证券代码','证券名称','交易状态']]
                    buy_df.to_excel(r'买入股票\买入股票.xlsx')
                else:
                    print('{} {} 没有买入股票'.format(cash_models,trader_models))
                sell_df=df[df['交易方向']=='sell']
                if sell_df.shape[0]>0:
                    sell_df=sell_df[['证券代码','证券名称','交易状态']]
                    sell_df.to_excel(r'卖出股票\卖出股票.xlsx')
                else:
                    print('{} {} 没有卖出股票'.format(cash_models,trader_models))
            #先卖在买
            elif cash_models=='雪球' and trader_models=='立马下单':
                sell_df=df[df['交易方向']=='sell']
                if sell_df.shape[0]>0:
                    for stock,amount in zip(sell_df['证券代码'],sell_df['数量']):
                        try:
                            price=self.data.get_spot_data(stock=stock)['最新价']
                            self.trader.sell(security=stock,price=price,amount=amount)
                            print('{} {} 卖出 股票{} 数量{} 价格{}'.format(cash_models,trader_models,stock,amount,price))
                        except Exception as e:
                            print(e)
                            print(print('{} {} 卖出 股票{} 有问题'.format(cash_models,trader_models,stock)))
                else:
                    print('{} {} 没有卖出股票'.format(cash_models,trader_models))
                buy_df=df[df['交易方向']=='buy']
                if buy_df.shape[0]>0:
                    for stock,amount in zip(buy_df['证券代码'],buy_df['数量']):
                        try:
                            price=self.data.get_spot_data(stock=stock)['最新价']
                            self.trader.buy(security=stock,price=price,amount=amount)
                            print('{} {} 买入 股票{} 数量{} 价格{}'.format(cash_models,trader_models,stock,amount,price))
                        except Exception as e:
                            print(e)
                            print(print('{} {} 买入 股票{} 有问题'.format(cash_models,trader_models,stock)))
                else:
                    print('{} {} 没有买入股票'.format(cash_models,trader_models))
            #先卖在买
            elif cash_models=='自定义' and trader_models=='立马下单':
                sell_df=df[df['交易方向']=='sell']
                if sell_df.shape[0]>0:
                    for stock in sell_df['证券代码'].tolist():
                        try:
                            price=self.data.get_spot_data(stock=stock)['最新价']
                            trader_type,amount,price=self.trader.check_av_target_trader(data_type=data_type,trader_type='sell',
                                        amount=amount1,limit_volume=limit_amount,value=value,limit_value=limit_value,
                                        stock=stock,price=price)
                            if trader_type=='sell':
                                self.trader.sell(security=stock,price=price,amount=amount)
                                print('{} {} 卖出 股票{} 数量{} 价格{}'.format(cash_models,trader_models,stock,amount,price))
                            else:
                                print('{} {} 卖出 股票{} 数量{} 价格{} 不可以交易'.format(cash_models,trader_models,stock))
                        except Exception as e:
                            print(e)
                            print(print('{} {} 卖出 股票{} 有问题'.format(cash_models,trader_models,stock)))
                else:
                    print('{} {} 没有卖出股票'.format(cash_models,trader_models))
                buy_df=df[df['交易方向']=='buy']
                if buy_df.shape[0]>0:
                    for stock,amount in zip(buy_df['证券代码'],buy_df['数量']):
                        try:
                            price=self.data.get_spot_data(stock=stock)['最新价']
                            trader_type,amount,price=self.trader.check_av_target_trader(data_type=data_type,trader_type='buy',
                                    amount=amount1,limit_volume=limit_amount,value=value,limit_value=limit_value,
                                    stock=stock,price=price)
                            if trader_type=='buy':
                                self.trader.buy(security=stock,price=price,amount=amount)
                                print('{} {} 买入 股票{} 数量{} 价格{}'.format(cash_models,trader_models,stock,amount,price))
                            else:
                                print('{} {} 买入 股票{} 数量{} 价格{} 不可以交易'.format(cash_models,trader_models,stock))
                        except Exception as e:
                            print(e)
                            print(print('{} {} 买入 股票{} 有问题'.format(cash_models,trader_models,stock)))
                else:
                    print('{} {} 没有买入股票'.format(cash_models,trader_models))
            else:
                print('未知的下单模式***********************')
        else:
            print('没有需要下单的数据**************************')
    def update_all_data(self):
        '''
        更新策略数据
        '''
        if self.base_func.check_is_trader_date_1():
            import time
            with open(r'{}\雪球跟单设置.json'.format(self.path),encoding='utf-8') as f:
                com=f.read()
            text=json.loads(com)
            name_list=text['组合名称']
            zu_list=text['组合id']
            update_time=text['不同策略间隔更新时间']
            for name,zu in zip(name_list,zu_list):
                try:
                    print(self.save_position())
                except Exception as e:
                    print(e)
                try:
                    print(self.save_balance())
                except Exception as e:
                    print(e)
                self.get_del_buy_sell_data(name=name,assembly_id=zu)
                self.get_del_not_trader_stock()
                self.get_trader_data()
                self.start_trader_on()
                time.sleep(update_time*60)
        else:
            print('雪球跟单{} 目前不是交易时间***************'.format(datetime.now()))

4通达信板块交易

源代码

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.etf_fund_data import etf_fund_data
from trader_tool.stock_upper_data import stock_upper_data
from trader_tool.ths_limitup_data import ths_limitup_data
from trader_tool.trader_frame import trader_frame
from trader_tool.unification_data import unification_data
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from trader_tool.dfcf_etf_data import dfcf_etf_data
import os
class tdx_plate_trader:
    def __init__(self,name='tdx_plate_trader'):
        '''
        通达信自选板块交易
        '''
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.name=name
    def read_tdx_trader_stock(self,path=r'C:\new_tdx\T0002\blocknew\BUY.blk'):
        '''
        读取通达信板块自选股交易
        '''
        try:
            stock_list=[]
            with open(r'{}'.format(path),'r+') as f:
                com=f.readlines()
            for i in com:
                i=i.strip()
                if len(i)>0:
                    stock_list.append(i)
            df=pd.DataFrame()
            df['证券代码']=stock_list
            df['证券代码']=df['证券代码'].apply(lambda x:str(x)[-6:])
        except:
            print('路径有问题{}'.format(path))
            df=pd.DataFrame()
            return df
    def read_tdx_trader_stock_buy(self):
        '''
        处理买入标的
        '''
        with open(r'{}/通达信板块交易.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        buy_path=text['买入板块路径']
        #持股数据
        hold_df=pd.read_excel(r'持股数据\持股数据.xlsx')
        hold_df=hold_df[hold_df['股票余额']>=10]
        print('持股*****************')
        if hold_df.shape[0]>0:
            hold_df['证券代码']=hold_df['证券代码'].astype(str)
            hold_stock_list=hold_df['证券代码'].tolist()
        else:
            hold_stock_list=[]
        #前买入股票
        pre_df=pd.read_excel(r'{}\买入标的.xlsx'.format(self.path),dtype='object')
        if pre_df.shape[0]>0:
            pre_df['证券代码']=pre_df['证券代码'].astype(str)
        #交易数据
        trader_df=self.read_tdx_trader_stock(path=buy_path)
        if trader_df.shape[0]>0:
            trader_df['证券代码']=trader_df['证券代码'].astype(str)
        print('目前买入板块的成分股***************************')
        trader_df.to_excel(r'{}\买入标的.xlsx'.format(self.path))
        print(trader_df)
        def select_stock(x):
            '''
            选择etf
            '''
            if x in hold_stock_list:
                return '持股'
            else:
                return "持股不足"
        if trader_df.shape[0]>0:
            trader_df['选择']=trader_df['证券代码'].apply(select_stock)
            trader_df=trader_df[trader_df['选择']=='持股不足']
            print('剔除持股的******************')
            print(trader_df)
        #没有买入的股票
        #前面股票池的列表
        if pre_df.shape[0]>0:
            pre_stock_list=pre_df['证券代码'].tolist()
        else:
            pre_stock_list=[]
        if trader_df.shape[0]>0:
            trader_df['选择']=trader_df['证券代码'].apply(lambda x: '是' if x in pre_stock_list else '不是')
            print('选择状态))))))))))))))))))')
            print(trader_df)
            buy=trader_df[trader_df['选择']=='不是']
            buy['交易状态']='未买'
            buy=buy[['证券代码','交易状态']]
            print('买入股票*********************')
            print(buy)
            if buy.shape[0]>0:
                buy.to_excel(r'买入股票\买入股票.xlsx')
            else:
                print('没有买入的股票*****************')
            return buy
        else:
            print('没有买入的股票*****************')
    def read_tdx_trader_stock_sell(self):
        '''
        处理卖出标的
        '''
        with open(r'{}/通达信板块交易.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        sell_path=text['卖出板块路径']
        #持股数据
        hold_df=pd.read_excel(r'持股数据\持股数据.xlsx')
        hold_df=hold_df[hold_df['股票余额']>=10]
        print('持股*****************')
        print(hold_df)
        if hold_df.shape[0]>0:
            hold_df['证券代码']=hold_df['证券代码'].astype(str)
            hold_stock_list=hold_df['证券代码'].tolist()
        else:
            hold_stock_list=[]
        #前买入股票
        pre_df=pd.read_excel(r'{}\买入标的.xlsx'.format(self.path),dtype='object')
        if pre_df.shape[0]>0:
            pre_df['证券代码']=pre_df['证券代码'].astype(str)
        #交易数据
        trader_df=self.read_tdx_trader_stock(path=sell_path)
        if trader_df.shape[0]>0:
            trader_df['证券代码']=trader_df['证券代码'].astype(str)
        print('目前卖出板块的成分股***************************')
        trader_df.to_excel(r'{}\卖出标的.xlsx'.format(self.path))
        print(trader_df)
        def select_stock(x):
            '''
            选择etf
            '''
            if x in hold_stock_list:
                return '持股'
            else:
                return "持股不足"
        if trader_df.shape[0]>0:
            trader_df['选择']=trader_df['证券代码'].apply(select_stock)
            print('持股选择***********************')
            print(trader_df)
            trader_df=trader_df[trader_df['选择']=='持股']
            print('剔除持股的******************')
            print(trader_df)
        #没有买入的股票
        #前面股票池的列表
        if pre_df.shape[0]>0:
            pre_stock_list=pre_df['证券代码'].tolist()
        else:
            pre_stock_list=[]
        if trader_df.shape[0]>0:
            trader_df['选择']=trader_df['证券代码'].apply(lambda x: '是' if x in pre_stock_list else '不是')
            print('选择状态))))))))))))))))))')
            print(trader_df)
            sell=trader_df[trader_df['选择']=='不是']
            sell['交易状态']='未卖'
            sell=sell[['证券代码','交易状态']]
            if sell.shape[0]>0:
                print('卖出股票*********************0000000000')
                print(sell)
                sell.to_excel(r'卖出股票\卖出股票.xlsx')
            else:
                print('没有卖出的股票*****************')
            return sell
        else:
            print('没有卖出的股票*****************')
    def update_all_data(self):
        '''
        更新全部数据
        '''
        self.read_tdx_trader_stock_buy()
        self.read_tdx_trader_stock_sell()
            

5问财交易系统策略

源代码

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.analysis_models import analysis_models
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from qmt_trader.qmt_trader_ths import qmt_trader_ths
from xgtrader.xgtrader import xgtrader
from trader_tool.ths_rq import ths_rq
from trader_tool.ths_board_concept_data import ths_board_concept_data
from trader_tool.unification_data import unification_data
import os
import pandas as pd
from trader_tool.dfcf_etf_data import dfcf_etf_data
from trader_tool.xueqie_data import xueqie_data
from datetime import datetime
import time
import pywencai
class wencai_trading_system:
    def __init__(self,trader_tool='qmt',exe='C:/同花顺软件/同花顺/xiadan.exe',tesseract_cmd='C:/Program Files/Tesseract-OCR/tesseract',
                qq='1029762153@qq.com',open_set='否',qmt_path='D:/国金QMT交易端模拟/userdata_mini',
                qmt_account='55009640',qmt_account_type='STOCK',name='customize_trading_strategies'):
        '''
        问财交易系统
        '''
        self.exe=exe
        self.tesseract_cmd=tesseract_cmd
        self.qq=qq
        self.trader_tool=trader_tool
        self.open_set=open_set
        self.qmt_path=qmt_path
        self.qmt_account=qmt_account
        self.qmt_account_type=qmt_account_type
        if trader_tool=='ths':
            self.trader=xgtrader(exe=self.exe,tesseract_cmd=self.tesseract_cmd,open_set=open_set)
        else:
            self.trader=qmt_trader_ths(path=qmt_path,account=qmt_account,account_type=qmt_account_type)
        self.stock_data=stock_data()
        self.bond_cov_data=bond_cov_data()
        self.ths_rq=ths_rq()
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.ths_board_concept_data=ths_board_concept_data()
        self.name=name
        self.data=unification_data(trader_tool=self.trader_tool)
        self.data=self.data.get_unification_data()
        self.dfcf_etf_data=dfcf_etf_data()
        self.trader.connect()
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        trader_type=text['交易品种']
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        df=self.trader.position()
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                if trader_type=='全部':
                    df=df
                else:
                    df['选择']=df['证券代码'].apply(self.trader.select_data_type)
                    df=df[df['选择']==trader_type]
                print(df)
                df=df[df['可用余额']>=10]
                df['黑名单']=df['证券代码'].apply(select_del_stock_list)
                df=df[df['黑名单']=='否']
                print('剔除黑名单**********')
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def save_balance(self):
        '''
        保持账户数据
        '''
        df=self.trader.balance()
        df.to_excel(r'账户数据\账户数据.xlsx')
        return df
    def get_wencai_data(self,text='人气排行'):
        '''
        获取问财数据
        '''
        try:
            df=pywencai.get(query=text,loop=True)
            return df
        except Exception as e:
            print(e)
            print('{}问题数据有问题'.format(text))
            df=pd.DataFrame()
            return df
    def get_buy_data(self):
        '''
        获取买入数据
        '''
        with open(r'{}\问财交易系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        is_open=text['是否开启买入条件']
        buy_list=text['买入条件']
        columns=text['买入的证券代码名称']
        if is_open=='是':
            print('开启买入条件************')
            df=self.get_wencai_data(text=buy_list)
            try:
                df['证券代码']=df[columns].apply(lambda x:str(x).split('.')[0])
            except:
                df['证券代码']=df[columns]
            print('买入的问财数据***********')
            print(df)
            df.to_excel(r'{}\买入数据\买入数据.xlsx'.format(self.path))
        else:
            print('不开启问财买入条件**************')
            df=pd.DataFrame()
            df.to_excel(r'{}\买入数据\买入数据.xlsx'.format(self.path))
    def get_sell_data(self):
        '''
        获取卖出数据
        '''
        with open(r'{}\问财交易系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        is_open=text['是否开启卖出条件']
        sell_list=text['卖出条件']
        columns=text['卖出的证券代码名称']
        if is_open=='是':
            print('开启卖出条件************')
            df=self.get_wencai_data(text=sell_list)
            try:
                df['证券代码']=df[columns].apply(lambda x:str(x).split('.')[0])
            except:
                df['证券代码']=df[columns]
            print('卖出的问财数据***********')
            print(df)
            df.to_excel(r'{}\卖出数据\卖出数据.xlsx'.format(self.path))
        else:
            print('不开启问财买入条件**************')
            df=pd.DataFrame()
            df.to_excel(r'{}\卖出数据\卖出数据.xlsx'.format(self.path))
    def dea_trader_data(self):
        '''
        处理交易股票池
        '''
        df=pd.read_excel(r'持股数据\持股数据.xlsx',dtype='object')
        df1=df[df['股票余额']>=10]
        if df1.shape[0]>0:
            df1['证券代码']=df1['证券代码'].apply(lambda x:'0'*(6-len(str(x)))+str(x))
            hold_stock_list=df1['证券代码'].tolist()

        else:
            hold_stock_list=[]
        trader_df=pd.read_excel(r'{}\买入数据\买入数据.xlsx'.format(self.path),dtype='object')
        if trader_df.shape[0]>0:
            trader_df['证券代码']=trader_df['证券代码'].apply(lambda x:'0'*(6-len(str(x)))+str(x))
            def select_data(stock):
                if str(stock) in hold_stock_list:
                    return '持股超过限制'
                else:
                    return '没有持股'
            trader_df['持股检查']=trader_df['证券代码'].apply(select_data)
            trader_df=trader_df[trader_df['持股检查'] !='持股超过限制']
            trader_df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        else:
            print('没有交易股票池数据******************')
            trader_df=pd.DataFrame()
            trader_df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
    def get_time_rotation(self):
        '''
        轮动方式
        '''
        with open(r'{}\问财交易系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        now_date=''.join(str(datetime.now())[:10].split('-'))
        now_time=time.localtime()                               
        trader_type=text['轮动方式']                               
        trader_wday=text['每周轮动时间']                               
        moth_trader_time=text['每月轮动时间']
        specific_time=text['特定时间']
        year=now_time.tm_year
        moth=now_time.tm_mon
        wday=now_time.tm_wday
        daily=now_time.tm_mday
        if trader_type=='每天':
            print('轮动方式每天')
            return True
        elif trader_type=='每周':
            if trader_wday==wday:
                return True
            elif trader_wday<wday:
                print('安周轮动 目前星期{} 轮动时间星期{} 目前时间大于轮动时间不轮动'.format(wday+1,trader_wday+1))
                return False
            else:
                print('安周轮动 目前星期{} 轮动时间星期{} 目前时间小于轮动时间不轮动'.format(wday+1,trader_wday+1))
                return False
        elif trader_type=='每月轮动时间':
            stats=''
            for date in moth_trader_time:
                data=''.join(data.split('-'))
                if int(moth_trader_time)==int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间等于轮动时间轮动'.format(now_date,date))
                    stats=True
                    break
                elif int(moth_trader_time)<int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间小于轮动时间轮动'.format(now_date,date))
                    stats=False
                else:
                    print('安月轮动 目前{} 轮动时间{} 目前时间大于轮动时间轮动'.format(now_date,date))
                    stats=False
            return stats
        else:
            #特别时间
            stats=''
            for date in specific_time:
                data=''.join(data.split('-'))
                if int(specific_time)==int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间等于轮动时间轮动'.format(now_date,date))
                    stats=True
                    break
                elif int(specific_time)<int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间小于轮动时间轮动'.format(now_date,date))
                    stats=False
                else:
                    print('安月轮动 目前{} 轮动时间{} 目前时间大于轮动时间轮动'.format(now_date,date))
                    stats=False
            return stats  
    def get_buy_sell_data(self):
        '''
        获取买卖数据
        '''   
        with open(r'{}\问财交易系统.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)  
        buy_num=text['买入排名前N']
        hold_limit=text['持有限制']
        buy_list=[]
        sell_list=[]
        buy_df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        sell_df=pd.read_excel(r'{}\卖出数据\卖出数据.xlsx'.format(self.path))
        hold_stock=pd.read_excel(r'持股数据\持股数据.xlsx'.format(self.path))
        hold_stock=hold_stock[hold_stock['股票余额']>=10]
        if hold_stock.shape[0]>0:
            hold_stock['证券代码']=hold_stock['证券代码'].apply(lambda x:'0'*(6-len(str(x)))+str(x))
            if sell_df.shape[0]>0:
                hold_stock_list=hold_stock['证券代码'].tolist()
                sell_df['证券代码']=sell_df['证券代码'].apply(lambda x:'0'*(6-len(str(x)))+str(x))
                sell_stock_list=sell_df['证券代码'].tolist()
                for stock in hold_stock_list:
                    if stock in sell_stock_list:
                        print('持股{} 在卖出列表'.format(stock))
                        sell_list.append(stock)
                    else:
                        print('持股{} 不在卖出列表继续持有'.format(stock))
            else:
                print('没有卖出的数据*******************')
        else:
            print('没有持股数据***************')
        sell=pd.DataFrame()
        sell['证券代码']=sell_list
        sell['交易状态']='未卖'
        print('卖出股票**************')
        print(sell)
        sell.to_excel(r'卖出股票\卖出股票.xlsx')
        if hold_stock.shape[0]>0:
            hold_num=hold_stock.shape[0]
        else:
            hold_num=0
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x:'0'*(6-len(str(x)))+str(x))
            buy_stock_list=buy_df['证券代码'].tolist()
            print(buy_stock_list)
            sell_num=sell.shape[0]
            av_buy=hold_limit-hold_num+sell_num
            print(av_buy,'((((((((((((((((((((((((()))))))))))))))))))))))))')
            if av_buy>=hold_limit:
                av_buy=hold_limit
            else:
                av_buy=av_buy
            buy=pd.DataFrame()
            buy['证券代码']=buy_stock_list[:av_buy]
            buy['交易状态']='未买'
            print('买入股票**********')
            print(buy)
            buy.to_excel(r'买入股票\买入股票.xlsx')
        else:
            print('没有买入的数据*****************')
    def get_del_not_trader_stock(self):
        '''
        剔除黑名单
        '''
        print('剔除黑名单______________*************************_______________________')
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        buy_df=pd.read_excel(r'买入股票\买入股票.xlsx',dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            buy_df['黑名单']=buy_df['证券代码'].apply(select_del_stock_list)
            buy_df=buy_df[buy_df['黑名单']=='否']
            #隔离策略
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            buy_df['品种']=buy_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            print('买入股票))))))))))))))))))))')
            buy_df.to_excel(r'买入股票\买入股票.xlsx')
            print(buy_df)
        else:
            print("没有买入的股票))))))))))))))")
        #卖出
        sell_df=pd.read_excel(r'卖出股票\卖出股票.xlsx',dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            sell_df['黑名单']=sell_df['证券代码'].apply(select_del_stock_list)
            sell_df=sell_df[sell_df['黑名单']=='否']
            #隔离策略
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            sell_df['品种']=sell_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            print('卖出股票))))))))))))))))))))')
            sell_df.to_excel(r'卖出股票\卖出股票.xlsx')
            print(sell_df)
        else:
            print('没有卖出的股票)))))))))))))))))))')
    def updata_all_data(self):
        '''
        更新全部数据
        '''
        if self.get_time_rotation()==True:
            print("今天{} 是轮动时间".format(datetime.now()))
            self.save_position()
            self.save_balance()
            self.get_buy_data()
            self.get_sell_data()
            self.dea_trader_data()
            self.get_buy_sell_data()
            self.get_del_not_trader_stock()
                
        else:
            print("今天{} 不是是轮动时间".format(datetime.now()))

           

6可转债三低交易策略

from trader_tool.stock_data import stock_data
from trader_tool.bond_cov_data import bond_cov_data
from trader_tool.shape_analysis import shape_analysis
from trader_tool.analysis_models import analysis_models
import pandas as pd
from trader_tool.ths_rq import ths_rq
from tqdm import tqdm
import numpy as np
import json
from  trader_tool import jsl_data
from qmt_trader.qmt_trader_ths import qmt_trader_ths
from xgtrader.xgtrader import xgtrader
import numpy as np
import os
from datetime import datetime
import time
class convertible_bonds_three_low_strategy:
    def __init__(self,trader_tool='ths',exe='C:/同花顺软件/同花顺/xiadan.exe',tesseract_cmd='C:/Program Files/Tesseract-OCR/tesseract',
                qq='1029762153@qq.com',open_set='否',qmt_path='D:/国金QMT交易端模拟/userdata_mini',
                qmt_account='55009640',qmt_account_type='STOCK',name='run_bond_cov_rend_strategy'):
        '''
        可转债三低策略
        '''
        self.exe=exe
        self.tesseract_cmd=tesseract_cmd
        self.qq=qq    
        self.trader_tool=trader_tool
        self.open_set=open_set
        self.qmt_path=qmt_path
        self.qmt_account=qmt_account
        self.qmt_account_type=qmt_account_type
        if trader_tool=='ths':
            self.trader=xgtrader(exe=self.exe,tesseract_cmd=self.tesseract_cmd,open_set=open_set)
        else:
            self.trader=qmt_trader_ths(path=qmt_path,account=qmt_account,account_type=qmt_account_type)
        self.stock_data=stock_data()
        self.bond_cov_data=bond_cov_data()
        self.ths_rq=ths_rq()
        self.path=os.path.dirname(os.path.abspath(__file__))
        self.name=name
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        self.trader.connect()
        df=self.trader.position()
        def select_bond_cov(x):
            '''
            选择可转债
            '''
            if x[:3] in ['110','113','123','127','128','111','118'] or x[:2] in ['11','12']:
                return '是'
            else:
                return '不是'
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                df['选择']=df['证券代码'].apply(select_bond_cov)
                try:
                    df['持股天数']=df['持股天数'].replace('--',1)
                except:
                    df['持股天数']=1
                df1=df[df['选择']=='是']
                df1=df1[df1['可用余额']>=10]
                df1['黑名单']=df1['证券代码'].apply(select_del_stock_list)
                df1=df1[df1['黑名单']=='否']
                print('剔除黑名单**********')
                df1.to_excel(r'持股数据\持股数据.xlsx')
                return df1
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def save_position(self):
        '''
        保存持股数据
        '''
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        self.trader.connect()
        df=self.trader.position()
        def select_bond_cov(x):
            '''
            选择可转债
            '''
            if x[:3] in ['110','113','123','127','128','111','118'] or x[:2] in ['11','12']:
                return '是'
            else:
                return '不是'
        try:
            if df==False:
                print('获取持股失败')
        except:
            if df.shape[0]>0:
                df['选择']=df['证券代码'].apply(select_bond_cov)
                try:
                    df['持股天数']=df['持股天数'].replace('--',1)
                except:
                    df['持股天数']=1
                df1=df[df['选择']=='是']
                df1=df1[df1['可用余额']>=10]
                df1['黑名单']=df1['证券代码'].apply(select_del_stock_list)
                df1=df1[df1['黑名单']=='否']
                print('剔除黑名单**********')
                df1.to_excel(r'持股数据\持股数据.xlsx')
                return df1
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None	
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                df.to_excel(r'持股数据\持股数据.xlsx')
                return df
    def select_bond_cov(self,x):
        '''
        选择证券代码
        '''
        if x[:3] in ['110','113','123','127','128','111'] or x[:2] in ['11','12']:
            return '是'
        else:
            return '不是'
    def save_balance(self):
        '''
        保持账户数据
        '''
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        self.trader.connect()
        df=self.trader.balance()
        df.to_excel(r'账户数据\账户数据.xlsx')
        return df
    def get_all_jsl_data(self):
        '''
        获取可转债全部数据
        '''
        print('获取可转债全部数据')
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        user=text['集思录账户']
        password=text['集思录密码']
        df=jsl_data.get_all_cov_bond_data(jsl_user=user,jsl_password=password)
        print(df)
        df.to_excel(r'{}\全部数据\全部数据.xlsx'.format(self.path))
        return df
    def calculated_double_low(self):
        '''
        计算三低
        三低=价格+100*转股溢价率+转债余额
        '''
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        max_yjl=text['可转债溢价率上限']
        min_yjl=text['可转债溢价率下限']
        max_gm=text['转债余额上限']
        min_gm=text['转债余额下限']
        min_value=text['三低最小值']
        max_value=text['三低最大值']
        max_price=text['价格上限']
        min_price=text['价格下限']
        yjl_weight=text['可转债溢价率权重']
        gm_weight=text['转债余额权重']
        price_weight=text['价格权重']
        max_time=text['剩余年限上限']
        min_time=text['剩余年限下限']
        trader_models=text['实盘交易模式']
        df=pd.read_excel(r'{}\全部数据\全部数据.xlsx'.format(self.path),dtype='object')
        try:
            df['转股溢价率']=df['转股溢价率_x']
        except:
            pass
        try:
            del df['Unnamed: 0']
        except:
            pass
        try:
            df['三低']=df['价格']*price_weight+df['转股溢价率']*yjl_weight+df['转债 余额']*gm_weight
        except:
            df['三低']=df['价格']*price_weight+df['转股溢价率']*yjl_weight+df['转债余额']*gm_weight
        if trader_models=='默认':
            df.to_excel(r'{}\原始三低\原始三低.xlsx'.format(self.path ))
            #排序
            df=df.sort_values(by='三低',ascending=True)
            df['三低']=pd.to_numeric(df['三低'])
            df1=df[df['三低']>=min_value]
            df2=df1[df1['三低']<=max_value]
            df3=df2[df2['价格']<=max_price]
            df4=df3[df3['价格']>=min_price]
            df5=df4[df4['转股溢价率']<=max_yjl]
            df6=df5[df5['转股溢价率']>=min_yjl]
            df7=df6[df6['剩余年限']<=max_time]
            df8=df7[df7['剩余年限']>=min_time]
            df8.to_excel(r'{}\三低\三低.xlsx'.format(self.path))
        else:
            #禄得老师的计算方式单因子排序加起来
            df['债溢价得分']=df['转股溢价率'].rank(ascending=False)*yjl_weight
            df['价格得分']=df['价格'].rank(ascending=False)*price_weight
            try:
                df['转债余额得分']=df['转债 余额'].rank(ascending=False)*gm_weight
            except:
                df['转债余额得分']=df['转债余额'].rank(ascending=False)*gm_weight
            df['总分']=df['债溢价得分']+df['价格得分']+df['转债余额得分']
            #从高到低排序,权重带了相关性
            df=df.sort_values(by='总分',ascending=False)
            df.to_excel(r'{}\全部打分\全部打分.xlsx'.format(self.path))
            df['代码']=df['证券代码'].tolist()
            df1=df[df['转股溢价率']<=max_yjl]
            df2=df1[df1['转股溢价率']>=min_yjl]
            try:
                df3=df2[df2['转债 余额']>=min_gm]
            except:
                df3=df2[df2['转债余额']>=min_gm]
            try:
                df3=df2[df2['转债 余额']<=max_gm]
            except:
                df3=df2[df2['转债余额']<=max_gm]
            df4=df3[df3['价格']<=max_price]
            df5=df4[df4['价格']>=min_price]
            df6=df5[df5['剩余年限']<=max_time]
            df7=df6[df6['剩余年限']>=min_time]
            df5.to_excel(r'{}\三低\三低.xlsx'.format(self.path))

    def mean_line_models(self,df):
        '''
        均线模型
        趋势模型
        5,10,20,30,60
        '''
        df=df
        #df=self.bond_cov_data.get_cov_bond_hist_data(stock=stock,start=start_date,end=end_date,limit=1000000000)
        df1=pd.DataFrame()
        df1['date']=df['date']
        df1['5']=df['close'].rolling(window=5).mean()
        df1['10']=df['close'].rolling(window=10).mean()
        df1['20']=df['close'].rolling(window=20).mean()
        df1['30']=df['close'].rolling(window=30).mean()
        df1['60']=df['close'].rolling(window=60).mean()
        score=0
        #加分的情况
        mean_5=df1['5'].tolist()[-1]
        mean_10=df1['10'].tolist()[-1]
        mean_20=df1['20'].tolist()[-1]
        mean_30=df1['30'].tolist()[-1]
        mean_60=df1['60'].tolist()[-1]
        if mean_5>mean_10:
            score+=25
        if mean_10>mean_20:
            score+=25
        if mean_20>mean_30:
            score+=25
        if mean_30>mean_60:
            score+=25
        return score
    def get_return_ananlysis(self,df='',n=5):
        '''
        收益率分析
        '''
        #涨跌幅
        df1=df
        prices=df1[-n:]['close']
        zdf= ((prices.iloc[-1] / prices.iloc[0]) - 1)*100
        #最大回撤
        max_down_result=((prices / prices.expanding(min_periods=1).max()).min() - 1)*100
        #累计收益】
        return zdf,max_down_result
    def get_cov_bond_shape_analysis(self):
        '''
        可转债形态分析
        '''
        print('可转债形态分析')
        df=pd.read_excel(r'{}\三低\三低.xlsx'.format(self.path),dtype='object')
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        n=text['跌破N日均线卖出']
        try:
            del df['Unnamed: 0']
        except:
            pass
        stock_list=df['证券代码'].tolist()
        over_lining=[]
        mean_line=[]
        for i in tqdm(range(len(stock_list))):
            stock=stock_list[i]
            try:
                hist_df=self.bond_cov_data.get_cov_bond_hist_data(stock=stock)
                models=shape_analysis(df=hist_df)
                over=models.get_over_lining_sell()
                over_lining.append(over)
                #均线分析
                line=models.get_down_mean_line_sell(n=n)
                mean_line.append(line)
            except:
                over_lining.append(None)
                mean_line.append(None)
        df['上影线']=over_lining
        df['跌破均线']=mean_line
        df1=df[df['跌破均线']=='不是']
        df1.to_excel(r'{}\选择可转债\选择可转债.xlsx'.format(self.path))
        return df1
    def get_stock_mean_line_retuen_analysis(self):
        '''
        可转债均线收益分析
        '''
        print('可转债均线收益分析')
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        n=text['最近N天']
        max_retuen=text['最近N天最大收益率']
        min_return=text['最近N天最小收益率']
        max_down=text['最近N天最大回撤']
        min_secore=text['均线最低分数']
        mean_sorce_list=[]
        zdf_list=[]
        max_down_list=[]
        df=pd.read_excel(r'{}\选择可转债\选择可转债.xlsx'.format(self.path),dtype='object')
        try:
            df['Unnamed: 0']
        except:
            pass
        stock_list=df['证券代码'].tolist()
        for i in tqdm(range(len(stock_list))):
            stock=stock_list[i]
            try:
                df1=self.bond_cov_data.get_cov_bond_hist_data(stock=stock,start='19990101',end='20500101',limit=10000000)
                sorce=self.mean_line_models(df=df1)
                zdf,down=self.get_return_ananlysis(df=df1,n=n)
                mean_sorce_list.append(sorce)
                zdf_list.append(zdf)
                max_down_list.append(down)
            except:
                mean_sorce_list.append(None)
                zdf_list.append(None)
                max_down_list.append(None)
        df['均线得分']=mean_sorce_list
        df['最近{}天收益'.format(n)]=zdf_list
        df['最近天{}最大回撤'.format(n)]=max_down_list
        df.to_excel(r'{}\分析原始数据\分析原始数据.xlsx'.format(self.path))
        df1=df[df['均线得分']>=min_secore]
        df2=df1[df1['最近{}天收益'.format(n)]>=min_return]
        df3=df2[df2['最近{}天收益'.format(n)]<=max_retuen]
        df4=df3[df3['最近天{}最大回撤'.format(n)]>=max_down]
        df4.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        return df4
    def get_select_trader_type(self):
        '''
        选择交易方式
        '''
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        rend=text['是否开启趋势轮动']
        if rend=='是':
            self.get_cov_bond_shape_analysis()
            self.get_stock_mean_line_retuen_analysis()
        else:
            df=pd.read_excel(r'{}\三低\三低.xlsx'.format(self.path),dtype='object')
            try:
                df['Unnamed: 0']
            except:
                pass
            df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
    def get_del_qzsh_data(self):
        '''
        剔除强制赎回
        '''
        print('剔除强制赎回')
        with open('{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_select=text['是否剔除强制赎回']
        n=text['距离强制赎回天数']
        df=self.bond_cov_data.bank_cov_qz()
        del_list=[]
        for i in range(1,n+1):
            n_text='至少还需{}天'.format(i)
            del_list.append(n_text)
        del_list.append('临近到期')
        del_list.append('已满足强赎条件')
        del_list.append('是否剔除强制赎回')
        text_n=''
        for select_text in del_list:
            text_n+='"{}" in x or '.format(select_text)
        text_n=text_n[:-3]
        if del_select=='是':
            df1=df
            def select_bond_cov(x):
                '''
                选择可转债
                '''
                if eval(text_n):
                    return '是'
                else:
                    return '不是'
            df1['选择']=df1['cell.redeem_count'].apply(select_bond_cov)
            df2=df1[df1['选择']=='是']
            df2.to_excel(r'{}\强制赎回\强制赎回.xlsx'.format(self.path))
            trader_stock=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path),dtype='object')
            try:
                trader_stock['Unnamed: 0']
            except:
                pass
            def select_trader_stock(x):
                '''
                选择交易股票池
                '''
                if x not in df2['cell.bond_id'].tolist():
                    return '不是'
                else:
                    return '是'
            trader_stock['强制赎回']=trader_stock['证券代码'].apply(select_trader_stock)
            trader_stock=trader_stock[trader_stock['强制赎回']=='不是']
            trader_stock['证券代码']=trader_stock['证券代码'].astype(str)
            df2['cell.bond_id']=df2['cell.bond_id'].astype(str)
            qssl_stock=df2['cell.bond_id'].tolist()
            trader_stock['强制赎回']=trader_stock['证券代码'].apply(lambda x: '是' if x in qssl_stock else '不是')
            trader_stock=trader_stock[trader_stock['强制赎回']=='不是']
            trader_stock.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
            return trader_stock
        else:
            trader_stock=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path),dtype='object')
            return trader_stock
    def get_del_buy_sell_data(self):
        '''
        处理交易股票池买入股票
        '''
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        limit=text['持股限制']
        df=self.save_position()
        df['证券代码']=df['证券代码'].astype(str)
        df1=df[df['可用余额']>=10]
        hold_stock_list=df1['证券代码'].tolist()
        n=text['跌破N日均线卖出']
        trader_df=self.get_del_qzsh_data()
        trader_df['证券代码']=trader_df['证券代码'].astype(str)
        def select_data(stock):
            if stock in hold_stock_list:
                return '持股超过限制'
            else:
                return '没有持股'
        trader_df['持股检查']=trader_df['证券代码'].apply(select_data)
        trader_df=trader_df[trader_df['持股检查'] !='持股超过限制']
        hold_stock_list=trader_df['证券代码'].tolist()
        trend=text['是否开启趋势轮动']
        if trend=='是':
            sell_list=[]
            for i in tqdm(range(len(hold_stock_list))):
                stock=hold_stock_list[i]
                try:
                    hist_df=self.bond_cov_data.get_cov_bond_hist_data(stock=stock)
                    models=shape_analysis(df=hist_df)
                    mean_line=models.get_down_mean_line_sell(n=n)
                    if mean_line=='是':
                        sell_list.append('是')
                    else:
                        sell_list.append('不是')
                except:
                    print('{}有问题'.format(stock))
                    sell_list.append('是')
            trader_df['跌破均线']=sell_list
            trader_df=trader_df[trader_df['跌破均线']=='不是']  
        else:
            trader_df=trader_df
        for i in range(0,10):
            try:
                trader_df['Unnamed: {}'.format(i/10)]
            except:
                pass
        trader_df.to_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path))
        return trader_df
    def get_time_rotation(self):
        '''
        轮动方式
        '''
        with open('{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        now_date=''.join(str(datetime.now())[:10].split('-'))
        now_time=time.localtime()                               
        trader_type=text['轮动方式']                               
        trader_wday=text['每周轮动时间']                               
        moth_trader_time=text['每月轮动时间']
        specific_time=text['特定时间']
        year=now_time.tm_year
        moth=now_time.tm_mon
        wday=now_time.tm_wday
        daily=now_time.tm_mday
        if trader_type=='每天':
            print('轮动方式每天')
            return True
        elif trader_type=='每周':
            if trader_wday==wday:
                return True
            elif trader_wday<wday:
                print('安周轮动 目前星期{} 轮动时间星期{} 目前时间大于轮动时间不轮动'.format(wday+1,trader_wday+1))
                return False
            else:
                print('安周轮动 目前星期{} 轮动时间星期{} 目前时间小于轮动时间不轮动'.format(wday+1,trader_wday+1))
                return False
        elif trader_type=='每月轮动时间':
            stats=''
            for date in moth_trader_time:
                data=''.join(data.split('-'))
                if int(moth_trader_time)==int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间等于轮动时间轮动'.format(now_date,date))
                    stats=True
                    break
                elif int(moth_trader_time)<int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间小于轮动时间轮动'.format(now_date,date))
                    stats=False
                else:
                    print('安月轮动 目前{} 轮动时间{} 目前时间大于轮动时间轮动'.format(now_date,date))
                    stats=False
            return stats
        else:
            #特别时间
            stats=''
            for date in specific_time:
                data=''.join(data.split('-'))
                if int(specific_time)==int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间等于轮动时间轮动'.format(now_date,date))
                    stats=True
                    break
                elif int(specific_time)<int(date):
                    print('安月轮动 目前{} 轮动时间{} 目前时间小于轮动时间轮动'.format(now_date,date))
                    stats=False
                else:
                    print('安月轮动 目前{} 轮动时间{} 目前时间大于轮动时间轮动'.format(now_date,date))
                    stats=False
            return stats                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    def get_buy_sell_stock(self):
        '''
        获取买卖数据
        '''
        with open('{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        buy_num=text['买入排名前N']
        hold_rank_num=text['持有排名前N']
        sell_rank_num=text['跌出排名卖出N']
        sell_value=text['三低平仓']
        hold_limit=text['持有限制']
        trader_models=text['实盘交易模式']
        df=pd.read_excel(r'持股数据\持股数据.xlsx',dtype='object')
        df['证券代码']=df['证券代码'].astype(str)
        df_yjl=pd.read_excel(r'{}\原始三低\原始三低.xlsx'.format(self.path))
        sd_dict=dict(zip(df_yjl['证券代码'],df_yjl['三低']))
        trend=text['是否开启趋势轮动']
        df1=df[df['可用余额']>=10]
        hold_stock_list=df['证券代码'].tolist()
        def select_stock(x):
            '''
            选择etf
            '''
            if x in hold_stock_list:
                return '持股'
            else:
                return "持股不足"
        try:
            del df['Unnamed: 0']
        except:
            pass
        trader_df=pd.read_excel(r'{}\交易股票池\交易股票池.xlsx'.format(self.path),dtype='object')
        trader_df['证券代码']=trader_df['证券代码'].astype(str)
        try:
            del trader_df['Unnamed: 0']
        except:
            pass
        print('交易股票池*******************')
        print(trader_df)
        trader_df['选择']=trader_df['证券代码'].apply(select_stock)
        trader_df=trader_df[trader_df['选择']=='持股不足']
        select=text['是否开启持股周期']
        hold_daily_limit=text['持股持股周期天数']
        try:
            del trader_df['Unnamed: 0']
        except:
            pass
        if df1.shape[0]>0:
            #卖出列表
            sell_list=[]
            #持股列表
            hold_stock_list=df['证券代码'].tolist()
            #排名列表
            if select=='是':
                hold_daily=df[df['证券代码']==stock]['持股天数'].tolist()[-1]
                if hold_daily>=hold_daily_limit:
                    sell_list.append(stock)
                else:
                    print('目前持股 {} 没有大于{}'.format(hold_daily,hold_daily_limit))
            else:
                print('不启动持股限制')
            #跌破均线分析
            n=text['跌破N日均线卖出'] 
            if trend=='是':
                for stock in hold_stock_list:
                        try:
                            hist_df=self.etf_fund_data.get_ETF_fund_hist_data(stock=stock)
                            models=shape_analysis(df=hist_df)
                            mean_line=models.get_down_mean_line_sell(n=n)
                            if mean_line=='是':
                                sell_list.append(stock)
                                print('{}跌破均线'.format(stock))
                            else:
                                pass
                        except:
                            pass
            else:
                print('**************************88不开启持股趋势分析')
            #三低平仓
            if trader_models=='默认':
                for stock in hold_stock_list:
                    value=sd_dict.get(stock,0)
                    if value>=sell_value:
                        print('三低平仓 {} 三低{} 大于 平仓值{}'.format(stock,value,sell_value))   
                        sell_list.append(stock)
                    else:
                        print('三低平仓 {} 三低{} 小于 平仓值{}'.format(stock,value,sell_value))   
                #跌出排名卖出N
            rank_df=pd.read_excel(r'{}\三低\三低.xlsx'.format(self.path),dtype='object') 
            sell_rank_stock=rank_df['证券代码'].tolist()[:sell_rank_num]   
            if len(sell_rank_stock)>0:
                for stock in hold_stock_list:
                    if stock in sell_rank_stock:
                        print('{} 在持有排名里面'.format(stock))
                    else:
                        print('{} 不在持有排名里面'.format(stock))
                        sell_list.append(stock)
            sell_list=list(set(sell_list))
            sell_df=pd.DataFrame()
            sell_df['证券代码']=sell_list
            sell_df['交易状态']='未卖'
            if sell_df.shape[0]>0:
                print('卖出etf*****************')
                print(sell_df)
                sell_df['策略名称']=self.name
                sell_df.to_excel(r'卖出股票\卖出股票.xlsx')
            else:
                print('没有卖出etf')
                sell_df['证券代码']=None
                sell_df['交易状态']=None
                sell_df['策略名称']=self.name
                sell_df.to_excel(r'卖出股票\卖出股票.xlsx')
            hold_num=df1.shape[0]
            if hold_num>0:
                av_buy_num=hold_limit-hold_num
                av_buy_num=av_buy_num+sell_df.shape[0]
                if av_buy_num>=hold_limit:
                    av_buy_num=hold_limit
                else:
                    av_buy_num=av_buy_num
                buy_df=trader_df[:av_buy_num]
            else:
                buy_df=trader_df[:buy_num]
            buy_df['交易状态']='未买'
            print('买入可转债*****************')
            df['证券代码']=df['证券代码']
            print(buy_df)
            buy_df['策略名称']=self.name
            buy_df.to_excel(r'买入股票\买入股票.xlsx')
            return buy_df
        else:
            buy_df=trader_df[:buy_num]
            print(trader_df)
            buy_df['证券代码']=buy_df['证券代码']
            buy_df['交易状态']='未买'
            print('买入etf*****************')
            print(buy_df)
            buy_df['策略名称']=self.name
            buy_df.to_excel(r'买入股票\买入股票.xlsx')
            return buy_df
    def get_del_not_trader_stock(self):
        '''
        剔除黑名单
        '''
        print('剔除黑名单______________*************************_______________________')
        with open(r'分析配置.json',encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        del_df=pd.read_excel(r'{}\黑名单\黑名单.xlsx'.format(self.path),dtype='object')
        del_trader_stock=text['黑名单']
        if del_df.shape[0]>0:
            del_df['证券代码']=del_df['证券代码'].apply(lambda x : str(x).split('.')[0])
            del_df['证券代码']=del_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            del_stock_list=del_df['证券代码'].tolist()
        else:
            del_stock_list=[]
        for del_stock in del_trader_stock:
            del_stock_list.append(del_stock)
        def select_del_stock_list(x):
            if str(x)[:6] in del_stock_list:
                return '是'
            else:
                return '否'
        buy_df=pd.read_excel(r'买入股票\买入股票.xlsx',dtype='object')
        if buy_df.shape[0]>0:
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del buy_df['Unnamed: 0']
            except:
                pass
            buy_df['黑名单']=buy_df['证券代码'].apply(select_del_stock_list)
            buy_df=buy_df[buy_df['黑名单']=='否']
            #隔离策略
            buy_df['证券代码']=buy_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            buy_df['品种']=buy_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            
            buy_df=buy_df[buy_df['品种']=='bond']
            buy_df.to_excel(r'买入股票\买入股票.xlsx')
            print(buy_df)
        else:
            pass
        #卖出
        sell_df=pd.read_excel(r'卖出股票\卖出股票.xlsx',dtype='object')
        if sell_df.shape[0]>0:
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            try:
                del sell_df['Unnamed: 0']
            except:
                pass
            sell_df['黑名单']=sell_df['证券代码'].apply(select_del_stock_list)
            sell_df=sell_df[sell_df['黑名单']=='否']
            #隔离策略
            sell_df['证券代码']=sell_df['证券代码'].apply(lambda x: '0'*(6-len(str(x)))+str(x))
            sell_df['品种']=sell_df['证券代码'].apply(lambda x: self.trader.select_data_type(x))
            sell_df=sell_df[sell_df['品种']=='bond']
            sell_df.to_excel(r'卖出股票\卖出股票.xlsx')
            print(sell_df)
        else:
            pass
    def updata_all_data(self):
        '''
        更新全部数据
        '''
        with open(r'{}/可转债三低策略设置.json'.format(self.path),encoding='utf-8') as f:
            com=f.read()
        text=json.loads(com)
        select=text['是否测试']
        if select=='是':
            self.save_position()
            self.save_balance()
            self.get_all_jsl_data()
            self.calculated_double_low()
            self.get_select_trader_type()
            self.get_del_qzsh_data()
            self.get_del_buy_sell_data()
            self.get_buy_sell_stock()
            self.get_del_not_trader_stock()
        else:
            if self.get_time_rotation()==True:
                self.save_position()
                self.save_balance()
                self.get_all_jsl_data()
                print("今天{} 是轮动时间".format(datetime.now()))
                self.calculated_double_low()
                self.get_select_trader_type()
                self.get_del_qzsh_data()
                self.get_del_buy_sell_data()
                self.get_buy_sell_stock()
                self.get_del_not_trader_stock()
            else:
                print("今天{} 不是是轮动时间".format(datetime.now()))

三xttrader使用教程,官网原来的内容,我写的参考教程

1获取全部的类强大qmt交易


#coding=utf-8
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
from xtquant import xtconstant
import time
import pandas as pd

class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        """
        连接断开
        :return:
        """
        print("connection lost")
    def on_stock_order(self, order):
        """
        委托回报推送
        :param order: XtOrder对象
        :return:
        """
        print("on order callback:")
        print(order.stock_code, order.order_status, order.order_sysid)
    def on_stock_asset(self, asset):
        """
        资金变动推送
        :param asset: XtAsset对象
        :return:
        """
        print("on asset callback")
        print(asset.account_id, asset.cash, asset.total_asset)
    def on_stock_trade(self, trade):
        """
        成交变动推送
        :param trade: XtTrade对象
        :return:
        """
        print("on trade callback")
        print(trade.account_id, trade.stock_code, trade.order_id)
    def on_stock_position(self, position):
        """
        持仓变动推送
        :param position: XtPosition对象
        :return:
        """
        print("on position callback")
        print(position.stock_code, position.volume)
    def on_order_error(self, order_error):
        """
        委托失败推送
        :param order_error:XtOrderError 对象
        :return:
        """
        print("on order_error callback")
        print(order_error.order_id, order_error.error_id, order_error.error_msg)
    def on_cancel_error(self, cancel_error):
        """
        撤单失败推送
        :param cancel_error: XtCancelError 对象
        :return:
        """
        print("on cancel_error callback")
        print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg)
    def on_order_stock_async_response(self, response):
        """
        异步下单回报推送
        :param response: XtOrderResponse 对象
        :return:
        """
        print("on_order_stock_async_response")
        print(response.account_id, response.order_id, response.seq)
    def on_account_status(self, status):
        """
        :param response: XtAccountStatus 对象
        :return:
        """
        print("on_account_status")
        print(status.account_id, status.account_type, status.status)

if __name__ == "__main__":
    print("demo test")
    # path为mini qmt客户端安装目录下userdata_mini路径
    path = 'D:/国金QMT交易端模拟/userdata_mini'
    # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号
    session_id = int(time.time())
    xt_trader = XtQuantTrader(path, session_id)
    # 创建资金账号为1000000365的证券账号对象
    acc = StockAccount('55011917',"STOCK")
    # StockAccount可以用第二个参数指定账号类型,如沪港通传'HUGANGTONG',深港通传'SHENGANGTONG'
    # acc = StockAccount('1000000365','STOCK')
    # 创建交易回调类对象,并声明接收回调
    callback = MyXtQuantTraderCallback()
    xt_trader.register_callback(callback)
    # 启动交易线程
    xt_trader.start()
    # 建立交易连接,返回0表示连接成功
    connect_result = xt_trader.connect()
    print(connect_result)
    # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
    subscribe_result = xt_trader.subscribe(acc)
    print(subscribe_result)
    if subscribe_result==0:
        print('链接成功')
    else:
        print('qmt链接失败')
    

输出的结果

链接成功

2获取账户资金

# 查询证券资产
print("query asset:")
asset = xt_trader.query_stock_asset(acc)
df=pd.DataFrame()
if asset:
    df['账号类型']=[asset.account_type]
    df['资金账户']=[asset.account_id]
    df['可用金额']=[asset.cash]
    df['冻结金额']=[asset.frozen_cash]
    df['持仓市值']=[asset.market_value]
    df['总资产']=[asset.total_asset]
df

获取结果


账号类型	资金账户	可用金额	冻结金额	持仓市值	总资产
0	2	55011917	19919535.36	0.0	75983.4	19995883.76

3当日委托

调用源代码

orders =xt_trader.query_stock_orders(acc)
print("委托数量", len(orders))
data=pd.DataFrame()
if len(orders) != 0:
    for i in range(len(orders)):
        df=pd.DataFrame()
        df['账号类型']=[orders[i].account_type]
        df['资金账号']=[orders[i].account_id]
        df['证券代码']=[orders[i].stock_code]
        df['订单编号']=[orders[i].order_id]
        df['柜台合同编号']=[orders[i].order_sysid]
        df['报单时间']=[orders[i].order_time]
        df['委托类型']=[orders[i].order_type]
        df['委托数量']=[orders[i].order_volume]
        df['报价类型']=[orders[i].price_type]
        df['委托价格']=[orders[i].price]
        df['成交数量']=[orders[i].traded_volume]
        df['成交均价']=[orders[i].traded_price]
        df['委托状态']=[orders[i].order_status]
        df['委托状态描述']=[orders[i].status_msg]
        df['策略名称']=[orders[i].strategy_name]
        df['委托备注']=[orders[i].order_remark]
        data=pd.concat([data,df],ignore_index=True)
data

输出的结果

	账号类型	资金账号	证券代码	订单编号	柜台合同编号	报单时间	委托类型	委托数量	报价类型	委托价格	成交数量	成交均价	委托状态	委托状态描述	策略名称	委托备注
0	2	55011917	513100.SH	1082187594	3436	1718588942	24	4300	50	1.440	4300	1.440	56			
1	2	55011917	159981.SZ	1082187617	3439	1718588951	24	4300	50	1.631	4300	1.631	56		

4当日成交

调用源代码

trades =xt_trader.query_stock_trades(acc)
print("成交数量:", len(trades))
data=pd.DataFrame()
if len(trades) != 0:
    for i in range(len(trades)):
        df=pd.DataFrame()
        df['账号类型']=[trades[i].account_type]
        df['资金账号']=[trades[i].account_id]
        df['证券代码']=[trades[i].stock_code]
        df['委托类型']=[trades[i].order_type]
        df['成交编号']=[trades[i].traded_id]
        df['成交时间']=[trades[i].traded_time]
        df['成交均价']=[trades[i].traded_price]
        df['成交数量']=[trades[i].traded_volume]
        df['成交金额']=[trades[i].traded_amount]
        df['订单编号']=[trades[i].order_id]
        df['柜台合同编号']=[trades[i].order_sysid]
        df['策略名称']=[trades[i].strategy_name]
        df['委托备注']=[trades[i].order_remark]
        data=pd.concat([data,df],ignore_index=True)
       
data

输出的结果

trades =xt_trader.query_stock_trades(acc)
print("成交数量:", len(trades))
data=pd.DataFrame()
if len(trades) != 0:
    for i in range(len(trades)):
        df=pd.DataFrame()
        df['账号类型']=[trades[i].account_type]
        df['资金账号']=[trades[i].account_id]
        df['证券代码']=[trades[i].stock_code]
        df['委托类型']=[trades[i].order_type]
        df['成交编号']=[trades[i].traded_id]
        df['成交时间']=[trades[i].traded_time]
        df['成交均价']=[trades[i].traded_price]
        df['成交数量']=[trades[i].traded_volume]
        df['成交金额']=[trades[i].traded_amount]
        df['订单编号']=[trades[i].order_id]
        df['柜台合同编号']=[trades[i].order_sysid]
        df['策略名称']=[trades[i].strategy_name]
        df['委托备注']=[trades[i].order_remark]
        data=pd.concat([data,df],ignore_index=True)
       
data

5持股

调用源代码

positions = xt_trader.query_stock_positions(acc)
print("持仓数量:", len(positions))
data=pd.DataFrame()
if len(positions) != 0:
    for i in range(len(positions)):
        df=pd.DataFrame()
        df['账号类型']=[positions[i].account_type]
        df['资金账号']=[positions[i].account_id]
        df['证券代码']=[positions[i].stock_code]
        df['持仓数量']=[positions[i].volume]
        df['可用数量']=[positions[i].can_use_volume]
        df['平均建仓成本']=[positions[i].open_price]
        df['市值']=[positions[i].market_value]
        data=pd.concat([data,df],ignore_index=True)
data

输出结果

持仓数量: 9
账号类型	资金账号	证券代码	持仓数量	可用数量	平均建仓成本	市值
0	2	55011917	513100.SH	4100	4100	1.319122	5908.1
1	2	55011917	600031.SH	500	500	19.411000	7825.0
2	2	55011917	000001.SZ	1700	1700	11.433000	17153.0
3	2	55011917	159502.SZ	100	100	1.122000	100.1
4	2	55011917	159509.SZ	4300	4300	1.521000	7125.1
5	2	55011917	159937.SZ	300	300	5.418000	1587.3
6	2	55011917	159980.SZ	5400	5400	1.862000	9342.0
7	2	55011917	159981.SZ	1600	1600	1.929687	2606.4
8	2	55011917	161128.SZ	2100	2100	4.883000	10867.5

6股票同步报单买入

调用代码

"""
释义
对股票进行下单操作
参数
account - StockAccount 资金账号
stock_code - str 证券代码,如'600000.SH'
order_type - int 委托类型
order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
price_type - int 报价类型
price - float 委托价格
strategy_name - str 策略名称
order_remark - str 委托备注
返回
系统生成的订单编号,成功委托后的订单编号为大于0的正整数,如果为-1表示委托失败
"""
stats=xt_trader.order_stock(account=acc, stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=200, price_type=xtconstant.FIX_PRICE, price=13.1, strategy_name='同步下单', 
                order_remark='同步下单')
print('订单编号')

输出的结果

"""
释义
对股票进行下单操作
参数
account - StockAccount 资金账号
stock_code - str 证券代码,如'600000.SH'
order_type - int 委托类型
order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
price_type - int 报价类型
price - float 委托价格
strategy_name - str 策略名称
order_remark - str 委托备注
返回
系统生成的订单编号,成功委托后的订单编号为大于0的正整数,如果为-1表示委托失败
"""
stats=xt_trader.order_stock(account=acc, stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=200, price_type=xtconstant.FIX_PRICE, price=13.1, strategy_name='同步下单', 
                order_remark='同步下单')
print('订单编号')

7同步下单卖出

调用源代码

"""
释义
对股票进行下单操作
参数
account - StockAccount 资金账号
stock_code - str 证券代码,如'600000.SH'
order_type - int 委托类型
order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
price_type - int 报价类型
price - float 委托价格
strategy_name - str 策略名称
order_remark - str 委托备注
返回
系统生成的订单编号,成功委托后的订单编号为大于0的正整数,如果为-1表示委托失败
"""
stats=xt_trader.order_stock(account=acc, stock_code='600031.SH', order_type=xtconstant.STOCK_SELL,
                    order_volume=200, price_type=xtconstant.FIX_PRICE, price=13.1, strategy_name='同步下单', 
                order_remark='同步下单')
print('订单编号')

输出的结果

订单编号
on order callback:on order callback:
600031.SH 50 7874
on trade callback
55011917 600031.SH 1082194571

600031.SH 50 7874
on trade callback
55011917 600031.SH 1082194571
on order callback:
600031.SH 56 7874
on order callback:
600031.SH 56 7874

8参数说明

"""
价格类型
# 最新价
LATEST_PRICE = 5
# 指定价/限价
FIX_PRICE = 11
# 市价最优价[郑商所][期货]
MARKET_BEST = 18
# 市价即成剩撤[大商所][期货]
MARKET_CANCEL = 19
# 市价全额成交或撤[大商所][期货]
MARKET_CANCEL_ALL = 20
# 市价最优一档即成剩撤[中金所][期货]
MARKET_CANCEL_1 = 21
# 市价最优五档即成剩撤[中金所][期货]
MARKET_CANCEL_5 = 22
# 市价最优一档即成剩转[中金所][期货]
MARKET_CONVERT_1 = 23
# 市价最优五档即成剩转[中金所][期货]
MARKET_CONVERT_5 = 24
# 最优五档即时成交剩余撤销[上交所][股票]
MARKET_SH_CONVERT_5_CANCEL = 42
# 最优五档即时成交剩转限价[上交所][股票]
MARKET_SH_CONVERT_5_LIMIT = 43
# 对手方最优价格委托[上交所[股票]][深交所[股票][期权]]
MARKET_PEER_PRICE_FIRST = 44
# 本方最优价格委托[上交所[股票]][深交所[股票][期权]]
MARKET_MINE_PRICE_FIRST = 45
# 即时成交剩余撤销委托[深交所][股票][期权]
MARKET_SZ_INSTBUSI_RESTCANCEL = 46
# 最优五档即时成交剩余撤销[深交所][股票][期权]
MARKET_SZ_CONVERT_5_CANCEL = 47
# 全额成交或撤销委托[深交所][股票][期权]
MARKET_SZ_FULL_OR_CANCEL = 48
"""
"""
下单的类型
STOCK_BUY = 23
STOCK_SELL = 24
CREDIT_BUY = 23    #担保品买入
CREDIT_SELL = 24   #担保品卖出
CREDIT_FIN_BUY = 27 #融资买入
CREDIT_SLO_SELL  = 28 #融券卖出
CREDIT_BUY_SECU_REPAY = 29 #买券还券
CREDIT_DIRECT_SECU_REPAY = 30 #直接还券
CREDIT_SELL_SECU_REPAY  = 31 #卖券还款
CREDIT_DIRECT_CASH_REPAY = 32 #直接还款
CREDIT_FIN_BUY_SPECIAL = 40 #专项融资买入
CREDIT_SLO_SELL_SPECIAL  = 41 #专项融券卖出
CREDIT_BUY_SECU_REPAY_SPECIAL = 42 #专项买券还券
CREDIT_DIRECT_SECU_REPAY_SPECIAL = 43 #专项直接还券
CREDIT_SELL_SECU_REPAY_SPECIAL  = 44 #专项卖券还款
CREDIT_DIRECT_CASH_REPAY_SPECIAL = 45 #专项直接还款
"""

9股票异步报单

调用源代码

"""
释义
对股票进行异步下单操作,异步下单接口如果正常返回了下单请求序号seq,会收到on_order_stock_async_response的委托反馈
参数
account - StockAccount 资金账号
stock_code - str 证券代码, 如'600000.SH'
order_type - int 委托类型
order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
price_type - int 报价类型
price - float 委托价格
strategy_name - str 策略名称
order_remark - str 委托备注
返回
返回下单请求序号seq,成功委托后的下单请求序号为大于0的正整数,如果为-1表示委托失败
"""
xt_trader.order_stock_async(account=acc, stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=200, price_type=xtconstant.FIX_PRICE, price=13.1, strategy_name='异步下单', 
                order_remark='异步下单')

输出的结果

on_order_stock_async_response
55011917 1082195192 2829
on order callback:
600031.SH 50 8253
on order callback:
600031.SH 50 8253
on trade callback
55011917 600031.SH 1082195192
on order callback:
600031.SH 56 8253
on trade callback
55011917 600031.SH 1082195192
on order callback:
600031.SH 56 8253

10股票同步撤单

调用源代码

"""
释义
根据订单编号对委托进行撤单操作
参数
account - StockAccount 资金账号
order_id - int 同步下单接口返回的订单编号
返回
返回是否成功发出撤单指令,0: 成功, -1: 表示撤单失败
"""
stats=xt_trader.cancel_order_stock(account=acc, order_id=12)
if stats==0:
    print('成功')
else:
    print('失败')

输出的结果

失败

11股票异步撤单

调用源代码

"""
释义
根据订单编号对委托进行异步撤单操作
参数
account - StockAccount 资金账号
order_id - int 下单接口返回的订单编号
返回
返回撤单请求序号, 成功委托后的撤单请求序号为大于0的正整数, 如果为-1表示委托失败
"""
stats=xt_trader.cancel_order_stock_async(account=acc, order_id=12)
if stats==0:
    print('成功')
else:
    print('失败')

输出结果

失败

12回调的类

class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        """
        连接状态回调
        :return:
        """
        print("connection lost")
    def on_account_status(self, status):
        """
        账号状态信息推送
        :param response: XtAccountStatus 对象
        :return:
        """
        print("on_account_status")
        print(status.account_id, status.account_type, status.status)
    def on_stock_asset(self, asset):
        """
        资金信息推送
        :param asset: XtAsset对象
        :return:
        """
        print("on asset callback")
        print(asset.account_id, asset.cash, asset.total_asset)
    def on_stock_order(self, order):
        """
        委托信息推送
        :param order: XtOrder对象
        :return:
        """
        print("on order callback:")
        print(order.stock_code, order.order_status, order.order_sysid)
    def on_stock_trade(self, trade):
        """
        成交信息推送
        :param trade: XtTrade对象
        :return:
        """
        print("on trade callback")
        print(trade.account_id, trade.stock_code, trade.order_id)
    def on_stock_position(self, position):
        """
        持仓信息推送
        :param position: XtPosition对象
        :return:
        """
        print("on position callback")
        print(position.stock_code, position.volume)
    def on_order_error(self, order_error):
        """
        下单失败信息推送
        :param order_error:XtOrderError 对象
        :return:
        """
        print("on order_error callback")
        print(order_error.order_id, order_error.error_id, order_error.error_msg)
    def on_cancel_error(self, cancel_error):
        """
        撤单失败信息推送
        :param cancel_error: XtCancelError 对象
        :return:
        """
        print("on cancel_error callback")
        print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg)
    def on_order_stock_async_response(self, response):
        """
        异步下单回报推送
        :param response: XtOrderResponse 对象
        :return:
        """
        print("on_order_stock_async_response")
        print(response.account_id, response.order_id, response.seq)
    def on_smt_appointment_async_response(self, response):
        """
        :param response: XtAppointmentResponse 对象
        :return:
        """
        print("on_smt_appointment_async_response")
        print(response.account_id, response.order_sysid, response.error_id, response.error_msg, response.seq)

四easy_qmt_trader交易

1简化版的qmt_trader 方便大家做策略的开发类的继承

源代码

#统一同花顺
from .xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from .xtquant.xttype import StockAccount
from .xtquant import xtconstant
import time
import pandas as pd
import random
import math
import json
from .qmt_data import qmt_data
import math
def conv_time(ct):
    '''
    conv_time(1476374400000) --> '20161014000000.000'
    '''
    local_time = time.localtime(ct / 1000)
    data_head = time.strftime('%Y%m%d%H%M%S', local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = '%s.%03d' % (data_head, data_secs)
    return time_stamp
class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        """
        连接断开
        :return:
        """
        print("connection lost")
    def on_stock_order(self, order):
        """
        委托回报推送
        :param order: XtOrder对象
        :return:
        """
        print("on order callback:")
        print(order.stock_code, order.order_status, order.order_sysid)
    def on_stock_asset(self, asset):
        """
        资金变动推送
        :param asset: XtAsset对象
        :return:
        """
        print("on asset callback")
        print(asset.account_id, asset.cash, asset.total_asset)
    def on_stock_trade(self, trade):
        """
        成交变动推送
        :param trade: XtTrade对象
        :return:
        """
        print("on trade callback")
        print(trade.account_id, trade.stock_code, trade.order_id)
    def on_stock_position(self, position):
        """
        持仓变动推送
        :param position: XtPosition对象
        :return:
        """
        print("on position callback")
        print(position.stock_code, position.volume)
    def on_order_error(self, order_error):
        """
        委托失败推送
        :param order_error:XtOrderError 对象
        :return:
        """
        print("on order_error callback")
        print(order_error.order_id, order_error.error_id, order_error.error_msg)
    def on_cancel_error(self, cancel_error):
        """
        撤单失败推送
        :param cancel_error: XtCancelError 对象
        :return:
        """
        print("on cancel_error callback")
        print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg)
    def on_order_stock_async_response(self, response):
        """
        异步下单回报推送
        :param response: XtOrderResponse 对象
        :return:
        """
        print("on_order_stock_async_response")
        print(response.account_id, response.order_id, response.seq)
class easy_qmt_trader:
    def __init__(self,path= r'D:/国金QMT交易端模拟/userdata_mini',
                  session_id = 123456,account='55009640',account_type='STOCK',
                  is_slippage=True,slippage=0.01) -> None:
        '''
        简化版的qmt_trder方便大家做策略的开发类的继承
        '''
        self.xt_trader=''
        self.acc=''
        self.path=path
        self.session_id=int(self.random_session_id())
        self.account=account
        self.account_type=account_type
        if is_slippage==True:
            self.slippage=slippage
        else:
            self.slippage=0
        self.data=qmt_data()
    def random_session_id(self):
        '''
        随机id
        '''
        session_id=''
        for i in range(0,9):
            session_id+=str(random.randint(1,9))
        return session_id
    def select_slippage(self,stock='600031',price=15.01,trader_type='buy'):
        '''
        选择滑点
        安价格来滑点,比如0.01就是一块
        etf3位数,股票可转债2位数
        '''
        stock=self.adjust_stock(stock=stock)
        data_type=self.select_data_type(stock=stock)
        if data_type=='fund' or data_type=='bond':
            slippage=self.slippage/10
            if trader_type=='buy' or trader_type==23:
                price=price+slippage
            else:
                price=price-slippage
        else:
            slippage=self.slippage
            if trader_type=='buy' or trader_type==23:
                price=price+slippage
            else:
                price=price-slippage
        return price
    def check_is_trader_date_1(self,trader_time=4,start_date=9,end_date=14,start_mi=0,jhjj='否'):
        '''
        检测是不是交易时间
        '''
        if jhjj=='是':
            jhjj_time=15
        else:
            jhjj_time=30
        loc=time.localtime()
        tm_hour=loc.tm_hour
        tm_min=loc.tm_min
        wo=loc.tm_wday
        if wo<=trader_time:
            if tm_hour>=start_date and tm_hour<=end_date:
                if tm_hour==9 and tm_min<jhjj_time:
                    return False
                elif tm_min>=start_mi:
                    return True
                else:
                    return False
            else:
                return False    
        else:
            print('周末')
            return False
    def select_data_type(self,stock='600031'):
        '''
        选择数据类型
        '''
        if stock[:3] in ['110','113','123','127','128','111','118'] or stock[:2] in ['11','12']:
            return 'bond'
        elif stock[:3] in ['510','511','512','513','514','515','516','517','518','588','159','501','164'] or stock[:2] in ['16']:
            return 'fund'
        else:
            return 'stock'
    def adjust_stock(self,stock='600031.SH'):
        '''
        调整代码
        '''
        if stock[-2:]=='SH' or stock[-2:]=='SZ' or stock[-2:]=='sh' or stock[-2:]=='sz':
            stock=stock.upper()
        else:
            if stock[:3] in ['600','601','603','688','510','511',
                             '512','513','515','113','110','118','501'] or stock[:2] in ['11']:
                stock=stock+'.SH'
            else:
                stock=stock+'.SZ'
        return stock
    def check_stock_is_av_buy(self,stock='128036',price='156.700',amount=10,hold_limit=100000):
        '''
        检查是否可以买入
        '''
        hold_stock=self.position()
        try:
            del hold_stock['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        #买入是价值
        value=price*amount
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        if cash>=value:
            print('允许买入{} 可用现金{}大于买入金额{} 价格{} 数量{}'.format(stock,cash,value,price,amount))
            return True
        else:
            print('不允许买入{} 可用现金{}小于买入金额{} 价格{} 数量{}'.format(stock,cash,value,price,amount))
            return False
    def check_stock_is_av_sell(self,stock='128036',amount=10):
        '''
        检查是否可以卖出
        '''
        #stock=self.adjust_stock(stock=stock)
        hold_data=self.position()
        try:
            del hold_data['Unnamed: 0']
        except:
            pass
        account=self.balance()
        try:
            del account['Unnamed: 0']
        except:
            pass
        #买入是价值
        cash=account['可用金额'].tolist()[-1]
        frozen_cash=account['冻结金额'].tolist()[-1]
        market_value=account['持仓市值'].tolist()[-1]
        total_asset=account['总资产'].tolist()[-1]
        stock_list=hold_data['证券代码'].tolist()
        if stock in stock_list:
            hold_num=hold_data[hold_data['证券代码']==stock]['可用余额'].tolist()[-1]
            if hold_num>=amount:
                print('允许卖出:{} 持股{} 卖出{}'.format(stock,hold_num,amount))
                return True
            else:
                print('不允许卖出持股不足:{} 持股{} 卖出{}'.format(stock,hold_num,amount))
                return False
        else:
            print('不允许卖出没有持股:{} 持股{} 卖出{}'.format(stock,0,amount))
            return False
    def connect(self):
        '''
        连接
        path qmt userdata_min是路径
        session_id 账户的标志,随便
        account账户,
        account_type账户内类型
        '''
        print('链接qmt')
        # path为mini qmt客户端安装目录下userdata_mini路径
        path = self.path
        # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号
        session_id = self.session_id
        xt_trader = XtQuantTrader(path, session_id)
        # 创建资金账号为1000000365的证券账号对象
        account=self.account
        account_type=self.account_type
        acc = StockAccount(account_id=account,account_type=account_type)
        # 创建交易回调类对象,并声明接收回调
        callback = MyXtQuantTraderCallback()
        xt_trader.register_callback(callback)
        # 启动交易线程
        xt_trader.start()
        # 建立交易连接,返回0表示连接成功
        connect_result = xt_trader.connect()
        if connect_result==0:
            # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
            subscribe_result = xt_trader.subscribe(acc)
            print(subscribe_result)
            self.xt_trader=xt_trader
            self.acc=acc
            return xt_trader,acc
        else:
            print('qmt连接失败')
    def order_stock(self,stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
            '''
            下单,统一接口
            :param account: 证券账号
                :param stock_code: 证券代码, 例如"600000.SH"
                :param order_type: 委托类型, 23:买, 24:卖
                :param order_volume: 委托数量, 股票以'股'为单位, 债券以'张'为单位
                :param price_type: 报价类型, 详见帮助手册
                :param price: 报价价格, 如果price_type为指定价, 那price为指定的价格, 否则填0
                :param strategy_name: 策略名称
                :param order_remark: 委托备注
                :return: 返回下单请求序号, 成功委托后的下单请求序号为大于0的正整数, 如果为-1表示委托失败
            '''
        
            # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
            subscribe_result = self.xt_trader.subscribe(self.acc)
            print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
            #print(subscribe_result)
            stock_code = self.adjust_stock(stock=stock_code)
            price=self.select_slippage(stock=stock_code,price=price,trader_type=order_type)
            # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
            fix_result_order_id = self.xt_trader.order_stock(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                            order_volume=order_volume, price_type=price_type,
                                                            price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id
    def buy(self,security='600031.SH', order_type=xtconstant.STOCK_BUY,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
        单独独立股票买入函数
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code =self.adjust_stock(stock=security)
        price=self.select_slippage(stock=security,price=price,trader_type='buy')
        order_volume=amount
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        if order_volume>0:
            fix_result_order_id = self.xt_trader.order_stock_async(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                                order_volume=order_volume, price_type=price_type,
                                                                price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id
        else:
            print('买入 标的{} 价格{} 委托数量{}小于0有问题'.format(stock_code,price,order_volume))
    def sell(self,security='600031.SH', order_type=xtconstant.STOCK_SELL,
                    amount=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
        单独独立股票卖出函数
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code =self.adjust_stock(stock=security)
        price=self.select_slippage(stock=security,price=price,trader_type='sell')
        order_volume=amount
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        if order_volume>0:
            fix_result_order_id = self.xt_trader.order_stock(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                                order_volume=order_volume, price_type=price_type,
                                                                price=price, strategy_name=strategy_name, order_remark=order_remark)
            print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
            return fix_result_order_id
        else:
            print('卖出 标的{} 价格{} 委托数量{}小于0有问题'.format(stock_code,price,order_volume))

    def order_stock_async(self,stock_code='600031.SH', order_type=xtconstant.STOCK_BUY,
                    order_volume=100,price_type=xtconstant.FIX_PRICE,price=20,strategy_name='',order_remark=''):
        '''
         释义 
        - 对股票进行异步下单操作,异步下单接口如果正常返回了下单请求序号seq,会收到on_order_stock_async_response的委托反馈
        * 参数
        - account - StockAccount 资金账号
        - stock_code - str 证券代码, 如'600000.SH'
        - order_type - int 委托类型
        - order_volume - int 委托数量,股票以'股'为单位,债券以'张'为单位
        - price_type - int 报价类型
        - price - float 委托价格
        - strategy_name - str 策略名称
        - order_remark - str 委托备注
        '''
        # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功
        subscribe_result = self.xt_trader.subscribe(self.acc)
        print(self.xt_trader.query_stock_asset_async(account=self.acc,callback=subscribe_result))
        #print(subscribe_result)
        stock_code = self.adjust_stock(stock=stock_code)
        price=self.select_slippage(stock=stock_code,price=price,trader_type=order_type)
        # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态
        fix_result_order_id = self.xt_trader.order_stock_async(account=self.acc,stock_code=stock_code, order_type=order_type,
                                                            order_volume=order_volume, price_type=price_type,
                                                            price=price, strategy_name=strategy_name, order_remark=order_remark)
        print('交易类型{} 代码{} 价格{} 数量{} 订单编号{}'.format(order_type,stock_code,price,order_volume,fix_result_order_id))
        return fix_result_order_id
    def cancel_order_stock(self,order_id=12):
        '''
        :param account: 证券账号
            :param order_id: 委托编号, 报单时返回的编号
            :return: 返回撤单成功或者失败, 0:成功,  -1:委托已完成撤单失败, -2:未找到对应委托编号撤单失败, -3:账号未登陆撤单失败
        '''
        # 使用订单编号撤单
        cancel_order_result = self.xt_trader.cancel_order_stock(account=self.acc,order_id=order_id)
        if cancel_order_result==0:
            print('成功')
        elif cancel_order_result==-1:
            print('委托已完成撤单失败')
        elif cancel_order_result==-2:
            print('找到对应委托编号撤单失败')
        elif cancel_order_result==-3:
            print('账号未登陆撤单失败')
        else:
            pass
        return cancel_order_result
    def cancel_order_stock_async(self,order_id=12):
        '''
        * 释义 
        - 根据订单编号对委托进行异步撤单操作
        * 参数
        - account - StockAccount  资金账号 
        - order_id - int 下单接口返回的订单编号
        * 返回 
        - 返回撤单请求序号, 成功委托后的撤单请求序号为大于0的正整数, 如果为-1表示委托失败
        * 备注
        - 如果失败,则通过撤单失败主推接口返回撤单失败信息
        '''
        # 使用订单编号撤单
        cancel_order_result = self.xt_trader.cancel_order_stock_async(account=self.acc,order_id=order_id)
        if cancel_order_result==0:
            print('成功')
        elif cancel_order_result==-1:
            print('委托已完成撤单失败')
        elif cancel_order_result==-2:
            print('找到对应委托编号撤单失败')
        elif cancel_order_result==-3:
            print('账号未登陆撤单失败')
        else:
            pass
        return cancel_order_result
    def query_stock_asset(self):
        '''
        :param account: 证券账号
            :return: 返回当前证券账号的资产数据
        '''
        # 查询证券资产
        
        asset = self.xt_trader.query_stock_asset(account=self.acc)
        data_dict={}
        if asset:
            data_dict['账号类型']=asset.account_type
            data_dict['资金账户']=asset.account_id
            data_dict['可用金额']=asset.cash
            data_dict['冻结金额']=asset.frozen_cash
            data_dict['持仓市值']=asset.market_value
            data_dict['总资产']=asset.total_asset
            return data_dict
        else:
            print('获取失败资金')
            data_dict['账号类型']=[None]
            data_dict['资金账户']=[None]
            data_dict['可用金额']=[None]
            data_dict['冻结金额']=[None]
            data_dict['持仓市值']=[None]
            data_dict['总资产']=[None]
            return  data_dict
    def balance(self):
        '''
        对接同花顺
        '''
        try:
            asset = self.xt_trader.query_stock_asset(account=self.acc)
            df=pd.DataFrame()
            if asset:
                df['账号类型']=[asset.account_type]
                df['资金账户']=[asset.account_id]
                df['可用金额']=[asset.cash]
                df['冻结金额']=[asset.frozen_cash]
                df['持仓市值']=[asset.market_value]
                df['总资产']=[asset.total_asset]
                return df
        except:
            print('获取账户失败,读取上次数据,谨慎使用')
            df=pd.DataFrame()
            return df
    def query_stock_orders(self):
        '''
        当日委托
         :param account: 证券账号
        :param cancelable_only: 仅查询可撤委托
        :return: 返回当日所有委托的委托对象组成的list
        '''
        orders = self.xt_trader.query_stock_orders(self.acc)
        print("委托数量", len(orders))
        data=pd.DataFrame()
        if len(orders) != 0:
            for i in range(len(orders)):
                df=pd.DataFrame()
                df['账号类型']=[orders[i].account_type]
                df['资金账号']=[orders[i].account_id]
                df['证券代码']=[orders[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['订单编号']=[orders[i].order_id]
                df['柜台合同编号']=[orders[i].order_sysid]
                df['报单时间']=[orders[i].order_time]
                df['委托类型']=[orders[i].order_type]
                df['委托数量']=[orders[i].order_volume]
                df['报价类型']=[orders[i].price_type]
                df['委托价格']=[orders[i].price]
                df['成交数量']=[orders[i].traded_volume]
                df['成交均价']=[orders[i].traded_price]
                df['委托状态']=[orders[i].order_status]
                df['委托状态描述']=[orders[i].status_msg]
                df['策略名称']=[orders[i].strategy_name]
                df['委托备注']=[orders[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['报单时间']=pd.to_datetime(data['报单时间'],unit='s')
            return data
        else:
            print('目前没有委托')
            return data
    def today_entrusts(self):
        '''
        对接同花顺
        今天委托
        '''
        def select_data(x):
            if x==48:
                return '未报'
            elif x==49:
                return '待报'
            elif x==50:
                return '已报'
            elif x==51:
                return '已报待撤'
            elif x==52:
                return '部分待撤'
            elif x==53:
                return '部撤'
            elif x==54:
                return '已撤'
            elif x==55:
                return '部成'
            elif x==56:
                return '已成'
            elif x==57:
                return '废单'
            else:
                return '废单'
        orders = self.xt_trader.query_stock_orders(self.acc)
        print("委托数量", len(orders))
        data=pd.DataFrame()
        if len(orders) != 0:
            for i in range(len(orders)):
                df=pd.DataFrame()
                df['账号类型']=[orders[i].account_type]
                df['资金账号']=[orders[i].account_id]
                df['证券代码']=[orders[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['订单编号']=[orders[i].order_id]
                df['柜台合同编号']=[orders[i].order_sysid]
                df['报单时间']=[orders[i].order_time]
                df['委托类型']=[orders[i].order_type]
                df['委托数量']=[orders[i].order_volume]
                df['报价类型']=[orders[i].price_type]
                df['委托价格']=[orders[i].price]
                df['成交数量']=[orders[i].traded_volume]
                df['成交均价']=[orders[i].traded_price]
                df['委托状态']=[orders[i].order_status]
                df['委托状态描述']=[orders[i].status_msg]
                df['策略名称']=[orders[i].strategy_name]
                df['委托备注']=[orders[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['报单时间']=df['报单时间'].apply(conv_time)
            data['委托状态翻译']=data['委托状态'].apply(select_data)
            data['未成交数量']=data['委托数量']-data['成交数量']
            data['未成交价值']=data['未成交数量']*data['委托价格']
            return data
        else:
            print('目前没有委托')
            return data
    def query_stock_trades(self):
        '''
        当日成交
        '''
        trades = self.xt_trader.query_stock_trades(self.acc)
        print("成交数量:", len(trades))
        data=pd.DataFrame()
        if len(trades) != 0:
            for i in range(len(trades)):
                df=pd.DataFrame()
                df['账号类型']=[trades[i].account_type]
                df['资金账号']=[trades[i].account_id]
                df['证券代码']=[trades[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['委托类型']=[trades[i].order_type]
                df['成交编号']=[trades[i].traded_id]
                df['成交时间']=[trades[i].traded_time]
                df['成交均价']=[trades[i].traded_price]
                df['成交数量']=[trades[i].traded_volume]
                df['成交金额']=[trades[i].traded_amount]
                df['订单编号']=[trades[i].order_id]
                df['柜台合同编号']=[trades[i].order_sysid]
                df['策略名称']=[trades[i].strategy_name]
                df['委托备注']=[trades[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            data['成交时间']=pd.to_datetime(data['成交时间'],unit='s')
            return data
        else:
            print('今日没有成交')     
            return data
    def today_trades(self):
        '''
        对接同花顺
        今日成交
        '''
        trades = self.xt_trader.query_stock_trades(self.acc)
        print("成交数量:", len(trades))
        data=pd.DataFrame()
        if len(trades) != 0:
            for i in range(len(trades)):
                df=pd.DataFrame()
                df['账号类型']=[trades[i].account_type]
                df['资金账号']=[trades[i].account_id]
                df['证券代码']=[trades[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['委托类型']=[trades[i].order_type]
                df['成交编号']=[trades[i].traded_id]
                df['成交时间']=[trades[i].traded_time]
                df['成交均价']=[trades[i].traded_price]
                df['成交数量']=[trades[i].traded_volume]
                df['成交金额']=[trades[i].traded_amount]
                df['订单编号']=[trades[i].order_id]
                df['柜台合同编号']=[trades[i].order_sysid]
                df['策略名称']=[trades[i].strategy_name]
                df['委托备注']=[trades[i].order_remark]
                data=pd.concat([data,df],ignore_index=True)
            def select_data(x):
                if x==xtconstant.STOCK_BUY:
                    return '证券买入'
                elif x==xtconstant.STOCK_SELL:
                    return '证券卖出'
                else:
                    return '无'
            df['操作']=df['委托类型'].apply(select_data)
            data['成交时间']=pd.to_datetime(data['成交时间'],unit='s')
            return data
        else:
            print('今日没有成交')     
            return data
    def query_stock_positions(self):
        '''
        查询账户所有的持仓
        '''
        positions = self.xt_trader.query_stock_positions(self.acc)
        print("持仓数量:", len(positions))
        data=pd.DataFrame()
        if len(positions) != 0:
            for i in range(len(positions)):
                df=pd.DataFrame()
                df['账号类型']=[positions[i].account_type]
                df['资金账号']=[positions[i].account_id]
                df['证券代码']=[positions[i].stock_code]
                df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                df['持仓数量']=[positions[i].volume]
                df['可用数量']=[positions[i].can_use_volume]
                df['平均建仓成本']=[positions[i].open_price]
                df['市值']=[positions[i].market_value]
                data=pd.concat([data,df],ignore_index=True)
            return data
        else:
            print('没有持股')
            df=pd.DataFrame()
            df['账号类型']=[None]
            df['资金账号']=[None]
            df['证券代码']=[None]
            df['持仓数量']=[None]
            df['可用数量']=[None]
            df['平均建仓成本']=[None]
            df['市值']=[None]
            return df
    def position(self):
        '''
        对接同花顺
        持股
        '''
        try:
            positions = self.xt_trader.query_stock_positions(self.acc)
            print("持仓数量:", len(positions))
            data=pd.DataFrame()
            if len(positions) != 0:
                for i in range(len(positions)):
                    df=pd.DataFrame()
                    df['账号类型']=[positions[i].account_type]
                    df['资金账号']=[positions[i].account_id]
                    df['证券代码']=[positions[i].stock_code]
                    df['证券代码']=df['证券代码'].apply(lambda x:str(x)[:6])
                    df['股票余额']=[positions[i].volume]
                    df['可用余额']=[positions[i].can_use_volume]
                    df['成本价']=[positions[i].open_price]
                    df['参考成本价']=[positions[i].open_price]
                    df['市值']=[positions[i].market_value]
                    data=pd.concat([data,df],ignore_index=True)
                return data
            else:
                df=pd.DataFrame()
                df['账号类型']=None
                df['资金账号']=None
                df['证券代码']=None
                df['股票余额']=None
                df['可用余额']=None
                df['成本价']=None
                df['市值']=None
                df['选择']=None
                df['持股天数']=None
                df['交易状态']=None
                df['明细']=None
                df['证券名称']=None
                df['冻结数量']=None
                df['市价']=None
                df['盈亏']=None
                df['盈亏比(%)']=None
                df['当日买入']=None	
                df['当日卖出']=None
                return df
                
        except:
            df=pd.DataFrame()
            return df
    def run_forever(self):
        '''
        阻塞线程,接收交易推送
        '''
        self.xt_trader.run_forever()
    def stop(self):
        self.xt_trader.stop()
if __name__=='__main__':
    models=easy_qmt_trader()
    models.connect()
    print(models.query_stock_orders())
    models.buy()
    models1=easy_qmt_trader(account='55009680',session_id=123457)
    models1.connect()
    print(models1.query_stock_positions())
    

五xtdata教程

1常用参数说明

"""
常用类型说明
stock_code - 合约代码
格式为 code.market,例如000001.SZ 600000.SH 000300.SH
period - 周期,用于表示要获取的周期和具体数据类型
level1数据
tick - 分笔数据
1m - 1分钟线
5m - 5分钟线
15m - 15分钟线
30m - 30分钟线
1h - 1小时线
1d - 日线
1w - 周线
1mon - 月线
1q - 季度线
1hy - 半年线
1y - 年线
level2数据
l2quote - level2实时行情快照
l2order - level2逐笔委托
l2transaction - level2逐笔成交
l2quoteaux - level2实时行情补充(总买总卖)
l2orderqueue - level2委买委卖一档委托队列
l2thousand - level2千档盘口
投研版 - 特色数据
warehousereceipt - 期货仓单
futureholderrank - 期货席位
interactiveqa - 互动问答
逐笔成交统计
transactioncount1m - 逐笔成交统计1分钟级
transactioncount1d - 逐笔成交统计日级
delistchangebond - 退市可转债信息
replacechangebond - 待发可转债信息
specialtreatment - ST 变更历史
港股通(深港通、沪港通)资金流向
northfinancechange1m - 港股通资金流向1分钟级
northfinancechange1d - 港股通资金流向日级
dividendplaninfo - 红利分配方案信息
historycontract - 过期合约列表
optionhistorycontract - 期权历史信息
historymaincontract - 历史主力合约
stoppricedata - 涨跌停数据
snapshotindex - 快照指标数据
时间范围,用于指定数据请求范围,表示的范围是[start_time, end_time]区间(包含前后边界)中最后不多于count个数据
start_time - 起始时间,为空则认为是最早的起始时间
end_time - 结束时间,为空则认为是最新的结束时间
count - 数据个数,大于0为正常限制返回个数,等于0为不需要返回,-1为返回全部
通常以[start_time = '', end_time = '', count = -1]表示完整数据范围,但数据请求范围过大会导致返回时间变长,需要按需裁剪请求范围
dividend_type - 除权方式,用于K线数据复权计算,对tick等其他周期数据无效
none 不复权
front 前复权
back 后复权
front_ratio 等比前复权
back_ratio 等比后复权
其他依赖库 numpy、pandas会在数据返回的过程中使用
本模块会尽可能减少对numpy和pandas库的直接依赖,以允许使用者在不同版本的库之间自由切换
pandas库中旧的三维数据结构Panel没有被使用,而是以dict嵌套DataFrame代替(后续可能会考虑使用xarray等的方案,也欢迎使用者提供改进建议)
后文中会按常用规则分别简写为np、pd,如np.ndarray、pd.DataFrame
"""

2订阅单股行情比如一分钟实时数据

调用源代码

#导入数据库
from xtquant import xtdata
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='1m',start_time='20240614',end_time='20240614')
    #获取最后面一个
    print(df[code_list[0]][-1:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_quote(stock_code='600031.SH',period='1m',start_time='20240614',end_time='20240614',count=-1,callback=f)
#进入循环
xtdata.run()
'''
参数
stock_code - string 合约代码
period - string 周期
start_time - string 起始时间
end_time - string 结束时间
count - int 数据个数
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock_code : [data1, data2, ...] }
'''

3获取tick实时连续数据

调用源代码

#导入数据库
#获取tick实时连续数据
from xtquant import xtdata
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='tick',start_time='20240614',end_time='20240614')
    #获取最后面2个
    print(df[code_list[0]][-2:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_quote(stock_code='600031.SH',period='tick',start_time='20240614',end_time='20240614',count=-1,callback=f)
#进入循环
xtdata.run()
'''
参数
stock_code - string 合约代码
period - string 周期
start_time - string 起始时间
end_time - string 结束时间
count - int 数据个数
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock_code : [data1, data2, ...] }
'''

输出的结果

***** xtdata连接成功 *****
服务信息: {'tag': 'sp3', 'version': '1.0'}
服务地址: 127.0.0.1:58610
数据路径: D:\国金QMT交易端模拟\bin.x64/../userdata_mini/datadir
设置xtdata.enable_hello = False可隐藏此消息

                         time  lastPrice   open   high    low  lastClose  \
20240614104747  1718333267000      15.61  15.51  15.68  15.46      15.57   
20240614104750  1718333270000      15.61  15.51  15.68  15.46      15.57   

                     amount  volume   pvolume  stockStatus  openInt  \
20240614104747  207267832.0  132844  13284363            3       13   
20240614104750  207267832.0  132844  13284363            3       13   

                lastSettlementPrice  \
20240614104747                  0.0   
20240614104750                  0.0   

                                                        askPrice  \
20240614104747  [15.620000000000001, 15.63, 15.64, 15.65, 15.66]   
20240614104750  [15.620000000000001, 15.63, 15.64, 15.65, 15.66]   

                                                         bidPrice  \
20240614104747  [15.610000000000001, 15.600000000000001, 15.59...   
20240614104750  [15.610000000000001, 15.600000000000001, 15.59... 

4单独订阅获取数据

调用源代码

#不利用回调模式获取日线数据,但是可以利用时间调度函数定时,循环获取
from xtquant import xtdata
#订阅单股数据
xtdata.subscribe_quote(stock_code='600031.SH',period='tick',start_time='20240614',end_time='20500101',count=-1)
df=xtdata.get_market_data_ex(stock_list=['600031.SH'],period='tick',start_time='20240614',end_time='20500101')
#获取最后面2个
df['600031.SH']

输出的结果

	time	lastPrice	open	high	low	lastClose	amount	volume	pvolume	stockStatus	openInt	lastSettlementPrice	askPrice	bidPrice	askVol	bidVol	settlementPrice	transactionNum	pe
20240614091503	1718327703000	15.50	0.00	0.00	0.00	15.57	0.0	0	0	0	12	0.0	[15.5, 0.0, 0.0, 0.0, 0.0]	[15.5, 0.0, 0.0, 0.0, 0.0]	[59, 0, 0, 0, 0]	[59, 241, 0, 0, 0]	0.0	0	0.0
20240614091506	1718327706000	15.57	0.00	0.00	0.00	15.57	0.0	0	0	0	12	0.0	[15.57, 0.0, 0.0, 0.0, 0.0]	[15.57, 0.0, 0.0, 0.0, 0.0]	[114, 486, 0, 0, 0]	[114, 0, 0, 0, 0]	0.0	0	0.0
20240614091509	1718327709000	15.57	0.00	0.00	0.00	15.57	0.0	0	0	0	12	0.0	[15.57, 0.0, 0.0, 0.0, 0.0]	[15.57, 0.0, 0.0, 0.0, 0.0]	[140, 517, 0, 0, 0]	[140, 0, 0, 0, 0]	0.0	0	0.0
20240614091511	1718327711000	15.57	0.00	0.00	0.00	15.57	0.0	0	0	0	12	0.0	[15.57, 0.0, 0.0, 0.0, 0.0]	[15.57, 0.0, 0.0, 0.0, 0.0]	[140, 518, 0, 0, 0]	[140, 0, 0, 0, 0]	0.0	0	0.0
20240614091514	1718327714000	15.57	0.00	0.00	0.00	15.57	0.0	0	0	0	12	0.0	[15.57, 0.0, 0.0, 0.0, 0.0]	[15.57, 0.0, 0.0, 0.0, 0.0]	[140, 518, 0, 0, 0]	[140, 0, 0, 0, 0]	0.0	0	0.0

6订阅多个tick,盘中实时数据

订阅全推行情,同时获取多个标的的数据支持订阅数据比如SH,SZ,期货等 比如同时订阅多个tick,盘中实时数据 调用源代码

'''
释义

订阅全推行情数据,返回订阅号
数据推送从callback返回,数据类型为分笔数据
参数
code_list - 代码列表,支持传入市场代码或合约代码两种方式
传入市场代码代表订阅全市场,示例:['SH', 'SZ']
传入合约代码代表订阅指定的合约,示例:['600000.SH', '000001.SZ']
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
'''
#获取tick实时连续数据
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='tick',start_time='20240614',end_time='20240614')
    #获取最后面2个
    print(df[code_list[0]][-2:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_whole_quote(code_list=stock_code,callback=f)
#进入循环
xtdata.run()

输出的结果

                         time  lastPrice   open   high    low  lastClose  \
20240614112956  1718335796000      15.62  15.51  15.71  15.46      15.57   
20240614112959  1718335799000      15.62  15.51  15.71  15.46      15.57   

                     amount  volume   pvolume  stockStatus  openInt  \
20240614112956  274072062.0  175589  17558863            3       13   
20240614112959  274072062.0  175589  17558863            3       13   

                lastSettlementPrice  \
20240614112956                  0.0   
20240614112959                  0.0   

                                                        askPrice  \
20240614112956  [15.620000000000001, 15.63, 15.64, 15.65, 15.66]   
20240614112959  [15.620000000000001, 15.63, 15.64, 15.65, 15.66]   

                                                         bidPrice  \
20240614112956  [15.610000000000001, 15.600000000000001, 15.59...   
20240614112959  [15.610000000000001, 15.600000000000001, 15.59...   

                                askVol                     bidVol  \
20240614112956  [50, 241, 108, 95, 59]  [289, 152, 147, 387, 260]   
20240614112959  [66, 241, 108, 95, 59]  [298, 152, 147, 387, 260]   

7全推送一分钟的实时数据

调用源代码

'''
释义

订阅全推行情数据,返回订阅号
数据推送从callback返回,数据类型为分笔数据
参数
code_list - 代码列表,支持传入市场代码或合约代码两种方式
传入市场代码代表订阅全市场,示例:['SH', 'SZ']
传入合约代码代表订阅指定的合约,示例:['600000.SH', '000001.SZ']
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
'''
#获取tick实时连续数据
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='1m',start_time='20240614',end_time='20240614')
    #获取最后面2个
    print(df[code_list[0]][-2:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_whole_quote(code_list=stock_code,callback=f)
#进入循环
xtdata.run()

输出的结果

                         time   open   high    low  close  volume      amount  \
20240614145900  1718348340000  15.68  15.68  15.68  15.68       0         0.0   
20240614150000  1718348400000  15.68  15.68  15.68  15.68   10365  16252320.0   

                settelementPrice  openInterest  preClose  suspendFlag  
20240614145900               0.0            18     15.68            0  
20240614150000               0.0            15     15.68            0  
*******************

8不要回调模式下载数据,订阅模式

调用源代码

#不要回调模式下载数据,订阅模式
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
xtdata.subscribe_whole_quote(code_list=stock_code)
df=xtdata.get_market_data_ex(stock_list=stock_code,period='1m',start_time='20240614',end_time='20240614')
df


输出的结果

{'600031.SH':                          time   open   high    low  close  volume      amount  \
 20240614093000  1718328600000  15.51  15.51  15.51  15.51    1461   2266011.0   
 20240614093100  1718328660000  15.52  15.68  15.46  15.58   16479  25665273.0   
 20240614093200  1718328720000  15.60  15.63  15.58  15.62    3908   6097042.0   
 20240614093300  1718328780000  15.63  15.63  15.59  15.60    3546   5537686.0   
 20240614093400  1718328840000  15.61  15.65  15.59  15.61    4377   6837773.0   
 ...                       ...    ...    ...    ...    ...     ...         ...   
 20240614104200  1718332920000  15.59  15.60  15.58  15.59     592    923323.0   
 20240614104300  1718332980000  15.60  15.60  15.59  15.59     252    392922.0   
 20240614104400  1718333040000  15.59  15.61  15.59  15.59    1417   2210376.0   
 20240614104500  1718333100000  15.59  15.61  15.59  15.60     868   1353705.0   
 20240614104600  1718333160000  15.61  15.61  15.59  15.60    1556   2428365.0   
 
                 settelementPrice  openInterest  preClose  suspendFlag  
 20240614093000               0.0            13     15.57            0  
 20240614093100               0.0            13     15.51            0  
 20240614093200               0.0            13     15.58            0  
 20240614093300               0.0            13     15.62            0  
 20240614093400               0.0            13     15.60            0  
 ...                          ...           ...       ...          ...  
 20240614104200               0.0            13     15.58            0  

9订阅全推行情

订阅全推行情,同时获取多个标的的数据支持订阅数据比如SH,SZ,期货等 比如同时订阅多个tick,盘中实时数据 调用源代码

'''
释义

订阅全推行情数据,返回订阅号
数据推送从callback返回,数据类型为分笔数据
参数
code_list - 代码列表,支持传入市场代码或合约代码两种方式
传入市场代码代表订阅全市场,示例:['SH', 'SZ']
传入合约代码代表订阅指定的合约,示例:['600000.SH', '000001.SZ']
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
'''
#获取tick实时连续数据
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='tick',start_time='20240614',end_time='20240614')
    #获取最后面2个
    print(df[code_list[0]][-2:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_whole_quote(code_list=stock_code,callback=f)
#进入循环
xtdata.run()

输出的结果

***** xtdata连接成功 *****
服务信息: {'tag': 'sp3', 'version': '1.0'}
服务地址: 127.0.0.1:58610
数据路径: D:\国金QMT交易端模拟\bin.x64/../userdata_mini/datadir
设置xtdata.enable_hello = False可隐藏此消息

                         time  lastPrice   open   high    low  lastClose  \
20240614145959  1718348399000      15.68  15.51  15.75  15.46      15.57   
20240614150003  1718348403000      15.68  15.51  15.75  15.46      15.57   

                     amount  volume  pvolume  stockStatus  openInt  \
20240614145959  569774054.0  364013        0            0       18   
20240614150003  586026374.0  374378        0            0       15   

                lastSettlementPrice  \
20240614145959                  0.0   
20240614150003                  0.0   

                                                         askPrice  \
20240614145959                        [15.68, 0.0, 0.0, 0.0, 0.0]   
20240614150003  [15.69, 15.7, 15.709999999999999, 15.719999999...   

10全推送一分钟的实时数据

调用的源代码

'''
释义

订阅全推行情数据,返回订阅号
数据推送从callback返回,数据类型为分笔数据
参数
code_list - 代码列表,支持传入市场代码或合约代码两种方式
传入市场代码代表订阅全市场,示例:['SH', 'SZ']
传入合约代码代表订阅指定的合约,示例:['600000.SH', '000001.SZ']
callback - 数据推送回调
回调定义形式为on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
'''
#获取tick实时连续数据
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
def f(datas):
    '''
    回调函数默认输入的是一个股票字典
    回调默认3秒一次
    '''
    code_list=list(datas.keys())
    #读取实时数据。返回的一个字典数据
    df=xtdata.get_market_data_ex(stock_list=code_list,period='1m',start_time='20240614',end_time='20240614')
    #获取最后面2个
    print(df[code_list[0]][-2:])
    print('*******************')
#订阅单股数据
xtdata.subscribe_whole_quote(code_list=stock_code,callback=f)
#进入循环
xtdata.run()

输出的结果

                         time   open   high    low  close  volume      amount  \
20240614145900  1718348340000  15.68  15.68  15.68  15.68       0         0.0   
20240614150000  1718348400000  15.68  15.68  15.68  15.68   10365  16252320.0   

                settelementPrice  openInterest  preClose  suspendFlag  
20240614145900               0.0            18     15.68            0  
20240614150000               0.0            15     15.68            0  

11 不要回调模式下载数据,订阅模式

调用源代码

#不要回调模式下载数据,订阅模式
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
xtdata.subscribe_whole_quote(code_list=stock_code)
df=xtdata.get_market_data_ex(stock_list=stock_code,period='1m',start_time='20240614',end_time='20240614')
df

输出的结果

#不要回调模式下载数据,订阅模式
from xtquant import xtdata
stock_code=['600031.SH','600111.SH']
xtdata.subscribe_whole_quote(code_list=stock_code)
df=xtdata.get_market_data_ex(stock_list=stock_code,period='1m',start_time='20240614',end_time='20240614')
df

12订阅模式下载历史数据

获取行情数据,2个模式可以选择一个是订阅,一个是下载数据一般用订阅 调用的代码

#订阅模式下载历史数据,获取
from xtquant import xtdata
import pandas as pd
stock_code='600031.SH'
xtdata.subscribe_quote(stock_code=stock_code,period='1m',
                       start_time='20240614',end_time='20240614')
#xtdata.get_market_data()和get_market_data_ex是一样的一般用带有ex的那个
df=xtdata.get_market_data(stock_list=[stock_code],period='1m',
                             start_time='20240614',end_time='20240614')
df

输出的结果

{'time':            20240614093000  20240614093100  20240614093200  20240614093300  \
 600031.SH   1718328600000   1718328660000   1718328720000   1718328780000   
 
            20240614093400  20240614093500  20240614093600  20240614093700  \
 600031.SH   1718328840000   1718328900000   1718328960000   1718329020000   
 
            20240614093800  20240614093900  ...  20240614145100  \
 600031.SH   1718329080000   1718329140000  ...   1718347860000   
 
            20240614145200  20240614145300  20240614145400  20240614145500  \
 600031.SH   1718347920000   1718347980000   1718348040000   1718348100000   

13历史下载数据的模式获取获取

调用源代码

from xtquant import xtdata
import pandas as pd
stock_code='600031.SH'
xtdata.download_history_data(stock_code=stock_code,period='1m',
                       start_time='20240614',end_time='20240614',incrementally=True)
df=xtdata.get_market_data(stock_list=[stock_code],period='1m',
                             start_time='20240614',end_time='20240614')
df

输出的结果

from xtquant import xtdata
import pandas as pd
stock_code='600031.SH'
xtdata.download_history_data(stock_code=stock_code,period='1m',
                       start_time='20240614',end_time='20240614',incrementally=True)
df=xtdata.get_market_data(stock_list=[stock_code],period='1m',
                             start_time='20240614',end_time='20240614')
df

14 获取本地行情数据,没有的历史数据先下载

调用源代码

from xtquant import xtdata
import pandas as pd
stock_code='600031.SH'
xtdata.download_history_data(stock_code=stock_code,period='1m',
                       start_time='20240614',end_time='20240614',incrementally=True)
df=xtdata.get_local_data(stock_list=[stock_code],period='1m',
                       start_time='20240614',end_time='20240614',)
df[stock_code]
"""
释义
从本地数据文件获取行情数据,用于快速批量获取历史部分的行情数据
参数
field_list - list 数据字段列表,传空则为全部字段
stock_list - list 合约代码列表
period - string 周期
start_time - string 起始时间
end_time - string 结束时间
count - int 数据个数
dividend_type - string 除权方式
fill_data - bool 是否向后填充空缺数据
data_dir - string MiniQmt配套路径的userdata_mini路径,用于直接读取数据文件。默认情况下xtdata会通过连接向MiniQmt直接获取此路径,无需额外设置。如果需要调整,可以将数据路径作为data_dir传入,也可以直接修改xtdata.data_dir以改变默认值
返回
period为1m 5m 1dK线周期时
返回dict { field1 : value1, field2 : value2, ... }
field1, field2, ... :数据字段
value1, value2, ... :pd.DataFrame 数据集,index为stock_list,columns为time_list
各字段对应的DataFrame维度相同、索引相同
period为tick分笔周期时
返回dict { stock1 : value1, stock2 : value2, ... }
stock1, stock2, ... :合约代码
value1, value2, ... :np.ndarray 数据集,按数据时间戳time增序排列
"""

15获取全推数据,盘中回调模式运行

调用的源代码

from xtquant import xtdata
import pandas as pd
code_list=['600031.SH','600111.SH']
def f(datas):
    code_list=list(datas.keys())
    tick=xtdata.get_full_tick(code_list=code_list)
    print(tick)
xtdata.subscribe_whole_quote(code_list=code_list,callback=f)
xtdata.run()

输出的结果

{'600031.SH': {'timetag': '20240618 15:00:02', 'lastPrice': 16.02, 'open': 15.64, 'high': 16.19, 'low': 15.42, 'lastClose': 15.64, 'amount': 935527400, 'volume': 591174, 'pvolume': 59117403, 'stockStatus': 0, 'op

16 一次性读取的,不需要订阅

调用源代码】

from xtquant import xtdata
import pandas as pd
code_list=['600031.SH','600111.SH']
tick=xtdata.get_full_tick(code_list=code_list)
print(tick)

输出的结果

{'600031.SH': {'timetag': '20240618 15:00:02', 'lastPrice': 16.02, 'open': 15.64, 'high': 16.19, 'low': 1

17下载历史数据

调用源代码

from xtquant import xtdata
import pandas as pd
code_list=['600031.SH','600111.SH']
xtdata.download_history_data(stock_code=code_list[-1],period='tick',start_time='20240613',end_time='20240615')
#读取本地数据
df=xtdata.get_local_data(stock_list=[code_list[-1]],period='tick',start_time='20240613',end_time='20240615',count=-1)
df[code_list[-1]]

输入的结果


time	lastPrice	open	high	low	lastClose	amount	volume	pvolume	stockStatus	openInt	lastSettlementPrice	askPrice	bidPrice	askVol	bidVol	settlementPrice	transactionNum	pe
20240613091500	1718241300000	0.00	0.00	0.00	0.00	18.2	0.0	0	0	0	12	0.0	[0.0, 0.0, 0.0, 0.0, 0.0]	[0.0, 0.0, 0.0, 0.0, 0.0]	[0, 0, 0, 0, 0]	[0, 0, 0, 0, 0]	0.0	0	0.0
20240613091503	1718241303000	0.00	0.00	0.00	0.00	18.2	0.0	0	0	0	12	0.0	[18.9, 0.0, 0.0, 0.0, 0.0]	[18.9, 0.0, 0.0, 0.0, 0.0]	[283, 0, 0, 0, 0]	[283, 37, 0, 0, 0]	0.0	0	0.0
20240613091506	1718241306000	0.00	0.00	0.00	0.00	18.2	0.0	0	0	0	12	0.0	[18.39, 0.0, 0.0, 0.0, 0.0]	[18.39, 0.0, 0.0, 0.0, 0.0]	[377, 457, 0, 0, 0]	[377, 0, 0, 0, 0]	0.0	0	0.0
20240613091509	1718241309000	0.00	0.00	0.00	0.00	18.2	0.0	0	0	0	12	0.0	[18.39, 0.0, 0.0, 0.0, 0.0]	[18.39, 0.0, 0.0, 0.0, 0.0]	[382, 595, 0, 0, 0]	[382, 0, 0, 0, 0]	0.0	0	0.0
20240613091512	1718241312000	0.00	0.00	0.00	0.00	18.2	0.0	0	0	0	12	0.0	[18.39, 0.0, 0.0, 0.0, 0.0]	[18.39, 0.0, 0.0, 0.0, 0.0]	[382, 635, 0, 0, 0]	[382, 0, 0, 0, 0]	0.0	0	0.0
...	...	...	...	...	...	...	...	...	...	...	...	...	...	...	...	...	...	...	...
20240614145951	1718348391000	18.05	17.91	18.07	17.74	18.0	641436194.0	358072	0	0	18	0.0	[17.93, 0.0, 0.0, 0.0, 0.0]	[17.93, 0.0, 0.0, 0.0, 0.0]	[36208, 0, 0, 0, 0]	[36208, 5464, 0, 0, 0]	0.0	54672	0.0
20240614145954	1718348394000	18.05	17.91	18.07	17.74	18.0	641436194.0	358072	0	0	18	0.0	[17.97, 0.0, 0.0, 0.0, 0.0]	[17.97, 0.0, 0.0, 0.0, 0.0]	[36413, 0, 0, 0, 0]	[36413, 247, 0, 0, 0]	0.0	54672	0.0
20240614145957	1718348397000	18.05	17.91	18.07	17.74	18.0	641436194.0	358072	0	0	18	0.0	[17.98, 0.0, 0.0, 0.0, 0.0]	[17.98, 0.0, 0.0, 0.0, 0.0]	[36517, 0, 0, 0, 0]	[36517, 30, 0, 0, 0]	0.0	54672	0.0
20240614150000	1718348400000	18.05	17.91	18.07	17.74	18.0	641436194.0	358072	0	0	18	0.0	[17.97, 0.0, 0.0, 0.0, 0.0]	[17.97, 0.0, 0.0, 0.0, 0.0]	[36838, 305, 0, 0, 0]	[36838, 0, 0, 0, 0]	0.0	54672	0.0
20240614150003	1718348403000	17.97	17.91	18.07	17.74	18.0	707634080.0	394910	0	0	15

18多线程下载历史数据

调用源代码

from xtquant import xtdata
import pandas as pd
code_list=['600031.SH','600111.SH']
def f(datas):
    '''
    多线程下载函数
    '''
    print(datas)
xtdata.download_history_data2(stock_list=code_list,period='tick',
                              start_time='20240601',end_time='20240615',callback=f)
#读取本地数据
df=xtdata.get_local_data(stock_list=[code_list[-1]],period='tick',
                         start_time='20240601',end_time='20240605',count=-1)
df[code_list[-1]]

输出的结果

{'finished': 1, 'total': 18, 'stockcode': '', 'message': '600031.SH'}
{'finished': 2, 'total': 18, 'stockcode': '', 'message': '600031.SH'}
time	lastPrice	open	high	low	lastClose	amount	volume	pvolume	stockStatus	openInt	lastSettlementPrice	askPrice	bidPrice	askVol	bidVol	settlementPrice	transactionNum	pe
20240603091501	1717377301000	0.00	0.00	0.00	0.00	18.90	0.0	0	0	0	12	0.0	[19.12, 0.0, 0.0, 0.0, 0.0]	[19.12, 0.0, 0.0, 0.0, 0.0]	[2, 88, 0, 0, 0]	[2, 0, 0, 0, 0]	0.0	0	0.0
20240603091504	1717377304000	0.00	0.00	0.00	0.00	18.90	0.0	0	0	0	12	0.0	[18.99, 0.0, 0.0, 0.0, 0.0]	[18.99, 0.0, 0.0, 0.0, 0.0]	[61, 63, 0, 0, 0]	[61, 0, 0, 0, 0]	0.0	0	0.0
20240603091507	1717377307000	0.00	0.00	0.00	0.00	18.90	0.0	0	0	0	12	0.0	[18.95, 0.0, 0.0, 0.0, 0.0]	[18.95, 0.0, 0.0, 0.0, 0.0]	[67, 149, 0, 0, 0]	[67, 0, 0, 0, 0]	0.0	0	0.0
20240603091510	1717377310000	0.00	0.00	0.00	0.00	18.90	0.0	

19获取交易日历

调用源代码

from xtquant import xtdata
df=xtdata.get_trading_calendar(market='SH',start_time='20240601',end_time='20241002')
df

输出的结果

20240703',
 '20240704',
 '20240705',
 '20240708',
...
 '20240926',
 '20240927',
 '20240930',
 '20241001',
 '20241002']

20获取财务数据,没有的先下载

调用源代码

from xtquant import xtdata
df=xtdata.get_financial_data(stock_list=['600031.SH'], table_list=['Balance'], start_time='20220101', end_time='20240620', report_type='report_time')
df
'''
释义

获取财务数据
参数

stock_list - list 合约代码列表

table_list - list 财务数据表名称列表


'Balance'          #资产负债表
'Income'           #利润表
'CashFlow'         #现金流量表
'Capital'          #股本表
'Holdernum'        #股东数
'Top10holder'      #十大股东
'Top10flowholder'  #十大流通股东
'Pershareindex'    #每股指标
start_time - string 起始时间

end_time - string 结束时间

report_type - string 报表筛选方式


'report_time' 	#截止日期
'announce_time' #披露日期
返回

dict 数据集 { stock1 : datas1, stock2 : data2, ... }
stock1, stock2, ... :合约代码
datas1, datas2, ... :dict 数据集 { table1 : table_data1, table2 : table_data2, ... }
table1, table2, ... :财务数据表名
table_data1, table_data2, ... :pd.DataFrame 数据集,数据字段详见附录 - 财务数据字段列表
'''

21下载历史数据财务数据

调用源代码

from xtquant import xtdata
code_list=['600031.SH','600111.SH']
xtdata.download_financial_data(stock_list=code_list, table_list=['Balance'])
df=xtdata.get_financial_data(stock_list=['600031.SH'], table_list=['Balance'], start_time='20220101', end_time='20240620', report_type='report_time')
df

输出的结果

{'600031.SH': {'Balance':   m_timetag m_anntime  internal_shoule_recv  fixed_capital_clearance  \
  0  20220331  20220429                   NaN                      NaN   
  1  20220630  20220831                   NaN                      NaN   
  2  20220930  20221029                   NaN                      NaN   
  3  20221231  20230401                   NaN                      NaN   
  4  20230331  20230426                   NaN                      NaN   
  5  20230630  20230831                   NaN                      NaN   
  6  20230930  20231031                   NaN                      NaN   
  7  20231231  20240429                   NaN                      NaN   
  8  20240331  20240429                   NaN                      NaN   
  
     should_pay_money  settlement_payment  receivable_premium  \
  0               NaN                 NaN                 NaN   
  1               NaN                 NaN                 NaN   

22获取合约基础信息

调用源代码

from xtquant import xtdata
code_list=['600031.SH','600111.SH']
df=xtdata.get_instrument_detail(stock_code=code_list[-1], iscomplete=True)
df
'''
get_instrument_detail(stock_code, iscomplete)
释义
获取合约基础信息
参数
stock_code - string 合约代码
iscomplete - bool 是否获取全部字段,默认为False
返回
dict 数据字典,{ field1 : value1, field2 : value2, ... },找不到指定合约时返回None
iscomplete为False时,返回以下字段
ExchangeID - string 合约市场代码
InstrumentID - string 合约代码
InstrumentName - string 合约名称
ProductID - string 合约的品种ID(期货)
ProductName - string 合约的品种名称(期货)
ExchangeCode - string 交易所代码
UniCode - string 统一规则代码
CreateDate - str 上市日期(期货)
OpenDate - str IPO日期(股票)
ExpireDate - int 退市日或者到期日
PreClose - float 前收盘价格
SettlementPrice - float 前结算价格
UpStopPrice - float 当日涨停价
DownStopPrice - float 当日跌停价
FloatVolume - float 流通股本
TotalVolume - float 总股本
LongMarginRatio - float 多头保证金率
ShortMarginRatio - float 空头保证金率
PriceTick - float 最小价格变动单位
VolumeMultiple - int 合约乘数(对期货以外的品种,默认是1)
MainContract - int 主力合约标记,1、2、3分别表示第一主力合约,第二主力合约,第三主力合约
LastVolume - int 昨日持仓量
InstrumentStatus - int 合约停牌状态
IsTrading - bool 合约是否可交易
IsRecent - bool 是否是近月合约
'''

23获取合约类型

调用源代码

from xtquant import xtdata
code_list=['600031.SH','600111.SH']
df=xtdata.get_instrument_type(stock_code=code_list[-1])
df
'''
获取合约类型
参数

stock_code - string 合约代码
返回

dict 数据字典,{ type1 : value1, type2 : value2, ... },找不到指定合约时返回None

type1, type2, ... :string 合约类型
value1, value2, ... :bool 是否为该类合约

'index'		#指数
'stock'		#股票
'fund'		#基金
'etf'		#ETF
'''

数的结果

STOCK

24数据备注

"""
tick - 分笔数据

'time'                  #时间戳
'lastPrice'             #最新价
'open'                  #开盘价
'high'                  #最高价
'low'                   #最低价
'lastClose'             #前收盘价
'amount'                #成交总额
'volume'                #成交总量
'pvolume'               #原始成交总量
'stockStatus'           #证券状态
'openInt'               #持仓量
'lastSettlementPrice'   #前结算
'askPrice'              #委卖价
'bidPrice'              #委买价
'askVol'                #委卖量
'bidVol'                #委买量
'transactionNum'		#成交笔数
"""
"""
1m / 5m / 1d - K线数据

'time'                  #时间戳
'open'                  #开盘价
'high'                  #最高价
'low'                   #最低价
'close'                 #收盘价
'volume'                #成交量
'amount'                #成交额
'settelementPrice'      #今结算
'openInterest'          #持仓量
'preClose'              #前收价
'suspendFlag'           #停牌标记 0 - 正常 1 - 停牌 -1 - 当日起复牌
"""
"""
l2quote - level2实时行情快照

'time'                  #时间戳
'lastPrice'             #最新价
'open'                  #开盘价
'high'                  #最高价
'low'                   #最低价
'amount'                #成交额
'volume'                #成交总量
'pvolume'               #原始成交总量
'openInt'               #持仓量
'stockStatus'           #证券状态
'transactionNum'        #成交笔数
'lastClose'             #前收盘价
'lastSettlementPrice'   #前结算
'settlementPrice'       #今结算
'pe'                    #市盈率
'askPrice'              #多档委卖价
'bidPrice'              #多档委买价
'askVol'                #多档委卖量
'bidVol'                #多档委买量
"""
"""
l2order - level2逐笔委托

'time'                  #时间戳
'price'                 #委托价
'volume'                #委托量
'entrustNo'             #委托号
'entrustType'           #委托类型
'entrustDirection'      #委托方向
l2transaction - level2逐笔成交

'time'                  #时间戳
'price'                 #成交价
'volume'                #成交量
'amount'                #成交额
'tradeIndex'            #成交记录号
'buyNo'                 #买方委托号
'sellNo'                #卖方委托号
'tradeType'             #成交类型
'tradeFlag'             #成交标志
l2quoteaux - level2实时行情补充(总买总卖)

'time'                  #时间戳
'avgBidPrice'           #委买均价
'totalBidQuantity'      #委买总量
'avgOffPrice'           #委卖均价
'totalOffQuantity'      #委卖总量
'withdrawBidQuantity'   #买入撤单总量
'withdrawBidAmount'     #买入撤单总额
'withdrawOffQuantity'   #卖出撤单总量
'withdrawOffAmount'     #卖出撤单总额
l2orderqueue - level2委买委卖一档委托队列

'time'                  #时间戳
'bidLevelPrice'         #委买价
'bidLevelVolume'        #委买量
'offerLevelPrice'       #委卖价
'offerLevelVolume'      #委卖量
'bidLevelNumber'        #委买数量
'offLevelNumber'        #委卖数量
数据字典
证券状态

0,10 - 默认为未知
11 - 开盘前S
12 - 集合竞价时段C
13 - 连续交易T
14 - 休市B
15 - 闭市E
16 - 波动性中断V
17 - 临时停牌P
18 - 收盘集合竞价U
19 - 盘中集合竞价M
20 - 暂停交易至闭市N
21 - 获取字段异常
22 - 盘后固定价格行情
23 - 盘后固定价格行情完毕
委托类型
level2逐笔委托 - entrustType 委托类型
level2逐笔成交 - tradeType 成交类型

0 - 未知
1 - 正常交易业务
2 - 即时成交剩余撤销
3 - ETF基金申报
4 - 最优五档即时成交剩余撤销
5 - 全额成交或撤销
6 - 本方最优价格
7 - 对手方最优价格
委托方向
level2逐笔委托 - entrustDirection 委托方向
注:上交所的撤单信息在逐笔委托的委托方向,区分撤买撤卖

1 - 买入
2 - 卖出
3 - 撤买(上交所)
4 - 撤卖(上交所)
成交标志
level2逐笔成交 - tradeFlag 成交标志
注:深交所的在逐笔成交的成交标志,只有撤单,没有方向

0 - 未知
1 - 外盘
2 - 内盘
3 - 撤单(深交所)
"""
"""
财务数据字段列表
Balance - 资产负债表

'm_anntime'                                 #披露日期
'm_timetag'                                 #截止日期
'internal_shoule_recv'                      #内部应收款
'fixed_capital_clearance'                   #固定资产清理
'should_pay_money'                          #应付分保账款
'settlement_payment'                        #结算备付金
'receivable_premium'                        #应收保费
'accounts_receivable_reinsurance'           #应收分保账款
'reinsurance_contract_reserve'              #应收分保合同准备金
'dividends_payable'                         #应收股利
'tax_rebate_for_export'                     #应收出口退税
'subsidies_receivable'                      #应收补贴款
'deposit_receivable'                        #应收保证金
'apportioned_cost'                          #待摊费用
'profit_and_current_assets_with_deal'       #待处理流动资产损益
'current_assets_one_year'                   #一年内到期的非流动资产
'long_term_receivables'                     #长期应收款
'other_long_term_investments'               #其他长期投资
'original_value_of_fixed_assets'            #固定资产原值
'net_value_of_fixed_assets'                 #固定资产净值
'depreciation_reserves_of_fixed_assets'     #固定资产减值准备
'productive_biological_assets'              #生产性生物资产
'public_welfare_biological_assets'          #公益性生物资产
'oil_and_gas_assets'                        #油气资产
'development_expenditure'                   #开发支出
'right_of_split_share_distribution'         #股权分置流通权
'other_non_mobile_assets'                   #其他非流动资产
'handling_fee_and_commission'               #应付手续费及佣金
'other_payables'                            #其他应交款
'margin_payable'                            #应付保证金
'internal_accounts_payable'                 #内部应付款
'advance_cost'                              #预提费用
'insurance_contract_reserve'                #保险合同准备金
'broker_buying_and_selling_securities'      #代理买卖证券款
'acting_underwriting_securities'            #代理承销证券款
'international_ticket_settlement'           #国际票证结算
'domestic_ticket_settlement'                #国内票证结算
'deferred_income'                           #递延收益
'short_term_bonds_payable'                  #应付短期债券
'long_term_deferred_income'                 #长期递延收益
'undetermined_investment_losses'            #未确定的投资损失
'quasi_distribution_of_cash_dividends'      #拟分配现金股利
'provisions_not'                            #预计负债
'cust_bank_dep'                             #吸收存款及同业存放
'provisions'                                #预计流动负债
'less_tsy_stk'                              #减:库存股
'cash_equivalents'                          #货币资金
'loans_to_oth_banks'                        #拆出资金
'tradable_fin_assets'                       #交易性金融资产
'derivative_fin_assets'                     #衍生金融资产
'bill_receivable'                           #应收票据
'account_receivable'                        #应收账款
'advance_payment'                           #预付款项
'int_rcv'                                   #应收利息
'other_receivable'                          #其他应收款
'red_monetary_cap_for_sale'                 #买入返售金融资产
'agency_bus_assets'                         #以公允价值计量且其变动计入当期损益的金融资产
'inventories'                               #存货
'other_current_assets'                      #其他流动资产
'total_current_assets'                      #流动资产合计
'loans_and_adv_granted'                     #发放贷款及垫款
'fin_assets_avail_for_sale'                 #可供出售金融资产
'held_to_mty_invest'                        #持有至到期投资
'long_term_eqy_invest'                      #长期股权投资
'invest_real_estate'                        #投资性房地产
'accumulated_depreciation'                  #累计折旧
'fix_assets'                                #固定资产
'constru_in_process'                        #在建工程
'construction_materials'                    #工程物资
'long_term_liabilities'                     #长期负债
'intang_assets'                             #无形资产
'goodwill'                                  #商誉
'long_deferred_expense'                     #长期待摊费用
'deferred_tax_assets'                       #递延所得税资产
'total_non_current_assets'                  #非流动资产合计
'tot_assets'                                #资产总计
'shortterm_loan'                            #短期借款
'borrow_central_bank'                       #向中央银行借款
'loans_oth_banks'                           #拆入资金
'tradable_fin_liab'                         #交易性金融负债
'derivative_fin_liab'                       #衍生金融负债
'notes_payable'                             #应付票据
'accounts_payable'                          #应付账款
'advance_peceipts'                          #预收账款
'fund_sales_fin_assets_rp'                  #卖出回购金融资产款
'empl_ben_payable'                          #应付职工薪酬
'taxes_surcharges_payable'                  #应交税费
'int_payable'                               #应付利息
'dividend_payable'                          #应付股利
'other_payable'                             #其他应付款
'non_current_liability_in_one_year'         #一年内到期的非流动负债
'other_current_liability'                   #其他流动负债
'total_current_liability'                   #流动负债合计
'long_term_loans'                           #长期借款
'bonds_payable'                             #应付债券
'longterm_account_payable'                  #长期应付款
'grants_received'                           #专项应付款
'deferred_tax_liab'                         #递延所得税负债
'other_non_current_liabilities'             #其他非流动负债
'non_current_liabilities'                   #非流动负债合计
'tot_liab'                                  #负债合计
'cap_stk'                                   #实收资本(或股本)
'cap_rsrv'                                  #资本公积
'specific_reserves'                         #专项储备
'surplus_rsrv'                              #盈余公积
'prov_nom_risks'                            #一般风险准备
'undistributed_profit'                      #未分配利润
'cnvd_diff_foreign_curr_stat'               #外币报表折算差额
'tot_shrhldr_eqy_excl_min_int'              #归属于母公司股东权益合计
'minority_int'                              #少数股东权益
'total_equity'                              #所有者权益合计
'tot_liab_shrhldr_eqy'                      #负债和股东权益总计
Income - 利润表

'm_anntime'                                 #披露日期
'm_timetag'                                 #截止日期
'revenue_inc'                               #营业收入
'earned_premium'                            #已赚保费
'real_estate_sales_income'                  #房地产销售收入
'total_operating_cost'                      #营业总成本
'real_estate_sales_cost'                    #房地产销售成本
'research_expenses'                         #研发费用
'surrender_value'                           #退保金
'net_payments'                              #赔付支出净额
'net_withdrawal_ins_con_res'                #提取保险合同准备金净额
'policy_dividend_expenses'                  #保单红利支出
'reinsurance_cost'                          #分保费用
'change_income_fair_value'                  #公允价值变动收益
'futures_loss'                              #期货损益
'trust_income'                              #托管收益
'subsidize_revenue'                         #补贴收入
'other_business_profits'                    #其他业务利润
'net_profit_excl_merged_int_inc'            #被合并方在合并前实现净利润
'int_inc'                                   #利息收入
'handling_chrg_comm_inc'                    #手续费及佣金收入
'less_handling_chrg_comm_exp'               #手续费及佣金支出
'other_bus_cost'                            #其他业务成本
'plus_net_gain_fx_trans'                    #汇兑收益
'il_net_loss_disp_noncur_asset'             #非流动资产处置收益
'inc_tax'                                   #所得税费用
'unconfirmed_invest_loss'                   #未确认投资损失
'net_profit_excl_min_int_inc'               #归属于母公司所有者的净利润
'less_int_exp'                              #利息支出
'other_bus_inc'                             #其他业务收入
'revenue'                                   #营业总收入
'total_expense'                             #营业成本
'less_taxes_surcharges_ops'                 #营业税金及附加
'sale_expense'                              #销售费用
'less_gerl_admin_exp'                       #管理费用
'financial_expense'                         #财务费用
'less_impair_loss_assets'                   #资产减值损失
'plus_net_invest_inc'                       #投资收益
'incl_inc_invest_assoc_jv_entp'             #联营企业和合营企业的投资收益
'oper_profit'                               #营业利润
'plus_non_oper_rev'                         #营业外收入
'less_non_oper_exp'                         #营业外支出
'tot_profit'                                #利润总额
'net_profit_incl_min_int_inc'               #净利润
'net_profit_incl_min_int_inc_after'         #净利润(扣除非经常性损益后)
'minority_int_inc'                          #少数股东损益
's_fa_eps_basic'                            #基本每股收益
's_fa_eps_diluted'                          #稀释每股收益
'total_income'                              #综合收益总额
'total_income_minority'                     #归属于少数股东的综合收益总额
'other_compreh_inc'                         #其他收益
CashFlow - 现金流量表

'm_anntime'                                 #披露日期
'm_timetag'                                 #截止日期
'cash_received_ori_ins_contract_pre'        #收到原保险合同保费取得的现金
'net_cash_received_rei_ope'                 #收到再保险业务现金净额
'net_increase_insured_funds'                #保户储金及投资款净增加额
'Net'                                       #处置交易性金融资产净增加额 increase_in_disposal
'cash_for_interest'                         #收取利息、手续费及佣金的现金
'net_increase_in_repurchase_funds'          #回购业务资金净增加额
'cash_for_payment_original_insurance'       #支付原保险合同赔付款项的现金
'cash_payment_policy_dividends'             #支付保单红利的现金
'disposal_other_business_units'             #处置子公司及其他收到的现金
'cash_received_from_pledges'                #减少质押和定期存款所收到的现金
'cash_paid_for_investments'                 #投资所支付的现金
'net_increase_in_pledged_loans'             #质押贷款净增加额
'cash_paid_by_subsidiaries'                 #取得子公司及其他营业单位支付的现金净额
'increase_in_cash_paid'                     #增加质押和定期存款所支付的现金 
'cass_received_sub_abs'                     #其中子公司吸收现金
'cass_received_sub_investments'             #其中:子公司支付给少数股东的股利、利润
'minority_shareholder_profit_loss'          #少数股东损益
'unrecognized_investment_losses'            #未确认的投资损失
'ncrease_deferred_income'                   #递延收益增加(减:减少)
'projected_liability'                       #预计负债
'increase_operational_payables'             #经营性应付项目的增加
'reduction_outstanding_amounts_less'        #已完工尚未结算款的减少(减:增加)
'reduction_outstanding_amounts_more'        #已结算尚未完工款的增加(减:减少)
'goods_sale_and_service_render_cash'        #销售商品、提供劳务收到的现金
'net_incr_dep_cob'                          #客户存款和同业存放款项净增加额
'net_incr_loans_central_bank'               #向中央银行借款净增加额(万元
'net_incr_fund_borr_ofi'                    #向其他金融机构拆入资金净增加额
'net_incr_fund_borr_ofi'                    #拆入资金净增加额
'tax_levy_refund'                           #收到的税费与返还
'cash_paid_invest'                          #投资支付的现金
'other_cash_recp_ral_oper_act'              #收到的其他与经营活动有关的现金
'stot_cash_inflows_oper_act'                #经营活动现金流入小计
'goods_and_services_cash_paid'              #购买商品、接受劳务支付的现金
'net_incr_clients_loan_adv'                 #客户贷款及垫款净增加额
'net_incr_dep_cbob'                         #存放中央银行和同业款项净增加额
'handling_chrg_paid'                        #支付利息、手续费及佣金的现金
'cash_pay_beh_empl'                         #支付给职工以及为职工支付的现金
'pay_all_typ_tax'                           #支付的各项税费
'other_cash_pay_ral_oper_act'               #支付其他与经营活动有关的现金
'stot_cash_outflows_oper_act'               #经营活动现金流出小计
'net_cash_flows_oper_act'                   #经营活动产生的现金流量净额
'cash_recp_disp_withdrwl_invest'            #收回投资所收到的现金
'cash_recp_return_invest'                   #取得投资收益所收到的现金
'net_cash_recp_disp_fiolta'                 #处置固定资产、无形资产和其他长期投资收到的现金
'other_cash_recp_ral_inv_act'               #收到的其他与投资活动有关的现金
'stot_cash_inflows_inv_act'                 #投资活动现金流入小计
'cash_pay_acq_const_fiolta'                 #购建固定资产、无形资产和其他长期投资支付的现金
'other_cash_pay_ral_oper_act'               #支付其他与投资的现金
'stot_cash_outflows_inv_act'                #投资活动现金流出小计
'net_cash_flows_inv_act'                    #投资活动产生的现金流量净额
'cash_recp_cap_contrib'                     #吸收投资收到的现金
'cash_recp_borrow'                          #取得借款收到的现金
'proc_issue_bonds'                          #发行债券收到的现金
'other_cash_recp_ral_fnc_act'               #收到其他与筹资活动有关的现金
'stot_cash_inflows_fnc_act'                 #筹资活动现金流入小计
'cash_prepay_amt_borr'                      #偿还债务支付现金
'cash_pay_dist_dpcp_int_exp'                #分配股利、利润或偿付利息支付的现金
'other_cash_pay_ral_fnc_act'                #支付其他与筹资的现金
'stot_cash_outflows_fnc_act'                #筹资活动现金流出小计
'net_cash_flows_fnc_act'                    #筹资活动产生的现金流量净额
'eff_fx_flu_cash'                           #汇率变动对现金的影响
'net_incr_cash_cash_equ'                    #现金及现金等价物净增加额
'cash_cash_equ_beg_period'                  #期初现金及现金等价物余额
'cash_cash_equ_end_period'                  #期末现金及现金等价物余额
'net_profit'                                #净利润
'plus_prov_depr_assets'                     #资产减值准备
'depr_fa_coga_dpba'                         #固定资产折旧、油气资产折耗、生产性物资折旧
'amort_intang_assets'                       #无形资产摊销
'amort_lt_deferred_exp'                     #长期待摊费用摊销
'decr_deferred_exp'                         #待摊费用的减少
'incr_acc_exp'                              #预提费用的增加
'loss_disp_fiolta'                          #处置固定资产、无形资产和其他长期资产的损失
'loss_scr_fa'                               #固定资产报废损失
'loss_fv_chg'                               #公允价值变动损失
'fin_exp'                                   #财务费用
'invest_loss'                               #投资损失
'decr_deferred_inc_tax_assets'              #递延所得税资产减少
'incr_deferred_inc_tax_liab'                #递延所得税负债增加
'decr_inventories'                          #存货的减少
'decr_oper_payable'                         #经营性应收项目的减少
'others'                                    #其他
'im_net_cash_flows_oper_act'                #经营活动产生现金流量净额
'conv_debt_into_cap'                        #债务转为资本
'conv_corp_bonds_due_within_1y'             #一年内到期的可转换公司债券
'fa_fnc_leases'                             #融资租入固定资产
'end_bal_cash'                              #现金的期末余额
'less_beg_bal_cash'                         #现金的期初余额
'plus_end_bal_cash_equ'                     #现金等价物的期末余额
'less_beg_bal_cash_equ'                     #现金等价物的期初余额
'im_net_incr_cash_cash_equ'                 #现金及现金等价物的净增加额
'tax_levy_refund'                           #收到的税费返还
PershareIndex - 主要指标

's_fa_ocfps'                                #每股经营活动现金流量
's_fa_bps'                                  #每股净资产
's_fa_eps_basic'                            #基本每股收益
's_fa_eps_diluted'                          #稀释每股收益
's_fa_undistributedps'                      #每股未分配利润
's_fa_surpluscapitalps'                     #每股资本公积金
'adjusted_earnings_per_share'               #扣非每股收益
'du_return_on_equity'                       #净资产收益率
'sales_gross_profit'                        #销售毛利率
'inc_revenue_rate'                          #主营收入同比增长
'du_profit_rate'                            #净利润同比增长
'inc_net_profit_rate'                       #归属于母公司所有者的净利润同比增长
'adjusted_net_profit_rate'                  #扣非净利润同比增长
'inc_total_revenue_annual'                  #营业总收入滚动环比增长
'inc_net_profit_to_shareholders_annual'     #归属净利润滚动环比增长
'adjusted_profit_to_profit_annual'          #扣非净利润滚动环比增长
'equity_roe'                                #加权净资产收益率
'net_roe'                                   #摊薄净资产收益率
'total_roe'                                 #摊薄总资产收益率
'gross_profit'                              #毛利率
'net_profit'                                #净利率
'actual_tax_rate'                           #实际税率
'pre_pay_operate_income'                    #预收款 / 营业收入
'sales_cash_flow'                           #销售现金流 / 营业收入
'gear_ratio'                                #资产负债比率
'inventory_turnover'                        #存货周转率
'm_anntime'                                 #公告日
'm_timetag'                                 #报告截止日
Capital - 股本表

'total_capital'                             #总股本
'circulating_capital'                       #已上市流通A股
'restrict_circulating_capital'              #限售流通股份
'm_timetag'                                 #报告截止日
'm_anntime'                                 #公告日
Top10holder/Top10flowholder - 十大股东/十大流通股东

'declareDate'                                #公告日期
'endDate'                                    #截止日期
'name'                                       #股东名称
'type'                                       #股东类型
'quantity'                                   #持股数量
'reason'                                     #变动原因
'ratio'                                      #持股比例
'nature'                                     #股份性质
'rank'                                       #持股排名
Holdernum - 股东数

'declareDate'                                 #公告日期
'endDate'                                     #截止日期
'shareholder'                                 #股东总数
'shareholderA'                                #A股东户数
'shareholderB'                                #B股东户数
'shareholderH'                                #H股东户数
'shareholderFloat'                            #已流通股东户数
'shareholderOther'                            #未流通股东户数
合约信息字段列表

'ExchangeID' 				#合约市场代码
'InstrumentID' 				#合约代码
'InstrumentName' 			#合约名称
'Abbreviation' 				#合约名称的拼音简写
'ProductID' 				#合约的品种ID(期货)
'ProductName' 				#合约的品种名称(期货)
'UnderlyingCode' 			#标的合约
'ExtendName' 				#扩位名称
'ExchangeCode' 				#交易所代码
'RzrkCode' 					#rzrk代码
'UniCode' 					#统一规则代码
'CreateDate' 				#上市日期(期货)
'OpenDate' 					#IPO日期(股票)
'ExpireDate' 				#退市日或者到期日
'PreClose' 					#前收盘价格
'SettlementPrice' 			#前结算价格
'UpStopPrice' 				#当日涨停价
'DownStopPrice' 			#当日跌停价
'FloatVolume' 				#流通股本
'TotalVolume' 				#总股本
'AccumulatedInterest' 		#自上市付息日起的累积未付利息额(债券)
'LongMarginRatio' 			#多头保证金率
'ShortMarginRatio' 			#空头保证金率
'PriceTick' 				#最小变价单位
'VolumeMultiple' 			#合约乘数(对期货以外的品种,默认是1)
'MainContract' 				#主力合约标记,1、2、3分别表示第一主力合约,第二主力合约,第三主力合约
'MaxMarketOrderVolume' 		#市价单最大下单量
'MinMarketOrderVolume' 		#市价单最小下单量
'MaxLimitOrderVolume' 		#限价单最大下单量
'MinLimitOrderVolume' 		#限价单最小下单量
'MaxMarginSideAlgorithm' 	#上期所大单边的处理算法
'DayCountFromIPO' 			#自IPO起经历的交易日总数
'LastVolume' 				#昨日持仓量
'InstrumentStatus' 			#合约停牌状态
'IsTrading' 				#合约是否可交易
'IsRecent' 					#是否是近月合约
'IsContinuous' 				#是否是连续合约
'bNotProfitable' 			#是否非盈利状态
'bDualClass' 				#是否同股不同权
'ContinueType' 				#连续合约类型
'secuCategory' 				#证券分类
'secuAttri' 				#证券属性
'MaxMarketSellOrderVolume' 	#市价卖单最大单笔下单量
'MinMarketSellOrderVolume' 	#市价卖单最小单笔下单量
'MaxLimitSellOrderVolume' 	#限价卖单最大单笔下单量
'MinLimitSellOrderVolume' 	#限价卖单最小单笔下单量
'MaxFixedBuyOrderVol' 		#盘后定价委托数量的上限(买)
'MinFixedBuyOrderVol' 		#盘后定价委托数量的下限(买)
'MaxFixedSellOrderVol' 		#盘后定价委托数量的上限(卖)
'MinFixedSellOrderVol' 		#盘后定价委托数量的下限(卖)
'HSGTFlag' 					#标识港股是否为沪港通或深港通标的证券。沪港通:0-非标的,1-标的,2-历史标的;深港通:0-非标的,3-标的,4-历史标的,5-是沪港通也是深港通
'BondParValue' 				#债券面值
'QualifiedType' 			#投资者适当性管理分类
'PriceTickType' 			#价差类别(港股用),1-股票,3-债券,4-期权,5-交易所买卖基金
'tradingStatus' 			#交易状态
'OptUnit' 					#期权合约单位
'MarginUnit' 				#期权单位保证金
'OptUndlCode' 				#期权标的证券代码或可转债正股标的证券代码
'OptUndlMarket' 			#期权标的证券市场或可转债正股标的证券市场
'OptLotSize' 				#期权整手数
'OptExercisePrice' 			#期权行权价或可转债转股价
'NeeqExeType' 				#全国股转转让类型,1-协议转让方式,2-做市转让方式,3-集合竞价+连续竞价转让方式(当前全国股转并未实现),4-集合竞价转让
'OptExchFixedMargin' 		#交易所期权合约保证金不变部分
'OptExchMiniMargin' 		#交易所期权合约最小保证金
'Ccy' 						#币种
'IbSecType' 				#IB安全类型,期货或股票
'OptUndlRiskFreeRate' 		#期权标的无风险利率
'OptUndlHistoryRate' 		#期权标的历史波动率
'EndDelivDate' 				#期权行权终止日
'RegisteredCapital' 		#注册资本(单位:百万)
'MaxOrderPriceRange' 		#最大有效申报范围
'MinOrderPriceRange' 		#最小有效申报范围
'VoteRightRatio' 			#同股同权比例
'm_nMinRepurchaseDaysLimit' #最小回购天数
'm_nMaxRepurchaseDaysLimit' #最大回购天数
'DeliveryYear' 				#交割年份
'DeliveryMonth' 			#交割月
'ContractType' 				#标识期权,1-过期,2-当月,3-下月,4-下季,5-隔季,6-隔下季
'ProductTradeQuota' 		#期货品种交易配额
'ContractTradeQuota' 		#期货合约交易配额
'ProductOpenInterestQuota' 	#期货品种持仓配额
'ContractOpenInterestQuota' #期货合约持仓配额
'ChargeType' 				#期货和期权手续费方式,0-未知,1-按元/手,2-按费率
'ChargeOpen' 				#开仓手续费率,-1表示没有
'ChargeClose' 				#平仓手续费率,-1表示没有
'ChargeClose'				#平仓手续费率,-1表示没有
'ChargeTodayOpen'			#开今仓(日内开仓)手续费率,-1表示没有
'ChargeTodayClose'			#平今仓(日内平仓)手续费率,-1表示没有
'OptionType'				#期权类型,-1为非期权,0为期权认购,1为期权认沽
'OpenInterestMultiple'		#交割月持仓倍数
"""

25 时间戳转换

源代码

#代码示例
#时间戳转换

import time
def conv_time(ct):
    '''
    conv_time(1476374400000) --> '20161014000000.000'
    '''
    local_time = time.localtime(ct / 1000)
    data_head = time.strftime('%Y%m%d%H%M%S', local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = '%s.%03d' % (data_head, data_secs)
    return time_stamp

参与贡献

  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request

特技

  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. Gitee 官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解 Gitee 上的优秀开源项目
  4. GVP 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
  5. Gitee 官方提供的使用手册 https://gitee.com/help
  6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 https://gitee.com/gitee-stars/
GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it!

简介

qmt交易系统,包含qmt_trader ,qmt_data数据支持高频交易 展开 收起
Python
LGPL-2.1
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/li-xingguo11111/qmt_trader.git
git@gitee.com:li-xingguo11111/qmt_trader.git
li-xingguo11111
qmt_trader
qmt_trader
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891