Giter Site home page Giter Site logo

erdewit / ib_insync Goto Github PK

View Code? Open in Web Editor NEW
2.7K 180.0 712.0 14.48 MB

Python sync/async framework for Interactive Brokers API

License: BSD 2-Clause "Simplified" License

Python 99.96% Shell 0.04%
python asyncio interactive-brokers twsapi ibapi trading

ib_insync's People

Contributors

805karansaini avatar abbass2 avatar alobbs avatar batterseapower avatar docker-tws avatar drathm avatar elektra58 avatar erdewit avatar gliptak avatar iovsiann avatar jarfo avatar jspahrsummers avatar losdaniel avatar m12t avatar mattsta avatar mikishab avatar onursatici avatar prurph avatar shaagerup avatar sharpkids avatar slmg avatar sohailsomani avatar stenri avatar stnatter avatar t1user avatar tankorsmash avatar yehoshuadimarsky avatar ynodir avatar zentooo avatar zhongdai813 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ib_insync's Issues

expired futures contracts

Hello,

Wondering if there is a way to search for expired futures contracts and download their bars?

Thanks

Example in README.rst doesn't work in read-only mode

I've got my API access in IB set to read-only mode. The example script, when run, warned me that the call could not be satisfied in read-only mode.

However, the example appears to be a request for historical data, which as far as I know shouldn't require write access.

reqHistoricalTicks reports error 'Unable to parse data. java.lang.NumberFormatException'

Repro Source Code:

from ib_insync import *

ib = IB()

ib.connect('127.0.0.1', 4003, clientId=1)

contract = Stock('AAPL', 'SMART', 'USD')

ticks = ib.reqHistoricalTicks(contract, startDateTime='2017-09-01', endDateTime='',
numberOfTicks=100, whatToShow='TRADES', useRth=False,
ignoreSize=False, miscOptions=None)
print(ticks)

Output:

ERROR:ib_insync.wrapper:Error 320, reqId -1: Error reading request:Message type -1. Unable to parse data. java.lang.NumberFormatException: For input string: "AAPL"
ERROR:ib_insync.client:Peer closed connection

Dividend Events Calendar

First off, thanks for writing this. It seems to work well so far.

But I had a question, I didn't see anything in here about getting dividend calendar event data. Is this something that I can request via ib_insync? If not, is this feature on the roadmap?

Thanks!

util.startLoop() outside of Jupyter Notebook

Hey there - thanks for an awesome Python Wrapper!!!

Is it possible to use the util.startLoop() method outside of Juypter notebook. I would like to schedule a CRON job that kicks of a script on an Amazon EC2 instance.

error I get when running the method outside of jupyter is:
RuntimeError: You didn't specify a kernel, and no IPython Application with a kernel appears to be running.

Thanks heaps...

How do I auto reconnect on disconnect?

I'm trying to call ib_insync.Client.connect(...) in a loop with a delay in wrapper.apiEnd and got an exception

RuntimeWarning: coroutine 'Client.connectAsync' was never awaited`

Is this the correct way to reconnect? Or do I need to del my client instance and create a new one?

real time bars to df issue

Hello

I got the error "'BarData' object has no attribute 'tuple'" when doing the following:

`bars = ib.reqHistoricalData(
contract_fut,
endDateTime='',
durationStr='60 S',
barSizeSetting='5 secs',
whatToShow='TRADES',
useRTH=True,
formatDate=1,
keepUpToDate=True)

util.df(bars)`

Grateful for advice.

AttributeError: 'Order' object has no attribute 'algoParamsCount'

Hello,
I get AttributeError: 'Order' object has no attribute 'algoParamsCount', after I submit an adaptive algo order, which is contructed (following the instructions at https://interactivebrokers.github.io/tws-api/ibalgos.html#gsc.tab=0) as:

def MarketOrder(**kwargs):
    order = Order(orderType='MKT', **kwargs)

    return order

def AdaptiveMarketOrder(priority='Normal', **kwargs):
    priority = priority.capitalize()
    valid_priorities = ['Critical', 'Urgent', 'Normal', 'Patient']
    assert priority in valid_priorities, "Invalid priority. Should be in %s." % (valid_priorities)

    order = MarketOrder(**kwargs)
    order.algoStrategy = "Adaptive"
    order.algoParams = []
    adaptivePriority = ib_insync.objects.TagValue('adaptivePriority', priority)
    order.algoParams.append(adaptivePriority)

    return order

class Data:
...
def order(self, contract: ib_insync.Contract, amount: int, style: ib_insync.order.Order, transmit=False):
        order = style
        order.account = self.data.account
        order.action = ('BUY' if amount >= 0 else 'SELL')
        order.totalQuantity = abs(int(amount))
        order.transmit = transmit

        trade = self.broker.placeOrder(contract, order)

        return trade.order
...

data.order(gld, 100, style=AdaptiveMarketOrder(priority='Normal'), transmit=True)

The full traceback:

2017-11-15 02:38:41,724 ib_insync.client ERROR Decode failed
Traceback (most recent call last):
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 223, in _onSocketHasData
    self._decode(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 378, in _decode
    self.decoder.interpret(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 1154, in interpret
    handleInfo.processMeth(self, iter(fields))
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 413, in processOpenOrder
    self.wrapper.openOrder(order.orderId, contract, order, orderState)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/wrapper.py", line 192, in openOrder
    order = Order(**order.__dict__)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/objects.py", line 53, in __init__
    setattr(self, k, v)
AttributeError: 'Order' object has no attribute 'algoParamsCount'
2017-11-15 02:38:41,725 ib_insync.wrapper INFO orderStatus: Trade(contract=Contract(conId=51529211, symbol='GLD', secType='STK', exchange='SMART', primaryExchange='ARCA', currency='USD', localSymbol='GLD', tradingClass='GLD'), order=Order(orderId=149, action='SELL', totalQuantity=100, orderType='MKT', account='U1744631', algoStrategy='Adaptive', algoParams=[TagValue(tag='adaptivePriority', value='Normal')]), orderStatus=OrderStatus(status='Submitted', remaining=100.0, permId=1483409048, clientId=34), fills=[], log=[TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 41, 392626, tzinfo=datetime.timezone.utc), status='PendingSubmit', message=''), TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 41, 723600, tzinfo=datetime.timezone.utc), status='Submitted', message='')])
2017-11-15 02:38:57,046 ib_insync.wrapper INFO position: Position(account='U1744631', contract=Contract(conId=51529211, symbol='GLD', secType='STK', exchange='ARCA', currency='USD', localSymbol='GLD', tradingClass='GLD'), position=524.0, avgCost=121.82631555)
2017-11-15 02:38:57,047 ib_insync.wrapper INFO execDetails: Fill(contract=Contract(conId=51529211, symbol='GLD', secType='STK', exchange='SMART', primaryExchange='ARCA', currency='USD', localSymbol='GLD', tradingClass='GLD'), execution=Execution(execId='00013911.5a0ad7f2.01.01', time='20171115  02:38:56', acctNumber='U1744631', exchange='ISLAND', side='SLD', shares=100.0, price=121.71, permId=1483409048, clientId=34, orderId=149, cumQty=100.0, avgPrice=121.71), commissionReport=CommissionReport(), time=datetime.datetime(2017, 11, 14, 20, 38, 57, 47655, tzinfo=datetime.timezone.utc))
2017-11-15 02:38:57,048 ib_insync.client ERROR Decode failed
Traceback (most recent call last):
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 223, in _onSocketHasData
    self._decode(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 378, in _decode
    self.decoder.interpret(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 1154, in interpret
    handleInfo.processMeth(self, iter(fields))
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 413, in processOpenOrder
    self.wrapper.openOrder(order.orderId, contract, order, orderState)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/wrapper.py", line 192, in openOrder
    order = Order(**order.__dict__)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/objects.py", line 53, in __init__
    setattr(self, k, v)
AttributeError: 'Order' object has no attribute 'algoParamsCount'
2017-11-15 02:38:57,049 ib_insync.wrapper INFO orderStatus: Trade(contract=Contract(conId=51529211, symbol='GLD', secType='STK', exchange='SMART', primaryExchange='ARCA', currency='USD', localSymbol='GLD', tradingClass='GLD'), order=Order(orderId=149, action='SELL', totalQuantity=100, orderType='MKT', account='U1744631', algoStrategy='Adaptive', algoParams=[TagValue(tag='adaptivePriority', value='Normal')]), orderStatus=OrderStatus(status='Filled', filled=100.0, avgFillPrice=121.71, permId=1483409048, lastFillPrice=121.71, clientId=34), fills=[Fill(contract=Contract(conId=51529211, symbol='GLD', secType='STK', exchange='SMART', primaryExchange='ARCA', currency='USD', localSymbol='GLD', tradingClass='GLD'), execution=Execution(execId='00013911.5a0ad7f2.01.01', time='20171115  02:38:56', acctNumber='U1744631', exchange='ISLAND', side='SLD', shares=100.0, price=121.71, permId=1483409048, clientId=34, orderId=149, cumQty=100.0, avgPrice=121.71), commissionReport=CommissionReport(), time=datetime.datetime(2017, 11, 14, 20, 38, 57, 47655, tzinfo=datetime.timezone.utc))], log=[TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 41, 392626, tzinfo=datetime.timezone.utc), status='PendingSubmit', message=''), TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 41, 723600, tzinfo=datetime.timezone.utc), status='Submitted', message=''), TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 57, 47655, tzinfo=datetime.timezone.utc), status='Submitted', message='Fill [email protected]'), TradeLogEntry(time=datetime.datetime(2017, 11, 14, 20, 38, 57, 47655, tzinfo=datetime.timezone.utc), status='Filled', message='')])
2017-11-15 02:38:57,051 ib_insync.client ERROR Decode failed
Traceback (most recent call last):
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 223, in _onSocketHasData
    self._decode(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/client.py", line 378, in _decode
    self.decoder.interpret(fields)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 1154, in interpret
    handleInfo.processMeth(self, iter(fields))
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ibapi-9.73.2-py3.6.egg/ibapi/decoder.py", line 413, in processOpenOrder
    self.wrapper.openOrder(order.orderId, contract, order, orderState)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/wrapper.py", line 192, in openOrder
    order = Order(**order.__dict__)
  File "/home/dias/anaconda3/lib/python3.6/site-packages/ib_insync/objects.py", line 53, in __init__
    setattr(self, k, v)
AttributeError: 'Order' object has no attribute 'algoParamsCount'

The order actually gets filled, but this error is disturbing.
Could you help?

reqHistoricalTicks - Can't find EId with tickerId:0

I'm trying to request historical tick data:

from ib_insync import *
import datetime

ib = IB()
ib.connect('127.0.0.1', 4001, clientId=76)

fdaxContract = Future(localSymbol='FDAX SEP 17', multiplier='25', currency='EUR', exchange='DTB')

start = datetime.datetime(2017, 9, 1, 1, 0, 0)
end = ''
ticks = ib.reqHistoricalTicks(fdaxContract, start, end, 1, 'MIDPOINT', True, False, [])
print(ticks)
print(util.df(ticks))
ERROR:ib_insync.wrapper:Error 300, reqId 0: Can't find EId with tickerId:0
ERROR:ib_insync.client:Peer closed connection

I could request data with:

bars = ib.reqHistoricalData(fdaxContract, endDateTime='', durationStr='30 D', barSizeSetting='1 hour', whatToShow='TRADES', useRTH=True)

any idea what I'm doing wrong?

AttributeError: 'BracketOrder' object has no attribute 'orderId'

Thank you for the great work on this package.
Most order types seem to work fine but having some trouble submitting a new bracket order.

Do you have a working example for bracket orders or a workaround?

ticker = 'AAPL'
contract = Stock(ticker, 'SMART', 'USD')
ib.qualifyContracts(contract)
bracketOrder = ib.bracketOrder("BUY", 75,120,140,100)
bracketTrade = ib.placeOrder(contract, bracketOrder)

AttributeError Traceback (most recent call last)
in ()
3 ib.qualifyContracts(contract)
4 bracketOrder = ib.bracketOrder("BUY", 75,120,140,100)
----> 5 bracketTrade = ib.placeOrder(contract, bracketOrder)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ib_insync/ib.py in placeOrder(self, contract, order)
517 status changes, fills, etc.
518 """
--> 519 orderId = order.orderId or self.client.getReqId()
520 self.client.placeOrder(orderId, contract, order)
521 now = datetime.datetime.now(datetime.timezone.utc)

AttributeError: 'BracketOrder' object has no attribute 'orderId'

Thank you!

positions of a particular contract?

hello
ib.positions() lists all contracts under the account. I was wondering if there is any way to get the position of a particular contract. Thanks.

class IB: vs class IB(Wrapper, Client)

Is there a functional reason why the switch was made from sub-classing directly to storing in attributes?

ib_insync:

class IB:

    def __init__(self):
        self.wrapper = Wrapper()
        self.client = Client(self.wrapper)

vs the standard ibapi:

class IB(Wrapper, Client)
        
    def __init__(self):
        Wrapper.__init__(self)
        Client.__init__(self, wrapper=self)

Is there a reason that depends on the asyncio integration?

Orders and Trades

What is the difference between an Order and a Trade?

If ib.openTrades() returned several Trade instances with order status pendingSubmit, and you quit the script, is it still possible to retrieve those trades and find their order status?

higher level functions for requesting historical data

thanks for setting up another python library for interactive brokers.

Right now it's possible to request historical data on bars and tick data. The main problem is that Interactive Brokers is limiting the look-back for historical data. Here's a list of limitations:
http://www.tradingsoftwarelab.com/jtwsdump/table.html
So the lowest level on bars to request is seconds and here you can look-back a maximum of 2000 seconds (~30min).
But it's possible to request a few month of tick data. You can request a maximum of 1000 ticks for each tick-request.
I'm not familiar with python yet, so I just cannot write it on my own yet and make a pull request, but here's the pseudo code:

  • make a tick request for a given start date
  • take the most recent timestamp received from this request and set it as the new start date for the second request. Loop until now. You will struggle with some pacing violations and you'll have to wait for them to release again. Best is to save all incoming tick data on a csv file for faster lookup.
  • take the tick data file and build bars out of them in the timeframe you want: 1-sec, 1-min, 22-min, 1hour. IBs data are not the best, so perhaps there is the need to make some winsorizing on them.

no exception handling on date parsing

If you try to request a head timestamp for 'AAL' - IB will give some uncommon date format and there is no handler to bypass it, so the app just hangs. Awaiting future result I guess.

ValueError: time data '2922690551202 16:47:04' does not match format '%Y%m%d %H:%M:%S'

code:

ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)

partial message:

File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '2922690551202 16:47:04' does not match format '%Y%m%d %H:%M:%S'

RT Trade Volume

Hi,

I would like to access RT Trade Volume from real time Ticker data . I couldn't find the field as a param in the code. So was wondering how to extract the same?

Regards,
Vijay Raajaa G S

disconnect issue

Sorry I would need to get your attention on closed issue #10.

Could we reopen it?

TypeError: onError() takes 4 positional arguments but 5 were given

Using Watchdog caused this error to show in logs.

I think that it may be related to:

  • Errors and warnings will now log the contract they apply to
  • IB error() callback signature changed to include contract
Traceback (most recent call last):
  File "(...)/venv/lib/python3.6/site-packages/ib_insync/wrapper.py", line 129, in _handleEvent
    cb(*args)
TypeError: onError() takes 4 positional arguments but 5 were given

TickType

Hi there,

When listening to every tick as they come in using self.ib.setCallback('pendingTickers', onPendingTickers), an example of a tick received is

TickData(time=datetime.datetime(2017, 12, 18, 22, 43, 25, 352791, tzinfo=datetime.timezone.utc), tickType=2, price=1.17828, size=4000000)

TickData(time=datetime.datetime(2017, 12, 18, 22, 43, 25, 352791, tzinfo=datetime.timezone.utc), tickType=3, price=1.17828, size=4000000)

Why are there 2 TickData with the same properties, but differing only in tickType?

What are tickType 2 and 3 referring to?

Which one of the TickData gives me the last traded price?

ib.fills() returns incorrect results for partially filled orders for multi-leg option COMBO trades

I developed a script TradeLogIB which uses ib_insync to download a list of option trades from IB and save them to a .csv file. Basically what this script does is:

        for fill in ib.fills():
            if fill.contract.secType != 'OPT':
                continue
            ....

Very compact and elegant code thanks to ib_insync. What I noticed TradeLogIB script does not save trades for a partically filled multi-leg option orders. I have to cancel an order or wait till it is completely filled, and only then trades from this order can be dumped using my script.

In contract version of TradeLogIB that worked with Python 2.7 + IbPy package works quite well, and is able to dump trades for a partially filled orders. So I know something is wrong with ib.fills() in ib_insync.

Here are the results of my research. When multi-leg option order is partially filled, ib.fills() returns something like this:
ib_insync_fills1

Notice a list of Fill() structures containing the same Contract() with the same conId and secType='BAG' indicating this is a contract for a multi-leg COMBO order.

And after the multi-leg option order is filled, ib.fills() finally returns the following:
ib_insync_fills2

This is a correct return result, what I expect it to return in both cases. Notice the first Fill() contains a Contract() with secType='BAG' (COMBO order). And second and third lines contains a Contract() with secType='OPT' (fills for individual option legs for a COMBO order above).

At this point I knew something was wrong with the Contract() field in the Fill() structure when order was in a partially filled state.

Now, let's take a look at wrapper.py at execDetails() implementation in ib_insync:

    @iswrapper
    def execDetails(self, reqId, contract, execution):
        # must handle both live fills and responses to reqExecutions
        key = (execution.clientId, execution.orderId)             # <--------- (1)
        trade = self.trades.get(key)
        if trade:
            contract = trade.contract                             # <--------- (2) BUGBUG: 
        else:
            contract = Contract(**contract.__dict__)
        execId = execution.execId
        execution = Execution(**execution.__dict__)
        fill = Fill(contract, execution, CommissionReport(), self.lastTime)

execDetails() merges self.trades.contract (opened orders) with the contract data that is passed as a parameter (see linke marked (2) BUGBUG:). And it uses a key consisting from clientId and orderId (see line marked (1) in the code above).

The problem is that multi-leg option COMBO orders contain several Fill()'s, each one with it's own Contract(). And all these Contract()'s have the same orderId and clientId as well. Some of the contracts are secType='BAG', others are secType='OPT' (see screenshot above). But orderId is the same as all these Contract()'s and Fill()'s belong to the same COMBO order.

So, when execDetails() decides not to use a contract passed as a function argument, but instead take the trade.contract based on key==(execution.clientId, execution.orderId):

        if trade:
            contract = trade.contract                             # <--------- (2) BUGBUG: 

It erroneously substitutes real Contract(secType='OPT') with a Contract(secType='BAG') from self.trades structure. And that causes problems.

Сonclusion: execDetails() can not use clientId / orderId pair as a key to determine a Contract() as it does not work correctly for a multi-leg option orders.

As a proof of concept I developed a fix to verify it solves the issue. If I rewrite the execDetails() code to throw out the offensive lines:

    @iswrapper
    def execDetails(self, reqId, contract, execution):
        # must handle both live fills and responses to reqExecutions
        key = (execution.clientId, execution.orderId)
        trade = self.trades.get(key)
        contract = Contract(**contract.__dict__)
        execId = execution.execId
        execution = Execution(**execution.__dict__)
        fill = Fill(contract, execution, CommissionReport(), self.lastTime)

TradeLogIB script starts to work as expected and correctly dumps partially filled multi-leg orders.

I do not know if this change breaks anything else, as it is not clear to me what the original intention was in replacing the contract in the Fill() structure. So, I am going to submit my patch as a pull request, and it is up to the ib_insync developer to decide how to fix this correctly.

P.S. I've also considered other methods to fix this. For example to use the key that contains "clientId, orderId, contract Id":

 key = (execution.clientId, execution.orderId, contract.conId)
```But I found that at least in one place in orderStatus() routine there is no access to a contract at all. And orderStatus() calculates a key.

Reduce Verbosity

Is there a way to reduce the verbosity, especially when doing ib.placeOrder?

Calling that function prints a lot of DEBUG level details that I will like to disable.

Eg: 2017-12-22 01:27:51 - DEBUG - decoder.py:1121 - arg USD type <class 'str'>

Parse ib.positions

So I get this list back from interactive brokers.

`b = IB()
ib.connect('127.0.0.1', 7497, clientId=2)

data = ib.positions()
print((data))
print(type(data))`

The data comes back as , but here is the response.

[Position(account='DUC00074', contract=Contract(conId=43645865, symbol='IBKR', secType='STK', exchange='NASDAQ', currency='USD', localSymbol='IBKR', tradingClass='NMS'), position=2800.0, avgCost=39.4058383), Position(account='DUC00074', contract=Contract(conId=72063691, symbol='BRK B', secType='STK',exchange='NYSE', currency='USD', localSymbol='BRK B', tradingClass='BRK B'), position=250.0, avgCost=163.4365424)]

I have got this far:

for x in data: print(type(x)) print(objects) #<class 'ib_insync.objects.Position'>
But I have no idea as to how I would parse and then dump into a DB, anything after Position(... So to be really clear, I don't know how I would parse, like I would say in php / json. Also what type of class is <class 'ib_insync.objects.Position'>



ib.openOrders() does not return pending orders (with "Master API client ID" )

I would like to get existing GoodTillCancel STOP Limit orders and update the limit price or perhaps cancel some of them.

from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=99)
ib.openOrders()
#Out[11]: []

ib.orders()
# Out[12]: []
  • Read-Only API unchecked
  • Master API client ID = 99

Did I miss anything? Thanks

typo

I think there is a typo for a logger expression, line 136 in wrapper.py, it should be exception instead of execption.

def _handleEvent(self, eventName, *args):
    # invoke optional callback
    cb = self._callbacks.get(eventName)
    if cb:
        try:
            cb(*args)
        except Exception:
            _logger.execption('Event %s(%s)', eventName, args)

how to replace ibapi.client.EClient with ib_insync.client.Client?

I replaced ibapi.client.EClient with ib_insync.client.Client like the following.

from ibapi.wrapper import EWrapper
# from ibapi.client import EClient
from ib_insync import Client
EClient = Client

class MyIBWrapper(EWrapper, EClient):

    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, self)
        EClient.reset(self)

......

BUT no any callbacks(tickPrice, tickSize) received in MyIBWrapper. Then, how to replace ibapi.client.EClient with ib_insync.client.Client? May you write some samples for this? Thanks.

Get a runtime error when trying to put this into Flask-restful

I try to make this library a rest wrapper but get a run time error when the code try to connect IB gateway. It is good without rest.

RuntimeError: There is no current event loop in thread 'Thread-1'.

`import asyncio
import json
import datetime
from time import time as timetime

from flask import Flask, request, jsonify
from flask_restful import Resource, Api, reqparse, abort
from flask.json import JSONEncoder

from ib_insync import *

class datetimeJSONEncoder(JSONEncoder):

def default(self, obj):
    if isinstance(obj, datetime.datetime) | \
            isinstance(obj, datetime.date) | \
            isinstance(obj, datetime.time):

        return int(timetime())

    return JSONEncoder.default(self, obj)

app = Flask(name)
api = Api(app)

class IbHistAPI(Resource):

def get(self, ibAssetCodes: str, lookback: int):
    iba = IB()
    iba.connect(port=7496, clientId=666, host='127.0.0.1')

    data = {}

    return jsonify(data)

api.add_resource(IbHistAPI, '/ib/getAssetHistory/string:ibAssetCodes/int:lookback')

if name == 'main':

app.run(debug=True)`

Any could help me to figure out what is the reason for this? Thanks

Regards,
ZHe

Historical Prices for Multiple Securities

Ewald, thanks so much for this package. I'm a beginner with Python and found IB's API unusable without it. For my analysis, I needed a dataframe of multiple securities. I didn't see that option so created a loop. I'm not sure if this would be of use to others and am sure you'd be able to code it more efficiently, but wanted to share in case you'd like to add having multiple securities to your notebook examples.

`symlist = (universe) #universe is a list created in a separate cell
df = pd.DataFrame()

for x in symlist:
contract = Stock(x, 'SMART', 'USD')
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='250 D',
barSizeSetting='1 day',
whatToShow='ADJUSTED_LAST', #use ADJUSTED_LAST for stocks, MIDPOINT for currencies
useRTH=True,
formatDate=1)
data = util.df(bars)
data = data.set_index('date')
data = data['close']
data = data.to_frame(x)
df = pd.concat([df, data], axis=1)`

disconnect method

This is probably a silly question so apologize in advance..:
I cannot seem to be able to have the disconnect method work - also, when looking into the source code I am not sure how it should work:
In the ib.py source file, the .disconnect() method is an overload from the .disconnect() in client.py.
In client.py, looking for the method using ctrl-f i find it in the Connection class. The Connection class is in turn referenced in the client proper in the connect_async method, but is declared as self.conn = Connection(host, port). This should be that the deconnect() method is at self,conn.disconnect()?
For me using
tws=Client()
tws.connect(.....)
tws.disconnect() # doesnt work
tws.conn.disconnect() # also doesnt work

I'm using the jupyter notebook, so it is somewhat more important to be able to properly explicitely disconnect()

can't get past import statement.

I cant get past the import statement:

from ib_insync import *

File "C:\Users\EG_User\Miniconda2\lib\site-packages\ib_insync\objects.py", line 56
kwargs = ', '.join(f'{k}={v!r}' for k, v in self.nonDefaults().items())
^
SyntaxError: invalid syntax

How can I retrieve FuturesOption() prices?

Hello! First of all I want to thank you for this beautiful piece of software.
Would you please be so kind and give me an example of how to retrieve FuturesOptions prices and greeks? Or if you could add that to your notebooks that would be great.
Am Looking at Option on the 10y Treasury Note Future (IB code is 'ZN'). Tried this to no avail:
contract = FuturesOption('ZN' , '20170922', 127.5, 'C', 'ECBOT')
Your help will be much appreciated.

Error validating request:-'bY' : cause - The API interface is currently in Read-Only mode.

@erdewit Thanks for sharing this new Python framework. I just gave your example a try, but I got the following error. Does it require write access even for downloading historical data? The reason I set my gateway to read-only mode is to prevent any mistake because I am not ready to place any orders through the API yet. Thanks!

ERROR:ib_insync.wrapper:Error 321, reqId 2147483647: Error validating request:-'bY' : cause - The API interface is currently in Read-Only mode.
ERROR:ib_insync.wrapper:Error 321, reqId 2147483647: Error validating request:-'a0' : cause - The account code is required for this operation.

from ib_insync import *

ib = IB()
ib.connect('127.0.0.1', 4003, clientId=1)

bars = ib.reqHistoricalData(
        contract=Stock('TSLA', 'SMART', 'USD'),
        endDateTime='',
        durationStr='30 D',
        barSizeSetting='1 hour',
        whatToShow='TRADES',
        useRTH=True)

print(bars)

TWS connection lost

hello

Just wondering if there is any good solution do deal with the issue of TWS losing connection when I am getting data and executing orders inside a loop.

Thanks.

Calling ib.accountValues() does not update values.

Calling ib.accountValues() does not update values in sync. Values are updated only upon connection. Tried both in TWS and IBG using real trading account with real-time data. Tags checked: 'EquityWithLoanValue', 'StockMarketValue'.

ib.accountSummary() does not update either. Only on the first run.

TWS Build 968.2d, Oct 10, 2017 2:59:29 PM

Does not detect newest version of ibapi

When cloning the repo and doing 'python setup.py install' (on Windows, no pip) I get:
"Old version of ibapi module detected. The newest version from http://interactivebrokers.github.io is required".
I have installed ibapi version 9.73.06 (as verified in API_VersionNum.txt), the docs say required is 'only' 9.73.03
Thanks for this beautiful package!

Manual orders order status

The IB API allows to forward messages related to manual orders to a designated client, identified by the "Master API client ID" in TWS (or IB gateway) settings. When the ib_insync client is identified as the designated client, the messages received are not correctly recognized, I see the following error reported

ERROR:ib_insync.wrapper:orderStatus: No order found for orderId 0 and clientId 0
ERROR:ib_insync.wrapper:orderStatus: No order found for orderId 0 and clientId 0
ERROR:ib_insync.wrapper:orderStatus: No order found for orderId 0 and clientId 0

There are multiple errors because there are multiple status messages for each order. Surprisingly all orders seem also tagged with the same orderId, i.e. a later message will get the same orderId. It is my first time experimenting with such a designated client, so I am not really sure about the expected format of the messages, i.e. how can messages be grouped meaningfully if they all have the same orderId.

I am not sure what would be the best method to handle these, possibly:

  • filter them out completely, so that no error message is reported
  • put them in a predefined bucket for orderId 0
  • something else?

coroutine 'Watchdog.watchAsync' was never awaited

/usr/lib/python3.6/socketserver.py:544: RuntimeWarning:

coroutine 'Watchdog.watchAsync' was never awaited

ib_insync 0.9.3

I am getting this warning when using new Watchdog. It uses one of 3 IBs that are connected all the time, to keep TWS alive with ib-controller.

Watchdog and other 2 IBs are run in separate threading.Thread that is the live algorithm using those clients.

First IBController is created:

self.controller = IBController(APP='GATEWAY',  # 'TWS' or 'GATEWAY'
                                   TWS_MAJOR_VRSN=config.get('TWSMajorVersion'),
                                   TRADING_MODE=config.get('TWSTradingMode'),
                                   IBC_INI=config.get('IBCIniPath'),
                                   IBC_PATH=config.get('IBCPath'),
                                   TWS_PATH=config.get('TWSPath'),
                                   LOG_PATH=config.get('IBCLogPath'),
                                   TWSUSERID='',
                                   TWSPASSWORD='',
                                   JAVA_PATH='',
                                   TWS_CONFIG_PATH='')

Then Watchdog is initialized and started:

super().__init__(controller=self.controller,
                 host='127.0.0.1',
                 port='4002',
                 clientId=self.client_id,
                 connectTimeout=connect_timeout,
                 appStartupTime=app_startup_time,
                 appTimeout=app_timeout,
                 retryDelay=retry_delay)
super().start()

Is there anything else that I have to do?

sample code in bar_data notebook is broken

Setup

  • pip install (miniconda, python 3.6)
  • running on Mac TWS build 967.1f
  • API version 9.73

The FOREX example in README.rst works as expected. But not for the TSLA example. See output below

In [4]: from ib_insync import *
   ...: 

In [5]: ib = IB()
   ...: ib.connect('127.0.0.1', 7497, clientId=14)
   ...: 
Out[5]: <IB connected to 127.0.0.1:7497 clientId=14>

In [6]: contract = Stock('TSLA', 'SMART', 'USD')
   ...: 
   ...: ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
   ...: 
Out[6]: datetime.datetime(2010, 6, 29, 8, 0)

In [7]: bars = ib.reqHistoricalData(
   ...:         contract,
   ...:         endDateTime='',
   ...:         durationStr='60 D',
   ...:         barSizeSetting='1 hour',
   ...:         whatToShow='TRADES',
   ...:         useRTH=True,
   ...:         formatDate=1)
   ...:         
ERROR:ib_insync.wrapper:Error 162, reqId 3: Historical Market Data Service error message:No market data permissions for ISLAND STK

In addition, the ib.reqHeadTimeStamp no longer works after the error above.

In [8]: ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
ERROR:ib_insync.wrapper:Error 354, reqId 4: Requested market data is not subscribed.

Finding order details using OrderId

After using ib.placeOrder to place a Limit order, I get back an object containing an orderId.

How can the order details be retrieved again using it's orderId? For example, I can have a new script that check the order status every 5 minutes.

historical bars in exchange timezone

is there a way to get the data based on exchange timezone, e.g. Eastern Time for SPX index ?

bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='300 S',
barSizeSetting='30 secs',
whatToShow='TRADES',
useRTH=True,
formatDate=1)

The above gives me times of my local time instead of exchange time, even if i do not click the 'show data in user time zone' box in the chart parameters settings of TWS chart.

Unfilled params

Intellij IDEA code inspection indicates incorrect call arguments for the following two methods:

  • def exerciseOptions (ib.py, line 798): parameter 'override' unfilled
  • def reqHistogramDataAsync (ib.py, line 1007): parameter 'timePeriod' unfilled

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.