1

我正在尝试获取帐户余额并将其存储为变量。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()
4

1 回答 1

0

您每次都覆盖文件而不是寻找平衡。用这个

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))
于 2020-07-20T22:26:57.757 回答