Skip to content

Commit

Permalink
Stricter flake8 conformity and CI integration
Browse files Browse the repository at this point in the history
  • Loading branch information
erdewit committed Dec 29, 2019
1 parent d59c042 commit 2001836
Show file tree
Hide file tree
Showing 16 changed files with 272 additions and 323 deletions.
8 changes: 6 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
dist: xenial # required for Python >= 3.7
dist: bionic # ubuntu 18.04
language: python
python:
- "3.6"
- "3.7"
- "3.8"
- "nightly"
install:
- pip install flake8 mypy
script:
- python setup.py build install

- python setup.py flake8
- mypy -p ib_insync
34 changes: 12 additions & 22 deletions ib_insync/client.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import struct
"""Socket client for communicating with Interactive Brokers."""

import asyncio
import io
import logging
import struct
import time
import io
from collections import deque
from typing import List

from eventkit import Event

from .contract import Contract
from .connection import Connection
from .contract import Contract
from .decoder import Decoder
from .objects import ConnectionStats
from .util import run, UNSET_INTEGER, UNSET_DOUBLE
from .util import UNSET_DOUBLE, UNSET_INTEGER, run

__all__ = ['Client']

Expand Down Expand Up @@ -136,15 +138,11 @@ def isConnected(self):
return self.connState == Client.CONNECTED

def isReady(self) -> bool:
"""
Is the API connection up and running?
"""
"""Is the API connection up and running?"""
return self._readyEvent.is_set()

def connectionStats(self) -> ConnectionStats:
"""
Get statistics about the connection.
"""
"""Get statistics about the connection."""
if not self.isReady():
raise ConnectionError('Not connected')
return ConnectionStats(
Expand All @@ -154,19 +152,15 @@ def connectionStats(self) -> ConnectionStats:
self._numMsgRecv, self.conn.numMsgSent)

def getReqId(self) -> int:
"""
Get new request ID.
"""
"""Get new request ID."""
if not self.isReady():
raise ConnectionError('Not connected')
newId = self._reqIdSeq
self._reqIdSeq += 1
return newId

def getAccounts(self) -> List[str]:
"""
Get the list of account names that are under management.
"""
"""Get the list of account names that are under management."""
if not self.isReady():
raise ConnectionError('Not connected')
return self._accounts
Expand Down Expand Up @@ -233,19 +227,15 @@ async def connect():
raise

def disconnect(self):
"""
Disconnect from IB connection.
"""
"""Disconnect from IB connection."""
self.connState = Client.DISCONNECTED
if self.conn is not None:
self._logger.info('Disconnecting')
self.conn.disconnect()
self.reset()

def send(self, *fields):
"""
Serialize and send the given fields using the IB socket protocol.
"""
"""Serialize and send the given fields using the IB socket protocol."""
if not self.isConnected():
raise ConnectionError('Not connected')

Expand Down
7 changes: 4 additions & 3 deletions ib_insync/connection.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Event-driven socket connection."""

import asyncio


class Connection(asyncio.Protocol):
"""
Socket connection.
"""
"""Socket connection."""

def __init__(self, host, port):
self.host = host
self.port = port
Expand Down
23 changes: 8 additions & 15 deletions ib_insync/contract.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""Financial instrument types used by Interactive Brokers."""

from typing import List, Optional

from ib_insync.objects import ComboLeg, DeltaNeutralContract, Object
Expand Down Expand Up @@ -77,6 +79,7 @@ class Contract(Object):
deltaNeutralContract (DeltaNeutralContract): Delta and underlying
price for Delta-Neutral combo orders.
"""

defaults = dict(
secType='',
conId=0,
Expand Down Expand Up @@ -319,9 +322,7 @@ def __repr__(self):
__str__ = __repr__

def pair(self) -> str:
'''
Short name of pair.
'''
"""Short name of pair."""
return self.symbol + self.currency


Expand Down Expand Up @@ -386,9 +387,7 @@ class Bond(Contract):
__slots__ = ()

def __init__(self, **kwargs):
"""
Bond.
"""
"""Bond."""
Contract.__init__(self, 'BOND', **kwargs)


Expand Down Expand Up @@ -427,27 +426,21 @@ class MutualFund(Contract):
__slots__ = ()

def __init__(self, **kwargs):
"""
Mutual fund.
"""
"""Mutual fund."""
Contract.__init__(self, 'FUND', **kwargs)


class Warrant(Contract):
__slots__ = ()

def __init__(self, **kwargs):
"""
Warrant option.
"""
"""Warrant option."""
Contract.__init__(self, 'WAR', **kwargs)


class Bag(Contract):
__slots__ = ()

def __init__(self, **kwargs):
"""
Bag contract.
"""
"""Bag contract."""
Contract.__init__(self, 'BAG', **kwargs)
29 changes: 13 additions & 16 deletions ib_insync/decoder.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
"""Deserialize and dispatch messages."""

import logging

from .contract import Contract
from .order import Order, OrderCondition
from .objects import (
ContractDetails, ContractDescription, ComboLeg, OrderComboLeg,
OrderState, TagValue, Execution, CommissionReport,
BarData, DeltaNeutralContract, SoftDollarTier, FamilyCode,
SmartComponent, DepthMktDataDescription, NewsProvider,
TickAttribBidAsk, TickAttribLast, HistogramData, PriceIncrement,
HistoricalTick, HistoricalTickBidAsk, HistoricalTickLast)
BarData, ComboLeg, CommissionReport, ContractDescription, ContractDetails,
DeltaNeutralContract, DepthMktDataDescription, Execution, FamilyCode,
HistogramData, HistoricalTick, HistoricalTickBidAsk, HistoricalTickLast,
NewsProvider, OrderComboLeg, OrderState, PriceIncrement, SmartComponent,
SoftDollarTier, TagValue, TickAttribBidAsk, TickAttribLast
)
from .order import Order, OrderCondition
from .util import UNSET_DOUBLE

__all__ = ['Decoder']


class Decoder:
"""
Decode IB messages and invoke corresponding wrapper methods.
"""
"""Decode IB messages and invoke corresponding wrapper methods."""

def __init__(self, wrapper, serverVersion):
self.wrapper = wrapper
self.serverVersion = serverVersion
Expand Down Expand Up @@ -179,9 +180,7 @@ def handler(fields):
return handler if method else lambda *args: None

def interpret(self, fields):
"""
Decode fields and invoke corresponding wrapper method.
"""
"""Decode fields and invoke corresponding wrapper method."""
try:
msgId = int(fields[0])
handler = self.handlers[msgId]
Expand All @@ -190,9 +189,7 @@ def interpret(self, fields):
self.logger.exception(f'Error handling fields: {fields}')

def parse(self, obj):
"""
Parse the object's properties according to its default types.
"""
"""Parse the object's properties according to its default types."""
for k, default in obj.__class__.defaults.items():
typ = type(default)
if typ is str:
Expand Down
28 changes: 10 additions & 18 deletions ib_insync/flexreport.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import time
"""Access to account statement webservice."""

import logging
import time
import xml.etree.ElementTree as et
from contextlib import suppress
from urllib.request import urlopen
import xml.etree.ElementTree as et

from ib_insync.objects import DynamicObject
from ib_insync import util
from ib_insync.objects import DynamicObject

__all__ = ('FlexReport', 'FlexError')

Expand Down Expand Up @@ -47,9 +49,7 @@ def __init__(self, token=None, queryId=None, path=None):
self.load(path)

def topics(self):
"""
Get the set of topics that can be extracted from this report.
"""
"""Get the set of topics that can be extracted from this report."""
return set(node.tag for node in self.root.iter() if node.attrib)

def extract(self, topic: str, parseNumbers=True) -> list:
Expand All @@ -71,15 +71,11 @@ def extract(self, topic: str, parseNumbers=True) -> list:
return results

def df(self, topic: str, parseNumbers=True):
"""
Same as extract but return the result as a pandas DataFrame.
"""
"""Same as extract but return the result as a pandas DataFrame."""
return util.df(self.extract(topic, parseNumbers))

def download(self, token, queryId):
"""
Download report for the given ``token`` and ``queryId``.
"""
"""Download report for the given ``token`` and ``queryId``."""
url = (
'https://gdcdyn.interactivebrokers.com'
f'/Universal/servlet/FlexStatementService.SendRequest?'
Expand Down Expand Up @@ -114,17 +110,13 @@ def download(self, token, queryId):
_logger.info('Statement retrieved.')

def load(self, path):
"""
Load report from XML file.
"""
"""Load report from XML file."""
with open(path, 'rb') as f:
self.data = f.read()
self.root = et.fromstring(self.data)

def save(self, path):
"""
Save report to XML file.
"""
"""Save report to XML file."""
with open(path, 'wb') as f:
f.write(self.data)

Expand Down
Loading

0 comments on commit 2001836

Please sign in to comment.