python - 互动经纪商 TWS API Python 获取账户余额
问题描述
我正在尝试获取帐户余额并将其存储为变量。accountSummary 值中有余额。我正在使用 print 来验证 var bal 中是否存储了数据。Print(bal) 将在终端中显示信息,但不会将其打印到文件 balance.txt。如果前面执行的代码中的 orderid 示例正常工作,为什么 Balance 不可以呢?
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
import math
import os.path
from os import path
class TestApp(wrapper.EWrapper, EClient):
posns = []
fname = 'fname.txt'
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
file = open("orders.txt","w")
file.write(str(orderId))
file.close()
# here is where you start using api
self.reqAccountSummary(9002, "All", "$LEDGER")
@iswrapper
def accountSummary(self, reqId:int, account:str, tag:str, value:str, currency:str):
bal=(value)
file = open("Balance.txt","w")
file.write(bal)
file.close()
@iswrapper
def accountSummaryEnd(self, reqId:int):
# 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()
解决方案
您每次都覆盖文件而不是寻找平衡。用这个
def accountSummary(self, reqId:int, account:str, tag:str, value:str, currency:str):
if tag == "CashBalance": # or whatever you want
with open('Balance.txt', 'a+') as file: #append, create if doesn't exist
file.write("%s, %s, %s, %s\n" % (account, tag, value, currency))
推荐阅读
- angular - 使用角度为ionic 4上的firestore生成问题和答案的动态表
- bootstrap-4 - Bootstrap 4 Navbar Collapse 未在单击时关闭
- php - 突然出现的字符串数组错误消息如何更正?
- python-3.x - 如何搜索模式并提取其背后的值
- jmeter - 无法使用 bsh.shared 在 JMeter 中的线程组之间共享数组
- python - 如何注释下图?
- reactjs - 使用 useMutations [Apollo/React hooks] 重定向后 useQuery 返回 undefined
- bash - 如何在 Git bash 中打开当前目录
- three.js - 无法让 Bloompass 和 EffectComposer 在 Three.js 中一起工作
- node.js - Mongodb With Nodejs我收到错误“需要'cursor'选项,除了带有解释参数的聚合”