Exemplo n.º 1
0
        self.client.requestFA(faDataType)
        try:
            await asyncio.wait_for(future, 4)
            return future.result()
        except:
            _logger.error('requestFAAsync: Timeout')
            return
        return future.result()


if __name__ == '__main__':
#     import uvloop
#     asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    from ib_insync.contract import *
    asyncio.get_event_loop().set_debug(True)
    util.logToConsole(logging.INFO)
    ib = IB()
    ib.connect('127.0.0.1', 7497, clientId=20)

    aex = Index('EOE', 'FTA')
    eurusd = Forex('EURUSD')
    intc = Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ')
    amd = Stock('AMD', 'SMART', 'USD')
    aapl = Stock('AAPL', 'SMART', 'USD')
    tsla = Stock('TSLA', 'SMART', 'USD')
    spy = Stock('SPY', 'ARCA')
    wrongContract = Forex('lalala')
    option = Option('EOE', '20170721', 505, 'C', 'FTA', multiplier=100)

    if 0:
        cds = ib.reqContractDetails(aex)
Exemplo n.º 2
0
import os
import sys
import time
import logging
import json
import base64
from ib_insync import ibcontroller
from ib_insync import IB
from ib_insync.ibcontroller import Watchdog
import ib_insync.util as util
from updateConfig import updateIbcConfig, updateTwsConfig

util.logToConsole(logging.DEBUG)
logger = logging.getLogger(name=__name__)
twsPort = os.getenv("TWS_PORT", "4001")

if __name__ == "__main__":

    ib = IB()

    ib.connect('127.0.0.1', twsPort, clientId=10)
    time.sleep(5)

    if not ib.isConnected():
        logging.debug('HEALTHCHECK: ib is not connected')
        sys.exit(1)
    else:
        logging.debug('HEALTHCHECK: ib is connected')
        sys.exit(0)
Exemplo n.º 3
0
            self.data = resp.read()
            self.root = et.fromstring(self.data)
            if self.root[0].tag == 'code':
                msg = self.root[0].text
                if msg.startswith('Statement generation in progress'):
                    _logger.info('still working...')
                    continue
                else:
                    raise FlexError(msg)
            break
        _logger.info('Statement retrieved.')

    def load(self, path):
        """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."""
        with open(path, 'wb') as f:
            f.write(self.data)


if __name__ == '__main__':
    util.logToConsole()
    report = FlexReport('945692423458902392892687', '272555')
    print(report.topics())
    trades = report.extract('Trade')
    print(trades)
Exemplo n.º 4
0
    def __init__(self):
        super(IBStore, self).__init__()

        self._env = None  # reference to cerebro for general notifications
        self.broker = None  # broker instance
        self.datas = list()  # datas that have registered over start
        # self.ccount = 0  # requests to start (from cerebro or datas)

        # self._lock_tmoffset = threading.Lock()
        # self.tmoffset = timedelta()  # to control time difference with server

        # # Structures to hold datas requests
        # self.qs = collections.OrderedDict()  # key: tickerId -> queues
        # self.ts = collections.OrderedDict()  # key: queue -> tickerId
        self.iscash = dict()  # tickerIds from cash products (for ex: EUR.JPY)

        self.acc_cash = AutoDict()  # current total cash per account
        self.acc_value = AutoDict()  # current total value per account
        self.acc_upds = AutoDict()  # current account valueinfos per account

        self.positions = collections.defaultdict(Position)  # actual positions

        self.orderid = None  # next possible orderid (will be itertools.count)

        self.managed_accounts = list()  # received via managedAccounts
        self.notifs = queue.Queue()  # store notifications for cerebro
        self.orders = collections.OrderedDict()  # orders by order ided

        self.opending = collections.defaultdict(list)  # pending transmission
        self.brackets = dict()  # confirmed brackets
        
        self.last_tick = None

        # Use the provided clientId or a random one
        if self.p.clientId is None:
            self.clientId = random.randint(1, pow(2, 16) - 1)
        else:
            self.clientId = self.p.clientId

        if self.p.timeout is None:
            self.timeout = 2
        else:
            self.timeout = self.p.timeout

        if self.p.readonly is None:
            self.readonly = False
        else:
            self.readonly = self.p.readonly

        if self.p.account is None:
            self.account = ""
        else:
            self.account = self.p.account
                    
        if self.p._debug:
            util.logToConsole(level=logging.DEBUG)
        
        util.patchAsyncio()
        util.startLoop()
        
        self.ib = IB()
        
        self.ib.connect(
                    host=self.p.host, port=self.p.port, 
                    clientId=self.clientId,
                    timeout=self.timeout,
                    readonly=self.readonly,
                    account=self.account,
                    )
        
        # This utility key function transforms a barsize into a:
        #   (Timeframe, Compression) tuple which can be sorted
        def keyfn(x):
            n, t = x.split()
            tf, comp = self._sizes[t]
            return (tf, int(n) * comp)

        # This utility key function transforms a duration into a:
        #   (Timeframe, Compression) tuple which can be sorted
        def key2fn(x):
            n, d = x.split()
            tf = self._dur2tf[d]
            return (tf, int(n))

        # Generate a table of reverse durations
        self.revdur = collections.defaultdict(list)
        # The table (dict) is a ONE to MANY relation of
        #   duration -> barsizes
        # Here it is reversed to get a ONE to MANY relation of
        #   barsize -> durations
        for duration, barsizes in self._durations.items():
            for barsize in barsizes:
                self.revdur[keyfn(barsize)].append(duration)

        # Once managed, sort the durations according to real duration and not
        # to the text form using the utility key above
        for barsize in self.revdur:
            self.revdur[barsize].sort(key=key2fn)
Exemplo n.º 5
0
import random
import sys
from decimal import Decimal

import uvicorn
from fastapi import FastAPI
from ib_insync import IB, MarketOrder, Stock, util

import crypto
import stocks
import testbed

app = FastAPI()

loglevel = 10
util.logToConsole(level=10)
logging.basicConfig()
logging.getLogger().setLevel(loglevel)
logging.info("Reporting INFO-level messages")


@app.get("/")
async def root():
    return 'Version 2.2 Online!'


@app.get("/test")
async def test():
    return await testbed.main()