Giter Site home page Giter Site logo

nooperpudd / ctpwrapper Goto Github PK

View Code? Open in Web Editor NEW
452.0 23.0 156.0 61.26 MB

上海期货交易所CTP接口 Shanghai Future CTP Interface CTP Python API Wrapper

License: Other

C++ 5.98% C 30.99% Python 40.85% Batchfile 0.17% Makefile 0.03% Dockerfile 0.01% Cython 21.98%
ctp shfe futures trading-api

ctpwrapper's Introduction

CTP期货 API Python Wrapper

build action Build status Codacy Badge pypi status pyversion implementation Downloads

CTP Website

Version: v6.7.0

Platform: Linux 64bit, Windows 64bit

Python Requirement: x86-64

Especially Support PyPy3-3.6 Linux 64bit

Inspire By lovelylain

Install

Before you install ctpwrapper package, you need to make sure you have already install cython package.

>>>pip install cython --upgrade
>>>pip install ctpwrapper --upgrade

Donate [捐助]

⚠️⚠️ notice ⚠️⚠️

sometimes quote the market futures data, but there is no trading data from the API stream, better just add time.sleep(2) func call after Init() method invoked, this could help to solve no data response issue.

Demo

sample code samples

issues

#62 this is a temporary solution for the UnicodeDecodeError issue.

 Traceback (most recent call last):
   File "ctpwrapper/TraderApi.pyx", line 1402, in ctpwrapper.TraderApi.TraderSpi_OnRspQrySettlementInfo
   File "/root/python/futures/trader_main.py", line 149, in OnRspQrySettlementInfo
     print(pSettlementInfo.Content)
   File "/root/python/futures/.venv/lib/python3.9/site-packages/ctpwrapper/base.py", line 28, in __getattribute__
     return value.decode("gbk")
 UnicodeDecodeError: 'gbk' codec can't decode byte 0xd2 in position 499: incomplete multibyte sequence
error_message = ""

def OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
    print("OnRspQryTradingAccount")
    print("nRequestID:", nRequestID)
    print("bIsLast:", bIsLast)
    print("pRspInfo:", pRspInfo)
    print("pTradingAccount:", pTradingAccount)
    # need to check is last message from the server.
    global error_message
    if not bIsLast:
       error_message+=pRspInfo.ErrorMsg
    else:
       error_message+=pRspInfo.ErrorMsg
       if isinstance(error_message,bytes):
           error_message.decode("gbk")

Documentation

CTP documentation can be found in the docs

Contact

If you have any question about the ctpwrapper API, contact [email protected]

ctpwrapper's People

Contributors

nooperpudd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ctpwrapper's Issues

6.6.1 交易认证失败

环境:

  • Ubuntu 18.04
  • Python: 3.6.9
  • CTP Wrapper branch: master
  • CTP 版本:6.6.1

结果:

行情正常,但是交易连接报错,提示认证失败

OnRspAuthenticate
pRspInfo: RspInfoField<ErrorID(63),ErrorMsg(CTP:客户端认证失败)>
nRequestID: 101

配置

用同样的配置,尝试了下本机 CTP 旧版本的6.3.15,对应的环境(非 python 环境),能正常下单。

问题

请问:6.6.1 和 6.3.15 在交易模块中,授权认证方面有什么调整吗?谢谢!

Trader 参数如何传参数

在使用samples/trader_main.py中,想调用user_trader.ReqQrySecAgentTradingAccount
知道这个函数在ctpwapper/trader.py中需要二个参数(self, pQryTradingAccount, nRequestID)
问,这二个参数如何构建

初始化下单数据是出现错误。

错误信息如下:
F:>ipython
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import ctpwrapper.ApiStructure as apidata

In [2]: orderdata=apidata.InputOrderField()

TypeError Traceback (most recent call last)
in
----> 1 orderdata=apidata.InputOrderField()

d:\miniconda3\lib\site-packages\ctpwrapper\ApiStructure.py in init(self, BrokerID, InvestorID, InstrumentID, OrderRef, UserID, OrderPriceType, Direction, CombOffsetFlag, CombHedgeFlag, LimitPrice, VolumeTotalOriginal, TimeCondition, GTDDate, VolumeCondition, MinVolume, ContingentCondition, StopPrice, ForceCloseReason, IsAutoSuspend, BusinessUnit, RequestID, UserForceClose, IsSwapOrder, ExchangeID, InvestUnitID, AccountID, CurrencyID, ClientID, IPAddress, MacAddress)
1626 self.OrderRef = self._to_bytes(OrderRef)
1627 self.UserID = self._to_bytes(UserID)
-> 1628 self.OrderPriceType = self._to_bytes(OrderPriceType)
1629 self.Direction = self._to_bytes(Direction)
1630 self.CombOffsetFlag = self._to_bytes(CombOffsetFlag)

TypeError: one character bytes, bytearray or integer expected

如何获取 pDepthMarketData行情返回的字段

print出来是这样的类型:DepthMarketDataField<TradingDay(20210623),reserve1(),ExchangeID(),reserve2(),LastPrice(2597.0),PreSettlementPrice(2591.0),PreClosePrice(2583.0),PreOpenInterest(603941.0),OpenPrice(2580.0),HighestPrice(2603.0),LowestPrice(2569.0),Volume(363103),Turnover(9396033190.0),OpenInterest(601336.0),ClosePrice(1.7976931348623157e+308),SettlementPrice(1.7976931348623157e+308),UpperLimitPrice(2772.0),LowerLimitPrice(2410.0),PreDelta(0.0),CurrDelta(1.7976931348623157e+308),UpdateTime(22:31:07),UpdateMillisec(0),BidPrice1(2597.0),BidVolume1(478),AskPrice1(2598.0),AskVolume1(873),BidPrice2(1.7976931348623157e+308),BidVolume2(0),AskPrice2(1.7976931348623157e+308),AskVolume2(0),BidPrice3(1.7976931348623157e+308),BidVolume3(0),AskPrice3(1.7976931348623157e+308),AskVolume3(0),BidPrice4(1.7976931348623157e+308),BidVolume4(0),AskPrice4(1.7976931348623157e+308),AskVolume4(0),BidPrice5(1.7976931348623157e+308),BidVolume5(0),AskPrice5(1.7976931348623157e+308),AskVolume5(0),AveragePrice(25877.04643035172),ActionDay(20210622),InstrumentID(c2109),ExchangeInstID(),BandingUpperPrice(0.0),BandingLowerPrice(0.0)>

如何获取里面的详细字段呢?比如lastprice

关于 CTP 个股期权 API 的封装

image

看了一下个股期权 API 的 h 文件,和 6.3.11 还是有一些差别的

而且,类和机构体等声明都给了命名空间 namespace ctp_sopt

如果想仿照 ctpwrapper 股期权的 API ,是不是按照 h 文件声明的差异修改相关 pxd pyx 文件即可?

请升级到CTP V6.3.17

目前生产最新版本为CTP V6.3.17_P4_20190628),客户端在使用tradeapi时,业务指令中有InvestorID和exchangeID的域都必须填写,之前没有填写的后台将会返回错误。

6.3.15版本下单时候会产生错误: 'CTP:缺少ExchangeID字段,请填入ExchangeID'

例子程序运行失败

运行sample下的trader_main.py

ubuntu@VM-0-3-ubuntu:~/ctp_quote_test$ python3 ctp_test_2.py
trader on front connection
Md user login successfully
trader started
20190111
Segmentation fault (core dumped)

如何替换期货公司给的so包

通常情况下每个期货公司提供的so包或者dll包跟生产环境统一使用的是有区别的,所以具体对接期货公司需要使用具体他们给提供的so包。这种情况下请问如何替换项目中的so包,并且打包编译,让项目能顺利通过呢?

improvement tips

  1. use concurrency instead of GIL.
  2. use shard_ptr instead of the extend heads

ModuleNotFoundError: No module named 'ctpwrapper.MdApi'

from ctpwrapper.MdApi import MdApiWrapper

ModuleNotFoundError: No module named 'ctpwrapper.MdApi'

I have added ctpwrapper as sources root.
While , when i run sample files, it shows No module named 'ctpwrapper.MdApi' . 非常的奇怪!

API封装的小疑惑

是否可以将字符串相关的API 进一步封装?比如象GetApiVersion()这样的方法,直接返回decode('gbk')后的字符串的话会非常方便。

获取结算单明细时GBK解码错误

你好, 我在测试使用 ctpwrapper 的 获取结算单明细回调 OnRspQrySettlementInfo 时, 发现回调的多条数据中, 有一些报错

Traceback (most recent call last):
  File "ctpwrapper/TraderApi.pyx", line 1402, in ctpwrapper.TraderApi.TraderSpi_OnRspQrySettlementInfo
  File "/root/python/futures/trader_main.py", line 149, in OnRspQrySettlementInfo
    print(pSettlementInfo.Content)
  File "/root/python/futures/.venv/lib/python3.9/site-packages/ctpwrapper/base.py", line 28, in __getattribute__
    return value.decode("gbk")
UnicodeDecodeError: 'gbk' codec can't decode byte 0xd2 in position 499: incomplete multibyte sequence

这是因为内置函数

    def __getattribute__(self, item):
        value = super().__getattribute__(item)
        if isinstance(value, bytes):
            return value.decode("gbk")
        else:
            return value

在获取到bytes时使用gbk解码, 解码出现了问题, 我修改了源代码为

    def __getattribute__(self, item):
        value = super().__getattribute__(item)
        if isinstance(value, bytes):
            return value.decode("gbk", errors="ignore")
        else:
            return value

设置decode时忽略解析错误的字符来规避错误, 在测试过程中也没有发现数据丢失或错误的情况, 同时也保证了程序正常运行
你是否能将其修改发布? 或者说有更好的解决办法? 这是一个非常好的模块, 给予了我很大帮助, 谢谢!

No callback?

I tried to modify your sample code -- trader_main.py as I got the following error:

  File "trade_monitor.py", line 229, in <module>
    main()
  File "trade_monitor.py", line 219, in main
    trader_account = ApiStructure.QryTradingAccountField(BrokerID=broker_id, InvestorID=investor_id)
  File "/home/hc/.local/lib/python3.8/site-packages/ctpwrapper/ApiStructure.py", line 2877, in __init__
    self.BizType = self._to_bytes(BizType)
TypeError: one character bytes, bytearray or integer expected

I fixed it by adding , BizType='0'.

Then, I noticed that OnRspQryTradingAccount() didn't get called.

Then, I removed ReqQryInvestor() and ReqQryTradingAccount() in your sample code, OnRspQryTradingAccount() did get called.

Any idea what's going on?

Thanks!

one character bytes, bytearray or integer expected

下单时一直报错
Traceback (most recent call last): File "I:\tools\anaconda\envs\insight\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "I:\workspace\py_ctp\py_ctp\new\tradeServer.py", line 140, in run self.funcs[action](code=code,action=action) File "I:\workspace\py_ctp\py_ctp\new\tradeServer.py", line 155, in longStock self.orderInsert(stock, requestN, TThostFtdcDirectionType.THOST_FTDC_D_Buy.value, stock.AskPrice1) # 卖一价 File "I:\workspace\py_ctp\py_ctp\new\tradeServer.py", line 169, in orderInsert orderfield = InputOrderField(self.broker_id,self.investor_id,depthMarketDataField.InstrumentID,UserID=self.user_id,OrderPriceType=b'50') # type:InputOrderField File "I:\tools\anaconda\envs\insight\lib\site-packages\ctpwrapper\ApiStructure.py", line 1634, in __init__ self.TimeCondition = self._to_bytes(TimeCondition) TypeError: one character bytes, bytearray or integer expected

关于Apistructure 初始化的问题

当遇到类型为ctypes.c_char的字段赋值是,如果用默认空值会出现typeerror
p = QryProductField()
Traceback (most recent call last):
File "D:\Users\Administrator\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 1, in
p = QryProductField()
File "D:\Users\Administrator\Anaconda3\lib\site-packages\ctpwrapper\ApiStructure.py", line 3119, in init
self.ProductClass = self._to_bytes(ProductClass)
TypeError: one character bytes, bytearray or integer expected

cython 3.0 编译中的一个 warning,nogil 应该写在行尾

一个小问题。
cython 3.0版本后,编译过程中提示warning,nogil 应该放在 except + 的后面
warning: ctpwrapper/headers/DataCollect.pxd:8:61: The keyword 'nogil' should appear at the end of the function signature line. Placing it before 'except' or 'noexcept' will be disallowed in a future version of Cython.
如要修复,简单调整顺序即可
void Release() nogil except +
修改为
void Release() except + nogil

报单成功未调用Response

查询持仓是可以看到已经成交的,但是调用接口成功后没有调用

# 报单录入请求响应
def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast):

报单的调用如下:

field = ApiStructure.InputOrderField(
BrokerID=RohonBrokerId,
InvestorID=account,
InstrumentID=instrument_id,
OrderRef=order_ref,
OrderPriceType=ctp_data_type.defineDict["THOST_FTDC_OPT_AnyPrice"],
Direction=direction,
CombOffsetFlag=ctp_data_type.defineDict["THOST_FTDC_OFEN_Open"],
CombHedgeFlag=ctp_data_type.defineDict["THOST_FTDC_HFEN_Speculation"],
LimitPrice=limit_price,
VolumeTotalOriginal=volume,
VolumeCondition=ctp_data_type.defineDict["THOST_FTDC_VC_CV"],
TimeCondition=ctp_data_type.defineDict["THOST_FTDC_TC_IOC"],
IsSwapOrder=0,
)
trader.ReqOrderInsert(field, 4)

Bug for ReqQryInvestorPosition

In the ctpwrapper/TradeApi.pyx, for ReqQryInvestorPosition, missing the following
cdef size_t address

Anyway, great project!

Second Callback Never Happens

I tried the latest sample code trader_main.py with the fix.

I noticed that OnRspQryTradingAccount() didn't get called.

Then, I removed ReqQryInvestor() and ReqQryTradingAccount() in your sample code, OnRspQryTradingAccount() did get called.

Any idea what's going on?

Thanks!

user_trader.ReqQryInstrument("",0) get error

File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\ctpwrapper\Trader.py", line 279, in ReqQryInstrument
return super(TraderApiPy, self).ReqQryInstrument(pQryInstrument, nRequestID)
File "ctpwrapper\TraderApi.pyx", line 502, in ctpwrapper.TraderApi.TraderApiWrapper.ReqQryInstrument
TypeError: invalid type

how to solve it?

small issue, "Md" should be "Td"

Hello,

samples\td_main.py, OnRspUserLogin()

print("Md OnRspUserLogin failed error_id=%s msg:%s",
print("Md user login successfully")

the "Md" should be "Td", that will make them more clear. thank you.

一段时间后无法获得订阅流

使用了samples里面提供的md_main.py
刚开始没有任何问题,但是一段时间后就无法获得订阅流了
我不知道是什么情况导致的,拜托了!!!!!!!!!!
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.