1 Star 1 Fork 3

云金杞/ib

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
sender.py 3.07 KB
一键复制 编辑 原始数据 按行查看 历史
云金杞 提交于 2024-07-30 13:52 +08:00 . try to fix bugs
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# Defines Sender class to handle outbound requests.
#
# Sender instances defer failed attribute lookup to their
# EClientSocket member objects.
#
##
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import time
from functools import wraps
from ib.ext.EClientSocket import EClientSocket
from ib.lib import toTypeName
from ib.opt.message import registry, clientSocketMethods
class Sender(object):
""" Encapsulates an EClientSocket instance, and proxies attribute
lookup to it.
"""
client = None
def __init__(self, dispatcher):
""" Initializer.
@param dispatcher message dispatcher instance
"""
self.dispatcher = dispatcher
self.clientMethodNames = [m[0] for m in clientSocketMethods]
# print("self.clientMethodNames = ", self.clientMethodNames)
def connect(self, host, port, clientId, handler, clientType=EClientSocket):
""" Creates a TWS client socket and connects it.
@param host name of host for connection; default is localhost
@param port port number for connection; default is 7496
@param clientId client identifier to send when connected
@param handler object to receive reader messages
@keyparam clientType=EClientSocket callable producing socket client
@return True if connected, False otherwise
"""
self.client = clientType(handler)
self.client.eConnect(host, port, clientId)
while (not self.client.isConnected()):
time.sleep(15)
print("connect to tws api, failed, try again, one seconds later")
self.reconnect(host, port, clientId)
print("connect to tws api success")
return True
def reconnect(self, host, port, clientId):
self.client.eConnect(host, port, clientId)
return self.client.isConnected()
def disconnect(self):
""" Disconnects the client.
@return True if disconnected, False otherwise
"""
client = self.client
if client and client.isConnected():
client.eDisconnect()
return not client.isConnected()
return False
def __getattr__(self, name):
""" x.__getattr__('name') <==> x.name
@return named attribute from EClientSocket object
"""
try:
value = getattr(self.client, name)
except (AttributeError, ):
raise
if name not in self.clientMethodNames:
return value
return value
preName, postName = name+'Pre', name+'Post'
preType, postType = registry[preName], registry[postName]
@wraps(value)
def wrapperMethod(*args):
mapping = dict(list(zip(preType.__slots__, args)))
results = self.dispatcher(preName, mapping)
if not all(results):
return # raise exception instead?
result = value(*args)
self.dispatcher(postName, mapping)
return result # or results?
return wrapperMethod
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yunjinqi/ib.git
git@gitee.com:yunjinqi/ib.git
yunjinqi
ib
ib
master

搜索帮助