erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.81k stars 755 forks source link

Can not exercise option by ib.exerciseOptions #152

Closed eric0470 closed 5 years ago

eric0470 commented 5 years ago

Hi! I am trying to exercise options, but get error:

Test code than I used:

    positions = ib.positions()
    options = []

    for position in positions:
        if isinstance(position.contract, (Option, )):
            options.append(position)

    for option in options:
        ib.exerciseOptions(option.contract, 1, option.position, option.account, 0)

Error form IB:

Error 320, reqId 362349789: Error reading request:Message id 362349789. Unable to parse data. java.lang.NumberFormatException: For input string: "BAC" Peer closed connection

What problem can be with the code?

TWS Version: 976.2h IB Insync Version: 0.9.51

erdewit commented 5 years ago

Thank you for the bug report. The client was sending one contract field too many, this should now be fixed in v0.9.52.

erdewit commented 5 years ago

Please note that exerciseQuantity should be an int, not a float.

eric0470 commented 5 years ago

The problem exist if i am using contract provided from ib.postions() like that:

    for position in positions:
        if isinstance(position.contract, (Option, )):
            options.append(position)

    for option in options:
        ib.exerciseOptions(option.contract, 1, option.position, option.account, 0)

I get in TWS this error: Message must contain field #207

But if i create contract using option constructor it exercise options:

 contract = Option('GLD', '20190621', 127, 'C', 'SMART')

Version of ib_insync is updated to 0.9.52

erdewit commented 5 years ago

Fix protocol field 207 referers to the securityExchange. Probably contract.exchange has to be set to 'SMART'. It's best to ask IB about this sort of logic.

eric0470 commented 5 years ago

Fix protocol field 207 referers to the securityExchange. Probably contract.exchange has to be set to 'SMART'. It's best to ask IB about this sort of logic.

The problem was with using account in exerciseOptions. If I put there empty string, exercise is executing successfully. I think this is bug in TWS system not in your code.