def currency_exchange(request, currencies='EURUSD'): # print(currencies) ss1 = 'ss1' ss2 = 'ss2' ss3 = 'ss3' ss4 = 'ss4' ss5 = 'ss5' ss6 = 'ss6' ss7 = 'ss7' ss8 = 'ss8' ss9 = 'ss9' df = None is_error = 0 try: loop = asyncio.get_event_loop_policy().new_event_loop() asyncio.set_event_loop(loop) ib_server = 'twoprojectsib1_tws_1' ib_port = 4003 if settings.DEBUG: ib_server = '127.0.0.1' ib_port = 4002 ib_ = IB() ci = randint(0, 100000) ib_.connect(ib_server, ib_port, clientId=ci) # print('ib_') # print(ib_) # print('ib_') ss1 = str(ib_) except Exception as e: ss1 = "Error connecting to: " + ib_server + ":" + str(ib_port) ss2 = e is_error = 1 try: c = Forex(currencies) bars = ib_.reqHistoricalData(c, endDateTime='', durationStr='1 D', barSizeSetting='1 min', whatToShow='MIDPOINT', useRTH=True) # print(bars) ss3 = 'good 3' df = util.df(bars) # print(df[['date', 'open', 'high', 'low', 'close']]) ss4 = 'good 4' df = df.sort_values(by=['date'], ascending=False) ss5 = 'good 5' ib_.disconnect() del ib_ ss6 = 'good 6' except Exception as e2: ss7 = e2 is_error = 1 context = { 'df': df, 'ss1': ss1, 'ss2': ss2, 'ss3': ss3, 'ss4': ss4, 'ss5': ss5, 'ss6': ss6, 'ss7': ss7, 'ss8': ss8, 'ss9': ss9, 'is_error': is_error, 'currencies': currencies, 'title': 'Currency Exchange', 'cur_list': [ 'GBPUSD', 'GBPZAR', 'HKDJPY', 'KRWAUD', 'KRWCAD', 'KRWCHF', 'KRWEUR', 'KRWGBP', 'KRWHKD', 'KRWJPY', 'KRWUSD', 'MXNJPY', 'NOKJPY', 'NOKSEK', 'NZDCAD', 'NZDCHF', 'NZDJPY', 'NZDUSD', 'SEKJPY', 'SGDCNH', 'SGDJPY', 'TRYJPY', 'USDCAD', 'USDCHF', 'USDCNH', 'USDCZK', 'USDDKK', 'USDHKD', 'USDHUF', 'USDILS', 'USDJPY', 'USDKRW', 'USDMXN', 'USDNOK', 'USDPLN', 'USDRUB', 'USDSEK', 'USDSGD', 'USDTRY', 'USDZAR', 'ZARJPY', 'EURPLN', 'EURRUB', 'EURSEK', 'EURSGD', 'EURTRY', 'EURUSD', 'EURZAR', 'GBPAUD', 'GBPCAD', 'GBPCHF', 'GBPCNH', 'GBPCZK', 'GBPDKK', 'GBPHKD', 'GBPHUF', 'GBPJPY', 'GBPMXN', 'GBPNOK', 'GBPNZD', 'GBPPLN', 'GBPSEK', 'GBPSGD', 'GBPTRY', 'GBPUSD', 'GBPZAR', 'HKDJPY', 'KRWAUD', 'KRWCAD', 'KRWCHF', 'KRWEUR', 'KRWGBP', 'KRWHKD', 'KRWJPY', 'KRWUSD', 'MXNJPY', 'NOKJPY', 'NOKSEK', 'NZDCAD', 'NZDCHF', 'NZDJPY', 'NZDUSD', 'SEKJPY', 'SGDCNH', 'SGDJPY', 'TRYJPY', 'USDCAD', 'USDCHF', 'USDCNH', 'USDCZK', 'USDDKK', 'USDHKD', 'USDHUF', 'USDILS', 'USDJPY', 'USDKRW', 'USDMXN', 'USDNOK', 'USDPLN', 'USDRUB', 'USDSEK', 'USDSGD', 'USDTRY', 'USDZAR', 'ZARJPY' ] } return render(request, 'trades/currency_exchange.html', context)
underlyingSecType=contract.secType, underlyingConId=contract.conId, ) async def get_margin(ib, contract, order): return await ib.whatIfOrderAsync(contract, order) if __name__ == "__main__": start = datetime.datetime.now() print(f"started at {time.strftime('%X')}") util.logToFile(data[market]["logpath"]+'main.log') with IB().connect(host=host, port=port, clientId=cid) as ib: symbols = ib.run(get_symbols()).symbol # symbols = ["CELG", "LIN"] contracts = [ib.run(get_contract(ib, symbol)) for symbol in symbols] contracts = [c for cs in contracts for c in cs if c] for c in contracts: df_ohlc = ib.run(get_ohlc(ib, c)) undPrice = ib.run(get_tick(ib, c))[0].marketPrice() chains = {c.symbol: ib.run(get_chain(ib, c))[0]} sek = {b for a in [list(product([k], m.expirations, m.strikes))
def ib(self): if not self.__ib: self.__ib = IB() return self.__ib
future_price: float, ) -> List[float]: right_is_call = rights.apply(lambda right: 1 if right == "C" or right == "CALL" else -1) return ((-1.0 * asks) + (right_is_call * (future_price - strikes))) * multipliers parser = argparse.ArgumentParser(description="Calculate option chain profits.") parser.add_argument('symbol', type=str, help="The stock symbol (eg: GOOG) to use.") parser.add_argument('-e', '--expirations', metavar="YYYYMMDD", type=str, nargs="+", help="Option expiration date(s).", required=True) parser.add_argument('-f', '--future_prices', type=float, nargs="+", help="Future price(s) for computing profit.", required=True) parser.add_argument('-m', '--strike_modulus', type=int, help="Modulus value for strike prices", required=False) parser.add_argument('--contract_per_price', dest="contract_per_price", type=int, default=3) args = parser.parse_args() pd.set_option("display.max_rows", None) ib = IB() ib.connect() contract = Stock(args.symbol, "SMART", "USD") ib.reqMarketDataType(1) ib.qualifyContracts(contract) [ticker] = ib.reqTickers(contract) current_price = ticker.marketPrice() strike_min=min(current_price * 0.9, min(args.future_prices)) strike_max=max(current_price * 1.1, max(args.future_prices)) strike_modulus = args.strike_modulus or None option_chain = get_option_chain(ib, contract, args.expirations, strike_min=strike_min, strike_max=strike_max, strike_modulus=strike_modulus) for future_price in args.future_prices: df = option_chain.copy()
#def barupdateEvent_15m(self, bars: objects.BarDataList, hasNewBar: bool): #logger.getLogger().info(f"Got 15m Bars.") #cci, avg = logic.calculate_cci(bars) #atr = logic.calculate_atr(bars) #bband_width, bband_b, = logic.calculate_bbands(bars) #qtrtime = datetime.now() #self.cci15.update(f"{cci:.02f}") #self.cci15_av.update(f"{avg:.02f}") #self.atr15.update(f"{atr:.02f}") #self.bband15_width.update(f"{bband_width:.04f}") #self.bband15_b.update(f"{bband_b:.04f}") #self.qtrhour.update(qtrtime) def main(ib: IB): try: logger.getLogger().info("Connecting...") ib.connect(config.HOST, config.PORT, clientId=config.CLIENTID) ib.reqMarketDataType(config.DATATYPE.value) except OSError: logger.getLogger().error("Connection Failed.") sys_exit() app = App(ib) app.run() if __name__ == '__main__': logger.setup() util.patchAsyncio() main(IB())
def main(symbol): # util.logToConsole(logging.DEBUG) util.logToFile('log.txt') s = symbol.upper() click.echo("Options for {} Loading: ".format(s), nl=False) ib = IB() ib.connect('127.0.0.1', 7497, clientId=3, readonly=True) contract = Stock(s, 'SMART', 'USD') ib.qualifyContracts(contract) click.echo('Chains ', nl=False) chains = ib.reqSecDefOptParams(contract.symbol, '', contract.secType, contract.conId) chain = next(c for c in chains if c.exchange == 'SMART') click.echo('Price '.format(s), nl=False) ib.reqMarketDataType(1) [ticker] = ib.reqTickers(contract) value = ticker.marketPrice() strikes = [ strike for strike in chain.strikes if value * 0.90 < strike < value * 1.0 ] expirations = sorted(exp for exp in chain.expirations)[:2] rights = ['P', 'C'] click.echo("Option Contracts {}@{} ".format(s, value), nl=False) contracts = [ Option(s, expiration, strike, right, 'SMART', tradingClass=s) for right in rights for expiration in expirations for strike in strikes ] click.echo('Validate ', nl=False) contracts = ib.qualifyContracts(*contracts) click.echo(len(contracts), nl=False) ib.reqMarketDataType(4) click.echo(' Ticker') tickers = ib.reqTickers(*contracts) options = [] for t in tickers: # click.echo(t) # calc = ib.calculateOptionPrice( # t.contract, volatility=0.14, underPrice=value) # print(calc) options.append(OptionData(t)) df = util.df(options, [ 'symbol', 'lastTradeDateOrContractMonth', 'strike', 'right', 'marketPrice', 'optionYield', 'timeToExpiration', 'spread', 'bid', 'ask', 'impliedVol', 'delta', 'gamma', 'vega' ]) click.echo(df) currentWeekPut = df[(df['right'] == 'P') & (df['lastTradeDateOrContractMonth'] == expirations[0])] click.echo(currentWeekPut.loc[(abs(abs(currentWeekPut.delta) - 0.2)).sort_values().index].head(2)) ib.disconnect()
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)
def findConIds(**kwargs): """prints a list of conIds for a hard-coded list of currencies""" ib = IB() ib.errorEvent += myErrorCallback clientId = kwargs.get('clientId'.lower()) ib.connect('127.0.0.1', 4002, clientId=clientId) # build a list of valid contracts # define contracts ForexStrs = [ # 'AUD', # 'CAD', 'CHF', 'CNH', 'GBP', 'JPY', 'USD', 'RUB', # 'CZK', # 'DKK', # 'HUF', # 'ILS', # 'MXN', # 'NOK', # 'NZD', # 'PLN', # 'SEK', # 'SGD', # 'TRY', # 'ZAR', ] # Indices and CFDs others = [ # { # 'secType': 'IND', # 'symbol': 'DAX', # 'exchange': 'DTB', # 'currency': 'EUR' # }, # { # 'secType': 'IND', # 'symbol': 'INDU', # 'exchange': 'CME', # 'currency': 'USD' # }, # { # 'secType': 'IND', # 'symbol': 'HSC50', # 'exchange': 'HKFE', # 'currency': 'HKD' # }, # { # 'secType': 'IND', # 'symbol': 'N225', # 'exchange': 'OSE.JPN', # 'currency': 'JPY' # }, # { # 'secType': 'IND', # 'symbol': 'SPX', # 'exchange': 'CBOE', # 'currency': 'USD' # }, { 'secType': 'CFD', 'symbol': 'IBCH20', 'exchange': 'SMART', 'currency': 'CHF' }, { 'secType': 'CFD', 'symbol': 'IBDE30', 'exchange': 'SMART', 'currency': 'EUR' }, { 'secType': 'CFD', 'symbol': 'IBEU50', 'exchange': 'SMART', 'currency': 'EUR' }, { 'secType': 'CFD', 'symbol': 'IBFR40', 'exchange': 'SMART', 'currency': 'EUR' }, { 'secType': 'CFD', 'symbol': 'IBGB100', 'exchange': 'SMART', 'currency': 'GBP' }, { 'secType': 'CFD', 'symbol': 'IBJP225', 'exchange': 'SMART', 'currency': 'JPY' }, { 'secType': 'CFD', 'symbol': 'IBHK50', 'exchange': 'SMART', 'currency': 'HKD' }, { 'secType': 'CFD', 'symbol': 'IBUS30', 'exchange': 'SMART', 'currency': 'USD' }, { 'secType': 'CFD', 'symbol': 'IBUS500', 'exchange': 'SMART', 'currency': 'USD' }, ] contractsQualified = [] # Forex for s in ForexStrs: try: contractsQualified.append( ib.qualifyContracts( Contract(secType='CASH', symbol='EUR', exchange='IDEALPRO', currency=s))[0]) pass except: print('could not qualify the contract for {}'.format(s)) pass pass # others for d in others: try: contractsQualified.append(ib.qualifyContracts(Contract(**d))[0]) pass except: print('could not qualify the contract for {}'.format(s)) pass pass # get contract information conIds = [] for c in contractsQualified: if c.secType in ['CASH', 'CFD']: whatToShow = 'MIDPOINT' else: whatToShow = 'TRADES' eDT = None try: req = ib.reqHeadTimeStampAsync(c, whatToShow=whatToShow, useRTH=False, formatDate=2) try: eDT = ib.run(asyncio.wait_for(req, 10)) except asyncio.TimeoutError: print('timeout') pass pass except: pass print(c.symbol, c.currency, c.localSymbol, c.exchange, c.conId, c.secType, eDT) # cD = ib.reqContractDetails(c)[0] # secType=cD.summary.secType # print (c.symbol, c.currency, c.localSymbol, c.exchange, c.conId, eDT, c.secType) conIds.append(c.conId) print(conIds)
pnlDict = {'dailyPnL': pnlobj.dailyPnL, 'unrealizedPnL': pnlobj.unrealizedPnL, 'realizedPnL': pnlobj.realizedPnL} return {**pnlDict, **fundDict} async def get_pnlAsync(market): """ Gets the pnl and liquidity for the market """ # ...variables initialization with open('var.json', 'r') as fp: data = json.load(fp) host = data['common']['host'] port = data[market]['port'] cid = 1 # ...generate PnL with funds with await IB().connectAsync(host=host, port=port, clientId=cid) as ib: p = ib.run(pnlAsync(ib)) return(p) if __name__ == '__main__': output = IB().run(get_pnlAsync('snp')) print(output)
# test to see how asyncio works with a timeout for one Stock symbol # note that it does not work for Index symbol (ref: https://groups.io/g/insync/message/4718) import asyncio import pandas as pd from ib_insync import IB, Index, Stock, util # build up the contracts HOST = '127.0.0.1' PORT = '1300' CID = 0 with IB().connect(HOST, PORT, CID) as ib: timeout = 5 # contract = ib.qualifyContracts(Stock(symbol='SBUX', exchange='SMART', currency='USD'))[0] contract = ib.qualifyContracts( Index(symbol='VIX', exchange='CBOE', currency='USD'))[0] req = ib.reqHistoricalDataAsync(contract=contract, endDateTime="", durationStr="2 D", barSizeSetting="1 day", whatToShow="Trades", useRTH=True) try: hist = ib.run(asyncio.wait_for(req, timeout)) except asyncio.exceptions.TimeoutError: hist = [] print(contract) print(hist)
def runProg(args): """run program""" util.patchAsyncio() # log to a file utils.logToFile(f'getRecentHistoricalData.log') # utils.logToConsole() apschedulerLogger = logging.getLogger('apscheduler') apschedulerLogger.setLevel(logging.ERROR) tradingLogger = logging.getLogger('trading') tradingLogger.setLevel(logging.WARNING) pd.set_option('display.width', 200) # load the config file configFile = args.configFile config = ConfigParser(interpolation=ExtendedInterpolation(), defaults=os.environ) config.read(configFile) # load data from configFile host = config.get('InteractiveBrokers', 'host') port = config.getint('InteractiveBrokers', 'port') DBType = config.get('DataBase', 'DBType') DBFileName = config.get('DataBase', 'DBFileName') clientId = config.get('InteractiveBrokers', 'clientId') # for production mode: watchdog if 1: # start watchdog # ibc = IBC(963, gateway=True, tradingMode='paper',ibcIni='/home/bn/IBController/configPaper.ini') ibcIni = config.get('InteractiveBrokers', 'ibcIni') tradingMode = config.get('InteractiveBrokers', 'tradingMode') ibc = IBC(970, gateway=True, tradingMode=tradingMode, ibcIni=ibcIni) myWatchdogapp = myWatchdog.myWatchdog(ibc, appStartupTime=15, port=4002) myWatchdogapp.start() ib = myWatchdogapp.ib pass if 0: # faster way for now ib = IB() ib.connect(host=host, port=port, clientId=clientId) pass pass # create database class mydb = database.tradingDB(DBType=DBType, DBFileName=DBFileName) # load existing database mydb.instantiateExistingTablesAndClasses(ib=ib) # set log level of sqlalchemy mydb._loggerSQLAlchemy.setLevel(logging.WARNING) qcs = mydb.MarketDataInfoTableDataFrame.qualifiedContract for qc in qcs: print(qc, type(qc)) ib.reqMktData(contract=qc, genericTickList='', snapshot=False, regulatorySnapshot=False, mktDataOptions=None) pass df = pd.DataFrame( columns='symbol bidSize bid ask askSize high low close'.split()) df['symbol'] = [qc.localSymbol for qc in qcs] contract2Row = {qc: i for (i, qc) in enumerate(qcs)} pprint.pprint(contract2Row) def onPendingTickers(tickers): for t in tickers: iRow = contract2Row[t.contract] localSymbol = t.contract.localSymbol if localSymbol == "EUR.USD": nowUTC = pd.to_datetime(pd.datetime.utcnow()).tz_localize(None) nowUTCRounded = nowUTC.floor('1 min') dateTime = pd.to_datetime(t.time).tz_localize(None) print(localSymbol, nowUTCRounded, ((dateTime - nowUTCRounded) / pd.Timedelta('1 sec')), t.close) # df.iloc[iRow, 1:] = (t.bidSize, t.bid, t.ask, t.askSize, t.high, t.low, t.close) # print(df) ib.setCallback('pendingTickers', onPendingTickers) # ib.sleep(300) if 1: util.allowCtrlC() # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed. try: asyncio.get_event_loop().run_forever() except (KeyboardInterrupt, SystemExit): pass
def __init__(self, host, port, clientId=0): self.ib_gateway = IB() self.ib_gateway.connect(host, port, clientId=clientId)
def client(self) -> IB: if self._client is None: self._client = IB() self._client.connect(host=self.host, port=self.port) return self._client
def __init__(self): self.ib = IB() self.connect()
def runProg(): """run program""" util.patchAsyncio() # log to a file util.logToFile(f'getRecentHistoricalData2.log') # util.logToConsole() # set pandas option pd.set_option('display.width', 200) # specify connection details host = '127.0.0.1' port = 4002 ibcIni = '/home/bn/IBController/configPaper.ini' tradingMode = 'paper' clientId = 12 # start watchdog ibc = IBC(970, gateway=True, tradingMode=tradingMode, ibcIni=ibcIni) ib = IB() watchdogApp = ibcontroller.Watchdog(ibc, ib=ib, appStartupTime=15, host=host, port=port, clientId=clientId) watchdogApp.start() pass # create some contracts qcs = [] c = Contract(symbol='EUR', currency='USD', exchange='IDEALPRO', secType='CASH') qc = ib.qualifyContracts(c)[0] qcs.append(qc) # request market data for qc in qcs: ib.reqMktData(contract=qc, genericTickList='', snapshot=False, regulatorySnapshot=False, mktDataOptions=None) pass # define some callback def onPendingTickers(tickers): for t in tickers: localSymbol = t.contract.localSymbol if localSymbol == "EUR.USD": nowUTC = pd.to_datetime(pd.datetime.utcnow()).tz_localize(None) nowUTCRounded = nowUTC.floor('1 min') dateTime = pd.to_datetime(t.time).tz_localize(None) print(localSymbol, nowUTCRounded, ((dateTime - nowUTCRounded) / pd.Timedelta('1 sec')), t.close) pass pass pass def myErrorCallback(reqId, errorCode, errorString, contract): # print("myErrorCallback", reqId,errorCode,errorString,contract) if errorCode == 322: print("myErrorCallback", reqId, errorCode, errorString, contract) # more than 50 simultaneous historical data requests app.ib.client.cancelHistoricalData(reqId) # register the callbacks with ib ib.setCallback('error', myErrorCallback) ib.setCallback('pendingTickers', onPendingTickers) # run and never stop ib.run()
# blocking PnL. Takes 8 seconds to give pnl and acc summary from ib_insync import IB import json market = 'snp' # ...variables initialization with open('var.json', 'r') as fp: data = json.load(fp) host = data['common']['host'] port = data[market]['port'] cid = 1 # ...connect to IB ib = IB().connect(host=host, port=port, clientId=cid) acct = ib.managedAccounts()[0] # ..get account summary accsum = ib.accountSummary(account=acct) # ..get liquidity and funds dictionary funds = { t.tag: t.value for t in accsum if t.tag in ["NetLiquidation", "AvailableFunds"] } # ..dailyPnl ib.reqPnL(acct) ib.sleep(8) pnlobj = ib.pnl()[0]
def start(config): import toml import thetagang.config_defaults as config_defaults with open(config, "r") as f: config = toml.load(f) config = normalize_config(config) validate_config(config) click.secho(f"Config:", fg="green") click.echo() click.secho(f" Account details:", fg="green") click.secho( f" Number = {config['account']['number']}", fg="cyan") click.secho( f" Cancel existing orders = {config['account']['cancel_orders']}", fg="cyan", ) click.secho( f" Margin usage = {config['account']['margin_usage']} ({config['account']['margin_usage'] * 100}%)", fg="cyan", ) click.secho( f" Market data type = {config['account']['market_data_type']}", fg="cyan", ) click.echo() click.secho(f" Roll options when either condition is true:", fg="green") click.secho( f" Days to expiry <= {config['roll_when']['dte']} and P&L >= {config['roll_when']['min_pnl']} ({config['roll_when']['min_pnl'] * 100}%)", fg="cyan", ) click.secho( f" P&L >= {config['roll_when']['pnl']} ({config['roll_when']['pnl'] * 100}%)", fg="cyan", ) click.echo() click.secho(f" Write options with targets of:", fg="green") click.secho(f" Days to expiry >= {config['target']['dte']}", fg="cyan") click.secho(f" Delta <= {config['target']['delta']}", fg="cyan") click.secho( f" Maximum new contracts = {config['target']['maximum_new_contracts']}", fg="cyan", ) click.secho( f" Minimum open interest = {config['target']['minimum_open_interest']}", fg="cyan", ) click.echo() click.secho(f" Symbols:", fg="green") for s in config["symbols"].keys(): click.secho( f" {s}, weight = {config['symbols'][s]['weight']} ({config['symbols'][s]['weight'] * 100}%)", fg="cyan", ) assert (sum([ config["symbols"][s]["weight"] for s in config["symbols"].keys() ]) == 1.0) click.echo() if config.get("ib_insync", {}).get("logfile"): util.logToFile(config["ib_insync"]["logfile"]) ibc = IBC(978, **config["ibc"]) def onConnected(): portfolio_manager.manage() ib = IB() ib.connectedEvent += onConnected completion_future = asyncio.Future() portfolio_manager = PortfolioManager(config, ib, completion_future) probeContractConfig = config["watchdog"]["probeContract"] watchdogConfig = config.get("watchdog") del watchdogConfig["probeContract"] probeContract = Contract( secType=probeContractConfig["secType"], symbol=probeContractConfig["symbol"], currency=probeContractConfig["currency"], exchange=probeContractConfig["exchange"], ) watchdog = Watchdog(ibc, ib, probeContract=probeContract, **watchdogConfig) watchdog.start() ib.run(completion_future) watchdog.stop() ibc.terminate()
import falcon from google.cloud.logging.handlers import ContainerEngineHandler from ib_insync import IB import logging # setup logging logger = logging.getLogger('ib-gw.healthcheck') logger.setLevel(logging.DEBUG) logger.addHandler(ContainerEngineHandler()) # instantiate ib-insync IB gateway ib_gw = IB() class HealthCheck: def __init__(self): logger.info('IB Gateway healthcheck is active.') @staticmethod def on_get(_, response): try: ib_gw.connect('localhost', 4003, 999) if ib_gw.isConnected() and ib_gw.client.isReady(): logger.info('IB Gateway healthcheck succeded.') logger.info(ib_gw.client.connectionStats()) response.body = '{"connState": "{' + str( ib_gw.client.connState ) + '}", "currentTime": "{' + ib_gw.reqCurrentTime().isoformat( ) + '}"}' response.status = falcon.HTTP_200
def instantiateMyDB(args): """instantiate all SQ ORM classes using a config file passed in the arguments""" # load the config file configFile = args.configFile config = ConfigParser(interpolation=ExtendedInterpolation(), defaults=os.environ) config.read(configFile) # create connection to IB ib = IB() ib.setCallback('error', myErrorCallback) # load data from configFile a = config.get('MarketData', 'ConIdList') conIdList = eval(a) host = config.get('InteractiveBrokers', 'host') port = config.getint('InteractiveBrokers', 'port') clientId = config.getint('InteractiveBrokers', 'clientId') DBType = config.get('DataBase', 'DBType') DBFileName = config.get('DataBase', 'DBFileName') timeOutTime = config.getint('InteractiveBrokers', 'timeOutTime') # override configFile if clientId is given on the command line if args.clientId is not None: clientId = args.clientId # override configFile if timeOutTime is given on the command line if args.timeOutTime is not None: timeOutTime = args.TimeOutTime # connect to interactive brokers ib.connect(host=host, port=port, clientId=clientId) # create database class mydb = tradingDB(DBType=DBType, DBFileName=DBFileName) # loop over all conIds defined in the config File and create the sqlalchemy ORM classes # these tables will appear in the metadata of the DBDeclarativeBase attribute of mydb # prepare a dataframe that holds all infos that should be put into the MarketDataInfoTable on disk # and the MarketDataInfoTableDataFrame in memory nTables = len(conIdList) featureList = [ 'conId', 'qualifiedContract', 'earliestDateTime', 'category', 'kwargs', 'tableName', 'tableORM', ] dfWithInfoAboutTables = pd.DataFrame(None, index=range(nTables), columns=featureList) dfWithInfoAboutTables.loc[:, 'conId'] = conIdList df = dfWithInfoAboutTables for indx in df.index: conId = df.at[indx, 'conId'] qc = utils.getQualifiedContractFromConId(ib=ib, conId=conId, timeOutTime=timeOutTime) df.at[indx, 'qualifiedContract'] = qc # calculate the earliest Date for this contract earliestDateTime = utils.getEarliestDateTimeFromIB( ib=ib, qualifiedContract=qc, timeOutTime=timeOutTime) df.at[indx, 'earliestDateTime'] = earliestDateTime # set the category that should be MarketData for the tables to be generated in this loop category = mydb.tableCategories.MarketData.value df.at[indx, 'category'] = category # set the keyword arguments for the call to calculateTableName kwargs = {} kwargs['category'] = category kwargs['earliestDateTime'] = earliestDateTime kwargs.update(qc.dict()) df.at[indx, 'kwargs'] = kwargs # calculate the tableName tableName = mydb.calculateTableName(**kwargs) df.at[indx, 'tableName'] = tableName # create the sqlalchemy ORM class; this will write the class to the mydb.DBDeclarativeBase.metadata object print( f'creating MarketData Table: conId: {conId}; tableName: {tableName}' ) tableORM = mydb.getTableORMByTablename(tableName=tableName) df.at[indx, 'tableORM'] = tableORM pass # now all the ORM tables should be defined. # they are not yet created on disk. # also, the MarketDataInfoTable is not populated and the MarketDataInfoTableDataFrame is not populated # loop over all conIds defined in the config File and create a row in the Market Data Info Table # also, populate the corresponding dataframe # create all tables on disk if they do not yet exist mydb.createAllTables() ssn = mydb.Session() for indx, row in dfWithInfoAboutTables.iterrows(): tableName = row.tableName print(f'upserting a row for {tableName} to the MarketDataInfoTable') # create a row for each conId in the MDIT table # first, instantiate a row in the MarketDataInfoTable MDIT = mydb.MarketDataInfoTable(tableName=tableName) # set all available column values kwargs = row.kwargs for k, v in kwargs.items(): if k in MDIT.__table__.columns: setattr(MDIT, k, v) pass pass # upsert this table Row to the table d = utils.convertTableRowToDict(MDIT) # only update values that are not none rowOfTableOnDisk = ssn.query(mydb.MarketDataInfoTable).filter( mydb.MarketDataInfoTable.tableName == tableName).first() for k, v in d.items(): if v is None: a = None try: a = getattr(rowOfTableOnDisk, 'earliestDateTime', None) except: pass d[k] = a pass pass ssn.execute(mydb.upsert(mydb.MarketDataInfoTable, [d])) ssn.commit() ssn.close() mydb.MarketDataInfoTableDataFrame = mydb.createMarketDataInfoTableDataFrameFromMarketDataInfoTable( ib=ib, timeOutTime=timeOutTime) # disconnect from interactive brokers ib.disconnect() return (mydb)