发送请求函数:ReqQryTradingAccount:

先查阅官方文档,可以知道以下重要信息:
1、需要发送的文件名是CThostFtdcQryTradingAccountField;
2、是否可作为过滤条件,意味着并非是必填项,其中重要的是币种代码
3、它的响应是:OnRspQryTradingAccount
根据以上信息可以写出查询合约的代码:
# 请求查询资金账户,响应: OnRspQryTradingAccount
def reqQryTradingAccount(self):
qryFile = tdapi.CThostFtdcQryTradingAccountField()
qryFile.BrokerID = str(self.Account.broker_id) # 经纪公司代码
qryFile.InvestorID = str(self.Account.investor_id) # 投资者代码
qryFile.CurrencyID = 'CNY' # 币种代码
ret = self.tduserapi.ReqQryTradingAccount(qryFile, 0) # 发送文件
if ret == 0:
print('发送查询资金账户成功!')
else:
print('发送查询资金账户,失败!')
judge_ret(ret)
响应函数:OnRspQryTradingAccount:

在官方文档里我们可以得到以下重要信息:
1、函数原型中带bIsLast,指示该次返回是否为最后一次返回,意思是返回多条数据,其中if bIsLast为真时,则已经查询结束,并返回最后一条数据。
2、返回的存储信息为pTradingAccount,返回的信息有很多,但我们这里只要自己想要的即可。
响应函数的代码:
def OnRspQryTradingAccount(self, pTradingAccount: 'CThostFtdcTradingAccountField',
pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
if bIsLast:
pTradingAccount = {
'投资者帐号': pTradingAccount.AccountID, # 投资者帐号
'当前保证金总额': pTradingAccount.CurrMargin, # 当前保证金总额
'手续费': pTradingAccount.Commission, # 手续费
'平仓盈亏': pTradingAccount.CloseProfit, # 平仓盈亏
'持仓盈亏': pTradingAccount.PositionProfit, # 持仓盈亏
'可用资金': pTradingAccount.Available, # 可用资金
}
print(pTradingAccount)
运行代码结果展示:

完整代码展示:
import json
from program.function import *
class CTraderSpi(tdapi.CThostFtdcTraderSpi):
def __init__(self, tduserapi, Account):
tdapi.CThostFtdcTraderSpi.__init__(self)
self.tduserapi = tduserapi
self.Account = Account
# 连接前台
def OnFrontConnected(self):
print("开始建立交易连接")
authfield = tdapi.CThostFtdcReqAuthenticateField()
authfield.BrokerID = str(self.Account.broker_id)
authfield.UserID = str(self.Account.investor_id)
authfield.AppID = str(self.Account.app_id)
authfield.AuthCode = str(self.Account.auth_code)
ret = self.tduserapi.ReqAuthenticate(authfield, 0)
if ret == 0:
print('发送穿透式认证请求成功!')
else:
print('发送穿透式认证请求失败!')
judge_ret(ret)
# 穿透式认证响应
def OnRspAuthenticate(self, pRspAuthenticateField, pRspInfo, nRequestID: 'int', bIsLast: 'bool'):
if pRspInfo.ErrorID != 0 and pRspInfo != None:
print('穿透式认证失败\n错误信息为:{}\n错误代码为:{}'.format(pRspInfo.ErrorMsg, pRspInfo.ErrorID))
else:
print('穿透式认证成功!')
# 发
本主题为课程学员专享,成为股票量化投资课程学员后可免费阅读
成为学员