0

I am using the latest version of IB's TWS API and I want to write real-time data(not historical) to a file as it becomes available. My problem is that although I get no error messages, the file is always empty after multiple times the data has arrived. I tried putting it here: (inside the def init for class TestAPP

class TestApp(TestWrapper, TestClient):
def __init__(self):
    TestWrapper.__init__(self)
    TestClient.__init__(self, wrapper=self)
    # ! [socket_init]
    self.nKeybInt = 0
    self.started = False
    self.nextValidOrderId = None
    self.permId2ord = {}
    self.reqId2nErr = collections.defaultdict(int)
    self.globalCancelOnly = False
    self.simplePlaceOid = None
    self.f = open('c:\\histdata\\myfile.txt', 'w')

and the write statement inside

 def tickPrice(self, reqId: TickerId, tickType: TickType, price: float,
              attrib: TickAttrib):
    super().tickPrice(reqId, tickType, price, attrib)
    print("TickPrice. TickerId:", reqId, "tickType:", tickType,
          "Price:", price, "CanAutoExecute:", attrib.canAutoExecute,
          "PastLimit:", attrib.pastLimit, end=' ')
    print(str(reqId)+" "+str(price)+'\n')
    self.f.write(str(reqId)+" "+str(price)+'\n');
 

The main portion program where the reqMktdata are placed looks like

 try:
    app = TestApp()
    if args.global_cancel:
        app.globalCancelOnly = True
    # ! [connect]
    app.connect("127.0.0.1", args.port, clientId=0)
    # ! [connect]
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                                  app.twsConnectionTime()))
    time.sleep(4)
    file1 = open('c:\\histdata\\InputSymbols.txt', 'r')
    count = 0
    contract = Contract()
    while True:
        count += 1

        # Get next line from file
        line = file1.readline()
        if not line:
            break
        splitline = line.split(',')
   
        contract.symbol =splitline[1].strip('\n')
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
        contract.primaryExchange="NASDAQ"
        app.reqMktData(1000+count,contract,"233,236",False,False,[])
        time.sleep(1);
    file1.close()
    
    print("hi")
    # ! [clientrun]
    app.run()
    # ! [clientrun]
    
except:
    raise
finally:
    app.dumpTestCoverageSituation()
    app.dumpReqAnsErrSituation()

The input data file InputSymbols.txt looks like

STK,AAPL
STK,NFLX
STK,FB

The output myfile.txt is empty which is the problem Sample output looks like (abbreviated)

TickPrice. TickerId: 1003 tickType: 7 Price: 357.11 CanAutoExecute: False PastLimit: False 1003 257.11

Thanks in advance for all looked at my problem!.

quinn
  • 177
  • 1
  • 2
  • 13
  • You never close the file. – brian Aug 13 '21 at 00:30
  • What you say is not completly true. Python automatically closes open files before as the program exits. Ref: https://askinglot.com/does-python-close-files-automaticallyBut to make sure, I added the following code and it still did not work.:...(have trouble editing sorry.) if (self.f.closed): a=1 else: print(str(reqId)+" "+str(price)+'\n') self.f.write(str(reqId)+" "+str(price)+'\n'); self.f.close – quinn Aug 13 '21 at 00:53
  • The program has no exit, you probably kill it somehow. Figure out how you want the program to exit then close the file at that point. – brian Aug 13 '21 at 01:25
  • I found the section of code when the user hits control=c to stop the program and added a self.f.close. Problem is still the same. I would really like to get some feedback from someone else who has good experience with TWS Python. Thanks for Trying brian. – quinn Aug 13 '21 at 02:08
  • Test it by adding `self.f.close() self.disconnect()` after `self.f.write(..` You will only get one line but you will see the problem. If you modify the source code you may have to re-install the ibapi for the change to take effect. BTW, I tested your program parts and added my own close logic and it worked fine. If you post a minimal simple working example I will fix it for you. – brian Aug 13 '21 at 13:49

0 Answers0