def check_sentiment(client): ''' Check SPY and VXX to determine sentiment ''' # Create a contract for the SPY ETF spy_con = Contract() spy_con.symbol = 'SPY' spy_con.secType = 'STK' spy_con.exchange = 'SMART' spy_con.currency = 'USD' # Access SPY data now = datetime.now().strftime('%Y%m%d, %H:%M:%S') client.reqHistoricalData(2, spy_con, now, '1 d', '1 day', 'MIDPOINT', False, 1, False, []) # Create a contract for the VXX ETN vxx_con = Contract() vxx_con.symbol = 'VXX' vxx_con.secType = 'STK' vxx_con.exchange = 'SMART' vxx_con.currency = 'USD' # Access VXX data client.reqHistoricalData(3, vxx_con, now, '1 d', '1 day', 'MIDPOINT', False, 1, False, []) time.sleep(3) # Determine market sentiment return client.sentiment
def main(): # Create the client and connect to TWS client = ReadTicker('127.0.0.1', 7497, 7) time.sleep(3) #Sleep interval to allow time for connection to server # Get expiration dates for contracts for symbol in client.symbols: # Define the contract contract = Contract() contract.symbol = symbol contract.secType = 'STK' contract.exchange = 'NSE' contract.conId = client.symbols[symbol] print('Contract ID for symbol {} is: {}'.format(symbol, client.symbols[symbol])) #take conId from IB website or contractDetails callback contract.currency = "INR" # Initialize the candle data dictionary for v in ['Date','Open', 'High', 'Low', 'Close', 'Volume']: client.candle_dict[v] = [] # Request OHLCV data now = datetime.now().strftime("%Y%m%d %H:%M:%S") client.reqHistoricalData(4, contract, now, '2 D', '5 mins', 'TRADES', False, 1, False, []) time.sleep(3) # Allow enough time for data to be returned. df = pd.DataFrame(client.candle_dict, columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume']) df['Date'] = pd.to_datetime(df['Date']) # Convert to pandas DateTime format # print(df.tail()) # print(df.columns) df.to_csv(symbol + '.csv', encoding='utf-8', index=False) client.candle_dict.clear() # Disconnect from TWS client.disconnect()
def main(): # Create the client and connect to TWS client = MarketReader('127.0.0.1', 7497, 0) # Request the current time con = Contract() con.symbol = 'IBM' con.secType = 'STK' con.exchange = 'SMART' con.currency = 'USD' # Request ten ticks containing midpoint data client.reqTickByTickData(0, con, 'MidPoint', 10, True) # Request market data client.reqMktData(1, con, '', False, False, []) # Request current bars client.reqRealTimeBars(2, con, 5, 'MIDPOINT', True, []) # Request historical bars now = datetime.now().strftime("%Y%m%d, %H:%M:%S") client.reqHistoricalData(3, con, now, '2 w', '1 day', 'MIDPOINT', False, 1, False, []) # Request fundamental data client.reqFundamentalData(4, con, 'ReportSnapshot', []) # Sleep while the requests are processed time.sleep(5) # Disconnect from TWS client.disconnect()
def get_contract_details(client): ''' Define the contract of intrest''' # pdb.set_trace() contract = Contract() contract.symbol = 'NIFTY50' contract.secType = "CONTFUT" contract.exchange = 'NSE' contract.primaryExchange = 'NSE' contract.currency = "INR" contract.includeExpired = True # Get complete details about the contract from IB's database client.contractDetailsEnd_available.clear( ) # internal flag is set to False client.reqContractDetails(1, contract) client.contractDetailsEnd_available.wait( ) # block thread until internal flag is set to True if client.local_symbol: print('Local Symbol : {}'.format(client.local_symbol)) # Set additional contract data contract.localSymbol = client.local_symbol contract.multiplier = client.multiplier else: print('Could not access contract data From reqContractDetails') exit_program(client) return contract
def create_stock(symbol, security_type='STK', exchange='SMART', currency='JPY'): contract = Contract() contract.symbol = symbol contract.secType = security_type contract.exchange = exchange contract.currency = currency return contract
def read_option_chain(client, ticker): # Define a contract for the underlying stock contract = Contract() contract.symbol = ticker contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' client.reqContractDetails(0, contract) time.sleep(2) # Get the current price of the stock client.reqTickByTickData(1, contract, "MidPoint", 1, True) time.sleep(4) # Request strike prices and expirations if client.conid: client.reqSecDefOptParams(2, ticker, '', 'STK', client.conid) time.sleep(2) else: print('Failed to obtain contract identifier.') exit() # Create contract for stock option req_id = 3 if client.strikes: for strike in client.strikes: client.chain[strike] = {} for right in ['C', 'P']: # Add to the option chain client.chain[strike][right] = {} # Define the option contract contract.secType = 'OPT' contract.right = right contract.strike = strike contract.exchange = client.exchange contract.lastTradeDateOrContractMonth = client.expiration # Request option data client.reqMktData(req_id, contract, '100', False, False, []) req_id += 1 time.sleep(1) else: print('Failed to access strike prices') exit() time.sleep(5) # Remove empty elements for strike in client.chain: if client.chain[strike]['C'] == {} or client.chain[strike]['P'] == {}: client.chain.pop(strike) return client.chain, client.atm_price
def main(): # Create the client and connect to TWS client = ReadFutures('127.0.0.1', 7497, 0) # Get expiration dates for contracts for symbol in client.symbols: # Define contract of interest con = Contract() con.symbol = symbol con.secType = "CONTFUT" con.exchange = client.symbols[symbol] con.currency = "USD" con.includeExpired = True client.reqContractDetails(0, con) time.sleep(3) # Request historical data for each contract if client.local_symbol: # Initialize price dict for v in ['CLOSE', 'LOW', 'HIGH', 'VOL']: client.price_dict[v] = [] # Set additional contract data con.localSymbol = client.local_symbol con.multiplier = client.multiplier # Request historical data end_date = datetime.today().date() - timedelta(days=1) client.reqHistoricalData(1, con, end_date.strftime("%Y%m%d %H:%M:%S"), '1 Y', '1 day', 'TRADES', 1, 1, False, []) time.sleep(3) # Write data to a CSV file if client.price_dict['CLOSE']: df = pd.DataFrame(data=client.price_dict) df.to_csv(symbol + '.csv', encoding='utf-8', index=False) client.price_dict.clear() else: print('Could not access contract data') exit() # Disconnect from TWS client.disconnect()
def main(): # Create the client and connect to TWS client = SubmitOrder('127.0.0.1', 7497, 0) # Define a contract for Apple stock contract = Contract() contract.symbol = 'AAPL' contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' # Define the limit order order = Order() order.action = 'BUY' order.totalQuantity = 200 order.orderType = 'LMT' order.lmtPrice = 150 order.transmit = False # Obtain a valid ID for the order client.reqIds(1) time.sleep(2) # Place the order if client.order_id: client.placeOrder(client.order_id, contract, order) time.sleep(5) else: print('Order ID not received. Ending application.') sys.exit() # Obtain information about open positions client.reqPositions() time.sleep(2) # Obtain information about account client.reqAccountSummary(0, 'All', 'AccountType,AvailableFunds') time.sleep(2) # Disconnect from TWS client.disconnect()
def main(): app = TestApp() app.connect("127.0.0.1", 7497, 2) # socket port is set in TWS or IB Gateway settings time.sleep(1) # short sleep to allow connection contract = Contract() contract.symbol = instrument contract.secType = securitytype contract.exchange = exchange contract.currency = "USD" contract.lastTradeDateOrContractMonth = "201903" app.reqHistoricalData(1, contract, "", length, barSize, "TRADES", 1, 1, False, []) print(instrument) app.run() wb.save('RandomRawData.xlsx')
def main(): # Create the client and connect to TWS client = Bollinger('127.0.0.1', 7497, 0) # Define a contract for IBM stock contract = Contract() contract.symbol = "IBM" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" # Request six months of historical data currentTime = datetime.today().strftime("%Y%m%d %H:%M:%S") client.reqHistoricalData(0, contract, currentTime, '6 M', '1 day', 'MIDPOINT', 1, 2, False, []) # Sleep while the request is processed time.sleep(5) # Disconnect from TWS client.disconnect()
def main(): # Create the client and connect to TWS client = ContractReader('127.0.0.1', 7497, 0) time.sleep(0.5) # Request descriptions of contracts related to cheesecake client.reqMatchingSymbols(0, 'Cheesecake') time.sleep(3) # Request details for the stock contract = Contract() contract.symbol = client.symbol contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" client.reqContractDetails(1, contract) # Sleep while the request is processed time.sleep(3) client.disconnect()
def big_fundamental(self): 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" fun_storage=self.wrapper.init_fun() self.reqFundamentalData(8001, contract, "RESC", []) MAX_WAIT_SECONDS = 10 try: current_fun = fun_storage.get(timeout=MAX_WAIT_SECONDS) except queue.Empty: print("Exceeded maximum wait for wrapper to respond") current_fun = None while self.wrapper.is_error(): print(self.get_error())
def main(): # Create the client and connect to TWS client = WriteFuturesToCSV('127.0.0.1', 7497, 0) client.nextValidId_available.wait( ) # block thread until internal flag is set to True print('\n Good to Go Baba. We are Connected to TWS') print(' The Order Id is: {}'.format(client.orderId)) print(' The Account Details are: {}\n'.format(client.accountsList)) # Get expiration dates for contracts for count, symbol in enumerate(client.symbols): # Define contract of interest contract = Contract() contract.symbol = symbol contract.secType = "CONTFUT" contract.exchange = client.symbols[symbol] contract.primaryExchange = client.symbols[symbol] contract.currency = "INR" contract.includeExpired = True client.contractDetailsEnd_available.clear( ) #internal flag is set to False client.reqContractDetails(count, contract) client.contractDetailsEnd_available.wait( ) # block thread until internal flag is set to True # Request historical data for each contract if client.local_symbol: print('Local Symbol : {}'.format(client.local_symbol)) print('Symbol : {}'.format(symbol)) # Set additional contract data contract.localSymbol = client.local_symbol contract.multiplier = client.multiplier # Initialize the deque client.date_dq.clear() client.open_dq.clear() client.high_dq.clear() client.low_dq.clear() client.close_dq.clear() client.volume_dq.clear() client.historicalDataEnd_available.clear( ) #internal flag is set to False # Request historical data query_time = (datetime.today().date() - timedelta(days=0)).strftime("%Y%m%d %H:%M:%S") client.reqHistoricalData(count, contract, query_time, '2 Y', '1 day', 'TRADES', 1, 1, False, []) client.historicalDataEnd_available.wait( ) # block thread until internal flag is set to True # Create List date_list = list(client.date_dq) open_list = list(client.open_dq) high_list = list(client.high_dq) low_list = list(client.low_dq) close_list = list(client.close_dq) volume_list = list(client.volume_dq) combined_list = [ date_list, open_list, high_list, low_list, close_list, volume_list ] # Write data to a CSV file df = pd.DataFrame(combined_list).transpose() df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] df['Date'] = pd.to_datetime( df['Date']) # Convert to pandas DateTime format df = df[df.Volume != 0] # Drop all entries for which volume traded = 0 df.to_csv(client.local_symbol + '.csv', encoding='utf-8', index=False) combined_list = [] # Empty the List else: print('Could not access contract data') sys.exit() # Disconnect from TWS. But first cancel open Subscriptions client.cancelHistoricalData(count) # provide ID of original request client.disconnect()
def place_order_with_stop(client, action, quantity, stopLoss): ''' Place the Order with IB ''' # Define the futures Contract prior to placing order contract = Contract() contract.localSymbol = client.local_symbol contract.secType = 'FUT' contract.exchange = 'NSE' contract.currency = 'INR' contract.primaryExchange = "NSE" # Request from TWS, the next valid ID for the order. client.nextValidId_available.clear() # internal flag is set to False client.reqIds(-1) # The parameter is always ignored. client.nextValidId_available.wait( ) # block thread until internal flag is set to True # Place the order if client.orderId: # for Market Orders use execDetails callback instead of orderStatus # execDetails callback event is trigerred ONLY if the order placed is Executed client.execDetails_available.clear() # internal flag is set to False if hasattr(client, "orderStatus_queue" ): # Clear the existing messages in the Q , if any with client.orderStatus_queue.mutex: client.orderStatus_queue.queue.clear() bracket = NiftyORB.OrderWithStop(client.orderId, action, quantity, stopLoss) for o in bracket: client.orders_list.append(o.orderId) client.placeOrder(o.orderId, contract, o) try: client.execDetails_available.wait(timeout=5) except: print( ' *** An Exception Occured in client.execDetails_available.wait(timeout=5) in place_order_with_stop *** ' ) else: # if try condition is successful with no execption, this 'else' follows if client.order_executed == True: print(" *** \nOrder is Successfully Executed ***\n") else: print(' *** \nOrder NOT Executed ***\n') # Handle the q from orderStatus callback # https://stackoverflow.com/questions/6517953/clear-all-items-from-the-queue if hasattr(client, "orderStatus_queue"): while not client.orderStatus_queue.empty( ): # If the queue is not empty try: order_status = client.orderStatus_queue.get(False) print( 'Status of Order: {}, Filled Positions: {}, Remaining Positions: {}, OrderId: {}, permId: {}' .format(order_status['status'], order_status['filled'], order_status['remaining'], order_status['orderId'], order_status['permId'])) if client.orderId == order_status[ 'orderId']: # for the latest orderId if (order_status['status'] == 'Submitted') or ( order_status['status'] == 'Filled' ): # if for even 1 message, the status is filled or submitted client.order_submitted = True except queue.Empty: continue client.orderStatus_queue.task_done( ) # task_done() is used to inform task completion # del client.orderStatus_queue # Delete the queue else: print('Order ID not received. Terminating Application') client.disconnect() sys.exit() if (client.order_executed == True) or (client.order_submitted == True): order_placed = True # set flag to True else: order_placed = False client.order_submitted = False # reset the flag to False for future use client.order_executed = False # reset the flag to False for future use return order_placed
# Triggered after all execDetails are received. print("In callback execDetailsEnd. ReqId: {}".format(reqId)) self.execDetailsEnd_available.set() #internal flag is set to True @iswrapper def error(self, req_id, code, msg): ''' Called if an error occurs ''' print('Error Request Id: {}, Error Code: {}, Error Message: {}'.format(req_id, code, msg)) print ("Main Program Starts Here. Going to Connect to TWS") # Create the client and connect to TWS client = TestApp('127.0.0.1', 7497, 4) client.nextValidId_available.wait() # block thread until internal flag is set to True # Define the futures Contract prior to placing order contract = Contract() contract.symbol = 'TCS' contract.secType = 'STK' contract.exchange = 'NSE' contract.currency = 'INR' contract.primaryExchange = "NSE" # Define the Order order = Order() order.action = 'BUY' order.totalQuantity = 4 order.orderType = 'MKT' # Request from TWS, the next valid ID for the order. client.nextValidId_available.clear() # internal flag is set to False client.reqIds(-1) # The parameter is always ignored.
def close_open_position(client, action: str, quantity: int): quantity = int(quantity) print('Entered Close Position') # Define the futures Contract prior to placing order contract = Contract() contract.localSymbol = client.local_symbol contract.secType = 'FUT' contract.exchange = 'NSE' contract.currency = 'INR' contract.primaryExchange = "NSE" # Define the Limit Order for BUY/SELL order = Order() order.action = action order.totalQuantity = quantity order.orderType = 'MKT' # Request from TWS, the next valid ID for the order. client.nextValidId_available.clear() # internal flag is set to False client.reqIds(-1) # The parameter is always ignored. client.nextValidId_available.wait( ) # block thread until internal flag is set to True # Place the order if client.orderId: # for Market Orders use execDetails callback instead of orderStatus # execDetails callback event is trigerred ONLY if the order placed is Executed client.execDetails_available.clear() # internal flag is set to False if hasattr(client, "orderStatus_queue" ): # Clear the existing messages in the Q , if any with client.orderStatus_queue.mutex: client.orderStatus_queue.queue.clear() # Place the order client.placeOrder(client.orderId, contract, order) try: client.execDetails_available.wait(timeout=5) except: print( ' *** An Exception Occured in client.execDetails_available.wait(timeout=5) in close_open_position *** ' ) else: # if try condition is successful with no execption, this 'else' follows if client.order_executed == True: print(" *** \nOrder is Successfully Executed ***\n") else: print(' *** \nOrder NOT Executed ***\n') # Handle the q from orderStatus callback if hasattr(client, "orderStatus_queue"): while not client.orderStatus_queue.empty( ): # If the queue is not empty try: order_status = client.orderStatus_queue.get(False) print( 'Status of Order: {}, Filled Positions: {}, Remaining Positions: {}, OrderId: {}, permId: {}' .format(order_status['status'], order_status['filled'], order_status['remaining'], order_status['orderId'], order_status['permId'])) if client.orderId == order_status[ 'orderId']: # for the latest orderId if (order_status['status'] == 'Submitted') or ( order_status['status'] == 'Filled' ): # if for even 1 message, the status is filled or submitted client.order_submitted = True except queue.Empty: continue client.orderStatus_queue.task_done( ) # task_done() is used to inform task completion del client.orderStatus_queue # Delete the queue else: print('Order ID not received. Terminating Application') client.disconnect() sys.exit() if (client.order_executed == True) or (client.order_submitted == True): position_closed = True # set flag to True else: position_closed = False client.order_submitted = False # reset the flag to False for future use client.order_executed = False # reset the flag to False for future use return position_closed
def main(): # Create the client and connect to TWS client = AdvOrder('127.0.0.1', 7497, 0) time.sleep(0.5) # Define the contract con = Contract() con.symbol = 'IBM' con.secType = 'STK' con.currency = 'USD' con.exchange = 'SMART' # Get unique ID for contract client.reqContractDetails(0, con) time.sleep(3) # Create a volume condition vol_condition = Create(OrderCondition.Volume) vol_condition.conId = client.con_id vol_condition.exchange = client.exch vol_condition.isMore = True vol_condition.volume = 20000 # Obtain an ID for the main order client.reqIds(1000) time.sleep(2) # Create the bracket order main_order = Order() main_order.orderId = client.order_id main_order.action = 'BUY' main_order.orderType = 'MKT' main_order.totalQuantity = 100 main_order.transmit = False main_order.conditions.append(vol_condition) # Set the algorithm for the order main_order.algoStrategy = 'Adaptive' main_order.algoParams = [] main_order.algoParams.append(TagValue('adaptivePriority', 'Patient')) # First child order - limit order first_child = Order() first_child.orderId = client.order_id + 1 first_child.action = 'SELL' first_child.orderType = 'LMT' first_child.totalQuantity = 100 first_child.lmtPrice = 170 first_child.parentId = client.order_id first_child.transmit = False # Stop order child second_child = Order() second_child.orderId = client.order_id + 2 second_child.action = 'SELL' second_child.orderType = 'STP' second_child.totalQuantity = 100 second_child.auxPrice = 120 second_child.parentId = client.order_id second_child.transmit = False # Submit each order client.placeOrder(client.order_id, con, main_order) client.placeOrder(client.order_id + 1, con, first_child) client.placeOrder(client.order_id + 2, con, second_child) # Sleep while the request is processed time.sleep(5) client.disconnect()