Skip to content

Commit

Permalink
flake8 compliant code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
erdewit committed Sep 28, 2018
1 parent 1b6ff9c commit 7f7761e
Show file tree
Hide file tree
Showing 13 changed files with 701 additions and 538 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
ib_insync/__pycache__
dist
build
examples
.vscode
.idea
.settings
.spyproject
Expand Down
7 changes: 7 additions & 0 deletions dist.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash
pushd docs
make html
popd
rm -Rf dist/*
python3 setup.py sdist bdist_wheel
python3 -m twine upload dist/*
31 changes: 20 additions & 11 deletions ib_insync/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,14 @@ def connect(self, host, port, clientId, timeout=2):
that is not in use elsewhere.
When timeout is not zero, asyncio.TimeoutError
is raised if the connection is not established within the timeout period.
is raised if the connection is not established
within the timeout period.
"""
util.syncAwait(self.connectAsync(host, port, clientId, timeout))

async def connectAsync(self, host, port, clientId, timeout=2):
self._logger.info(
f'Connecting to {host}:{port} with clientId {clientId}...')
f'Connecting to {host}:{port} with clientId {clientId}...')
self.host = host
self.port = port
self.clientId = clientId
Expand Down Expand Up @@ -191,7 +192,9 @@ def sendMsg(self, msg):
if not self._isThrottling:
self._isThrottling = True
self._logger.warn('Started to throttle requests')
loop.call_at(times[0] + Client.RequestsInterval, self.sendMsg, None)
loop.call_at(
times[0] + Client.RequestsInterval,
self.sendMsg, None)
else:
if self._isThrottling:
self._isThrottling = False
Expand All @@ -205,7 +208,8 @@ def _onSocketConnected(self):
self._logger.info('Connected')
# start handshake
msg = b'API\0'
msg += self._prefix(b'v%d..%d' % (100, 142))
versionRange = (100, 142)
msg += self._prefix(b'v%d..%d' % versionRange)
self.conn.sendMsg(msg)
self.decoder = ibapi.decoder.Decoder(self.wrapper, None)

Expand All @@ -232,7 +236,8 @@ def _onSocketHasData(self, data):
self._numMsgRecv += 1

if debug:
self._logger.debug('<<< %s', ','.join(f.decode() for f in fields))
self._logger.debug(
'<<< %s', ','.join(f.decode() for f in fields))

if not self.serverVersion_ and len(fields) == 2:
# this concludes the handshake
Expand All @@ -248,7 +253,7 @@ def _onSocketHasData(self, data):
# decode and handle the message
try:
self._decode(fields)
except:
except Exception:
self._logger.exception('Decode failed')

if self._tcpDataProcessed:
Expand Down Expand Up @@ -312,22 +317,26 @@ def _decode(self, fields):
# bypass the ibapi decoder for ticks for more efficiency
if msgId == 2:
_, _, reqId, tickType, size = fields
self.wrapper.tickSize(int(reqId), int(tickType), int(size))
self.wrapper.tickSize(
int(reqId), int(tickType), int(size))
return
elif msgId == 1:
if self._priceSizeTick:
_, _, reqId, tickType, price, size, _ = fields
self._priceSizeTick(int(reqId), int(tickType),
self._priceSizeTick(
int(reqId), int(tickType),
float(price), int(size))
return
elif msgId == 12:
_, _, reqId, position, operation, side, price, size = fields
self.wrapper.updateMktDepth(int(reqId), int(position),
self.wrapper.updateMktDepth(
int(reqId), int(position),
int(operation), int(side), float(price), int(size))
return
elif msgId == 46:
_, _, reqId, tickType, value = fields
self.wrapper.tickString(int(reqId), int(tickType), value.decode())
self.wrapper.tickString(
int(reqId), int(tickType), value.decode())
return

# snoop for nextValidId and managedAccounts response,
Expand Down Expand Up @@ -372,7 +381,7 @@ def _onConnectionCreated(self, future):
def connect(self):
loop = asyncio.get_event_loop()
coro = loop.create_connection(lambda: Socket(self),
self.host, self.port)
self.host, self.port)
future = asyncio.ensure_future(coro)
future.add_done_callback(self._onConnectionCreated)
return future
Expand Down
56 changes: 35 additions & 21 deletions ib_insync/contract.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ibapi.contract
import ibapi.contract

from ib_insync.objects import Object

Expand All @@ -13,7 +13,7 @@ class Contract(Object):
arguments. To simplify working with contracts, there are also more
specialized contracts that take optional positional arguments.
Some examples::
Contract(conId=270639)
Stock('AMD', 'SMART', 'USD')
Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ')
Expand All @@ -25,8 +25,8 @@ class Contract(Object):
"""
defaults = {'secType': '', **ibapi.contract.Contract().__dict__}
__slots__ = list(defaults.keys()) + \
['comboLegsCount', 'underCompPresent', 'deltaNeutralContractPresent',
'secIdListCount'] # bug in decoder.py
['comboLegsCount', 'underCompPresent', 'deltaNeutralContractPresent',
'secIdListCount'] # bug in decoder.py

@staticmethod
def create(**kwargs):
Expand Down Expand Up @@ -56,13 +56,13 @@ def create(**kwargs):
def isHashable(self):
"""
See if this contract can be hashed by conId.
Note: Bag contracts always get conId=28812380 and ContFutures get the
same conId as the front contract, so these contract types are
not hashable.
"""
return self.conId and self.conId != 28812380 and \
self.secType not in ('BAG', 'CONTFUT')
self.secType not in ('BAG', 'CONTFUT')

def __eq__(self, other):
return self.isHashable() and isinstance(other, Contract) and \
Expand All @@ -89,17 +89,20 @@ class Stock(Contract):
__slots__ = ()

def __init__(self, symbol='', exchange='', currency='', **kwargs):
Contract.__init__(self, secType='STK', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)
Contract.__init__(
self, secType='STK', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)


class Option(Contract):
__slots__ = ()

def __init__(self, symbol='', lastTradeDateOrContractMonth='',
def __init__(
self, symbol='', lastTradeDateOrContractMonth='',
strike='', right='', exchange='', multiplier='',
currency='', **kwargs):
Contract.__init__(self, 'OPT', symbol=symbol,
Contract.__init__(
self, 'OPT', symbol=symbol,
lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,
strike=strike, right=right, exchange=exchange,
multiplier=multiplier, currency=currency, **kwargs)
Expand All @@ -108,10 +111,12 @@ def __init__(self, symbol='', lastTradeDateOrContractMonth='',
class Future(Contract):
__slots__ = ()

def __init__(self, symbol='', lastTradeDateOrContractMonth='',
def __init__(
self, symbol='', lastTradeDateOrContractMonth='',
exchange='', localSymbol='', multiplier='',
currency='', **kwargs):
Contract.__init__(self, 'FUT', symbol=symbol,
Contract.__init__(
self, 'FUT', symbol=symbol,
lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,
exchange=exchange, localSymbol=localSymbol,
multiplier=multiplier, currency=currency, **kwargs)
Expand All @@ -120,23 +125,27 @@ def __init__(self, symbol='', lastTradeDateOrContractMonth='',
class ContFuture(Contract):
__slots__ = ()

def __init__(self, symbol='', exchange='', localSymbol='', multiplier='',
def __init__(
self, symbol='', exchange='', localSymbol='', multiplier='',
currency='', **kwargs):
Contract.__init__(self, 'CONTFUT', symbol=symbol,
Contract.__init__(
self, 'CONTFUT', symbol=symbol,
exchange=exchange, localSymbol=localSymbol,
multiplier=multiplier, currency=currency, **kwargs)


class Forex(Contract):
__slots__ = ()

def __init__(self, pair='', exchange='IDEALPRO',
def __init__(
self, pair='', exchange='IDEALPRO',
symbol='', currency='', **kwargs):
if pair:
assert len(pair) == 6
symbol = symbol or pair[:3]
currency = currency or pair[3:]
Contract.__init__(self, 'CASH', symbol=symbol,
Contract.__init__(
self, 'CASH', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)

def __repr__(self):
Expand All @@ -161,23 +170,26 @@ class Index(Contract):
__slots__ = ()

def __init__(self, symbol='', exchange='', currency='', **kwargs):
Contract.__init__(self, 'IND', symbol=symbol,
Contract.__init__(
self, 'IND', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)


class CFD(Contract):
__slots__ = ()

def __init__(self, symbol='', exchange='', currency='', **kwargs):
Contract.__init__(self, 'CFD', symbol=symbol,
Contract.__init__(
self, 'CFD', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)


class Commodity(Contract):
__slots__ = ()

def __init__(self, symbol='', exchange='', currency='', **kwargs):
Contract.__init__(self, 'CMDTY', symbol=symbol,
Contract.__init__(
self, 'CMDTY', symbol=symbol,
exchange=exchange, currency=currency, **kwargs)


Expand All @@ -191,10 +203,12 @@ def __init__(self, **kwargs):
class FuturesOption(Contract):
__slots__ = ()

def __init__(self, symbol='', lastTradeDateOrContractMonth='',
def __init__(
self, symbol='', lastTradeDateOrContractMonth='',
strike='', right='', exchange='', multiplier='',
currency='', **kwargs):
Contract.__init__(self, 'FOP', symbol=symbol,
Contract.__init__(
self, 'FOP', symbol=symbol,
lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,
strike=strike, right=right, exchange=exchange,
multiplier=multiplier, currency=currency, **kwargs)
Expand Down
20 changes: 10 additions & 10 deletions ib_insync/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class Event:
"""
Enable event passing between loosely coupled compenents.
An event contains a list of callables (the listener slots) that are
called in order when the event is emitted.
"""
Expand All @@ -21,17 +21,17 @@ def connect(self, c, weakRef=True, hiPriority=False):
"""
Connect the callable c to this event.
The ``+=`` operator can be used as a synonym for this method.
When ``weakRef=True`` the callable can be garbage collected upon which
it will be automatically disconnected from this event;
it will be automatically disconnected from this event;
When ``weakRef=False`` a strong reference to the callable will be kept.
With ``hiPriority=True`` the callable will be placed in the first slot,
otherwise it will be placed last.
"""
if c in self:
raise ValueError(f'Duplicate callback: {c}')

obj, func = self._split(c)
if weakRef and hasattr(obj, '__weakref__'):
ref = weakref.ref(obj, self._onFinalize)
Expand All @@ -49,7 +49,7 @@ def disconnect(self, c):
"""
Disconnect the callable from this event.
The ``-=`` operator can be used as a synonym for this method.
It's okay (i.e. not considered an error) if the callable is
already not connected.
"""
Expand Down Expand Up @@ -97,7 +97,7 @@ def init(obj, eventNames):
__iadd__ = connect
__isub__ = disconnect
__call__ = emit

def __repr__(self):
return f'Event<{self.name}, {self.slots}>'

Expand All @@ -122,11 +122,11 @@ def _split(self, c):
"""
Split given callable in (object, function) tuple.
"""
if type(c) is types.FunctionType:
if isinstance(c, types.FunctionType):
t = (None, c)
elif type(c) is types.MethodType:
elif isinstance(c, types.MethodType):
t = (c.__self__, c.__func__)
elif type(c) is types.BuiltinMethodType:
elif isinstance(c, types.BuiltinMethodType):
if type(c.__self__) is type:
# built-in method
t = (c.__self__, c)
Expand All @@ -138,7 +138,7 @@ def _split(self, c):
else:
raise ValueError(f'Invalid callable: {c}')
return t

def _onFinalize(self, ref):
for slot in self.slots:
if slot[1] is ref:
Expand Down
14 changes: 8 additions & 6 deletions ib_insync/flexreport.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,24 @@
_logger = logging.getLogger('ib_insync.flexreport')


class FlexError(Exception): pass
class FlexError(Exception):
pass


class FlexReport:
"""
Download and parse IB account statements via the Flex Web Service.
https://www.interactivebrokers.com/en/software/am/am/reports/flex_web_service_version_3.htm
To obtain a ``token`` in account management, go to
Reports -> Settings -> Flex Web Service.
Tip: choose a 1 year expiry.
To obtain a ``queryId``: Create and save a query with
Report -> Activity -> Flex Queries or
Report -> Trade Confirmations -> Flex Queries.
Find the query ID (not the query name).
A large query can take a few minutes. In the weekends the query servers
can be down.
"""
Expand All @@ -53,7 +54,7 @@ def topics(self):
def extract(self, topic: str, parseNumbers=True) -> list:
"""
Extract items of given topic and return as list of objects.
The topic is a string like TradeConfirm, ChangeInDividendAccrual,
Order, etc.
"""
Expand Down Expand Up @@ -82,7 +83,8 @@ def download(self, token, queryId):
"""
Download report for the given ``token`` and ``queryId``.
"""
url = ('https://gdcdyn.interactivebrokers.com'
url = (
'https://gdcdyn.interactivebrokers.com'
f'/Universal/servlet/FlexStatementService.SendRequest?'
f't={token}&q={queryId}&v=3')
resp = urlopen(url)
Expand Down
Loading

0 comments on commit 7f7761e

Please sign in to comment.