1
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from threading import Timer

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

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    def nextValidId(self, orderId):
        self.start()

    def historicalData(self, reqId, bar):
        # print("HistoricalData. ", reqId, " Date:", ...., bar.average)
        return bar.high


    def start(self):
        contract = Contract()
        contract.symbol = "TSLA"
        contract.secType = "STK"
        contract.exchange = "SMART"
        contract.currency = "USD"
       x = self.reqHistoricalData(1, contract, "", "60 s", "1 min", "MIDPOINT", 0, 1, False, [])
        print(x)


    def stop(self):
        self.done = True
        self.disconnect()
def main():
    app = TestApp()
    app.nextOrderId = 0
    app.connect("127.0.0.1", 7497, 0)

    Timer(4, app.stop).start()
    app.run()


if __name__ == "__main__":
    main()

Instead of printing HistoricalData, how would I be able to return bar.high in this case?
It's not giving me anything right now.
Any help is appreciated.
What am I missing?

Thank you very much.

misantroop
  • 2,276
  • 1
  • 16
  • 24

1 Answers1

1

You've added a return value to historicalData and you're hoping to access it through reqHistoricalData. But they're completely different functions. Unless you're willing to rewrite the API's classes, you can't invoke historicalData like a normal function. So you can't access its return value.

In my code, I use callback functions like historicalData to set member variables of the containing class. Then, after waiting a couple seconds in the main thread, I access the variables to obtain the historical data.

MatthewScarpino
  • 5,672
  • 5
  • 33
  • 47
  • How do you use callback functions like historicalData to set member variables of the containing class? – user2697873 Feb 26 '20 at 15:58
  • Unlike regular variables, instance variables inside a class are preceded by `self`, which represents the class. You can find out more [here](https://www.python-course.eu/python3_class_and_instance_attributes.php). For example, you could define an instance variable named `high` by inserting `self.high = 0.0` inside `__init__`. Then, inside `historicalData`, you can set `self.high = bar.high`. Lastly, after you've waited for the data to arrive, you can access the value through the instance's `high` variable. – MatthewScarpino Feb 26 '20 at 16:41