{"id":17511720,"url":"https://github.com/nicai0609/python-ctpapi","last_synced_at":"2025-04-04T19:06:47.363Z","repository":{"id":50749814,"uuid":"163746173","full_name":"nicai0609/Python-CTPAPI","owner":"nicai0609","description":"Python CTP API","archived":false,"fork":false,"pushed_at":"2021-09-07T15:04:16.000Z","size":71404,"stargazers_count":368,"open_issues_count":2,"forks_count":162,"subscribers_count":22,"default_branch":"master","last_synced_at":"2025-03-13T16:14:06.596Z","etag":null,"topics":["api","ctp","python3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nicai0609.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-01-01T15:20:58.000Z","updated_at":"2025-03-09T03:22:17.000Z","dependencies_parsed_at":"2022-09-02T23:52:31.537Z","dependency_job_id":null,"html_url":"https://github.com/nicai0609/Python-CTPAPI","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicai0609%2FPython-CTPAPI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicai0609%2FPython-CTPAPI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicai0609%2FPython-CTPAPI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nicai0609%2FPython-CTPAPI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nicai0609","download_url":"https://codeload.github.com/nicai0609/Python-CTPAPI/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244835492,"owners_count":20518263,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","ctp","python3"],"created_at":"2024-10-20T05:09:01.246Z","updated_at":"2025-03-21T17:10:53.147Z","avatar_url":"https://github.com/nicai0609.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 一、简介\n此CTP Python API在windows上由于Python3.X系列互不兼容，所以之前的老版本（v6.3.19）分别编译了Python3.7和Python3.8的版本，新版本（v6.6.1）只编译了Python3.8的版本，windows上使用时请务必安装对应Python版本，linux上无此问题。  \n该API是用swig方法在官方C++ API上编译得到，完全开源，有兴趣自己编译的读者windows64版可以参考笔者[\nCTP Python API及Demo（利用Swig封装）Windows版（traderapi）](https://blog.csdn.net/pjjing/article/details/77338423)这篇博客，Linux版只需要参考笔者其他博客，更改下makefile即可。  \n此方法编译得到的API在数据结构，参数名，函数名及用法上与C++版API完全一致，十分容易上手。  \n**Github上如果不方便下，请到gitee上下载 https://gitee.com/nicai0609/Python-CTPAPI 或者扫码进入QQ群群文件中下载。编译维护不易，欢迎star，fork鼓励。**\n\n# 二、文件清单\n```\n.\n|-- 6.6.1P1_API接口说明_20210805.chm //官方文档，也可至http://www.sfit.com.cn/下载(加了日期便于区别版本)\n|-- demo  //相关demo，见下面章节详述\n|   |-- calculate_volume_delta.py\n|   |-- candle_demo.py\n|   |-- md_demo.py\n|   |-- td_demo(auth).py\n|   `-- td_demo.py\n|-- LICENSE\n|-- README.md  //本文档\n|-- v6.3.19_P1_20200106   //CTP生产版本，用于正式交易或连simnow\n|   |-- linux   //linux下版本（不区分Python3.X系列，通用）\n|   |   |-- libthostmduserapi_se.so\n|   |   |-- libthosttraderapi_se.so\n|   |   |-- thostmduserapi.py\n|   |   |-- _thostmduserapi.so\n|   |   |-- thosttraderapi.py\n|   |   `-- _thosttraderapi.so\n|   `-- win64   //windows下版本，由于Python3.7和Python3.8不兼容，现同时提供两种\n|       |-- py37 //Python3.7版本\n|       |   |-- _thostmduserapi.pyd   //交易库转换文件\n|       |   `-- _thosttraderapi.pyd   //行情库转换文件\n|       |-- py38 //Python3.8版本\n|       |   |-- _thostmduserapi.pyd\n|       |   `-- _thosttraderapi.pyd\n|       |-- thostmduserapi.py      //行情头文件（以下4个文件对于Python3.7和Python3.8版本是共用的）\n|       |-- thostmduserapi_se.dll  //行情官方动态库\n|       |-- thosttraderapi.py      //交易头文件\n|       `-- thosttraderapi_se.dll  //交易官方动态库\n|-- v6.3.19_T1_20200423 //CTP评测版本，用于穿透式认证评测，文件内容具体同上说明\n|   |-- linux\n|   |   |-- libthostmduserapi_se.so\n|   |   |-- libthosttraderapi_se.so\n|   |   |-- thostmduserapi.py\n|   |   |-- _thostmduserapi.so\n|   |   |-- thosttraderapi.py\n|   |   `-- _thosttraderapi.so\n|   `-- win64\n|       |-- py37\n|       |   |-- _thostmduserapi.pyd\n|       |   `-- _thosttraderapi.pyd\n|       |-- py38\n|       |   |-- _thostmduserapi.pyd\n|       |   `-- _thosttraderapi.pyd\n|       |-- thostmduserapi.py\n|       |-- thostmduserapi_se.dll\n|       |-- thosttraderapi.py\n|       `-- thosttraderapi_se.dll\n|-- v6.6.1_P1_20210406 //CTP生产版本，用于正式交易或连simnow，该版本官方新增了一些函数，具体参考chm文档\n|   |-- linux\n|   |   |-- libthostmduserapi_se.so\n|   |   |-- libthosttraderapi_se.so\n|   |   |-- thostmduserapi.py\n|   |   |-- _thostmduserapi.so\n|   |   |-- thosttraderapi.py\n|   |   `-- _thosttraderapi.so\n|   `-- win64\n|       |-- py38\n|       |   |-- _thostmduserapi.pyd\n|       |   `-- _thosttraderapi.pyd\n|       |-- thostmduserapi.py\n|       |-- thostmduserapi_se.dll\n|       |-- thosttraderapi.py\n|       `-- thosttraderapi_se.dll\n`-- v6.6.1_P1_CP_20210406 //CTP评测版本\n    |-- linux\n    |   |-- libthostmduserapi_se.so\n    |   |-- libthosttraderapi_se.so\n    |   |-- thostmduserapi.py\n    |   |-- _thostmduserapi.so\n    |   |-- thosttraderapi.py\n    |   `-- _thosttraderapi.so\n    `-- win64\n        |-- py38\n        |   |-- _thostmduserapi.pyd\n        |   `-- _thosttraderapi.pyd\n        |-- thostmduserapi.py\n        |-- thostmduserapi_se.dll\n        |-- thosttraderapi.py\n        `-- thosttraderapi_se.dll\n```\n# 三、请求函数及数据结构\n所有函数名、参数及参数数据结构都是与官方```C++```版一致的，可以参见上期技术官网文档。以登录请求为例：  \n官方C++版：  \n函数名\n```\nvirtual int ReqUserLogin(CThostFtdcReqUserLoginField *pReqUserLoginField, int nRequestID) = 0;\n```\n调用方法\n```\nCThostFtdcReqUserLoginField reqUserLogin = { 0 };\nstrcpy_s(reqUserLogin.BrokerID, “0000”);\nstrcpy_s(reqUserLogin.UserID, “00001”);\nstrcpy_s(reqUserLogin.Password, “123456”); \nm_pUserApi-\u003eReqUserLogin(\u0026reqUserLogin, nRequestID++);\n```\nPython版：  \n函数名\n```\ndef ReqUserLogin(self, pReqUserLoginField: 'CThostFtdcReqUserLoginField', nRequestID: 'int') -\u003e \"int\":\n```\n调用方法\n```\nloginfield = api.CThostFtdcReqUserLoginField()\nloginfield.BrokerID=\"0000\"\nloginfield.UserID=\"00001\"\nloginfield.Password=\"123456\"\ntradeapi.ReqUserLogin(loginfield,0)\n```\n所有的函数名均可以在相应头文件底部```class CThostFtdcTraderApi```和```class CThostFtdcMdApi```中查到，函数声明中自带了参数类型，参数结构直接在头文件中搜索就可以。至于对应的函数怎么用，请参考附带官方文档。以登录为例，找到文档中\n```\n/6.6.1P1_API接口说明/交易接口/CThostFtdcTraderApi/ReqUserLogin\n```\n这里面写的非常清楚。\n\n\n# 四、回调函数及数据结构\n所有函数名、参数及参数数据结构都是与官方```C++```版一致的，可以参见上期技术官网文档。以登录响应为例： \n官方C++版：  \n函数名\n```\nvirtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};\n```\n调用方法为继承该函数所在类，重写该函数调用。  \nPython版：  \n函数名\n```\ndef OnRspUserLogin(self, pRspUserLogin: 'CThostFtdcRspUserLoginField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -\u003e \"void\":\n```\n调用方法同样是继承所在CThostFtdcTraderSpi类，重写该函数，实现自己需要的逻辑。  \n所有的函数名均可以在头文件底部```class CThostFtdcTraderSpi```和```class CThostFtdcMdSpi```中查到，函数名中自带了参数类型，参数结构直接在头文件中搜索就可以。\n\n# 五、Demo及其用法\n将td_demo(auth).py文件直接拷贝到API库交易相关文件(3个)同一文件夹中，切换到该目录运行Python td_demo(auth).py即可直接运行。此时如下几个文件应该在一个文件夹底下：\n```\n.\n|-- _thosttraderapi.pyd\n|-- td_demo(auth).py\n|-- thosttraderapi.py\n`-- thosttraderapi_se.dll\n```\nmd_demo.py用法相同。\n\n- td_demo.py实现了简单的登录，查询结算单，确认结算单并买开一手rb1909合约的功能。注意，要将td_demo.py顶部的几个参数改为你自己测试环境参数；合约过期的话要换成非过期合约。  \n- md_demo.py实现了订阅\"au1912\",\"IC1909\",\"i2001\",\"TA001\"这4个合约的功能，并将收取行情存入csv，可以修改subID列表订阅别的合约，同时也要注意修改底部的行情前置地址。\n- td_demo(auth).py实现了加入认证功能后的登录报单等功能，适用于正式生产上。\n- candle_demo.py实现了绘制K线图数据功能\n\n# 六、常见问题\n## 1. 运行时“ImportError: DLL load failed: 找不到指定的模块” \n\n首先确认运行的python版本，运行`python -V`，确保是对应的Python版本（目前仅支持Python3.7和Python3.8版本）。如果版本没有问题，windows上搜索“微软常用运行库合集64位” 安装，linux上确保so所在目录在环境变量LD_LIBRARY_PATH中。\n\n## 2.出错直接退出\n\n通常都是类型对象为None，却直接使用了该对象的成员变量。以查结算单为例，返回回调中，如果输出结算单内容通常直接写成：\n```\ndef OnRspQrySettlementInfo(self, pSettlementInfo: 'CThostFtdcSettlementInfoField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -\u003e \"void\":\n    print (\"content:\",pSettlementInfo.Content)\n```\n这时如果查到结算单自然没有问题，但如果查回结算单为空则直接出错退出，因为pSettlementInfo是None类型。所以正确写法应该先判断是否为空，写成如下：\n```\ndef OnRspQrySettlementInfo(self, pSettlementInfo: 'CThostFtdcSettlementInfoField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -\u003e \"void\":\n    if  pSettlementInfo is not None :\n        print (\"content:\",pSettlementInfo.Content)\n```\n\n## 3.API调用init后为啥没有任何反应（demo运行没有任何反应或者没有OnFrontConnected回调）？\n先检查网络链路是否畅通，可以telnet一下CTP前置地址，是否通畅。再检查API版本是否正确，**连生产或者simnow现必须是v6.3.19_P1_20200106或者v6.6.1_P1_20210406版本api，评测请用v6.3.19_T1_20200423或者v6.6.1_P1_CP_20210406**。详细参考如下：\n![image](https://img-blog.csdnimg.cn/20210907225923920.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5pmv6Imy5q2j5aW9,size_20,color_FFFFFF,t_70,g_se,x_16)\n\n## 4.运行mddemo没有收到行情？\n请参考[CTP程序化交易入门系列之四：行情订阅常见问题解答](https://blog.csdn.net/pjjing/article/details/100532276)这篇博客\n\n# 七、欢迎交流\n欢迎扫二维码关注或者搜索程序化交易入门(QuantRoad2019)，一起学习程序化交易！  \n![image](https://img-blog.csdnimg.cn/20190520205748924.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lpc2h1aWhhbjEyMTI=,size_16,color_FFFFFF,t_70)\n\nQQ交流群（767101469），一起讨论程序化交易！  \n![image](https://img-blog.csdnimg.cn/20191005173130764.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lpc2h1aWhhbjEyMTI=,size_16,color_FFFFFF,t_70)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicai0609%2Fpython-ctpapi","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnicai0609%2Fpython-ctpapi","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnicai0609%2Fpython-ctpapi/lists"}