盈透证券刚刚发布了其API的python版本。我正在尝试获取数据。
我正在使用"Program.py"中的"示例",只是试图获取帐户值。我只想知道帐户清算价值是多少,并将其放入python中。这是文档。这是创建和发送请求的代码:
app = TestApp()
app.connect("127.0.0.1", 4001, clientId=0)
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
app.twsConnectionTime()))
app.reqAccountSummary(9004, 'All', '$LEDGER')
我可以使用 IB 网关,并查看正在发送的请求,以及返回 IB 网关的响应。我不知道如何将响应放入 Python。如果我正确阅读了文档,我会看到以下内容:
Receiving
Summarised information is delivered via IBApi.EWrapper.accountSummary and IBApi.EWrapper.accountSummaryEnd
1 class TestWrapper(wrapper.EWrapper):
...
1 def accountSummary(self, reqId: int, account: str, tag: str, value: str,
2 currency: str):
3 super().accountSummary(reqId, account, tag, value, currency)
4 print("Acct Summary. ReqId:", reqId, "Acct:", account,
5 "Tag: ", tag, "Value:", value, "Currency:", currency)
6
...
1 def accountSummaryEnd(self, reqId: int):
2 super().accountSummaryEnd(reqId)
3 print("AccountSummaryEnd. Req Id: ", reqId)
我该怎么办?似乎我调用这个函数来获取值,但这个函数需要我想要返回的值作为输入!我错过了什么??!
感谢任何人都可以提供的任何帮助。
编辑:
我认为这是"回调":
@iswrapper
# ! [accountsummary]
def accountSummary(self, reqId: int, account: str, tag: str, value: str,
currency: str):
super().accountSummary(reqId, account, tag, value, currency)
print("Acct Summary. ReqId:", reqId, "Acct:", account,
"Tag: ", tag, "Value:", value, "Currency:", currency)
这就是我感到困惑的地方。这似乎期望帐户的值(声明中的"value:str"),这正是我要求它生成的。我找不到我会说
如下的话:myMonies = whateverTheHellGetsTheValue(reqID)
因此,"myMonies"将持有账户价值,我可以继续我的快乐之路。
我在这里回答了一个非常相似的问题。 https://stackoverflow.com/a/42868938/2855515
这是一个程序,我在同一类中对EWrapper
和EClient
进行子类化,并将其用于所有内容,请求和接收回调。
您调用 EClient 方法来请求数据,并通过 EWrapper 方法反馈数据。 这些是带有@iswrapper
符号的那些。
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
class TestApp(wrapper.EWrapper, EClient):
def __init__(self):
wrapper.EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
self.nextValidOrderId = orderId
# here is where you start using api
self.reqAccountSummary(9002, "All", "$LEDGER")
@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
@iswrapper
def accountSummary(self, reqId:int, account:str, tag:str, value:str, currency:str):
print("Acct Summary. ReqId:" , reqId , "Acct:", account,
"Tag: ", tag, "Value:", value, "Currency:", currency)
@iswrapper
def accountSummaryEnd(self, reqId:int):
print("AccountSummaryEnd. Req Id: ", reqId)
# now we can disconnect
self.disconnect()
def main():
app = TestApp()
app.connect("127.0.0.1", 7497, clientId=123)
app.run()
if __name__ == "__main__":
main()
致其他像我这样的新手:
另请注意;我试图:
print(self.reqHistoricalData(4102, ContractSamples.EurGbpFx(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, []))
或者抓住self.reqHistoricalData()
的回报. 如上所述,布莱恩;EClient
发送请求,EWrapper
接收回信息。
所以似乎试图掌握self.reqHistoricalData()
不会给你任何东西(我得到None
类型)
但是,将请求添加到
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
self.nextValidOrderId = orderId
# here is where you start using api
self.reqAccountSummary(9002, "All", "$LEDGER")
self.reqHistoricalData(4102, ContractSamples.EurGbpFx(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
contract = Contract()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
self.reqHistoricalData(4103, contract, queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
足以让接收器(EWrapper
)打印到控制台
更新 2019-01-05:EWrapper
需要知道如何处理收到的消息。 为了让EWrapper
为您提供一个句柄,例如打印到控制台;代码的编写者必须在代码中指定装饰器语句,超出表示"# here is where you start using api"
举个例子: 如果代码包含以下代码段:
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
#super().nextValidId(orderId)
self.nextValidOrderId = orderId
#here is where you start using api
queryTime = (datetime.datetime.today() - datetime.timedelta(days=5)).strftime("%Y%m%d %H:%M:%S")
self.reqHistoricalData(4102, ContractSamples.EurGbpFx(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
@iswrapper
def historicalData(self, reqId:int, bar: BarData):
print("HistoricalData. ReqId:", reqId, "BarData.", bar)
然后我们将打印到控制台。 如果忽略包装器装饰器方法,则不会打印到控制台。 例如在此代码中:
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
#super().nextValidId(orderId)
self.nextValidOrderId = orderId
#here is where you start using api
queryTime = (datetime.datetime.today() - datetime.timedelta(days=5)).strftime("%Y%m%d %H:%M:%S")
self.reqHistoricalData(4102, ContractSamples.EurGbpFx(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
#@iswrapper
#def historicalData(self, reqId:int, bar: BarData):
# print("HistoricalData. ReqId:", reqId, "BarData.", bar)
因此,在您的情况下,请寻找正确的回调。 例如,如果您请求一个选项(即测试平台/contractOperations_req)。结果进入contractDetails(@iswrapper),您可以在其中指定要执行的操作...也许打印(合同详细信息.摘要.符号)等。因此,只需找到帐户信息的相应回调,然后将其打印/返回/等返回到您的程序。
此脚本 (get-account.py) 将在代码行返回用户帐户"value"的值:
print(f"myfunds> {app.get_myfunds()}")
。可以(当然)分配给变量以进行进一步处理等。
这里重要的是,帐户"值"在代码的过程/脚本部分作为对应用程序对象的方法调用可用。
我将脚本部分的部分置于睡眠状态 while 循环 "time.sleep(1)" 中,以便异步 "EWrapper" 回调方法有时间返回来自 IB API 的响应(在继续下一行之前)。
run_loop() 是从线程内部调用的。我对多线程编程相当陌生,所以我对为什么它会起作用没有任何真正的见解,但它似乎是脚本成功执行的关键。我尝试在没有多线程的情况下运行脚本,它只是挂起,迫使我>"杀死-9 PID"杀死进程。
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
import threading
import time
class IBapi(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
# Custom attributes
self.myfunds = ''
self.connection_status = False
def get_myfunds(self):
""" Custom getter method that returns current value of custom attribute self.myfunds. """
return self.myfunds
def get_connection_status(self):
""" Custom getter method that returns current value of custom attribute self.connection_status. """
return self.connection_status
# @iswrapper
def accountSummary(self, reqId:int, account:str, tag:str, value:str, currency:str):
""" Returns the data from the TWS Account Window Summary tab in response to reqAccountSummary(). """
# Update value of custom attribute self.myfunds
self.myfunds = value
# @iswrapper
def accountSummaryEnd(self, reqId:int):
""" This method is called once all account summary data for a given request are received. """
self.done = True # This ends the messages loop
# @iswrapper
def connectAck(self):
""" Callback signifying completion of successful connection. """
# Update value of custom attribute self.connection_status
self.connection_status = True
def run_loop():
app.run()
app = IBapi()
# IP: ipconfig /all > Ethernet adapter Ethernet > IPv4 Address
# Production port: 7496 | Sandbox (paper account) port: 7497
# Client ID: 123 (used to identify this script to the API, can be any unique positive integer).
app.connect('127.0.0.1', 7497, 123)
# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
while app.get_connection_status() == False:
time.sleep(1) # Sleep interval to allow time for connection to server
print(f"Connection status > {app.get_connection_status()}")
app.reqAccountSummary(reqId = 2, groupName = "All", tags = "TotalCashValue")
while app.get_myfunds() == '':
time.sleep(1) # Sleep interval to allow time for incoming data
if app.get_myfunds() != '':
print(f"myfunds > {app.get_myfunds()}")
app.disconnect()