erdewit / ib_insync

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

Wrong avg cost number in portfolio Item #175

Closed eric0470 closed 5 years ago

eric0470 commented 5 years ago

Hi! I'm getting wrong average number for some future contracts. For example GC contract.

Code to test:

import uuid
import asyncio
import traceback
from ib_insync import IB, Future, MarketOrder
from ib_insync import util as ib_util

async def default_test():
    try:
        ib = IB()
        await ib.connectAsync('localhost', 4002, 1, 5)

        contract = Future('GC', '20191227', 'NYMEX')
        ib.qualifyContracts(contract)
        order = MarketOrder('BUY', 1)
        trade = ib.placeOrder(contract, order)

        # Wait to execute
        await asyncio.sleep(4)
        fill_avg = trade.fills[0].execution.avgPrice
        print('FILL AVG:', fill_avg)

        for item in ib.portfolio():
            if item.contract.symbol == 'GC':
                print('AVG:', item.averageCost)

    except:  # noqa
        print(traceback.format_exc())
    finally:
        ib.disconnect()
        await asyncio.sleep(4)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    ib_util.patchAsyncio()
    loop.run_until_complete(default_test())
    loop.close()

Result print:

FILL AVG: 1477.3
AVG: 147732.37

As you can see numbers are different. Can you fix this? P.S Before run test code make sure you don't have open positions for GC contract

erdewit commented 5 years ago

Both numbers are shown as they are delivered by IB. The factor 100 difference is probably the contract multiplier, or in formula form: cost = multiplier * price.