0

I am using the IBAPI to gather historical stock quotes, and currently, I am using this code to achieve that:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract


def print_to_file(*args):
    with open('text2.txt', 'w') as fh:
        fh.write(' '.join(map(str,args)))
        fh.write('\n')
        fh.close()
print = print_to_file


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)


    Layout = "{!s:1} {!s:2} {!s:3} {!s:4} {!s:5} {!s:6} {!s:7} {!s:8} {!s:8} '\n'"
    print(Layout.format("Ticker;", "Date;", "None;", "Time;", "Open;", "High;", "Low;", "Close;", "Volume", '\n'))


    def historicalData(self, reqId, bar):
        print("AAPL", ";", bar.date.replace(' ', '; '), ";", bar.open, ";", bar.high, ";", bar.low, ";", bar.close, ";", bar.volume)


def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    contract = Contract ()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqHistoricalData(0, contract, "", "1 D", "1 min", "TRADES", 0, 1, False, [])

    app.run()

if __name__ == "__main__":
    main()

This code worked fine at first, but is suddenly returning me just 1 row of text instead of all the rows that come with the request.

Could someone here try to help me out and figure out what the problem is?

The code that is supposed to write to a text file is:

def print_to_file(*args):
    with open('text2.txt', 'w') as fh:
        fh.write(' '.join(map(str,args)))
        fh.write('\n')
        fh.close()
print = print_to_file

If I let the code write to the terminal instead of the file, I do get the entire request instead of just 1 line.

Thanks!

Majo_Jose
  • 744
  • 1
  • 10
  • 24
Hoogoo
  • 15
  • 1
  • 8

1 Answers1

0

The file is opened in mode 'w' so the function truncates the file at every opening. Mode 'a' should be used instead.

https://docs.python.org/3/library/functions.html#open

'w' open for writing, truncating the file first

'a' open for writing, appending to the end of the file if it exists

Community
  • 1
  • 1
vargab95
  • 342
  • 1
  • 8