def send_order(self, req: OrderRequest): """ Send a new order. """ if not self.status: return "" if req.exchange not in EXCHANGE_VT2IB: self.gateway.write_log(f"不支持的交易所:{req.exchange}") return "" if req.type not in ORDERTYPE_VT2IB: self.gateway.write_log(f"不支持的价格类型:{req.type}") return "" self.orderid += 1 ib_contract = Contract() ib_contract.conId = str(req.symbol) ib_contract.exchange = EXCHANGE_VT2IB[req.exchange] ib_order = Order() ib_order.orderId = self.orderid ib_order.clientId = self.clientid ib_order.action = DIRECTION_VT2IB[req.direction] ib_order.orderType = ORDERTYPE_VT2IB[req.type] ib_order.lmtPrice = req.price ib_order.totalQuantity = req.volume self.client.placeOrder(self.orderid, ib_contract, ib_order) self.client.reqIds(1) order = req.create_order_data(str(self.orderid), self.gateway_name) self.gateway.on_order(order) return order.vt_orderid
def subscribe(self, req: SubscribeRequest): """ Subscribe tick data update. """ if not self.status: return if req.exchange not in EXCHANGE_VT2IB: self.gateway.write_log(f"不支持的交易所{req.exchange}") return ib_contract = Contract() ib_contract.conId = str(req.symbol) ib_contract.exchange = EXCHANGE_VT2IB[req.exchange] # Get contract data from TWS. self.reqid += 1 self.client.reqContractDetails(self.reqid, ib_contract) # Subscribe tick data and create tick object buffer. self.reqid += 1 self.client.reqMktData(self.reqid, ib_contract, "", False, False, []) tick = TickData( symbol=req.symbol, exchange=req.exchange, datetime=datetime.now(), gateway_name=self.gateway_name, ) self.ticks[self.reqid] = tick self.tick_exchange[self.reqid] = req.exchange
def _fetchFutureMonth(self): contract = Contract() ''' contract.secType = "CONTFUT" #contract.lastTradeDateOrContractMonth="201812" # CONTFUT can be used to get details of contract from which we can get month for order contract.symbol="SBIN" contract.exchange="NSE" ''' contract.secType = "FUT" contract.lastTradeDateOrContractMonth="201805" contract.symbol="SBIN" contract.exchange="NSE" ## resolve the contract self.ib.reqContractDetails(213, contract)
def newTrade(self, contractSymbol:str, entryPrice:float, stopPrice:float ): # TEMP contractSymbol="EURUSD" contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "GBP" contract.exchange = "IDEALPRO" contract.tickSize = 0.00005 contract.lotSize = 20000 # TEMP #if( self.trades[contractSymbol] ) ''' contractDetails = s.getContractDetails( contractSymbol ) contract = Contract() contract.exchange = contractDetails.exchange contract.secType = contractDetails.secType contract.symbol = contractSymbol contract.lastTradeDateOrContractMonth = contractDetails.expiry contract.tickSize = contractDetails.tickSize # Custom field contract.lotSize = contractDetails.lotSize # Custom field ''' diff = abs(entryPrice-stopPrice) qty = self.capital * s.RiskPerTrade / diff t = trade.Trade( self.ib, contract ) t.placeNewTrade( qty, entryPrice, stopPrice ) self.trades[contractSymbol] = t
def combo_generator_Box(symbol: str, lessdays =120): specpath = r'E:\newdata\IB data\Option Specs' file = specpath + os.sep + symbol + '-specs.json' jf = open(file, 'r') jdict = json.load(jf) jf.close() underlyingfile = r'E:\newdata\IB data\Underlying_Contract_Details.csv' underlying = pd.read_csv(underlyingfile) syms = list(underlying['symbol']) idx = syms.index(symbol) last = underlying['Last'][idx] underlyingleg = ComboLeg() underlyingleg.conId = underlying['conID'][idx] underlyingleg.ratio = 100 underlyingleg.action = 'BUY' underlyingleg.exchange = 'SMART' Pleg = ComboLeg() Pleg.ratio = 1 Pleg.action = 'BUY' Pleg.exchange = 'SMART' Cleg = ComboLeg() Cleg.ratio = 1 Cleg.action = 'SELL' Cleg.exchange = 'SMART' contract = Contract() contract.symbol = symbol contract.secType = 'BAG' contract.currency = 'USD' contract.exchange = 'SMART' Combos = [] for mi, di in jdict.items(): jm = IBdate_to_Date(mi) today = date.today() if (jm - today).days <= lessdays: stricks = list(di['C'].keys()) stricks_1 = [float(i) for i in stricks] ps = pick_stricks_2(last, stricks_1, 2) for si in ps: Pleg.conId = di['P'][str(si)]['conID'] Cleg.conId = di['C'][str(si)]['conID'] contract.comboLegs = [] contract.comboLegs.append(underlyingleg) contract.comboLegs.append(Pleg) contract.comboLegs.append(Cleg) Combos.append([deepcopy(contract), si]) return Combos
def FX_order(symbol): contract = Contract() contract.symbol = symbol[:3] contract.secType = 'CASH' contract.exchange = 'IDEALPRO' contract.currency = symbol[3:] return contract
def nse_contract(symbol): contract=Contract() contract.symbol=symbol contract.secType = "STK" contract.exchange = "NSE" contract.currency = "INR" return contract
def forex_contract3(): forex_contract = Contract() forex_contract.symbol = 'EUR' forex_contract.secType = 'CASH' forex_contract.exchange = 'IDEALPRO' forex_contract.currency = 'JPY' return forex_contract
def defineContract(symbol, secType, exchange, currency='USD'): contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.currency = currency return contract
def create_contract(stock_symbol, sec_type, currency, exchange): contract = Contract() contract.symbol = stock_symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange return contract
def fxPair(pair, sec_type="CASH", exchange="IDEALPRO"): contract = Contract() contract.symbol = pair.split("/")[0] contract.secType = sec_type contract.currency = pair.split("/")[1] contract.exchange = exchange return contract
def createcontractstk(ticker): cont = Contract() cont.symbol = ticker cont.secType = "STK" cont.currency = "AUD" cont.exchange = "ASX" return cont
def createcontract(ticker): cont = Contract() cont.symbol = ticker cont.secType = "CFD" cont.currency = "AUD" cont.exchange = "SMART" return cont
def FX_order(symbol): contract = Contract() contract.symbol = 'APXT' contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' return contract
def gen_contract(symbol, sec_type, exchange, currency, other_param_dict: Dict = None): """ shortcut for creating a contract :param other_param_dict: :param symbol: :param sec_type: :param exchange: :param currency: :return: """ result_contract = Contract() result_contract.symbol = symbol result_contract.secType = sec_type result_contract.exchange = exchange result_contract.currency = currency if other_param_dict is None: param_dict = {} else: param_dict = other_param_dict for k, v in iter(param_dict.items()): setattr(result_contract, k, v) return result_contract
def contract_maker(symbol, sec_type="STK", exchange="NSE", currency="INR"): contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.exchange = exchange contract.currency = currency return contract
def index_contract(): spx_contract = Contract() spx_contract.conId = "416904" spx_contract.symbol = 'SPX' spx_contract.secType = "IND" spx_contract.exchange = "CBOE" return spx_contract
def stock_contract(): amzn_contract = Contract() amzn_contract.symbol = 'AMZN' amzn_contract.secType = 'STK' amzn_contract.exchange = 'SMART' amzn_contract.currency = 'USD' return amzn_contract
def createStk(symbol, sec_type="STK", currency="INR", exchange="NSE"): contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange return contract
def ContractMaker(date, secType='FUT', currency="USD", exchane='CFE', symbol='VXK1', tradingClass='VX'): contrac = Contract() contrac.symbol = symbol contrac.secType = secType contrac.currency = currency contrac.exchange = exchane contrac.tradingClass = tradingClass contrac.lastTradeDateOrContractMonth = date return contrac
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 = IBcontract() ibcontract.secType = "FUT" ibcontract.symbol = meta_data['symbol'] ibcontract.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 __init__(self, symbol: str, exchange: str, secType: str, client: RobotClient): ''' a wrapper/collection to store all Signals related to one Contract secType is either 'FUT' or 'STK' ''' if secType not in ['FUT', 'STK']: raise RuntimeError( f"secType must be 'FUT' or 'STK', but received: {secType}") self.client = client self.signals: Dict[str, Signal] = dict() self.contract = Contract() self.contract.symbol = symbol self.contract.exchange = exchange self.contract.currency = 'USD' self.contract.secType = secType if not self.client.client_connected(): self.client.connect_client() reqId = self.client.get_new_reqIds()[0] self.client.contractDetailsObtained[reqId] = False self.client.client_adapter.reqContractDetails(reqId=reqId, contract=self.contract) wait_until( condition_function=lambda: self.client.contractDetailsObtained[ reqId], seconds_to_wait=5, msg= f"Waited more than 5 secs to get contract details for: {symbol}@{exchange}" ) self.client.contractDetailsObtained.pop(reqId) contracts = self.client.resolvedContracts.pop(reqId) self.client.resolve_request(reqId) if secType == 'FUT': date_now = int(ClockController.utcnow().to( ClockController.time_zone).shift(days=-1).format("YYYYMMDD")) max_month = 30000000 for contract in contracts: contract_month = int(contract.lastTradeDateOrContractMonth) if date_now < contract_month < max_month: max_month = contract_month self.contract = contract else: self.contract = contracts[0] self.asset_key = f"{symbol}@{exchange}"
def generate_ib_contract(symbol: str, exchange: Exchange) -> Optional[Contract]: """""" try: fields = symbol.split(JOIN_SYMBOL) ib_contract = Contract() ib_contract.exchange = EXCHANGE_VT2IB[exchange] ib_contract.secType = fields[-1] ib_contract.currency = fields[-2] ib_contract.symbol = fields[0] if ib_contract.secType in ["FUT", "OPT", "FOP"]: ib_contract.lastTradeDateOrContractMonth = fields[1] if ib_contract.secType in ["OPT", "FOP"]: ib_contract.right = fields[2] ib_contract.strike = float(fields[3]) ib_contract.multiplier = int(fields[4]) except IndexError: ib_contract = None return ib_contract
def __init__(self): self.ids = [] self.lots = 5 self.params = pd.read_csv(r'C:/Users/JD/Google Drive/Quantitative Trading/Trading Params/UsoXle Params.csv', header=0, index_col=0) xleC, usoC = Contract(), Contract() xleC.secType, usoC.secType = 'STK', 'STK' xleC.symbol, usoC.symbol = 'XLE', 'USO' xleC.currency, usoC.currency = 'USD', 'USD' xleC.exchange, usoC.exchange = 'ARCA', 'ARCA' self.contracts = (xleC, usoC)
def start(self): contract = Contract() contract.symbol = 'TGP' contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" self.reqHistoricalData(1, contract, "", "26 W", "1 day", "MIDPOINT", 0, 1, False, [])
def main(): app = TestApp() app.connect("127.0.0.1", 4002, 0) # 7497 live # Crete a contract contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ"
def send_order(self, req: OrderRequest): """ Send a new order. """ if not self.status: return "" if req.exchange not in EXCHANGE_VT2IB: self.gateway.write_log(f"不支持的交易所:{req.exchange}") return "" if req.type not in ORDERTYPE_VT2IB: self.gateway.write_log(f"不支持的价格类型:{req.type}") return "" self.orderid += 1 ib_contract = Contract() ib_contract.conId = str(req.symbol) ib_contract.exchange = EXCHANGE_VT2IB[req.exchange] ib_order = Order() ib_order.orderId = self.orderid ib_order.clientId = self.clientid ib_order.action = DIRECTION_VT2IB[req.direction] ib_order.orderType = ORDERTYPE_VT2IB[req.type] ib_order.totalQuantity = req.volume if req.type == OrderType.LIMIT: ib_order.lmtPrice = req.price elif req.type == OrderType.STOP: ib_order.auxPrice = req.price self.client.placeOrder(self.orderid, ib_contract, ib_order) self.client.reqIds(1) order = req.create_order_data(str(self.orderid), self.gateway_name) self.gateway.on_order(order) return order.vt_orderid
def BondWithCusip(): contract = Contract() # enter CUSIP as symbol contract.symbol = "912828C57" contract.secType = "BOND" contract.exchange = "SMART" contract.currency = "USD" return contract
def OptionWithLocalSymbol(): contract = Contract() # Watch out for the spaces within the local symbol! contract.localSymbol = "C DBK DEC 20 1600" contract.secType = "OPT" contract.exchange = "DTB" contract.currency = "EUR" return contract
def USStock(): contract = Contract() contract.symbol = "IBKR" contract.secType = "STK" contract.currency = "USD" # In the API side, NASDAQ is always defined as ISLAND in the exchange field contract.exchange = "ISLAND" return contract
def Commodity(symbol): contract = Contract() contract.symbol = symbol # contract.symbol = symbol[:3] contract.secType = 'CMDTY' contract.exchange = 'SMART' contract.currency = symbol[3:] return contract
def Stock_contract(symbol, secType='STK', exchange='SMART', currency='USD'): ''' custom function to create stock contract ''' contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.currency = currency return contract
def make_contract(symbol: str, sec_type: str, currency: str, exchange: str) -> Contract: contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange return contract
def forex(code): foreign, local = code[:3], code[3:] contract = Contract() contract.currency = local contract.secType = "CASH" contract.symbol = foreign contract.exchange = "IDEALPRO" return contract