前言:
关于ctp我就不多介绍了,反正就是快,登录快,下单快,获取行情快,且自由度高,但并不容易学习,我也是花了挺长的时间去学习,以及不断吸收和优化,同时这个系列我会不断分享和完善,代码里有测试账号供大家学习使用,基本就是开箱即用。
交易接口:
CTP有MdApi和TraderApi两个独立的开放接口,它们互不影响,这里我先讲TraderApi
TraderApi负责交易相关的操作(买、卖、撤、查)。
它们的执行过程都是异步的,维护一个TCP的连接,实现了客户端和综合交易平台间的双向异步通讯,这个业务过程就好比邮局寄信,当我发送请求时(寄邮件),我还能做其他事情,而不是等待回信我才能做其他事。
代码:
from program.function import *
from API import thosttraderapi as tdapi
class CTradeSpi(tdapi.CThostFtdcTraderSpi):
def __init__(self, tduserapi, account):
tdapi.CThostFtdcTraderSpi.__init__(self)
self.tduserapi = tduserapi
self.account = account
# 连接前台
def OnFrontConnected(self) -> "void":
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('发送穿透式认证请求失败!')
# 穿透式认证响应
def OnRspAuthenticate(self, pRspAuthenticateField: 'CThostFtdcRspAuthenticateField',pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
if pRspInfo.ErrorID != 0 and pRspInfo != None:
print('穿透式认证失败\n错误信息为:{}\n错误代码为:{}'.format(pRspInfo.ErrorMsg, pRspInfo.ErrorID))
else:
print('穿透式认证成功!')
loginfield = tdapi.CThostFtdcReqUserLoginField()
loginfield.BrokerID = str(self.account.broker_id)
loginfield.UserID = str(self.account.investor_id)
loginfield.Password = str(self.account.password)
loginfield.UserProductInfo = "python dll"
ret = self.tduserapi.ReqUserLogin(loginfield, 0)
if ret == 0:
print('发送登录交易账户成功!')
else:
print('发送登录交易账户失败!')
# 登录请求响应
def OnRspUserLogin(self, pRspUserLogin: 'CThostFtdcRspUserLoginField', pRspInfo: 'CThostFtdcRspInfoField',
nRequestID: 'int', bIsLast: 'bool') -> "void":
if pRspInfo.ErrorID != 0 and pRspInfo != None:
print('登录交易账户失败\n错误信息为:{}\n错误代码为:{}'.format(pRspInf
本主题为课程学员专享,成为股票量化投资课程学员后可免费阅读
成为学员