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')
def c_order(self, buy_sell): '''click buy button''' if self.check_login(): return prod = self.box_product.currentText()[0:3] prodM = self.box_month.currentText()[0:6] price = self.box_price.value() qty = self.box_qty.value() hsi = Future(prod, prodM) if web_trade.ib.qualifyContracts(hsi): if buy_sell == 'B': order = LimitOrder('BUY', qty, price, outsideRth=self.c_t1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") else: order = LimitOrder('SELL', qty, price, outsideRth=self.c_t1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) print("%s%s %d@%d" % (prod, prodM, qty if buy_sell == 'B' else -qty, price)) if web_trade.status == 2: w.statusBar().showMessage(web_trade.error)
def __init__(self): self.ib = IB() self.ib.connect('127.0.0.1', 7497, clientId=np.random.randint(10, 1000)) self.tickers_ret = {} self.endDateTime = '' self.No_days = '43200 S' self.interval = '30 secs' self.tickers_signal = "Hold" self.ES = Future(symbol='ES', lastTradeDateOrContractMonth='20200619', exchange='GLOBEX', currency='USD') self.ib.qualifyContracts(self.ES) self.ES_df = self.ib.reqHistoricalData(contract=self.ES, endDateTime=self.endDateTime, durationStr=self.No_days, barSizeSetting=self.interval, whatToShow='TRADES', useRTH=False, keepUpToDate=True) self.tickers_ret = [] self.options_ret = [] self.option = {'call': FuturesOption, 'put': FuturesOption} self.options_history = {} self.trade_options = {'call': [], 'put': []} self.price = 0 self.i = -1 self.ES_df.updateEvent += self.make_clean_df self.Buy = True self.Sell = False self.ib.positionEvent += self.order_verify self.waitTimeInSeconds = 120 self.tradeTime = 0
def c_stop(self, buy_sell): if self.check_login(): return prod = self.box_product.currentText()[0:3] prodM = self.box_month.currentText()[0:6] qty = self.box_qty.value() stop_price = self.box_stop_price.value() stop_type = self.box_stop_type.currentText()[0:1] addon = self.box_add2.value() # print(prod, prodM, qty, stop_price, stop_type, addon) hsi = Future(prod, prodM) if web_trade.ib.qualifyContracts(hsi): if buy_sell == 'B': order = StopLimitOrder('BUY', qty, stop_price + addon, stop_price, outsideRth=self.c_t1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") else: order = StopLimitOrder('SELL', qty, stop_price - addon, stop_price, outsideRth=self.c_t1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) if web_trade.status == 2: w.statusBar().showMessage(web_trade.error)
def ib_futures_instrument( futures_instrument_with_ib_data: futuresInstrumentWithIBConfigData): """ Get an IB contract which is NOT specific to a contract date Used for getting expiry chains :param futures_instrument_with_ib_data: instrument with .metadata suitable for IB :return: IBcontract """ ib_data = futures_instrument_with_ib_data.ib_data ibcontract = Future(ib_data.symbol, exchange=ib_data.exchange) if ib_data.ibMultiplier is NOT_REQUIRED_FOR_IB: pass else: ibcontract.multiplier = int(ib_data.ibMultiplier) if ib_data.currency is NOT_REQUIRED_FOR_IB: pass else: ibcontract.currency = ib_data.currency return ibcontract
def get_contracts(ib_gw, series, n): contract_years = [str(datetime.now().year + i)[-1] for i in range(2)] contract_symbols = [ series + m + y for y in contract_years for m in CONTRACT_SPECS[series]['months'] ] logging.info( 'Requesting contract details for {}...'.format(contract_symbols)) contract_details = {} for symbol in contract_symbols: cd = ib_gw.reqContractDetails( Future(localSymbol=symbol, exchange=CONTRACT_SPECS[series]['exchange'], currency=CONTRACT_SPECS[series]['currency'])) contract_details[symbol] = cd[0].contract if len(cd) > 0 else None contracts = { k: v for k, v in contract_details.items() if v is not None and v.lastTradeDateOrContractMonth > (datetime.now() + timedelta(days=6)).strftime('%Y%m%d') } return [ contracts[k] for k in [k for k in contract_symbols if k in contracts.keys()][:n] ]
def cb_close1(self): if self.check_login(): return getLots = self.box_lot2.value() if getLots == 0: return Lots, Price = self.calc_close() if Lots is None or Price is None: return prod = self.set1['合约'] web_trade.ib.waitOnUpdate(0.1) able_lots = web_trade.get_lots('LMT') if prod not in able_lots or able_lots[prod] == 0: return if abs(Lots) > abs(able_lots[prod]): Lots = able_lots[prod] # prod_code=prod[0:3] # prod_month=prod[3:5] # web_trade.orderdata['prod_code'] = prod_code # web_trade.orderdata['contract_mth'] = prod_month lotsList = self.getList(abs(int(Lots))) # print(getLots,prod,Lots,Price,lotsList,self.c_close1.isChecked()) hsi = Future(localSymbol=prod) if web_trade.ib.qualifyContracts(hsi): if Lots > 0: for x in lotsList: # web_trade.order_buy(Price, x, prod_code=prod_code) zy, thereAre = self.zszyGroup('zy') order = LimitOrder('BUY', x, Price, ocaGroup=zy, ocaType=2, outsideRth=self.c_close1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) print("%s %d@%d" % (prod, x, Price)) else: for x in lotsList: # web_trade.order_sell(Price, x, prod_code=prod_code) zy, thereAre = self.zszyGroup('zy') order = LimitOrder('SELL', x, Price, ocaGroup=zy, ocaType=2, outsideRth=self.c_close1.isChecked(), orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) print("%s -%d@%d" % (prod, x, Price)) self.box_lot2.setValue(0) self.c_orderlist()
def c_gostop(self): if self.check_login(): return getLots = self.box_lot1.value() if getLots == 0: return Lots, StopPrice = self.calc_stop() if Lots is None or StopPrice is None: return addon = self.box_add.value() prod = self.set1['合约'] web_trade.ib.waitOnUpdate(0.1) able_lots = web_trade.get_lots('STP LMT') if prod not in able_lots or able_lots[prod] == 0: return if abs(Lots) > abs(able_lots[prod]): Lots = able_lots[prod] lotsList = self.getList(abs(int(Lots))) # print(getLots,Lots,StopPrice,addon,prod,lotsList) hsi = Future(localSymbol=prod) if web_trade.ib.qualifyContracts(hsi): if Lots > 0: for i in lotsList: # web_trade.order_stopS(StopPrice,i,prod,addon) zs, thereAre = self.zszyGroup('zs') order = StopLimitOrder('BUY', i, StopPrice + addon, StopPrice, ocaGroup=zs, ocaType=2, orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) print("%d@%d-%s" % (i, StopPrice, prod)) else: for i in lotsList: # web_trade.order_stopB(StopPrice,i, prod,addon) zs, thereAre = self.zszyGroup('zs') order = StopLimitOrder('SELL', i, StopPrice - addon, StopPrice, ocaGroup=zs, ocaType=2, orderRef=f"PY_{self.pwd_id[-1]}") web_trade.ib.placeOrder(hsi, order) print("%d@%d-%s" % (-i, StopPrice, prod)) self.box_lot1.setValue(0) self.c_orderlist()
def lookup_futures(self, obj: List[Future]) -> List[Future]: futures = [] for o in obj: o.update(includeExpired=True) futures.append([ Future(**c.contract.dict()) for c in self.ib.reqContractDetails(o) ]) return list(itertools.chain(*futures))
def contract_details_cl(): # Write pickled CL contract details to a file client = ib_insync.IB() client.connect() contract = Future( instrument_id="CL", lastTradeDateOrContractMonth="20211119", exchange="NYMEX", currency="USD", ) details = client.reqContractDetails(contract) with open("contract_details_cl.pickle", "wb") as file: pickle.dump(details[0], file)
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
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')
def get_futures(contract_str, remove_weekly=False): ibw = IbWrapper() ib = ibw.ib vix = Future(contract_str, includeExpired=False) cds = ib.reqContractDetails(vix) contracts = [cd.contract for cd in cds] if remove_weekly: contracts = [ contract for contract in contracts if len(contract.localSymbol) <= 4 ] bars_list = [] for contract in contracts: bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='5 D', barSizeSetting='1 day', whatToShow='TRADES', useRTH=True, formatDate=1) if bars: bars_list.append(util.df(bars)) ib.disconnect() contract_df = util.df(contracts) close_list = [item.loc[:, ['date', 'close']] for item in bars_list] close_list = [item.set_index('date') for item in close_list] close_list = [ item.rename(index=str, columns={'close': name}) for item, name in zip( close_list, pd.to_datetime(contract_df['lastTradeDateOrContractMonth'])) ] future_series = pd.concat(close_list, axis=1, sort=False) future_series = future_series.transpose().sort_index() future_series.columns = pd.to_datetime(future_series.columns) return future_series, contract_df
def ib_futures_instrument(futures_instrument_object): """ Get an IB contract which is NOT specific to a contract date Used for getting expiry chains :param futures_instrument_object: instrument with .metadata suitable for IB :return: IBcontract """ meta_data = futures_instrument_object.meta_data ibcontract = Future(meta_data['symbol'], exchange=meta_data['exchange']) if meta_data['ibMultiplier'] is NOT_REQUIRED: pass else: ibcontract.multiplier = int(meta_data['ibMultiplier']) if meta_data['currency'] is NOT_REQUIRED: pass else: ibcontract.currency = meta_data['currency'] return ibcontract
def get_contracts(series, n): """ Requests contract details for a series of futures :param series: ticker symbol (str) :param n: number of consecutive contracts (int) :return: list of Contract """ contract_years = [str(datetime.now().year + i)[-1] for i in range(2)] contract_symbols = [ series + m + y for y in contract_years for m in CONTRACT_SPECS[series]['months'] ] module_logger.info( 'Requesting contract details for {}...'.format(contract_symbols)) contract_details = {} for symbol in contract_symbols: cd = ib_gw.reqContractDetails( Future(localSymbol=symbol, exchange=CONTRACT_SPECS[series]['exchange'], currency=CONTRACT_SPECS[series]['currency'])) contract_details[symbol] = cd[0].contract if len(cd) > 0 else None contracts = { k: v for k, v in contract_details.items() # roll over 6 days prior to expiry if v is not None and v.lastTradeDateOrContractMonth > (datetime.now() + timedelta(days=6)).strftime('%Y%m%d') } return [ contracts[k] for k in [k for k in contract_symbols if k in contracts.keys()][:n] ]
def parse_contract(ticker): """ Backtrader contract specification (https://www.backtrader.com/docu/live/ib/ib.html): TICKER # Stock type and SMART exchange TICKER-STK # Stock and SMART exchange TICKER-STK-EXCHANGE # Stock TICKER-STK-EXCHANGE-CURRENCY # Stock TICKER-CFD # CFD and SMART exchange TICKER-CFD-EXCHANGE # CFD TICKER-CDF-EXCHANGE-CURRENCY # Stock TICKER-IND-EXCHANGE # Index TICKER-IND-EXCHANGE-CURRENCY # Index TICKER-YYYYMM-EXCHANGE # Future TICKER-YYYYMM-EXCHANGE-CURRENCY # Future TICKER-YYYYMM-EXCHANGE-CURRENCY-MULT # Future TICKER-FUT-EXCHANGE-CURRENCY-YYYYMM-MULT # Future TICKER-YYYYMM-EXCHANGE-CURRENCY-STRIKE-RIGHT # FOP TICKER-YYYYMM-EXCHANGE-CURRENCY-STRIKE-RIGHT-MULT # FOP TICKER-FOP-EXCHANGE-CURRENCY-YYYYMM-STRIKE-RIGHT # FOP TICKER-FOP-EXCHANGE-CURRENCY-YYYYMM-STRIKE-RIGHT-MULT # FOP CUR1.CUR2-CASH-IDEALPRO # Forex TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT # OPT TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT-MULT # OPT TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT # OPT TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT-MULT # OPT :return: """ contract_type, symbol, exchange, currency, expire, multiplier = \ AsyncIBDataProvider.exctract_symbol(ticker) if contract_type == 'FX': return Forex(pair=symbol) if contract_type == 'IND': return Index(symbol, exchange, currency) if contract_type == 'FUT': return Future(symbol, expire, exchange, currency=currency, multiplier=multiplier) else: return Stock(symbol, exchange, currency)
from kafka import KafkaProducer import json from time import sleep def json_serializer(data): return json.dumps(data).encode("utf-8") ib = IB() print(ib.connect('127.0.0.1', 7497, 5)) symbol = 'MNQ' exchange = 'GLOBEX' expiration = ib.reqContractDetails(Future( symbol, exchange))[0].contract.lastTradeDateOrContractMonth contract = Future(symbol=symbol, exchange=exchange, lastTradeDateOrContractMonth=expiration) sleep(20) bars = ib.reqRealTimeBars(contract, 5, 'MIDPOINT', False) print(bars) producer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=json_serializer) while True: print(bars[-1]) producer.send('first_topic', bars[-1])
"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 = [] for t in tickers: encodedTick = json.dumps(util.tree(t)) ticks.append({"Data": encodedTick})
class TestIBInstrumentProvider: def setup(self): self.ib = MagicMock() self.loop = asyncio.get_event_loop() self.clock = LiveClock() self.logger = LiveLogger( loop=self.loop, clock=self.clock, level_stdout=LogLevel.DEBUG, ) self.provider = InteractiveBrokersInstrumentProvider( client=self.ib, logger=self.logger, config=InstrumentProviderConfig()) @staticmethod def async_return_value(value: object) -> asyncio.Future: future: asyncio.Future = asyncio.Future() future.set_result(value) return future @pytest.mark.parametrize( "filters, expected", [ ( { "secType": "STK", "symbol": "AMD", "exchange": "SMART", "currency": "USD" }, Stock("AMD", "SMART", "USD"), ), ( { "secType": "STK", "symbol": "INTC", "exchange": "SMART", "primaryExchange": "NASDAQ", "currency": "USD", }, Stock("INTC", "SMART", "USD", primaryExchange="NASDAQ"), ), ( { "secType": "CASH", "symbol": "EUR", "currency": "USD", "exchange": "IDEALPRO" }, Forex(symbol="EUR", currency="USD"), ), # EUR/USD, ({ "secType": "CFD", "symbol": "IBUS30" }, CFD("IBUS30")), ( { "secType": "FUT", "symbol": "ES", "exchange": "GLOBEX", "lastTradeDateOrContractMonth": "20180921", }, Future("ES", "20180921", "GLOBEX"), ), ( { "secType": "OPT", "symbol": "SPY", "exchange": "SMART", "lastTradeDateOrContractMonth": "20170721", "strike": 240, "right": "C", }, Option("SPY", "20170721", 240, "C", "SMART"), ), ( { "secType": "BOND", "secIdType": "ISIN", "secId": "US03076KAA60" }, Bond(secIdType="ISIN", secId="US03076KAA60"), ), ( { "secType": "CRYPTO", "symbol": "BTC", "exchange": "PAXOS", "currency": "USD" }, Crypto("BTC", "PAXOS", "USD"), ), ], ) def test_parse_contract(self, filters, expected): result = self.provider._parse_contract(**filters) fields = [ f.name for f in expected.__dataclass_fields__.values() if getattr(expected, f.name) ] for f in fields: assert getattr(result, f) == getattr(expected, f) @pytest.mark.asyncio async def test_load_equity_contract_instrument(self, mocker): # Arrange instrument_id = InstrumentId.from_str("AAPL.NASDAQ") contract = IBTestStubs.contract(symbol="AAPL") contract_details = IBTestStubs.contract_details("AAPL") mocker.patch.object( self.provider._client, "reqContractDetailsAsync", return_value=self.async_return_value([contract_details]), ) mocker.patch.object( self.provider._client, "qualifyContractsAsync", return_value=self.async_return_value([contract]), ) # Act await self.provider.load(secType="STK", symbol="AAPL", exchange="NASDAQ") equity = self.provider.find(instrument_id) # Assert assert InstrumentId(symbol=Symbol("AAPL"), venue=Venue("NASDAQ")) == equity.id assert equity.asset_class == AssetClass.EQUITY assert equity.asset_type == AssetType.SPOT assert 100 == equity.multiplier assert Price.from_str("0.01") == equity.price_increment assert 2, equity.price_precision @pytest.mark.asyncio async def test_load_futures_contract_instrument(self, mocker): # Arrange instrument_id = InstrumentId.from_str("CLZ2.NYMEX") contract = IBTestStubs.contract(symbol="CLZ2", exchange="NYMEX") contract_details = IBTestStubs.contract_details("CLZ2") mocker.patch.object( self.provider._client, "reqContractDetailsAsync", return_value=self.async_return_value([contract_details]), ) mocker.patch.object( self.provider._client, "qualifyContractsAsync", return_value=self.async_return_value([contract]), ) # Act await self.provider.load(symbol="CLZ2", exchange="NYMEX") future = self.provider.find(instrument_id) # Assert assert future.id == instrument_id assert future.asset_class == AssetClass.INDEX assert future.multiplier == 1000 assert future.price_increment == Price.from_str("0.01") assert future.price_precision == 2 @pytest.mark.asyncio async def test_load_options_contract_instrument(self, mocker): # Arrange instrument_id = InstrumentId.from_str("AAPL211217C00160000.SMART") contract = IBTestStubs.contract(secType="OPT", symbol="AAPL211217C00160000", exchange="NASDAQ") contract_details = IBTestStubs.contract_details("AAPL211217C00160000") mocker.patch.object( self.provider._client, "reqContractDetailsAsync", return_value=self.async_return_value([contract_details]), ) mocker.patch.object( self.provider._client, "qualifyContractsAsync", return_value=self.async_return_value([contract]), ) # Act await self.provider.load(secType="OPT", symbol="AAPL211217C00160000", exchange="SMART") option = self.provider.find(instrument_id) # Assert assert option.id == instrument_id assert option.asset_class == AssetClass.EQUITY assert option.multiplier == 100 assert option.expiry_date == datetime.date(2021, 12, 17) assert option.strike_price == Price.from_str("160.0") assert option.kind == OptionKind.CALL assert option.price_increment == Price.from_str("0.01") assert option.price_precision == 2 @pytest.mark.asyncio async def test_load_forex_contract_instrument(self, mocker): # Arrange instrument_id = InstrumentId.from_str("EUR/USD.IDEALPRO") contract = IBTestStubs.contract(secType="CASH", symbol="EURUSD", exchange="IDEALPRO") contract_details = IBTestStubs.contract_details("EURUSD") mocker.patch.object( self.provider._client, "reqContractDetailsAsync", return_value=self.async_return_value([contract_details]), ) mocker.patch.object( self.provider._client, "qualifyContractsAsync", return_value=self.async_return_value([contract]), ) # Act await self.provider.load(secType="CASH", symbol="EURUSD", exchange="IDEALPRO") fx = self.provider.find(instrument_id) # Assert assert fx.id == instrument_id assert fx.asset_class == AssetClass.FX assert fx.multiplier == 1 assert fx.price_increment == Price.from_str("0.00005") assert fx.price_precision == 5 @pytest.mark.asyncio async def test_contract_id_to_instrument_id(self, mocker): # Arrange contract = IBTestStubs.contract(symbol="CLZ2", exchange="NYMEX") contract_details = IBTestStubs.contract_details("CLZ2") mocker.patch.object( self.provider._client, "qualifyContractsAsync", return_value=self.async_return_value([contract]), ) mocker.patch.object( self.provider._client, "reqContractDetailsAsync", return_value=self.async_return_value([contract_details]), ) # Act await self.provider.load(symbol="CLZ2", exchange="NYMEX") # Assert expected = {138979238: InstrumentId.from_str("CLZ2.NYMEX")} assert self.provider.contract_id_to_instrument_id == expected def test_filters(self): pass
def ib_futures_instrument_just_symbol(symbol): ibcontract = Future(symbol=symbol) return ibcontract
logger.debug("Hit take profit") logger.debug(f"{self.take_profit}") logger.debug( "----------------------------------------------") self.cancel_order(self.stop_loss.order) if __name__ == "__main__": import logging import sys logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(sys.stdout)) logger.addHandler(logging.FileHandler("trades.log")) ib = IB() ib.connect("127.0.0.1", 4002, clientId=1) # TWS=7496, PAPER=7497, GTW=4001 ib.reqMarketDataType(1) # this isn't a proper way to roll the f*****g futures ES = ib.reqContractDetails(Future(symbol="ES", exchange="GLOBEX"))[0].contract MES = ib.reqContractDetails(Future(symbol="MES", exchange="GLOBEX"))[0].contract ds = DocStrat(ib=ib, es=ES, mes=MES) logger.debug("Doc Strategy instantiated") ds.run()
str(datetime.datetime.now())) logs.write(str(zs[:2] + [ccl]) + '\n') ccl = 0 else: ccl += zs[2] xiadan(zs[1], zs[2]) print(zs, '下单时间:', str(datetime.datetime.now())) logs.write(str(zs) + '\n') logs.flush() print(f'持仓:{ccl}') # print(data[-2:]) # time.sleep(0.05) time.sleep(30) ib = IB() CODE = 'HSIH9' ib.connect('192.168.2.204', 7496, clientId=8, timeout=3) hsi = Future(localSymbol=CODE) ib.qualifyContracts(hsi) if __name__ == '__main__': argv = sys.argv ccl = 0 # 持仓量 if len(argv) > 1: try: ccl = int(argv[1]) except: pass main(ccl)
conexionBBDD.execute( "UPDATE CLIENT_ID SET CLIENT_ID = %s WHERE USUARIO = %s", (clientId, usuario)) return clientId engine = c.engine conexionBBDD = engine.connect() clientID = getClientId() conexionBBDD.close() ib = IB() ib.connect(host="127.0.0.1", port=7496, clientId=clientID) '''FUTURO 1''' '''Descargamos todos los datos del futuro continuo''' details = ib.reqContractDetails(Future(futuro1, exchange1, includeExpired=True)) '''Cogemos solo los contratos, y filtramos los que tengan fecha superior a hoy''' contracts = [ d.contract for d in details if d.contract.lastTradeDateOrContractMonth > fDesde and d.contract.exchange == exchange1 ] '''Necesitamos hacer esta chapu para poder ordenar y quedarnos con los N primeros''' '''Creamos una lista de listas, que luego sí podemos ordenar''' lista1 = [] for contract in contracts: lista2 = [] lista2.append(contract.conId) lista2.append(contract.localSymbol) lista2.append(contract.lastTradeDateOrContractMonth)