def main(): # Create the client and connect to TWS client = StockScanner('127.0.0.1', 7497, 7) time.sleep(3) # Create the object ScannerSubscription scanSub = ScannerSubscription() # Defines a market scanner request scanSub.instrument = 'STOCK.HK' scanSub.locationCode = 'STK.HK.NSE' # scanSub.scanCode = 'ALL_SYMBOLS_ASC' scanSub.scanCode = 'TOP_TRADE_COUNT' # Set additional filter criteria tagvalues = [] tagvalues.append(TagValue('hasOptionsIs', 'true')) tagvalues.append(TagValue("usdPriceAbove", "0")) tagvalues.append(TagValue("usdPriceBelow", "2")) print(tagvalues) # Request the scanner subscription client.reqScannerSubscription(7, scanSub, [], tagvalues) # Disconnect from TWS time.sleep(5) client.disconnect()
def FillBalanceImpactRiskParams(baseOrder: Order, maxPctVol: float, riskAversion: str, forceCompletion: bool): baseOrder.algoStrategy = "BalanceImpactRisk" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append( TagValue("forceCompletion", int(forceCompletion)))
def FillPctVolParams(baseOrder: Order, pctVol: float, startTime: str, endTime: str, noTakeLiq: bool, monetaryValue: float): baseOrder.algoStrategy = "PctVol" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("pctVol", pctVol)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def processBondContractDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = -1 if version >= 3: reqId = decode(int, fields) contract = ContractDetails() contract.summary.symbol = decode(str, fields) contract.summary.secType = decode(str, fields) contract.cusip = decode(str, fields) contract.coupon = decode(int, fields) contract.maturity = decode(str, fields) contract.issueDate = decode(str, fields) contract.ratings = decode(str, fields) contract.bondType = decode(str, fields) contract.couponType = decode(str, fields) contract.convertible = decode(bool, fields) contract.callable = decode(bool, fields) contract.putable = decode(bool, fields) contract.descAppend = decode(str, fields) contract.summary.exchange = decode(str, fields) contract.summary.currency = decode(str, fields) contract.marketName = decode(str, fields) contract.summary.tradingClass = decode(str, fields) contract.summary.conId = decode(int, fields) contract.minTick = decode(float, fields) if self.serverVersion >= MIN_SERVER_VER_MD_SIZE_MULTIPLIER: contract.mdSizeMultiplier = decode(int, fields) contract.orderTypes = decode(str, fields) contract.validExchanges = decode(str, fields) contract.nextOptionDate = decode(str, fields) # ver 2 field contract.nextOptionType = decode(str, fields) # ver 2 field contract.nextOptionPartial = decode(bool, fields) # ver 2 field contract.notes = decode(str, fields) # ver 2 field if version >= 4: contract.longName = decode(str, fields) if version >= 6: contract.evRule = decode(str, fields) contract.evMultiplier = decode(int, fields) if version >= 5: contract.secIdListCount = decode(int, fields) if contract.secIdListCount > 0: contract.secIdList = [] for idxSecIdList in range(contract.secIdListCount): tagValue = TagValue() tagValue.tag = decode(str, fields) tagValue.value = decode(str, fields) contract.secIdList.append(tagValue) if self.serverVersion >= MIN_SERVER_VER_AGG_GROUP: contract.aggGroup = decode(int, fields) self.wrapper.bondContractDetails(reqId, contract)
def FillClosePriceParams(baseOrder: Order, maxPctVol: float, riskAversion: str, startTime: str, forceCompletion: bool, monetaryValue: float): baseOrder.algoStrategy = "ClosePx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("forceCompletion", int(forceCompletion))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def decodeSmartComboRoutingParams(self, fields): if self.version >= 26: smartComboRoutingParamsCount = decode(int, fields) if smartComboRoutingParamsCount > 0: self.order.smartComboRoutingParams = [] for _ in range(smartComboRoutingParamsCount): tagValue = TagValue() tagValue.tag = decode(str, fields) tagValue.value = decode(str, fields) self.order.smartComboRoutingParams.append(tagValue)
def processContractDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = -1 if version >= 3: reqId = decode(int, fields) contract = ContractDetails() contract.summary.symbol = decode(str, fields) contract.summary.secType = decode(str, fields) contract.summary.lastTradeDateOrContractMonth = decode(str, fields) contract.summary.strike = decode(float, fields) contract.summary.right = decode(str, fields) contract.summary.exchange = decode(str, fields) contract.summary.currency = decode(str, fields) contract.summary.localSymbol = decode(str, fields) contract.marketName = decode(str, fields) contract.summary.tradingClass = decode(str, fields) contract.summary.conId = decode(int, fields) contract.minTick = decode(float, fields) if self.serverVersion >= MIN_SERVER_VER_MD_SIZE_MULTIPLIER: contract.mdSizeMultiplier = decode(int, fields) contract.summary.multiplier = decode(str, fields) contract.orderTypes = decode(str, fields) contract.validExchanges = decode(str, fields) contract.priceMagnifier = decode(int, fields) # ver 2 field if version >= 4: contract.underConId = decode(int, fields) if version >= 5: contract.longName = decode(str, fields) contract.summary.primaryExchange = decode(str, fields) if version >= 6: contract.contractMonth = decode(str, fields) contract.industry = decode(str, fields) contract.category = decode(str, fields) contract.subcategory = decode(str, fields) contract.timeZoneId = decode(str, fields) contract.tradingHours = decode(str, fields) contract.liquidHours = decode(str, fields) if version >= 8: contract.evRule = decode(str, fields) contract.evMultiplier = decode(int, fields) if version >= 7: contract.secIdListCount = decode(int, fields) if contract.secIdListCount > 0: contract.secIdList = [] for idxSecIdList in range(contract.secIdListCount): tagValue = TagValue() tagValue.tag = decode(str, fields) tagValue.value = decode(str, fields) contract.secIdList.append(tagValue) self.wrapper.contractDetails(reqId, contract)
def FillTwapParams(baseOrder: Order, strategyType: str, startTime: str, endTime: str, allowPastEndTime: bool, monetaryValue: float): baseOrder.algoStrategy = "Twap" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("strategyType", strategyType)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillDarkIceParams(baseOrder: Order, displaySize: int, startTime: str, endTime: str, allowPastEndTime: bool, monetaryValue: float): baseOrder.algoStrategy = "DarkIce" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("displaySize", displaySize)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def decodeAlgoParams(self, fields): if self.version >= 21: self.order.algoStrategy = decode(str, fields) if self.order.algoStrategy: algoParamsCount = decode(int, fields) if algoParamsCount > 0: self.order.algoParams = [] for _ in range(algoParamsCount): tagValue = TagValue() tagValue.tag = decode(str, fields) tagValue.value = decode(str, fields) self.order.algoParams.append(tagValue)
def get_tag_value_obj(tag_value_dict: Dict[str, Any]) -> TagValue: """Get object from dictionary. Args: tag_value_dict: dictionary to be used to restore the tag_value Returns: An instance of TagValue """ tag_value = TagValue() tag_value.__dict__ = copy.deepcopy(tag_value_dict) return tag_value
def FillQBAlgoInLineParams(baseOrder: Order, startTime: str, endTime: str, duration: float, benchmark: str, percentVolume: float, noCleanUp: bool): # must be direct-routed to "QBALGO" baseOrder.algoStrategy = "STROBE" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("StartTime", startTime)) baseOrder.algoParams.append(TagValue("EndTime", endTime)) #This example uses endTime instead of duration #baseOrder.algoParams.append(TagValue("Duration", str(duration))) baseOrder.algoParams.append(TagValue("Benchmark", benchmark)) baseOrder.algoParams.append( TagValue("PercentVolume", str(percentVolume))) baseOrder.algoParams.append(TagValue("NoCleanUp", int(noCleanUp)))
def ComboLimitOrder(action: str, quantity: float, limitPrice: float, nonGuaranteed: bool): order = Order() maxleg = round(0.2 * quantity) order.action = action order.orderType = "LMT" order.totalQuantity = quantity order.lmtPrice = limitPrice if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue( "NonGuaranteed", "1", )) order.smartComboRoutingParams.append(TagValue('MaxSegSize', maxleg)) return order
def execDetails(self, reqId, contract, execution): super().execDetails(reqId, contract, execution) module_logger.info( f'Order Executed: {reqId} {contract.symbol} {contract.secType} {contract.currency} {execution.execId} {execution.orderId} {execution.shares} {execution.lastLiquidity}' ) ticker = contract.symbol if (db_data.loc[ticker, 'first_order_quantity'] == execution.cumQty and execution.orderId == db_data.loc[ticker, 'first_order_id']): # place order for buy iLmtPrice = db_data.loc[ticker, 'first_price'] group_nav = get_groupnavs(11, GROUP_NAME) iTotalQuantity = int( round( group_nav * db_data.loc[ticker, 'allocation'] * db_data.loc[ticker, 'v1_buy_alloc'] / iLmtPrice, 0)) - execution.cumQty order = create_order_for_buy(ticker, iTotalQuantity, iLmtPrice, 'MKT') order.algoStrategy = "Adaptive" order.algoParams = [TagValue("adaptivePriority", "Normal")] order.outsideRth = False module_logger.info( f'Buy order for {ticker} totalQuantity={iTotalQuantity} LmtPrice={iLmtPrice}' ) contract = stock_contract(ticker, currency=db_data.loc[ticker, 'currency']) app.placeOrder(app.nextorderId, contract, order) app.nextorderId += 1
def create_adaptive_order(action, order_type, quantity): order = Order() order.action = action order.orderType = order_type order.totalQuantity = quantity order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", "Normal")) return order
def RelativeMarketCombo(action: str, quantity: float, nonGuaranteed: bool): order = Order() order.action = action order.totalQuantity = quantity order.orderType = "REL + MKT" if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue( "NonGuaranteed", "1")) return order
def FillAccumulateDistributeParams(baseOrder: Order, componentSize: int, timeBetweenOrders: int, randomizeTime20: bool, randomizeSize55: bool, giveUp: int, catchUp: bool, waitForFill: bool, startTime: str, endTime: str): baseOrder.algoStrategy = "AD" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("componentSize", componentSize)) baseOrder.algoParams.append(TagValue("timeBetweenOrders", timeBetweenOrders)) baseOrder.algoParams.append(TagValue("randomizeTime20", int(randomizeTime20))) baseOrder.algoParams.append(TagValue("randomizeSize55", int(randomizeSize55))) baseOrder.algoParams.append(TagValue("giveUp", giveUp)) baseOrder.algoParams.append(TagValue("catchUp", int(catchUp))) baseOrder.algoParams.append(TagValue("waitForFill", int(waitForFill))) baseOrder.algoParams.append(TagValue("activeTimeStart", startTime)) baseOrder.algoParams.append(TagValue("activeTimeEnd", endTime))
def RelativeLimitCombo(action: str, quantity: float, limitPrice: float, nonGuaranteed: bool): order = Order() order.action = action order.totalQuantity = quantity order.orderType = "REL + LMT" order.lmtPrice = limitPrice if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue( "NonGuaranteed", "1")) return order
def FillPriceVariantPctVolParams(baseOrder: Order, pctVol: float, deltaPctVol: float, minPctVol4Px: float, maxPctVol4Px: float, startTime: str, endTime: str, noTakeLiq: bool, monetaryValue: float): baseOrder.AlgoStrategy = "PctVolPx" baseOrder.AlgoParams = [] baseOrder.AlgoParams.append(TagValue("pctVol", pctVol)) baseOrder.AlgoParams.append(TagValue("deltaPctVol", deltaPctVol)) baseOrder.AlgoParams.append(TagValue("minPctVol4Px", minPctVol4Px)) baseOrder.AlgoParams.append(TagValue("maxPctVol4Px", maxPctVol4Px)) baseOrder.AlgoParams.append(TagValue("startTime", startTime)) baseOrder.AlgoParams.append(TagValue("endTime", endTime)) baseOrder.AlgoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.AlgoParams.append(TagValue("monetaryValue", monetaryValue))
def main(): # Create the client and connect to TWS client = StockScanner('127.0.0.1', 7497, 0) time.sleep(0.5) # Create the ScannerSubscription object ss = ScannerSubscription() ss.instrument = 'STK' ss.locationCode = 'STK.US.MAJOR' ss.scanCode = 'HOT_BY_VOLUME' # Set additional filter criteria tagvalues = [] tagvalues.append(TagValue('avgVolumeAbove', '500000')) tagvalues.append(TagValue('marketCapAbove1e6', '10')) # Requet the scanner subscription client.reqScannerSubscription(0, ss, [], tagvalues) # Sleep while the request is processed time.sleep(5) client.disconnect()
def ComboMarketOrder(action:str, quantity:float, nonGuaranteed:bool): # ! [combomarket] order = Order() order.action = action order.orderType = "MKT" order.totalQuantity = quantity if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1")) # ! [combomarket] return order
def ComboLimitOrder(action:str, quantity:float, limitPrice:float, nonGuaranteed:bool): # ! [combolimit] order = Order() order.action = action order.orderType = "LMT" order.totalQuantity = quantity order.lmtPrice = limitPrice if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1")) # ! [combolimit] return order
def LimitOrderForComboWithLegPrices(action: str, quantity: float, legPrices: list, nonGuaranteed: bool): order = Order() order.action = action order.orderType = "LMT" order.totalQuantity = quantity order.orderComboLegs = [] for price in legPrices: comboLeg = OrderComboLeg() comboLeg.price = price order.orderComboLegs.append(comboLeg) if nonGuaranteed: order.smartComboRoutingParams = [] order.smartComboRoutingParams.append(TagValue( "NonGuaranteed", "1")) return order
def FillArrivalPriceParams(baseOrder: Order, maxPctVol: float, riskAversion: str, startTime: str, endTime: str, forceCompletion: bool, allowPastTime: bool, monetaryValue: float): baseOrder.algoStrategy = "ArrivalPx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("forceCompletion", int(forceCompletion))) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillVwapParams(baseOrder: Order, maxPctVol: float, startTime: str, endTime: str, allowPastEndTime: bool, noTakeLiq: bool, monetaryValue: float): baseOrder.algoStrategy = "Vwap" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def MarketOrder(action: str, quantity: float, adaptive=False, priority="Normal"): #! [market] order = Order() order.action = action order.orderType = "MKT" order.totalQuantity = quantity if adaptive: order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", priority)) #! [market] return order
def order(self, asset, amount, style): ib_symbol = self._asset_symbol(asset) contract = Contract() contract.symbol = ib_symbol contract.exchange = 'SMART' primaryExchange = 'ISLAND' contract.secType = 'STK' contract.currency = self.currency order = Order() order.totalQuantity = int(fabs(amount)) order.action = "BUY" if amount > 0 else "SELL" is_buy = (amount > 0) order.lmtPrice = style.get_limit_price(is_buy) or 0 order.auxPrice = style.get_stop_price(is_buy) or 0 if isinstance(style, MarketOrder): order.orderType = "MKT" order.tif = "DAY" order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", "Patient")) elif isinstance(style, LimitOrder): order.orderType = "LMT" order.tif = "GTC" elif isinstance(style, StopOrder): order.orderType = "STP" order.tif = "GTC" elif isinstance(style, StopLimitOrder): order.orderType = "STP LMT" order.tif = "GTC" order.orderRef = self._create_order_ref(order) ib_order_id = self._tws.next_order_id zp_order = self._get_or_create_zp_order(ib_order_id, order, contract) self.log_order(contract, ib_order_id, order) self._tws.placeOrder(ib_order_id, contract, order) return zp_order
def change_to_ib_order(self, order: Order) -> IBOrder: # 市价单和限价单直接提交 ib_order: IBOrder = IBOrder() if isinstance(order, MKTOrder): ib_order.orderType = "MKT" ib_order.totalQuantity = order.quantity ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL' # 设置自适应算法 ib_order.algoStrategy = 'Adaptive' ib_order.algoParams = [TagValue("adaptivePriority", 'Urgent')] elif isinstance(order, LimitOrder): ib_order.orderType = "LMT" ib_order.totalQuantity = order.quantity # 价格调整到两位小数 ib_order.lmtPrice = round(order.limit_price, 2) ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL' else: # 穿越单和延迟单转化为IB的条件单 if isinstance(order, DelayMKTOrder): ib_order.orderType = "MKT" ib_order.totalQuantity = order.quantity ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL' cond = order_condition.Create(OrderCondition.Time) cond.isMore = True time = (Timestamp.now(tz='Asia/Shanghai') + order.delay_time).strftime('%Y%m%d %H:%M:%S') cond.time(time) ib_order.conditions.append(cond) elif isinstance(order, CrossMKTOrder): ib_order.orderType = "MKT" ib_order.totalQuantity = order.quantity ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL' price_cond = order_condition.Create(OrderCondition.Price) contract = self.cli.code_to_contract(order.code) price_cond.conId = contract.conId price_cond.price = round(order.cross_price, 2) price_cond.isMore = True if order.cross_direction == CrossDirection.UP else False price_cond.exchange = contract.exchange price_cond.triggerMethod = PriceCondition.TriggerMethodEnum.Default ib_order.conditions.append(price_cond) return ib_order
def LimitOrder(action: str, quantity: float, limitPrice: float, adaptive=False, priority="Normal"): """ priority values: Urgent, Normal, Patient """ order = Order() order.action = action order.orderType = "LMT" order.totalQuantity = quantity order.lmtPrice = limitPrice if adaptive: order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", priority)) return order
def create_order_pct(sAction="SELL", iPercent="-100", sOrderType="MKT", iTotalQuantity=0.0, bTransmit=True, sTif='DAY', sPriority="Normal"): order = Order() order.action = sAction order.faGroup = GROUP_NAME order.faMethod = "PctChange" order.faPercentage = iPercent order.orderType = sOrderType if sOrderType == "MKT": order.algoStrategy = "Adaptive" order.algoParams = [TagValue("adaptivePriority", sPriority)] order.totalQuantity = iTotalQuantity order.tif = sTif order.transmit = bTransmit return order