def HotUSStkByVolume(): # Hot US stocks by volume scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "HOT_BY_VOLUME" return scanSub
def TopPercentGainersIbis(): # Top % gainers at IBIS scanSub = ScannerSubscription() scanSub.instrument = "STOCK.EU" scanSub.locationCode = "STK.EU.IBIS" scanSub.scanCode = "TOP_PERC_GAIN" return scanSub
def MostActiveFutSoffex(): # Most active futures at SOFFEX scanSub = ScannerSubscription() scanSub.instrument = "FUT.EU" scanSub.locationCode = "FUT.EU.SOFFEX" scanSub.scanCode = "MOST_ACTIVE" return scanSub
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 HighOptVolumePCRatioUSIndexes(): # High option volume P/C ratio US indexes scanSub = ScannerSubscription() scanSub.instrument = "IND.US" scanSub.locationCode = "IND.US" scanSub.scanCode = "HIGH_OPT_VOLUME_PUT_CALL_RATIO" return scanSub
def ComplexOrdersAndTrades(): #! [combolatesttrade] # High option volume P/C ratio US indexes scanSub = ScannerSubscription() scanSub.instrument = "NATCOMB" scanSub.locationCode = "NATCOMB.OPT.US" scanSub.scanCode = "COMBO_LATEST_TRADE" #! [combolatesttrade] return scanSub
def TopPercentLoserUsEquity1(): # top percent losers of stocks with Market Cap < 1B and # average volume greater than 100K #! [toppercentloserusequity] scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "TOP_PERC_LOSER" return scanSub
def LowPriceEarningsRatio(): scanSub = ScannerSubscription() # low price to earnings ratio stocks #! [lowpriceearningsratio] scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "LOW_PE_RATIO" #! [lowpriceearningsratio] return scanSub
def nextValidId(self, orderId: int): scanSub = ScannerSubscription() scanSub.instrument = 'STK' scanSub.locationCode = 'STK.US' scanSub.scanCode = 'HIGH_OPT_IMP_VOLAT' scanSub.abovePrice = 100 scanSub.numberOfRows = 1000 scanSub.scannerSettingPairs = 'Annual, true' self.reqScannerSubscription(1, scanSub, [], [])
def main(): scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "TOP_PERC_GAIN" scanSub.marketCapAbove = 8000000000 app = TestApp(scanSub) app.connect("127.0.0.1", 7497, 1) app.run()
def hot_us_stk(abovePrice, belowPrice, locationCode, scanCode): #! [hotusvolume] #Hot US stocks by volume scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = locationCode #scanSub.locationCode = "STK.NASDAQ" #scanSub.scanCode = "HOT_BY_VOLUME" scanSub.scanCode = scanCode #scanSub.scanCode = "MOST_ACTIVE" scanSub.belowPrice = str(belowPrice) scanSub.abovePrice = str(abovePrice) return scanSub
def HottestPennyStocks(): """ Subscribe to US stocks 1 < price < 10 and vol > 1M. Scan code = TOP_PERC_GAIN """ scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US" scanSub.scanCode = "TOP_PERC_GAIN" scanSub.abovePrice = 2 scanSub.belowPrice = 50 scanSub.aboveVolume = 1000000 return scanSub
def scan(self, req_id: int, exchange_abbrev: str): """Performs a market scan of contracts through the IB API""" # Creates the scanner object to be used in reqScannerSubscription() scanner = ScannerSubscription() scanner.instrument = 'STK' scanner.locationCode = 'STK.' + exchange_abbrev scanner.stockTypeFilter = 'CORP' scanner.scanCode = "MOST_ACTIVE_AVG_USD" scanner.abovePrice = 10.0 scanner.belowPrice = 20.0 # Third argument of reqScannerSubscription() should always be an empty list. It is used internally by IB API. # Fourth argument is an optional list of filters as TagValue objects. self.reqScannerSubscription(req_id, scanner, [], [])
def assemble_stock_list(client, sentiment): ''' Use scanner to obtain stock list ''' # Define scanner subscription ss = ScannerSubscription() ss.instrument = 'STK' ss.locationCode = 'STK.US.MAJOR' ss.abovePrice = 10.0 ss.belowPrice = client.funds / 200.0 ss.aboveVolume = 20000 ss.numberOfRows = 5 # Set scan code according to sentiment if sentiment == Sentiment.BULLISH: ss.scanCode = 'HIGH_VS_13W_HL' else: ss.scanCode = 'LOW_VS_13W_HL' # Request securities client.reqScannerSubscription(4, ss, [], []) time.sleep(3)
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 main(): cmdLineParser = argparse.ArgumentParser("api tests") #cmdLineParser.add_option("-c", action="store_true", dest="use_cache", default = False, help = "use the cache") #cmdLineParser.add_option("-f", action="store", type="string", dest="file", default="", help="the input file") cmdLineParser.add_argument("-p", "--port", action="store", type=int, dest="port", default=4005, help="The TCP port to use") args = cmdLineParser.parse_args() print("Using args", args) import logging logging.debug("Using args %s", args) #print(args) logging.debug("now is %s", datetime.datetime.now()) logging.getLogger().setLevel(logging.ERROR) #enable logging when member vars are assigned import utils from order import Order Order.__setattr__ = utils.setattr_log from contract import Contract, DeltaNeutralContract Contract.__setattr__ = utils.setattr_log DeltaNeutralContract.__setattr__ = utils.setattr_log from tag_value import TagValue TagValue.__setattr__ = utils.setattr_log TimeCondition.__setattr__ = utils.setattr_log ExecutionCondition.__setattr__ = utils.setattr_log MarginCondition.__setattr__ = utils.setattr_log PriceCondition.__setattr__ = utils.setattr_log PercentChangeCondition.__setattr__ = utils.setattr_log VolumeCondition.__setattr__ = utils.setattr_log #from inspect import signature as sig #import code; code.interact(local=dict(globals(), **locals())) #sys.exit(1) app = TestApp() app.connect("127.0.0.1", args.port, 0) app.reqCurrentTime() app.reqManagedAccts() app.reqAccountSummary(reqId=2, groupName="All", tags="NetLiquidation") app.reqAllOpenOrders() contract = Contract() contract.symbol = "AMD" contract.secType = "STK" contract.currency = "USD" contract.exchange = "SMART" #app.reqMarketDataType(1) #app.reqMktData(1001, contract, "", snapshot=True) #app.cancelMktData(1001) #app.reqExecutions(2001, ExecutionFilter()) #app.reqContractDetails(3001, contract) #app.reqPositions() #app.reqIds(2) #app.reqMktDepth(4001, contract, 5, "") #app.cancelMktDepth(4001) #app.reqNewsBulletins(allMsgs=True) #app.cancelNewsBulletins() #app.requestFA(FaDataTypeEnum.GROUPS) #app.reqHistoricalData(5001, contract, "20161215 16:00:00", "2 D", # "1 hour", "TRADES", 0, 1, []) #app.cancelHistoricalData(5001) #app.reqFundamentalData(6001, contract, "ReportSnapshot") #app.cancelFundamentalData(6001) #app.queryDisplayGroups(7001) #app.subscribeToGroupEvents(7002, 1) #app.unsubscribeFromGroupEvents(7002) #app.reqScannerParameters() ss = ScannerSubscription() ss.instrument = "STK" ss.locationCode = "STK.US" ss.scanCode = "TOP_PERC_LOSE" #app.reqScannerSubscription(8001, ss, []) #app.cancelScannerSubscription(8001) #app.reqRealTimeBars(9001, contract, 5, "TRADES", 0, []) #app.cancelRealTimeBars(9001) #app.reqSecDefOptParams(10001, "AMD", "", "STK", 4391) #app.reqSoftDollarTiers(11001) #app.reqFamilyCodes() #app.reqMatchingSymbols(12001, "AMD") contract = Contract() contract.symbol = "AMD" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20170120" contract.strike = 10 contract.right = "C" contract.multiplier = "100" #Often, contracts will also require a trading class to rule out ambiguities contract.tradingClass = "AMD" #app.calculateImpliedVolatility(13001, contract, 1.3, 10.85) #app.calculateOptionPrice(13002, contract, 0.65, 10.85) app.run()
def LowPriceTangibleBookRatio(): scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "LOW_PRICE_2_TAN_BOOK_RATIO" return scanSub
def LowReturnOnEquity(): scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "LOW_RETURN_ON_EQUITY"
def HighReturnOnEquity(): scanSub = ScannerSubscription() scanSub.instrument = "STK" scanSub.locationCode = "STK.US.MAJOR" scanSub.scanCode = "HIGH_RETURN_ON_EQUITY" return scanSub
########### Connect to TWS Start ############## try: app = TradingApp() app.connect("127.0.0.1", 4001, clientId=2) # starting a separate daemon thread to execute the websocket connection con_thread = threading.Thread(target=websocket_con, daemon=True) con_thread.start() time.sleep( 1) # some latency added to ensure that the connection is established except Exception as ex: logger.error("Error connecting gateway %s", ex) ########### Connect to TWS End ############## scanSub = ScannerSubscription() scanSub.instrument = "STOCK.HK" scanSub.locationCode = "STK.HK.NSE" scanSub.scanCode = "TOP_PERC_GAIN" newdata = app.reqScannerSubscription(7001, scanSub, [], []) #app.reqScannerParameters() ########### Get available cash balance ######### app.reqAccountSummary(9002, "All", "$LEDGER") time.sleep(3) ########### Get available cash balance end ######### ########### Prepare Historical Data Start ############## tickers = [] #["AXISBANK","RELIANCE", "HDFC","ICICIBANK","MARUTI","BAJFINANC"] queryTime = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime("%Y%m%d %H:%M:%S")