コード例 #1
0
    def find_eligible_contracts(self, symbol, right):
        EXCHANGE = 'SMART'
        MAX_STRIKE_OFFSET = 5

        stock = Stock(symbol, EXCHANGE, currency="USD")
        self.ib.qualifyContracts(stock)
        [ticker] = self.ib.reqTickers(stock)
        ticker_value = ticker.marketPrice()
        chains = self.ib.reqSecDefOptParams(stock.symbol, "", stock.secType, stock.conId)
        chain = next(c for c in chains if c.exchange == EXCHANGE)

        def valid_strike(strike):
            if strike % 1 == 0:
                if right == 'C':
                    max_ntm_call_strike = ticker_value + MAX_STRIKE_OFFSET
                    return ticker_value <= strike <= max_ntm_call_strike
                elif right == 'P':
                    min_ntm_put_strike = ticker_value - MAX_STRIKE_OFFSET
                    return min_ntm_put_strike <= strike <= ticker_value
            return False

        strikes = [strike for strike in chain.strikes if valid_strike(strike)]

        # TODO: Remove slicing once contract selection algorithm implemented
        exp_offset = self.config["nope"]["expiry_offset"]
        expirations = sorted(exp for exp in chain.expirations)[exp_offset:exp_offset + 1]

        contracts = [Option(self.SYMBOL, expiration, strike, right, EXCHANGE, tradingClass=self.SYMBOL)
                     for expiration in expirations
                     for strike in strikes]

        return contracts
コード例 #2
0
def get_valid_spy_contract(idx) -> OptionContract:
    from ib_insync import IB, Stock

    ib = IB()
    ib.connect(clientId=idx + 1)
    ib_stk_con = Stock(symbol="SPY", exchange="SMART", currency="USD")
    ib_details = ib.reqContractDetails(ib_stk_con)[0]
    ib.reqMarketDataType(4)
    tick = ib.reqMktData(contract=ib_stk_con, snapshot=True)
    while np.isnan(tick.ask):
        ib.sleep()
    ask = tick.ask
    ib_con_id = ib_details.contract.conId
    ib_chains = ib.reqSecDefOptParams(
        underlyingSymbol="SPY",
        futFopExchange="",
        underlyingSecType="STK",
        underlyingConId=ib_con_id,
    )
    ib_chain = ib_chains[0]
    ib_chain.strikes.sort(key=lambda s: abs(s - ask))
    strike = ib_chain.strikes[0]
    expiration_str = ib_chain.expirations[idx]
    expiration_date = datetime.strptime(expiration_str, "%Y%m%d")
    spy_contract = OptionContract(
        symbol="SPY",
        strike=strike,
        right=Right.CALL,
        multiplier=int(ib_chain.multiplier),
        last_trade_date=expiration_date,
    )
    ib.disconnect()

    return spy_contract
コード例 #3
0
 def get_contract(self):
     if self.market == 'futures':
         expiration = self.ib.reqContractDetails(Future(self.symbol,self.exchange))[0].contract.lastTradeDateOrContractMonth 
         self.contract = Future(symbol=self.symbol, exchange=self.exchange, lastTradeDateOrContractMonth=expiration)
     elif self.market == 'forex':
         self.contract = Forex(self.symbol)
     elif self.market == 'stocks':
         self.contract = Stock(symbol=self.symbol, exchange=self.exchange, currency='USD')
コード例 #4
0
def main(ib):
    from ib_insync import Stock, Forex, Index
    win_historical_ticks = sg.Window('IBKR Historical Ticks', layout)
    #win_historical_ticks.Element('_TickCount_').Update('0')
    
    # Event Loop to process "events" and get the "values" of the inputs
    while True:  # Event Loop
        event, values = win_historical_ticks.Read()

        if event == '_CloseWindow_':
            #? commenting out "disconnect()" because any calling procedure would not want a child to disconnect it
            #ib.disconnect()
            logging.info("Close hit")
            win_historical_ticks.close()
            break

        if event == 'Qualify':
            # Update the "output" element to be the value of "input" element
            win_historical_ticks.Element('_OUTPUT_').Update(values['_Symbol_'])
            if values['_SecType_'] == 'STK':
                contract = Stock(values['_Symbol_'], values['_Exchange_'],values['_Currency_'])
            if values['_SecType_'] == 'CASH':
                contract = Forex(values['_Symbol_'])
            if values['_SecType_'] == 'IND':
                contract = Index(values['_Symbol_'], values['_Exchange_'],values['_Currency_'])
            qual = ib.qualifyContracts(contract)
            logging.info(str(qual))

        if event == 'Fetch':
            #NOTE add validations here
            if values['_targetFolder_'] != '':
                dtmStartTime = datetime.strptime(str(values['_StartDate_']), '%Y-%m-%d %H:%M:%S')
                dtmStartTime = dtmStartTime.replace(hour=0, minute=1)
                dtmEndTime  = datetime.strptime(str(values['_EndDate_']), '%Y-%m-%d %H:%M:%S')
                dtmEndTime = dtmEndTime.replace(hour=23, minute=59)
                
                intTicks = int(values['_tickCount_'])
                # whatToShow (str) – One of ‘Bid_Ask’, ‘Midpoint’ or ‘Trades’.
                strWhatToShow = str(values['_whatToShow_'])
                # useRTH – If True then only show data from within Regular Trading Hours, if False then show all data.
                boolUseRTH = bool(values['_useRTH_'])
                # ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
                boolIgnoreSize = bool(values['_ignoreSize_'])
                #sg.popup(str([dtmStartTime, " - ", dtmEndTime, " - ", intTicks, " - ", strWhatToShow, " - ", boolUseRTH, " - ", boolIgnoreSize]))
                if dtmEndTime > dtmStartTime:
                    listTicks = loop_reqHistoricalTicks(ib, contract, dtmStartTime, dtmEndTime, intTicks, strWhatToShow, boolUseRTH, boolIgnoreSize)
                #convert listTicks to a CSV and save
                dfTicks = pd.DataFrame(listTicks)
                dfTicks = dfTicks.rename(columns={'tickAttribLast':'symbol', 'specialConditions':'currency'})
                dfTicks['symbol'] = contract.symbol
                dfTicks['exchange'] = contract.exchange
                dfTicks['currency'] = contract.currency
                dfTicks['time'] = dfTicks['time'].apply(utc2local)
                dfTicks['dataType'] = 'Ticks_' + str(values['_whatToShow_']) +('_RTH' if boolUseRTH else '_RHT+AMO')
                #For Linux uncomment below
                #dfTicks.to_csv(values['_targetFolder_'] +'/'+ contract.symbol +'_'+ str(dtmStartTime) +'_'+ str(dtmEndTime)+'.csv', index=False)
                #For Windows uncomment below
                dfTicks.to_csv(str_default_path +'//'+ contract.symbol +'_'+ dtmStartTime.strftime("%Y%M%d_%H%M%S") +'_'+ dtmEndTime.strftime("%Y%M%d_%H%M%S") +'.csv', index=False)
コード例 #5
0
def StockFromJson(s: str) -> Stock:
    d = json.loads(s)['Stock']
    return Stock(conId=d['conId'],
                 symbol=d['symbol'],
                 exchange=d['exchange'],
                 primaryExchange=d['primaryExchange'],
                 currency=d['currency'],
                 localSymbol=d['localSymbol'],
                 tradingClass=d['tradingClass'])
コード例 #6
0
ファイル: ib.py プロジェクト: ajmal017/ta_scanner
 def request_stock_instrument(
     self, instrument_symbol: str, dt: datetime.datetime, what_to_show: str
 ) -> pd.DataFrame:
     exchange = Exchange.SMART.value
     contract = Stock(instrument_symbol, exchange, Currency.USD.value)
     duration = "2 D"
     bar_size_setting = "1 min"
     use_rth = False
     return self._execute_req_historical(
         contract, dt, duration, bar_size_setting, what_to_show, use_rth
     )
コード例 #7
0
 def load_hist_data(self, dt_ts_str, symbol, duration_secs):
     contract = Stock(symbol, 'SMART', 'USD')
     data_ = self.ib.reqHistoricalData(
         contract,
         endDateTime=''.format(dt_ts_str),
         durationStr='{} S'.format(duration_secs),
         barSizeSetting='{} secs'.format(BAR_SIZE),
         whatToShow='ADJUSTED_LAST',
         useRTH=True,
         formatDate=1)
     # ss.cancelScannerSubscription(ss)
     # self.ib.cancelScannerSubscription(ss)
     # arr = np.array(scan)
     return data_
コード例 #8
0
    async def GetStockHistoricalData(
            self, stream: Stream[GetStockHistoricalDataRequest, Bar]) -> None:
        request = await stream.recv_message()
        assert request is not None

        contract = Stock(request.symbol, request.exchange, request.currency)
        endDate = request.endDate.ToDatetime()
        if endDate == datetime(1970, 1, 1, 0, 0):
            endDate = None

        head_ts = await self.ib.reqHeadTimeStampAsync(contract,
                                                      useRTH=True,
                                                      whatToShow="TRADES",
                                                      formatDate=2)

        print(contract, endDate)
        while True:
            # Compare the date as the head timestamp does not
            # always matches what we get on the last request
            if endDate is not None and head_ts.date() >= endDate.date():
                break

            bars = await self.ib.reqHistoricalDataAsync(
                contract,
                endDateTime=endDate,
                durationStr="10 D",
                barSizeSetting="5 mins",
                useRTH=True,
                whatToShow="TRADES",
                formatDate=2,
            )

            if not bars:
                break

            endDate = bars[0].date

            for bar in reversed(bars):
                await stream.send_message(
                    Bar(
                        timestamp=timestamp_from_datetime(bar.date),
                        duration=duration_from_timedelta(timedelta(minutes=5)),
                        open=bar.open,
                        high=bar.high,
                        low=bar.low,
                        close=bar.close,
                        volume=bar.volume,
                        trades=bar.barCount,
                        vwap=bar.average,
                    ))
コード例 #9
0
    def find_eligible_contracts(self, symbol, right):
        is_auto_select = self.config["nope"]["contract_auto_select"]
        EXCHANGE = "SMART"
        MAX_STRIKE_OFFSET = 6 if is_auto_select else 11

        stock = Stock(symbol, EXCHANGE, currency="USD")
        self.ib.qualifyContracts(stock)
        [ticker] = self.ib.reqTickers(stock)
        ticker_value = ticker.marketPrice()
        chains = self.ib.reqSecDefOptParams(stock.symbol, "", stock.secType,
                                            stock.conId)
        chain = next(c for c in chains if c.exchange == EXCHANGE)

        def valid_strike(strike):
            if strike % 1 == 0:
                if right == "C":
                    max_ntm_call_strike = ticker_value + MAX_STRIKE_OFFSET
                    min_itm_call_strike = (ticker_value - MAX_STRIKE_OFFSET
                                           if is_auto_select else ticker_value)
                    return min_itm_call_strike <= strike <= max_ntm_call_strike
                elif right == "P":
                    min_ntm_put_strike = ticker_value - MAX_STRIKE_OFFSET
                    max_itm_put_strike = (ticker_value + MAX_STRIKE_OFFSET
                                          if is_auto_select else ticker_value)
                    return min_ntm_put_strike <= strike <= max_itm_put_strike
            return False

        strikes = [strike for strike in chain.strikes if valid_strike(strike)]

        if is_auto_select:
            min_dte = self.config["nope"]["auto_min_dte"]
            expirations = sorted(
                exp for exp in chain.expirations)[min_dte:min_dte + 5]
        else:
            exp_offset = self.config["nope"]["expiry_offset"]
            expirations = sorted(
                exp for exp in chain.expirations)[exp_offset:exp_offset + 1]

        contracts = [
            Option(
                self.SYMBOL,
                expiration,
                strike,
                right,
                EXCHANGE,
                tradingClass=self.SYMBOL,
            ) for expiration in expirations for strike in strikes
        ]

        return contracts
コード例 #10
0
ファイル: z_async_errors.py プロジェクト: ajmal017/learn
async def coro():

    with await IB().connectAsync(host='127.0.0.1', port=1300,
                                 clientId=0) as ib:

        contracts = await ib.qualifyContractsAsync(*[
            Stock(s, "SMART", "USD")
            for s in ['AAPL', 'INTC', 'BLK', 'ABBV', 'LOWE']
        ])

        # The bad egg!!
        contracts.extend([
            Stock(conId=11758,
                  symbol='RTN',
                  exchange='SMART',
                  primaryExchange='NYSE',
                  currency='USD',
                  localSymbol='RTN',
                  tradingClass='RTN')
        ])

        tasks = [ohlcAsync(ib, c) for c in contracts]

        return await asyncio.gather(*tasks)
コード例 #11
0
ファイル: download.py プロジェクト: freevanx/ib_dl
def _fetch_to_df(ib, symbol, duration, bar_size):
    logger.info(f'Downloading historical data of {symbol} for {duration} '
                f'with {bar_size} resolution')

    contract = Stock(symbol, exchange='SMART', currency='USD')
    bars = ib.reqHistoricalData(
        contract, endDateTime='', durationStr=duration,
        barSizeSetting=bar_size, whatToShow='TRADES', useRTH=True)

    df = util.df(bars)
    df.set_index('date', inplace=True)
    df.index = df.index.tz_localize(LOCAL_TZ).tz_convert('UTC')
    df['volume'] *= 100

    return df
コード例 #12
0
ファイル: basem.py プロジェクト: codcodog/ib-api-examples
    def crawl_data(self, codes):
        ''' 爬取 IB 接口股票的交易信息
        '''
        futures = []
        i = 0
        for code in codes:
            i += 1
            symbol, _ = code
            stock  = Stock(symbol, Config.hk_exchange, Config.hk_currency)
            future = self.ib.reqHistoricalDataAsync(stock, endDateTime='', durationStr='900 S',
                                                    barSizeSetting='5 mins', whatToShow='TRADES', useRTH=True)
            self.ib.sleep(0.02)
            future.add_done_callback(functools.partial(self.deal_data, symbol=symbol))
            futures.append(future)

        return futures
コード例 #13
0
ファイル: data_request.py プロジェクト: aestrad494/kafka
 def get_contract(self):
     if self.market == 'futures':
         local = self._local_symbol_selection()
         self.contract = Future(symbol=self.symbol,
                                exchange=self.exchange,
                                localSymbol=local)
         print(
             self.ib.reqContractDetails(
                 self.contract)[0].contract.lastTradeDateOrContractMonth)
         '''expiration = self.ib.reqContractDetails(Future(self.symbol,self.exchange))[0].contract.lastTradeDateOrContractMonth
         self.contract = Future(symbol=self.symbol, exchange=self.exchange, lastTradeDateOrContractMonth=expiration)'''
     elif self.market == 'forex':
         self.contract = Forex(self.symbol)
     elif self.market == 'stocks':
         self.contract = Stock(symbol=self.symbol,
                               exchange=self.exchange,
                               currency='USD')
コード例 #14
0
def fnCreateIBSymbol(ticker_tk=None, ticker_at=None):

    if not ticker_tk:
        ticker_tk = 'SPY'
    if not ticker_at:
        ticker_at = 'EQT'

    symIB = None

    if ticker_at == 'EQT':
        symIB = [ticker_tk, Stock(ticker_tk, 'SMART', 'USD')]
    elif ticker_at == 'FUT':
        symIB = [ticker_tk, Future(ticker_tk, 'SMART', 'USD')]
    elif ticker_at == 'FX':
        symIB = [ticker_tk, Forex(ticker_tk, 'IDEALPRO')]

    return symIB
コード例 #15
0
ファイル: _test.py プロジェクト: reservoirinvest/ibkr
async def basedata(ib, symbols):

    contracts = [
        await ib.qualifyContractsAsync(Stock(s, 'SMART', 'USD'))
        for s in symbols
    ]

    # Dictionary to eliminate duplicate symbols
    contracts = {s.symbol: s for c in contracts for s in c}

    d = {}

    # get prices, chains and ohlcs with standard deviaPtion
    for contract in contracts.values():
        tick = await ib.reqTickersAsync(contract)
        chain = await ib.reqSecDefOptParamsAsync(
            underlyingSymbol=contract.symbol,
            futFopExchange='',
            underlyingSecType=contract.secType,
            underlyingConId=contract.conId)

        ohlc = await ib.reqHistoricalDataAsync(contract=contract,
                                               endDateTime='',
                                               durationStr='365 D',
                                               barSizeSetting='1 day',
                                               whatToShow='Trades',
                                               useRTH=True)
        ohlc = util.df(ohlc)

        ohlc = ohlc.assign(dte=ohlc.index.astype(int))

        ohlc = ohlc.assign(sd=ohlc.close.expanding(1).std(ddof=0))

        ohlc.insert(1, 'symbol', contract.symbol)
        # ohlc = ohlc.groupby('symbol').apply(lambda df: df.sort_values(
        #     'date', ascending=False)).reset_index(drop=True)
        # ohlcsd = ohlc.groupby('symbol').apply(
        #     lambda df: df.assign(sd=df.close.expanding(1).std(ddof=0)))

        d[contract.symbol] = (tick[0].marketPrice(), chain[0].expirations,
                              chain[0].strikes, ohlc)

    return d
コード例 #16
0
    def crawl_data(self, codes):
        ''' IB 接口爬取数据
        '''
        # 计算与上一次爬取日期的差值
        records = self.db.get_records()
        if not records.rowcount:
            raise Exception('获取上次爬取数据日期失败,数据库 records 表返回空.')
        last_time = list(records)[0].date
        now_time  = datetime.datetime.now()
        diff      = now_time - last_time
        dur       = diff.days
        i         = 0
        total     = len(codes)

        for code in codes:
            symbol = code[0]
            stock  = Stock(symbol, Config.hk_exchange, Config.hk_currency)
            future = self.ib.reqHistoricalDataAsync(stock, endDateTime='', durationStr='%d D' % dur,
                                                    barSizeSetting='1 day', whatToShow='TRADES', useRTH=True)
            self.ib.sleep(0.02)
            future.add_done_callback(functools.partial(self.deal_data, symbol=symbol, last_time=last_time))
            self.f.append(future)
コード例 #17
0
    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()
    print("\n\n")
    print(f"For: {contract.symbol} with future price of {future_price}")
    df["Price"] = df["Ask"] * df["Multiplier"]
コード例 #18
0
    def mkt_cap(self, symbol_, threshold_):
        log_start = datetime.datetime.now()
        log = logging_.Logging(
            self.lt.runtime_tm, log_start,
            str(self.__class__.__name__ + ',' +
                sys._getframe().f_code.co_name))

        if isinstance(threshold_, int) or isinstance(threshold_, float):
            raise Exception('invalid value, must be a letter at end')
        if threshold_[-1] == 'M':
            mult_ = 1000000
        elif threshold_[-1] == 'B':
            mult_ = 1000000000
        else:
            mult_ = 1
        threshold_ = int(threshold_[:-1]) * mult_
        self.lt.hlprs.add_to_manager(self.lt.manager_, *log.monitor())

        contract_ = Stock(symbol_, 'ISLAND', 'USD')
        snapshot_xml = self.lt.ib.reqFundamentalData(contract_,
                                                     'ReportSnapshot')
        if len(snapshot_xml) > 0:
            snapshot = xmltodict.parse(snapshot_xml)
            fin_stat_xml = self.lt.ib.reqFundamentalData(
                contract_, 'ReportsFinStatements')
            fin_stat = xmltodict.parse(fin_stat_xml)
            px_ = float(snapshot \
                ['ReportSnapshot']\
                ['Ratios']\
                ['Group']\
                [0]\
                ['Ratio']\
                [0]\
                ['#text'])
            coa_ = fin_stat \
                ['ReportFinancialStatements']\
                ['FinancialStatements']\
                ['COAMap']\
                ['mapItem']
            # periods = fin_stat \
            #     ['ReportFinancialStatements']\
            #     ['FinancialStatements']\
            #     ['AnnualPeriods']\
            #     ['FiscalPeriod']
            line_items_ = fin_stat \
                ['ReportFinancialStatements']\
                ['FinancialStatements']\
                ['AnnualPeriods']\
                ['FiscalPeriod']\
                [0]\
                ['Statement']\
                [1]\
                ['lineItem']
            # [len(periods)-1]\
            for ix_, acc_grp in enumerate(coa_):
                if acc_grp['#text'] == 'Total Common Shares Outstanding':
                    where = coa_[ix_]['@coaItem']
                    precision_ = int(acc_grp['@precision'])
                    if precision_ == 1:
                        zeros = 1000.0
                    elif precision_ == 2:
                        zeros = 1000000.0
                    else:
                        zeros = 1.0
                    for ix2, line_ in enumerate(line_items_):
                        if line_['@coaCode'] == where:
                            shares_outstanding_ = float(
                                line_items_[ix2]['#text']) * zeros
                            break
            mkt_cap = px_ * shares_outstanding_
        else:
            mkt_cap = 0.0
        log.log()
        if mkt_cap > threshold_:
            return True
        else:
            return False
コード例 #19
0
    "XME",
    "FXI",
    "EWZ",
    "FB",
    "AAPL",
    "NFLX",
    "MSFT",
    "BABA",
    "INTC",
    "TSLA",
]
FUTURES = [
    "ES", "NQ", "RTY", "CL", "NG", "ZB", "ZN", "GC", "MXP", "EUR", "JPY", "GBP"
]

stockContracts = [Stock(s, "SMART", "USD") for s in STOCK]
ib.qualifyContracts(*stockContracts)

futures = [ib.reqContractDetails(Future(f)) for f in FUTURES]
futuresContracts = [c.contract for f in futures for c in f]
futuresContracts = [
    c for c in futuresContracts if c.tradingClass == c.symbol
    and c.lastTradeDateOrContractMonth.startswith("2019")
]

for contract in stockContracts + futuresContracts:
    ib.reqMktData(contract, "", False, False)


def onPendingTickers(tickers):
    ticks = []
コード例 #20
0
import os

from ib_insync import Forex, Stock

from models.hft_model_1 import HftModel1

if __name__ == '__main__':
    TWS_HOST = os.environ.get('TWS_HOST', '127.0.0.1')
    TWS_PORT = os.environ.get('TWS_PORT', 4002)

    print('Connecting on host:', TWS_HOST, 'port:', TWS_PORT)

    model = HftModel1(
        host=TWS_HOST,
        port=TWS_PORT,
        client_id=1,
    )

    to_trade = [
        ('SPY', Stock('SPY', 'SMART', 'USD')),
        ('QQQ', Stock('QQQ', 'SMART', 'USD')),
    ]

    # to_trade = [
    # 	Stock('QQQ', 'SMART', 'USD'),
    # 	Stock('SPY', 'SMART', 'USD')
    # ]

    model.run(to_trade=to_trade, trade_qty=100)
from ib_insync import Forex, Stock

from models.cointegration_model_1 import coint1

from multiprocessing import Process

if __name__ == '__main__':
    hotspot = '192.168.43.7'
    local = '127.0.0.1'
    TWS_HOST = os.environ.get('TWS_HOST', local)
    TWS_PORT = os.environ.get('TWS_PORT', 7497)

    print('Connecting on host:', TWS_HOST, 'port:', TWS_PORT)
    data_directory = 'D:/PRISMO/historicalData/data/allOrdsnobiasFINAL.pickle'
    model = coint1(data_directory=data_directory,
                   delta=4e-07,
                   ve=2e-05,
                   host=TWS_HOST,
                   port=TWS_PORT,
                   quantityPerTrade=1000,
                   client_id=3)

    to_trade = [('1548', Stock("1548", "SEHK")),
                ('1426', Stock("1426", 'SEHK'))]

    model.run(to_trade=to_trade, trade_qty=100)

# to_trade = [
# ('IOO',Stock("IOO","ASX")),
# ('IZZ', Stock("IZZ",'ASX'))
# 	]
コード例 #22
0
equities = [e for e in list(df_snp.Symbol) if e in list(df_cboe.Ticker)]

# filter and list the etfs
df_etf = df_cboe[df_cboe.ProductType == 'ETF'].reset_index(drop=True)

etfs = [e for e in df_etf.Ticker if e not in 'VXX']  # Remove VXX

stocks = sorted(equities + etfs)

# list the indexes (sometimes does not work!!!)
# indexes = sorted('OEX,XEO,XSP'.split(','))
indexes = []

#...Build a list of contracts
stocks = [
    Stock(symbol=s, currency=currency, exchange=exchange) for s in set(stocks)
]

# sort the stocks
s_dict = {s.symbol: s for s in stocks}
od = OrderedDict(sorted(s_dict.items()))
ss = [v for k, v in od.items()]

# ixs = [Index(symbol=s,currency=currency, exchange='CBOE') for s in set(indexes)]
ixs = [
    Index(symbol=s, currency=currency, exchange='CBOE') for s in set(indexes)
]

cs = ss + ixs

# cs = cs[15:18] # DATA LIMITER!!!
import os

from ib_insync import Forex, Stock

from models.cointegration_model_1 import coint1

from multiprocessing import Process

if __name__ == '__main__':
    hotspot = '192.168.43.7'
    local = '127.0.0.1'
    TWS_HOST = os.environ.get('TWS_HOST', local)
    TWS_PORT = os.environ.get('TWS_PORT', 7497)

    print('Connecting on host:', TWS_HOST, 'port:', TWS_PORT)
    data_directory = 'D:/PRISMO/historicalData/data/allOrdsnobiasFINAL.pickle'
    model = coint1(data_directory=data_directory,
                   delta=4e-07,
                   ve=2e-05,
                   host=TWS_HOST,
                   port=TWS_PORT,
                   client_id=2)

    to_trade = [('NKE', Stock("NKE", "NYSE")), ('IBM', Stock("IBM", 'NYSE'))]

    model.run(to_trade=to_trade, trade_qty=100)

# to_trade = [
# ('IOO',Stock("IOO","ASX")),
# ('IZZ', Stock("IZZ",'ASX'))
# 	]
コード例 #24
0
async def get_contract(ib, symbol):
    return await ib.qualifyContractsAsync(Stock(symbol, "SMART", "USD"))
コード例 #25
0
            if FLAG_FOR_TESTING:
                stock_traded_condition = False

            if stock_traded_condition:
                logger.info(
                    "A trade for %s has already been filled. Moving to the next stock"
                    % stock)

            else:
                logger.info(
                    "Run the strategy's buy logic for %s stock (stock number %s in the list of %s stocks)"
                    % (stock, stock_count + 1, len(symbols_list)))

                logger.info('Create the contract object')
                stock_contract = Stock(stock, exchange, currency)
                ib.qualifyContracts(stock_contract)

                last_price, todays_total_volume, \
                latest_prevclose_change, latest_open_change = extract_quotes(stock_contract, ib)

                todays_total_volume = y_quotes(stock)[1]
                #                print( str(stock) + ' Price: ' + str(last_price) + ' Vol: ' + str(todays_total_volume) + ' PrevCloseChage: ' + str(latest_prevclose_change) + ' OpenChange: ' + str(latest_open_change))

                if (net_balance > 0) and all(number is not None for number in [
                        last_price, todays_total_volume,
                        latest_prevclose_change, latest_open_change
                ]):

                    # check for the required conditions
                    logger.info(
コード例 #26
0
    df_unds = pd.read_pickle(FSPATH + '_df_unds.pkl')
    """ #### Testing get_2_ohlc(). Successful!!
    
    # Make two contracts
    contracts = df_unds.groupby('ctype').head(1).contract

    with IB().connect(host=HOST, port=PORT, clientId=CID) as ib:
        oh_list = [get_2_ohlcs(ib, c) for c in contracts]
        
    df_ohlcs = pd.concat(oh_list)
    print(df_ohlcs) """

    #### Testing tqdm with a bad egg.

    # Get some contracts
    contracts = list(df_unds[df_unds.symbol.isin(['INTC', 'SBUX'])].contract)

    # RTN is a bad egg!
    rtn = [
        Stock(conId=11758,
              symbol='RTN',
              exchange='SMART',
              primaryExchange='NYSE',
              currency='USD',
              localSymbol='RTN',
              tradingClass='RTN')
    ]
    contracts.extend(rtn)

    print(asyncio.run(main()))
コード例 #27
0
# nseSymbol to ibSymbol dictionary for conversion
ntoi = {'M&M': 'MM', 'M&MFIN': 'MMFIN', 'L&TFH': 'LTFH', 'NIFTY': 'NIFTY50'}

# remap ibSymbol, based on the dictionary
df_slm.ibSymbol = df_slm.ibSymbol.replace(ntoi)

# separate indexes and equities, eliminate discards from df_slm
indexes = ['NIFTY50', 'BANKNIFTY']
discards = ['NIFTYMID5', 'NIFTYIT', 'LUPIN']
equities = sorted([s for s in df_slm.ibSymbol if s not in indexes + discards])

symbols = equities + indexes

cs = [
    Stock(s, exchange) if s in equities else Index(s, exchange)
    for s in symbols
]

# cs = cs[:5] # DATA LIMITER!!!


def nse_list(ib):
    '''returns a list of qualified nse underlyings, with symbols and option chains for them
    Args: ib as the active ib object
    Returns: qualified list with conID
    '''
    qcs = ib.qualifyContracts(*cs)  # qualified underlyings

    qcs_chains = []
    for i in range(0, len(qcs), 50):
コード例 #28
0
ファイル: aio_hist_simn.py プロジェクト: ajmal017/learn
# test to see how asyncio works with a timeout for many symbols.
# Index symbol (ref: https://groups.io/g/insync/message/4718)
# Index symbols have also been put into the mix!

import asyncio
import time

import pandas as pd
from ib_insync import IB, Index, Stock, util

HOST = '127.0.0.1'
PORT = '1300'
CID = 0
""" contracts = ib.qualifyContracts(*[
Stock(symbol='SBUX', exchange='SMART', currency='USD'),
Stock(symbol='AAPL', exchange='SMART', currency='USD'),
Stock(symbol='INTC', exchange='SMART', currency='USD'),
Index(symbol='VIX', exchange='CBOE', currency='USD'),
Index(symbol='MXEA', exchange='CBOE', currency='USD')
])
ib.sleep(0.1) """

start_time = time.time()

# Get the contracts
contracts = pd.read_pickle(
    "C:/Users/User/Documents/Business/Projects/asyncib/data/snp/df_syms.pkl"
).contract.dropna()
duration = 365

    TWS_HOST = os.environ.get('TWS_HOST', local)
    TWS_PORT = os.environ.get('TWS_PORT', 7497)

    print('Connecting on host:', TWS_HOST, 'port:', TWS_PORT)
    directories = {}
    directories['Path'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/'
    directories['GUI'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/gui/'
    directories[
        'Data'] = 'D:/PRISMO/historicalData/data/allOrdsnobiasFINAL.pickle'
    directories[
        'Orderbook'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/orderMetaData/orderBooks/'
    directories[
        'Comissions'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/orderMetaData/comission/'
    directories[
        'Price_Histories'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/orderMetaData/priceHistories/'
    directories['logs'] = 'C:/Users/Billy/Documents/PRISMO/Executioner/logs/'
    model = coint1(directories=directories,
                   delta=9e-06,
                   ve=0.002,
                   host=TWS_HOST,
                   port=TWS_PORT,
                   client_id=2)

    to_trade = [('ABP', Stock("ABP", "ASX")), ('SPK', Stock("SPK", 'ASX'))]

    model.run(to_trade=to_trade, trade_qty=100)

# to_trade = [
# ('IOO',Stock("IOO","ASX")),
# ('IZZ', Stock("IZZ",'ASX'))
コード例 #30
0
ファイル: scanners1.py プロジェクト: rmlv159/live_trading
    def run_(self):
        if self.strat.debugging.dummy_time:
            _now = self.strat.lt._manipulated_time(datetime.datetime.now())
        else:
            _now = datetime.datetime.now()
        while self.strat.lt.us_tz_op(_now).time() < datetime.datetime.strptime(
                self.analysis_logic_start_time, '%H:%M:%S').time():
            if self.strat.debugging.dummy_time:
                _now = self.strat.lt._manipulated_time(datetime.datetime.now())
            else:
                _now = datetime.datetime.now()
            self.strat.lt.ib.sleep(5)

        _analysis_logic = datetime.datetime.strptime(
            self.analysis_logic_start_time, '%H:%M:%S')  # .time()
        _trading_logic = datetime.datetime.strptime(
            self.trading_logic_start_time, '%H:%M:%S')  # .time()
        _n_iters = int((_trading_logic - _analysis_logic).seconds / 60)
        _tries = 0
        while _tries < _n_iters:
            # if self.market_open.debugging:
            if self.strat.debugging.dummy_data:
                self.__winners = self.strat.debugging.dummy_instr
                break
            else:
                try:
                    self.__winners = self.find_winners(
                        self.strat.parallel_traded_instr_per_strat)
                    self.strat.add_to_manager(self.strat.strat_name,
                                              '__winners', self.__winners)
                    break
                except Exception as e:
                    self.cons_disp.print_warning(
                        'waiting 60 secs because no winner could be determined in this iteration'
                    )
                    self.strat.lt.ib.sleep(60)
                    _tries += 1
        else:
            raise Exception('couldnt determine winners')
        _par = self.strat.parallel_traded_instr_per_strat
        _until = _par if _par < len(self.__winners) else len(self.__winners)
        pre_select = self.__winners[0:_until]
        self._iter_ = 0
        traded_instr_this_strat = self._check_tradeability_of_instr(pre_select)
        while True:
            # for customReqId, symbol in enumerate(self.strat.lt.traded_instr):
            for customReqId, symbol in enumerate(traded_instr_this_strat):
                contract = Stock(symbol, 'ISLAND', 'USD')
                # if self.market_open.debugging:
                status = None
                if self.strat.debugging.dummy_data:
                    if customReqId < len(self.strat.lt.traded_instr):
                        self.last_price = {}
                        self.last_price[symbol] = 236.39
                    # simulate down turn after n minutes
                    mins_down_turn = 4
                    delta_mins = (datetime.datetime.now() -
                                  self.strat.lt.start_cet).seconds * 60
                    if delta_mins < mins_down_turn:
                        # _sign = random.choice(['+','-'])
                        _sign = '+'
                    else:
                        _sign = '-'
                    _price = self.last_price[symbol] * float(
                        eval('1.0' + _sign + str(random.uniform(0.001, 0.05))))
                    _size = random.randint(20, 8000)
                    ticker = helpers.Tick_(
                        contract=contract,
                        domBids=[
                            helpers.Lines_(price=_price + 0.3,
                                           size=_size * (1 - 0.15)),
                            helpers.Lines_(price=_price + 0.2,
                                           size=_size * (1 - 0.10)),
                            helpers.Lines_(price=_price + 0.1,
                                           size=_size * (1 - 0.05)),
                            helpers.Lines_(price=_price, size=_size)
                        ],
                        domAsks=[
                            helpers.Lines_(price=_price - 0.3,
                                           size=_size * (1 - 0.05)),
                            helpers.Lines_(price=_price - 0.4,
                                           size=_size * (1 - 0.10)),
                            helpers.Lines_(price=_price - 0.5,
                                           size=_size * (1 - 0.15)),
                            helpers.Lines_(price=_price - 0.6,
                                           size=_size * (1 - 0.20)),
                            helpers.Lines_(price=_price - 0.7,
                                           size=_size * (1 - 0.25))
                        ])
                else:
                    ticker, status = self.strat.lt.req_mkt_dpt_ticker_(
                        contract)
                # self.market_open.lt.req_handling(ticker, 'mktDepth')
                if customReqId == 0:
                    self.last_iteration = datetime.datetime.now()
                    unix_ts = int(time.time())
                if status != 1:
                    status = self.collect_hist_ticks(ticker, unix_ts)
                if status == 1:
                    self.strat.lt.cancel_mkt_dpt_ticker_(contract)
                    next_in_line = self.__winners.pop(0)
                    self.reshuffle_winners(
                        self.strat.parallel_traded_instr_per_strat,
                        next_in_line,
                        remove=symbol)
                    traded_instr_this_strat = self._check_tradeability_of_instr(
                        traded_instr_this_strat)
                    # _trix_ = traded_instr_this_strat.index(symbol)
                    # del traded_instr_this_strat[_trix_]
                    break

                if self._iter_ == 0:
                    # self.scanner_based._init_trade_cnt(self.__traded_instr)
                    self.strat._init_trade_cnt(self.strat.lt.traded_instr)

                self.strat.update_trade_flow(ticker)
                self.strat.lt.cancel_mkt_dpt_ticker_(contract)
                self._iter_ += 1

            while (datetime.datetime.now() -
                   self.last_iteration).seconds < self.strat.bar_size_secs:
                # print('looping through bar seconds gate', '(datetime.datetime.now() - self.last_iteration).seconds < BAR_SIZE_SECS: ',
                #       (datetime.datetime.now() - self.last_iteration).seconds < BAR_SIZE_SECS)
                # self.market_open.lt.ib.sleep(1)
                continue
            try:
                self.strat._check_if_done()
                continue
            except Exception as e:
                self.strat.exc.handle_(e, self.strat.debugging.raise_errors)
            self.strat.conclude_results()
            break