def __init__(self, name='broker'):
        """ initialize broker class
        """
        self.name = name
        self.log = logger.getLogger(self.name)


        self.log.debug('Initializing broker. Pandas version={0}'.format(pandas.__version__))
        self.contracts = {}  # a dict to keep track of subscribed contracts


        self.tws = ibConnection()  # tws interface
        self.nextValidOrderId = None


        self.dataModel = Subscriptions(self.tws)  # data container


        self.tws.registerAll(self.defaultHandler)
        #self.tws.register(self.debugHandler,message.TickPrice)
        self.tws.register(self.nextValidIdHandler, 'NextValidId')
        self.log.debug('Connecting to tws')
        self.tws.connect()

        self.tws.reqAccountUpdates(True, '')
Ejemplo n.º 2
0
def main():
    #connect
    # conn = Connection.create(port=7497,clientId=4)
    conn = ibConnection()
    conn.registerAll(print_message_from_ib)
    conn.unregister(print_message_from_ib, message.tickSize, message.tickPrice,
                    message.tickString, message.tickOptionComputation)
    conn.register(my_BidAsk, message.tickPrice)

    conn.connect()
    print("test:", Gbid)

    ##get contract
    newContract = Contract()
    newContract.m_symbol = 'EUR'  #買入物
    newContract.m_secType = 'CASH'  #股票,外匯
    newContract.m_exchange = 'IDEALPRO'  #交易所
    newContract.m_currency = 'USD'  #交易貨幣
    tickID = 3
    conn.reqMktData(tickID, newContract, '', False)
    # print(message.tickPrice.price)

    #test = 1.17363
    #if( Gbid > test ):
    #orderID = 104
    #mktOrder = Order()
    #mktOrder.m_totalQuantity = 100
    #mktOrder.m_orderType = 'LMT'
    #mktOrder.m_action = 'BUY'
    #mktOrder.m_lmtPrice = Gbid + 0.001
    #conn.placeOrder(orderID,newContract,mktOrder)

    time.sleep(1)
    conn.disconnect()
Ejemplo n.º 3
0
    def request_market_data(self, timeframe, interval, symbol, sectype, \
                                        exchange, currency=None, expiry=None, \
                                        primexch=None, latestdate=None):
        # Establish a connection
        sys.stdout.write("\nCalling connection\n")
        connection = ibConnection()
        connection.register(self.ibhndl.my_callback_handler, \
                                                        message.historicalData)
        connection.connect()
 
        #Contract
        contract = Contract()
        contract.m_symbol = symbol
        contract.m_secType = sectype
        contract.m_exchange = exchange
        contract.m_currency = currency
 
        if primexch:
            contract.m_primaryExch = primexch
 
        if expiry:
            contract.m_expiry = expiry
 
        # Get historical data
        rtnData = self.ibhndl.reqHistoricalData(contract, interval, connection,\
                                                        timeframe, latestdate)
        connection.disconnect()
 
        if not rtnData[0]:
            sys.stderr.write("ERROR: No data return for %s : %s\n" % (symbol,\
                                                                    interval)) 
            return rtnData, ""

        dateList = list()
        stockFile = list()
        for data, volume in zip(rtnData[0], rtnData[1]):
            dateList = dateList + [data[0]]
            dataStr = '%s, %s, %s, %s, %s, %s' % \
                        (strftime("%Y-%m-%d %H:%M:%S", \
                              localtime(int(str(data[0]))/1000)), data[1], \
                              data[2], data[3], data[4], str(volume[1]))
        
            stockFile = stockFile + [dataStr]
        
        convertStr = '%Y-%m-%d %H:%M:%S'
        date, _, _, _, closep, volume = \
                        np.loadtxt(stockFile, delimiter=',', unpack=True, \
                       converters={0:mdates.strpdate2num(convertStr)})
        
        #PATTERNS
        retpat = []
        try:
            patterndb = PatternDB()
            patterndb.add(HS())
            patterndb.add(IHS())
        
            retpat = patterndb.check(closep[-60:], date[-60:])
        except Exception, excp:
            sys.stderr.write("ERROR: PATTERNS failed with exception " \
                                                            "%s\n" % excp)
Ejemplo n.º 4
0
Archivo: Stock.py Proyecto: huhe56/IB
 def connect(self):
     self._con = ibConnection()
     self._con.registerAll(self.watcher)
     self._con.unregister(self.watcher, 'ContractDetails', 'ContractDetailsEnd', 'TickPrice', 'TickSize', 'TickString', 'TickGeneric')
     self._con.register(self.tick_price_hander, 'TickPrice')
     self._con.register(self.tick_snapshot_end_handler, 'TickSnapshotEnd')
     self._con.connect()
Ejemplo n.º 5
0
    def __init__(self, host='localhost', port=4001,
                 client_id=130, is_use_gateway=False, evaluation_time_secs=20,
                 resample_interval_secs='30s',
                 moving_window_period=dt.timedelta(seconds=60)):
        self.moving_window_period = moving_window_period
#        self.chart = Chart()
        self.ib_util = IBUtil()

        # Store parameters for this model
#        self.strategy_params = StrategyParameters(evaluation_time_secs,
#                                                  resample_interval_secs)

        self.stocks_data = {}  # Dictionary storing StockData objects.
        self.symbols = None  # List of current symbols
        self.account_code = ""
        self.prices = None  # Store last prices in a DataFrame
        self.ohlc = None # I need another store for minute data (I think)        
        self.trade_qty = 0
        self.order_id = 0
        self.lock = threading.Lock()
        #addition for hdf store
        self.data_path = os.path.normpath("/Users/maxime_back/Documents/avocado/data.csv")
        self.ohlc_path = os.path.normpath("/Users/maxime_back/Documents/avocado/ohlc.csv")
        self.last_trim = dt.datetime.now()


        # Use ibConnection() for TWS, or create connection for API Gateway
        self.conn = ibConnection() if is_use_gateway else \
            Connection.create(host=host, port=port, clientId=client_id)
        self.__register_data_handlers(self.__on_tick_event,
                                      self.__event_handler)
Ejemplo n.º 6
0
    def tick_csv(self):
        #linked to button "csv"
        connected = varCon.get()

        #init variables
        self.bid = None
        self.bidsz = None
        self.ask = None
        self.asksz = None

        #create csv
        init_time = time.strftime("%d-%m-%Y_%H'%M'%S")
        security = varSymbol.get()
        myFile = "data/Tick/EUR." + str(security) + "_" + str(
            init_time) + ".txt"

        #create csv header
        csvheader = ["Time", "Bid", "Bidsize", "Ask", "Asksize"]
        f = open(str(myFile), "w+")
        self.writer = csv.writer(f, delimiter=' ')
        self.writer.writerow(csvheader)

        #check if connected
        if connected:
            self.disconnect()
            self.led_off()
        connected = TRUE
        self.led_on()

        #establish connection
        self.con = ibConnection(port=myPort, clientId=myclientId)
        self.con.register(self.error_handler, message.Error)
        self.con.register(self.nextValidId_handler, message.nextValidId)
        self.con.register(self.BidAsk, message.tickPrice, message.tickSize)
        self.con.connect()
Ejemplo n.º 7
0
    def __init__(
            self, data_handler, position_handler, portfolio_handler, account,
            gmail_and_password=None
    ):
        """Initialize parameters of the Interactive Brokers Portfolio."""
        super(InteractiveBrokersPortfolio, self).__init__(
            data_handler, position_handler, portfolio_handler
        )
        # Set the account identifier for this portfolio. This should correspond
        # to either the live trading account or the paper trading account.
        self.account = account
        # Now create connections to the Trader Workstation.
        self.conn = ibConnection(
            clientId=IB.portfolio_id.value, port=IB.port.value
        )
        self.conn.register(
            self.__update_portfolio_handler, message.updatePortfolio
        )
        self.conn.register(self.__error_handler, message.error)
        if not self.conn.connect():
            raise ValueError(
                "Odin was unable to connect to the Trader Workstation."
            )

        # If we want to receive email notifications that trades have been
        # filled, then we provide the gmail account and its password.
        self.gmail_and_password = gmail_and_password
Ejemplo n.º 8
0
 def get_market_depth(self, contract_=Contract(), numRows_=5):
     """
     This mathod helps to get the depth of the market before placing an order
     
     """
     # First step is to define a dictionary whill will be populated by IB API
     con = ibConnection(port=4001, clientId=998)
     #con.registerAll(self.watcher)
     con.register(self.my_market_depth_handler, 'UpdateMktDepth')
     # Setting up the connection
     con.connect()
     # Cleaning up the market depth
     self.market_depth.drop(range(self.market_depth.shape[0]), inplace=True)
     self.market_depthL2.drop(range(self.market_depthL2.shape[0]),
                              inplace=True)
     self.all_market_depth.drop(range(self.all_market_depth.shape[0]),
                                inplace=True)
     self.all_market_depthL2.drop(range(self.all_market_depthL2.shape[0]),
                                  inplace=True)
     # Requesting the market depth
     con.reqMktDepth(1, contract_, numRows_)
     # Sleep
     sleep(1)
     # Canceling the request
     con.cancelMktDepth(tickerId=1)
     # Storing The Data
     # ...
     # Disconnecting
     print('Disconnected', con.disconnect())
Ejemplo n.º 9
0
    def __init__(self):
        self.tws = ibConnection(port=4001, clientId=999)
        self.tws.register(self.bidaskHandler, message.tickPrice)
        # ib poses a ~1min/req rate limit on updateAccountValue and orderStatus
        self.tws.register(self.accountHandler, message.updateAccountValue)
        self.tws.register(self.portfolioHandler, message.updatePortfolio)
        self.tws.register(self.orderStatusHandler, message.orderStatus)
        self.tws.register(self.openOrderHandler, message.openOrder)
        self.tws.register(self.validIdHandler, message.nextValidId)
        self.tws.register(self.serverTimeHandler, message.currentTime)
        self.tws.connect()

        self.netliq = []
        self.pSym = []
        self.pSiz = []
        self.pVal = []
        self.bids = []
        self.asks = []

        self.openOrderIds = []
        self.openParentIds = []
        self.openAuxPrices = []  # stop prices

        self.reqId = 0
        self.orderId = []

        self.server_time = [
        ]  # used to ping IB periodically in case of lost connection
Ejemplo n.º 10
0
    def get_updates(self):
        """
        This method helps us to get the historical data. It is not written in the most optimal way yet.
        """
        # First step is to define a dictionary whill will be populated by IB API
        con = ibConnection(port=4001, clientId=998)
        con.register(self.my_acct_handler, 'UpdateAccountValue')
        con.register(self.my_tick_handler, message.tickPrice, message.tickSize)
        con.register(self.my_hist_data_handler, message.historicalData)
        # Setting up the connection
        con.connect()

        # Defining the contract
        aapl = Contract()
        aapl.m_symbol = 'AAPL'
        aapl.m_secType = 'STK'
        aapl.m_exchange = 'SMART'

        # con.reqMktData(1, aapl, '', False)
        # con.reqHistoricalData(tickerId=1,
        #                      contract=aapl,
        #                      endDateTime=datetime.datetime.today().strftime("%Y%m%d %H:%M:%S %Z"),
        #                      durationStr='1 Y',
        #                      barSizeSetting='1 day',
        #                      whatToShow='MIDPOINT',
        #                      useRTH=0,
        #                      formatDate=1)

        # Sleep
        sleep(5)

        # Disconnecting
        print('Disconnected', con.disconnect())
Ejemplo n.º 11
0
    def get_execution(self, executionFilter_=ExecutionFilter()):
        """
        Getting the details of the execution within the past 24 hours. Commission reports as well
        
        An executionFilter needs to be passed in
        """
        # First step is to define a dictionary will will be populated by IB API
        con = ibConnection(port=4001, clientId=999)

        # Registering Handlers
        #con.registerAll(self.watcher)
        con.register(self.my_execution_handler, message.execDetails)
        con.register(self.my_commission_handler, message.commissionReport)
        con.register(self.my_execution_end, message.execDetailsEnd)

        # Setting up the connection
        con.connect()

        # Cleaning up the this_execution first
        if not self.this_execution.empty:
            self.this_execution.drop(range(self.this_execution.shape[0]),
                                     inplace=True)
        # Cleaning up the this_execution first
        if not self.this_commission.empty:
            self.this_commission.drop(range(self.this_commission.shape[0]),
                                      inplace=True)

        # Asking the execution details
        #filter_in = self.make_exec_filter(secType = 'BAG')
        con.reqExecutions(1, executionFilter_)
        sleep(5)
        # Disconnecting
        print('Disconnected', con.disconnect())
    def __init__(self):
        """Initialize parameters of the Interactive Brokers price handler
        object.
        """
        super(InteractiveBrokersPriceHandler, self).__init__()
        self.conn = ibConnection(clientId=IB.data_handler_id.value,
                                 port=IB.port.value)
        self.conn.register(self.__tick_price_handler, message.tickPrice)
        if not self.conn.connect():
            raise ValueError(
                "Odin was unable to connect to the Trader Workstation.")

        # Set the target field to download data from.
        today = dt.datetime.today()
        open_t, close_t = dt.time(9, 30), dt.time(16)
        cur_t = today.time()
        # If today is a weekday and the timing is correct, then we use the most
        # recently observed price. Otherwise we use the close price.
        if today.weekday() < 5 and cur_t >= open_t and cur_t <= close_t:
            self.field = TickType.LAST
        else:
            self.field = TickType.CLOSE

        # Initialize a pandas panel to store the price data.
        self.bar = pd.Panel(items=[PriceFields.current_price.value])
Ejemplo n.º 13
0
    def __init__(self, contract, date, t, bar_size='5 mins', duration='1 D', rth=1, outfile='none'):
        self.outfile = outfile
        self.headings = ['date', 'time', 'open', 'high', 'low', 'close', 'volume', 'count', 'WAP', 'hasGaps']
        self.bars = []       
        self.contract = contract
        self.date = date
        self.t = t
        self.bar_size = bar_size
        self.duration = duration
        self.rth = rth
        self.tick_id = 1
        self.con = ibConnection(host = 'localhost', port = 7496, clientId = 139)

        self.con.registerAll(self.all_msgs)
        self.con.register(self.incoming_bars, message.historicalData)
        self.con.connect(); time.sleep(1)
        end_datetime = ('%s %s US/Eastern' % (self.date, self.t))
        self.con.reqHistoricalData(tickerId=self.tick_id, contract=self.contract, endDateTime=end_datetime, 
                                   durationStr=self.duration, barSizeSetting=self.bar_size, 
                                   whatToShow='TRADES', useRTH=self.rth, formatDate=1)
        self.finished = False        
        while not self.finished:    # loop here until self._incoming_bars() finishes
            pass
        self.con.cancelHistoricalData(self.tick_id); time.sleep(1)
        self.con.disconnect(); time.sleep(1)
        self.bars = pd.DataFrame(self.bars, columns=self.headings)
        if self.outfile != 'none':
            self.bars.to_csv(self.outfile, cols=self.headings)
Ejemplo n.º 14
0
    def __init__(self, config):
        self.config = config
        config = ConfigParser.ConfigParser()
        config.read("config/app.cfg")
        host = config.get("market", "ib.gateway").strip('"').strip("'")
        port = int(config.get("market", "ib.port"))
        appid = int(config.get("market", "ib.appid.portfolio"))   
        
        r_host = config.get("redis", "redis.server").strip('"').strip("'")
        r_port = config.get("redis", "redis.port")
        r_db = config.get("redis", "redis.db")             
        
        
        self.r_conn = redis.Redis(r_host, r_port, r_db)
        
        self.con = ibConnection(host, port, appid)
        self.con.registerAll(self.on_ib_message)
        #self.con.registerAll(self.xyz)

        self.cal_greeks_settings['rate'] = config.get("market", "portfolio.cal.param.rate")
        self.cal_greeks_settings['div'] = config.get("market", "portfolio.cal.param.div")
        self.rs_port_keys['port_conid_set'] = config.get("redis", "redis.datastore.key.port_conid_set").strip('"').strip("'")
        
        
        self.session_id = self.gen_session_id()
        logging.info("********** Starting up portfolio-ex manager")
        logging.info("********** session id preix is [%s], this id is prepended to every key in the redis db" % self.session_id)
        logging.info("**********")
        
        logging.info("********** clear the redis datastore for all records that start with this session id [%s]" % self.session_id)
        self.clear_redis_portfolio()
Ejemplo n.º 15
0
    def __init__(self):
        options = get_options()
        basicConfig()
        self.connection = ibConnection(options.host, options.port,
                                       options.clientid)
        self.clientid = options.clientid
        self.connection.register(self._reply_next_valid_order_id,
                                 'NextValidId')
        self.connection.register(self._update_account_value, 'AccountSummary')
        self.connection.register(self._reply_managed_accounts,
                                 'ManagedAccounts')
        self.connection.register(self._reply_current_time, 'CurrentTime')
        self.connection.register(self._reply_realtime_snapshot,
                                 message.tickPrice, message.tickSize)

        self.connection.register(self._reply_place_order, 'OrderStatus')
        self.connection.register(self._error_handler, 'Error')
        self.connection.register(self._reply_execution_details, 'ExecDetails')
        self.connection.registerAll(self._reply_all)

        self.ib_account_cash = dict()
        self.ib_account_list = list()
        self.market_data = dict()
        self._requested_tickers = dict()

        self.orders = dict()
        self._order_events = set()

        self._current_time = None

        self._time_received_next_valid_order_id = None
        self._next_valid_order_id = None
        self.messages = list()
        self.execution_allocation_msgs = list()
        self.execution_allocations = AccountAllocations()
Ejemplo n.º 16
0
    def __init__(self, host='localhost', port=4001,
                 client_id=101, is_use_gateway=False, evaluation_time_secs=20,
                 resample_interval_secs='30s',
                 moving_window_period=dt.timedelta(hours=1)):
        self.moving_window_period = moving_window_period
        self.chart = Chart()
        self.ib_util = IBUtil()

        # Store parameters for this model
        self.strategy_params = StrategyParameters(evaluation_time_secs,
                                                  resample_interval_secs)

        self.stocks_data = {}  # Dictionary storing StockData objects.
        self.symbols = None  # List of current symbols
        self.account_code = ""
        self.prices = None  # Store last prices in a DataFrame
        self.trade_qty = 0
        self.order_id = 0
        self.lock = threading.Lock()

        # Use ibConnection() for TWS, or create connection for API Gateway
        self.conn = ibConnection() if is_use_gateway else \
            Connection.create(host=host, port=port, clientId=client_id)
        self.__register_data_handlers(self.__on_tick_event,
                                      self.__event_handler)
Ejemplo n.º 17
0
def get_market_value(symbol, sec_type, exchange, currency, expiry, strike,
                     right):
    con = ibConnection()
    con.registerAll(watcher)
    con.unregister(watcher, message.tickSize, message.tickPrice,
                   message.tickString, message.tickOptionComputation)
    con.register(ticket_price_handler, message.tickPrice)
    con.connect()
    sleep(1)
    tickId = 1
    contract = Contract()
    contract.m_symbol = symbol
    contract.m_secType = sec_type
    contract.m_exchange = exchange
    contract.m_currency = currency
    contract.m_expiry = expiry
    contract.m_strike = strike
    contract.m_right = right
    print('* * * * REQUESTING MARKET DATA * * * *')
    con.reqMktData(tickId, contract, '', False)
    sleep(2)
    print('* * * * CANCELING MARKET DATA * * * *')
    con.cancelMktData(tickId)
    sleep(0.1)
    con.disconnect()
Ejemplo n.º 18
0
    def generate_spx(self, symbol="SPX", exchange="SMART", currency="USD", \
                                            secType="OPT", expiry="20151023",
                                            strikep=None):
        """ Function to resemble a main function """
        # Establish a connection
        sys.stdout.write("\nCalling connection\n")
        connection = ibConnection()
        connection.registerAll(self.ibhndl.my_callback_handler)
        connection.connect()

        # Get contract details
        contract_values = Contract()
        contract_values.m_symbol = symbol
        contract_values.m_exchange = exchange
        contract_values.m_currency = currency
        contract_values.m_secType = secType
        contract_values.m_expiry = expiry
        
        if strikep:
            contract_values.m_strike = strikep

        self.ibhndl.get_contract_details(connection, 1, contract_values)

        # Get Market values
        self.ibhndl.get_market_data(connection)

        if not os.path.isdir(os.path.join('.', 'spx_files')):
            os.makedirs('spx_files')

        mydir = os.path.join(os.getcwd(), 'spx_files', \
                         datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
        os.makedirs(mydir)

        OPTIONS.to_csv(os.path.join(mydir, 'Options.csv'))
        sys.stdout.write("\n\n")
Ejemplo n.º 19
0
 def start(self):
     """Start the connection and read the realtime bars for the specified 
     tickers.
     """
     # connection and handler
     self.connection = ibConnection(
                                    host=self.host, 
                                    port=self.port, 
                                    clientId=self.client_id)
     
     # registration
     self.connection.register( self.ticker_updated, message.RealtimeBar )
     
     # connect
     self.connection.connect()
     
     for inx,stock in enumerate(self.stocks):
         print "Requesting:\t%d = %s" % (inx,stock)
         # create the contract
         contract = Contract()
         contract.m_symbol = stock
         contract.m_secType = 'STK'
         contract.m_exchange = self.exchange
         contract.m_currency = 'USD'
         self.connection.reqRealTimeBars(inx, contract, 5, 'TRADES', False)
Ejemplo n.º 20
0
    def __init__(self):
        self.tws = ibConnection(port=4001, clientId=999)
        self.tws.register(self.bidaskHandler, message.tickPrice)
        # ib poses a ~1min/req rate limit on updateAccountValue and orderStatus
        self.tws.register(self.accountHandler, message.updateAccountValue)
        self.tws.register(self.portfolioHandler, message.updatePortfolio)
        self.tws.register(self.orderStatusHandler, message.orderStatus)
        self.tws.register(self.openOrderHandler, message.openOrder)
        self.tws.register(self.validIdHandler, message.nextValidId)
        self.tws.register(self.serverTimeHandler, message.currentTime)
        self.tws.connect()

        self.netliq = []
        self.pSym = []
        self.pSiz = []
        self.pVal = []
        self.bids = []
        self.asks = []

        self.openOrderIds  = []
        self.openParentIds = []
        self.openAuxPrices = []    # stop prices

        self.reqId = 0
        self.orderId = []

        self.server_time = []    # used to ping IB periodically in case of lost connection
Ejemplo n.º 21
0
 def create_tws_connection(self):
     """ Connect to the TWs running on port 7496, with a clientId of 10.
     Need a separate ID for market data connection, if used elsewhere.
     """
     tws_conn = ibConnection()
     tws_conn.connect()
     return tws_conn
Ejemplo n.º 22
0
    def __init__(self, config):
        self.config = config

        host = config.get("market", "ib.gateway").strip('"').strip("'")
        port = int(config.get("market", "ib.port"))
        appid = int(config.get("market", "ib.appid.portfolio"))   
        self.rs_port_keys['port_conid_set'] = config.get("redis", "redis.datastore.key.port_conid_set").strip('"').strip("'")
        self.rs_port_keys['port_prefix'] = config.get("redis", "redis.datastore.key.port_prefix").strip('"').strip("'")        
        self.rs_port_keys['port_summary'] = config.get("redis", "redis.datastore.key.port_summary").strip('"').strip("'")
        self.rs_port_keys['port_items'] = config.get("redis", "redis.datastore.key.port_items").strip('"').strip("'")
        
        
        self.rs_port_keys['acct_summary'] = config.get("redis", "redis.datastore.key.acct_summary").strip('"').strip("'") 
        self.account_tags = eval(config.get("portfolio", "portfolio.account_summary_tags").strip('"').strip("'"))
        
        self.epc = eval(config.get("portfolio", "portfolio.epc").strip('"').strip("'"))
        # instantiate a epc object if the config says so
        
        
        if self.epc['stream_to_Kafka']:
            self.epc['epc'] = EPCPub(config) 
        
        r_host = config.get("redis", "redis.server").strip('"').strip("'")
        r_port = config.get("redis", "redis.port")
        r_db = config.get("redis", "redis.db")             
        
        self.r_conn = redis.Redis(r_host, r_port, r_db)
        
        self.con = ibConnection(host, port, appid)
        self.con.registerAll(self.on_ib_message)
        
        
    	self.download_states = [False, False]
        self.tlock = Lock()
    def __init__(self, host='localhost', port=4001,
                 client_id=101, is_use_gateway=False, evaluation_time_secs=20,
                 resample_interval_secs='30s',
                 moving_window_period=dt.timedelta(hours=1)):
        self.moving_window_period = moving_window_period
        self.chart = Chart()
        self.ib_util = IBUtil()

        # Store parameters for this model
        self.strategy_params = StrategyParameters(evaluation_time_secs,
                                                  resample_interval_secs)

        self.stocks_data = {}  # Dictionary storing StockData objects.
        self.symbols = None  # List of current symbols
        self.account_code = ""
        self.prices = None  # Store last prices in a DataFrame
        self.trade_qty = 0
        self.order_id = 0
        self.lock = threading.Lock()

        # Use ibConnection() for TWS, or create connection for API Gateway
        self.conn = ibConnection() if is_use_gateway else \
            Connection.create(host=host, port=port, clientId=client_id)
        self.__register_data_handlers(self.__on_tick_event,
                                      self.__event_handler)
Ejemplo n.º 24
0
def main(options):
    basicConfig()
    logging.root.setLevel(verbose_levels.get(options.verbose, ERROR))
    options.port
    con = ibConnection(options.host, 7497, options.clientid)

    # con.registerAll(reply_handler)
    con.register(error_handler, 'Error')
    con.register(update_account_value, 'AccountSummary')
    con.register(my_BidAsk, message.tickPrice, message.tickSize)
    con.register(reply_handler, 'UpdateMktDepth')

    con.connect()
    short_sleep()

    request_account_summary(connection=con, options=options)
    request_market_data(connection=con, options=options, symbol='GOOG')
    request_market_data(connection=con, options=options, symbol='MSFT')
    request_market_depth(connection=con, options=options)

    #test_000(connection=con, options=options)
    #test_003(connection=con, options=options)
    #test_999(connection=con, options=options)

    sleep(2)
    con.eDisconnect()
Ejemplo n.º 25
0
	def __init__(self,account='',limit_adjust_interval = 15, max_adjust_time=5,loglevel = logging.INFO):

		self.logger = logging.getLogger('mxIBhandler')
		self.logger.setLevel(loglevel)
		#logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

		self.con = ibConnection()
		self.NextOrderID = 100
		self.__connected = True

		self.available_cash = dict()
		self.__updatePortfolioEvent = Event()
		self.__updatePortfolioEvent.clear()

		self.__OrdersFinished = Event()
		self.__OrdersFinished.set()
		self.__portfolio = dict()
		self.openorders = dict()
		self.log = dict()
		self.__SyncStockGetOrderID = None
		self.__SyncStockGetEvent = Event()
		self.__SyncStockGetEvent.set()
		self.__SyncStockGetPrice = None
		self.__SyncStockGetType = TickTypeBid 

		self.__SyncStockGetMultipleEvent = Event()
		self.__SyncStockGetMultipleEvent.set()
		self.__SyncStockGetMultipleType = TickTypeBid 
		self.__SyncStockGetMultiplePrice = dict()
		self.__SyncStockGetMultipleIDs = dict()
		self._account = account

		self.__MapToOriginalOrderID = dict() #map orderid to unique id
		self.__MapToExecuteOrderID = dict()

		self.limit_adjust_interval = limit_adjust_interval
		self.adjist_limits_thread = None
		self.max_adjust_time = datetime.timedelta(minutes=max_adjust_time)

		#register callback handlers
		self.con.register(self.updateAccountValueHandler, message.updateAccountValue)
		self.con.register(self.updatePortfolioHandler, message.updatePortfolio)
		self.con.register(self.accountDownloadEndHandler, message.accountDownloadEnd)
		self.con.register(self.tickPriceHandler, message.tickPrice)
		self.con.register(self.tickSizeHandler, message.tickSize)
		self.con.register(self.nextValidIdHandler, message.nextValidId)
		self.con.register(self.orderStatusHandler, message.orderStatus)
		self.con.register(self.errorHandler, message.error)

		self.logger.debug("mxIBhandler connecting...")
		self.con.connect()

		self.con.reqAccountUpdates(True, self._account)

		if not (self.__updatePortfolioEvent.wait(timeout=10) and (self.__connected == True)):
			self.logger.error("mxIBhandler connection timeout")
			raise IOError("Connection timeout")
		else:
			self.logger.debug("mxIBhandler connection succesful")
Ejemplo n.º 26
0
 def __init__(self, contract, Id=1, mkt_depth=5, ClientId=512):
     self.mkt_data = snapshot()
     self.con = ibConnection(clientId=ClientId)
     self.contract = contract
     self.mkt_depth = mkt_depth
     self.Id = Id  #orderId, autoincrement.
     self.order_book = {}
     self.ticker_id = 1
Ejemplo n.º 27
0
 def __init__(self, host='localhost', port=7496, clientid=0):
     self.__con = ibConnection(host, port, clientid)
     self.__con.registerAll(log_reply_handler)
     self.__con.register(save_order_id, 'NextValidId')
     self.__con.register(save_tick, 'TickSize', 'TickPrice')
     self.__con.register(historical_data_handler, 'HistoricalData')
     self.__con.connect()
     short_sleep()
Ejemplo n.º 28
0
 def __init__(self,contract,Id=1,mkt_depth=5,ClientId=512):
     self.mkt_data = snapshot()
     self.con  = ibConnection(clientId=ClientId)
     self.contract = contract
     self.mkt_depth = mkt_depth
     self.Id = Id #orderId, autoincrement.
     self.order_book = {}
     self.ticker_id = 1
Ejemplo n.º 29
0
def main():
    global con
    con = ibConnection(port=7497, clientId=1618)
    # 7496 for real account, 7497 for paper trader
    con.register(marketDataHandler, message.tickPrice)
    con.register(contractDetailsHandler, 'ContractDetails')
    con.register(historicalDataHandler, message.historicalData)
    con.connect()
Ejemplo n.º 30
0
	def __init__(self):
		"""__init__ passes the object its first parameters."""
		self.con = ibConnection()
		self.con.register(self.tickPriceHandler, 'TickPrice')
		self.con.registerAll(self.listener)
		self.con.connect()
		self.tickID = 1
		self.recordFile = open('aapl_100.dat', 'a')	
Ejemplo n.º 31
0
 def __init__(self):
     """__init__ passes the object its first parameters."""
     self.con = ibConnection()
     self.con.register(self.tickPriceHandler, 'TickPrice')
     self.con.registerAll(self.listener)
     self.con.connect()
     self.tickID = 1
     self.recordFile = open('aapl_100.dat', 'a')
Ejemplo n.º 32
0
	def create_tws_connection(self):
		"""
		Connect to the Trader Workstation (TWS) running on 
		usual port of 7496, with clientID 10. The clientID
		is chosen; two seperate IDs - one for execution 
		connection and market data connection.
		"""
		tws_conn = ibConnection() #ibConnection().connect()
		return tws_conn.connect()
Ejemplo n.º 33
0
 def create_tws_connection(self):
     '''
     Connect to the Trader Workstation (TWS) running on the usual port of 7496 (7497 for paper trading?), with a
     clientId of 10. The clientId is chosen by us and we will need separate IDs for the execution connection and
     market data connection, if the market data connection is used elsewhere
     '''
     tws_conn = ibConnection()
     tws_conn.connect()
     return tws_conn
Ejemplo n.º 34
0
 def create_tws_connection(self):
     """
     Connect to the Trader Workstation (TWS) running on the usual port of 7496, with a clientId of 10.
     The clientId is chosen by us and we will need to separate IDs for both the execution connection and market data connection, if the latter is used elsewhere.
     """
     tws_conn = ibConnection()
     # Perform connection.
     tws_conn.connect()
     return tws_conn
Ejemplo n.º 35
0
 def create_tws_connection(self):
     """
     Connect to the Trader Workstation (TWS) running on the usual port of 7496, with a clientId of 10.
     The clientId is chosen by us and we will need to separate IDs for both the execution connection and market data connection, if the latter is used elsewhere.
     """
     tws_conn = ibConnection()
     # Perform connection.
     tws_conn.connect()
     return tws_conn
Ejemplo n.º 36
0
    def __init__(self, config):
        self.config = config
        ibgw = config.get("market", "ib.gateway").strip('"').strip("'")
        ibport = config.get("market", "ib.port")
        ibid = config.get("market", "ib.appid")
        logging.debug("ibgw, port, app id: %s %s %s" % (ibgw, ibport, ibid))
        self.con = ibConnection(ibgw, int(ibport), int(ibid))

        self.con.registerAll(self.on_ib_message)
Ejemplo n.º 37
0
 def connect(self):
     """ connect to tws """
     self.tws =  ibConnection() # tws interface
     self.tws.registerAll(self._defaultHandler) 
     self.tws.register(self._nextValidIdHandler,'NextValidId')
     self.log.debug('Connecting to tws')
     self.tws.connect()  
     
     self.tws.reqAccountUpdates(True,'')
     self.tws.register(self._priceHandler,'TickPrice')
Ejemplo n.º 38
0
    def _connect(self):
        self._conn = ibConnection(host=self._opts.twsHost,
                                  port=self._opts.twsPort,
                                  clientId=self._opts.twsClientId)
        self._conn.connect()
        # Sleep for 1 second.
        sleep(1)

        print("Connected to IB")
        self._connected = True
Ejemplo n.º 39
0
    def connect(self):
        """ connect to tws """
        self.tws = ibConnection()  # tws interface
        self.tws.registerAll(self._defaultHandler)
        self.tws.register(self._nextValidIdHandler, 'NextValidId')
        self.log.debug('Connecting to tws')
        self.tws.connect()

        self.tws.reqAccountUpdates(True, '')
        self.tws.register(self._priceHandler, 'TickPrice')
Ejemplo n.º 40
0
 def create_tws_connection(self):
     '''
     Connect to the TWS running on the usual port of 7496, with a clientId of 10.
     The clientId is chose by us and we will need separate IDs for both the execution connection
     and market data connection, if the latter is used elsewhere.
     :return: TWS Connection
     '''
     tws_conn = ibConnection()
     tws_conn.connect()
     return tws_conn
Ejemplo n.º 41
0
 def __init__(self):
     """
     Connection to the IB API
     """
     print "Calling connection"
     # Creation of Connection class
     self.connection = ibConnection()
     # Register data handlers
     self.connection.registerAll(self.process_messages)
     # Connect
     self.connection.connect()
Ejemplo n.º 42
0
 def create_tws_connection(self):
     """
     Collegamento alla Trader Workstation (TWS) in esecuzione
     sulla porta standard 7496, con un clientId di 10.
     Il clientId è scelto da noi e avremo bisogno ID separati
     sia per la connessione di esecuzione che per la connessione
     ai dati di mercato, se quest'ultima è utilizzata altrove.
     """
     tws_conn = ibConnection()
     tws_conn.connect()
     return tws_conn
def testConnection():
    """ a simple test to check working of streaming prices etc """
    tws = ibConnection()
    tws.registerAll(dummyHandler)

    tws.connect()

    c = createContract('SPY')
    tws.reqMktData(1, c, '', False)
    sleep(3)

    print 'testConnection done.'
Ejemplo n.º 44
0
def testConnection():
    ''' a simple test to check working of streaming prices etc '''
    tws = ibConnection(clientId=1050)
    tws.registerAll(dummyHandler)

    tws.connect()
    
    c = mkContract('TSLA')
    tws.reqMktData(2,c,'',False)
    sleep(3)
    
    print 'testConnection done.'
Ejemplo n.º 45
0
def testConnection():
    ''' a simple test to check working of streaming prices etc '''
    tws = ibConnection(clientId=1050)
    tws.registerAll(dummyHandler)

    tws.connect()

    c = mkContract('TSLA')
    tws.reqMktData(2, c, '', False)
    sleep(3)

    print 'testConnection done.'
Ejemplo n.º 46
0
def populate_price():
		# open the
		con = ibConnection()
		con.registerAll(watchAll)
		con.unregister(watchAll, message.historicalData)
		con.register(printData, message.historicalData)
		con.connect()
		time.sleep(1)



		cursor.execute("select e.eh_sk, e.cik, s.symbol, e.form,  YEAR(e.insert_ts) as year, MONTH(e.insert_ts) as month, DAY(e.insert_ts) as day, HOUR(e.insert_ts) as hour, MINUTE(e.insert_ts) as minute, c.industry_id from extract_history e, company c, symbol s where e.cik = c.cik and e.status = 'S' and e.cik = s.cik and e.date_id > s.start_date_id and e.date_id <= s.end_date_id and e.date_id > 8767  and hour(e.insert_ts) < 15 and cast(e.insert_ts as time) > cast('08:30:00' as time)  and eh_sk = 1359157 group by cik, year, month, day, hour, minute order by e.insert_ts limit 20")
Ejemplo n.º 47
0
def newTest(options):
    # if we're still here, we should connect
    con = ibConnection(options.host, options.port, options.clientid)
    con.registerAll(reply_handler)
    con.register(save_order_id, 'NextValidId')
    con.register(save_tick, 'TickSize', 'TickPrice')
    con.connect()
    short_sleep()
    #test_002(con, options)
    test_007(con, options)
    #test_009(con, options)
    long_sleep()
def testConnection():
    """ a simple test to check working of streaming prices etc """
    tws = ibConnection()
    tws.registerAll(dummyHandler)	

    tws.connect()

    c = createContract('SPY')
    tws.reqMktData(1, c, '', False)
    sleep(3)

    print 'testConnection done.'
Ejemplo n.º 49
0
    def run(self):
        host = config.get("market", "ib.gateway").strip('"').strip("'")
        port = int(config.get("market", "ib.port"))
        appid = int(config.get("market", "ib.appid.portfolio"))

        self.con = ibConnection(host, port, appid)
        self.con.registerAll(self.on_ib_message)
        self.con.connect()
        while 1:
            self.con.reqAllOpenOrders()
            self.reqExecutions()
            sleep(2)
Ejemplo n.º 50
0
 def connect(self):
     self._con = ibConnection()
     self._con.registerAll(self.watcher)
     self._con.unregister(self.watcher, 'ContractDetails', 'ContractDetailsEnd', 'TickPrice', 'TickSize', 'TickString', 'TickOptionComputation', 'TickGeneric')
     self._con.register(self.contract_details_handler, 'ContractDetails')
     self._con.register(self.contract_details_end_handler, 'ContractDetailsEnd')
     self._con.register(self.tick_price_hander, 'TickPrice')
     self._con.register(self.tick_size_handler, 'TickSize')
     self._con.register(self.tick_string_handler, 'TickString')
     self._con.register(self.tick_option_computation_handler, 'TickOptionComputation')
     self._con.register(self.tick_generic_handler, 'TickGeneric')
     self._con.register(self.tick_snapshot_end_handler, 'TickSnapshotEnd')
     self._con.connect()
Ejemplo n.º 51
0
def connect():
    global con
    con = ibConnection(port=7496, clientId=1618)
    # 7496 for real account, 7497 for paper trader
    con.registerAll(allMessageHandler)
    con.register(accountDetailsHandler, 'UpdateAccountValue')
    con.register(positionsHandler, 'UpdatePortfolio')
    con.register(accountDetailsEnder, 'AccountDownloadEnd')
    con.register(marketDataHandler, message.tickPrice)
    con.register(contractDetailsHandler, 'ContractDetails')
    con.register(contractDetailsEnder, 'ContractDetailsEnd')
    con.register(historicalDataHandler, message.historicalData)
    con.connect()
Ejemplo n.º 52
0
    def create_tws_connection(self):
        """
        Connect to the Trader Workstation (TWS, IB API using the IbPy ibConnection
        object) using the standard port of 7496, with a clientId of 10.

        The clientId is chosen by the user and we will need separate IDs for
        both the execution connection and the market data connection, if the
        latter is also used elsewhere.
        """

        tws_conn = ibConnection()
        tws_conn.connect()
        return tws_conn
Ejemplo n.º 53
0
 def __init__(self, contract, date, t, duration, outfile):
   self.outfile = outfile
   self.contract = contract
   self.date = date
   self.t = t
   self.duration = str(duration) + ' S'
   self.tick_id = 1
   self.con = ibConnection()
   self.con.register(self.process_data, message.historicalData)
   self.con.connect()
   time.sleep(1)
   end_datetime = ('%s %s US/Eastern' % (self.date, self.t))
   self.con.reqHistoricalData(tickerId=self.tick_id, contract=self.contract, endDateTime=end_datetime, durationStr=self.duration, barSizeSetting='5 secs', whatToShow='TRADES', useRTH=0, formatDate=1)
   self.data_received = False
Ejemplo n.º 54
0
def logTicks(contracts,verbose=False):
    ''' 
    log ticks from IB to a csv file
    
    Parameters
    ----------
    contracts : ib.ext.Contract objects
    verbose : print out all tick events
    '''
    # check for correct input
    assert isinstance(contracts,(list,Contract)) ,'Wrong input, should be a Contract or list of contracts'
    
    #---create subscriptions  dictionary. Keys are subscription ids   
    subscriptions = {}
    try:
        for idx, c in enumerate(contracts):
            subscriptions[idx+1] = c
    except TypeError: # not iterable, one contract provided
        subscriptions[1] = contracts
    
    tws = ibConnection()
    logger = TickLogger(tws,subscriptions)
    
    if verbose: tws.registerAll(printMessage)
     
    tws.connect()

    #-------subscribe to data
    for subId, c in subscriptions.items():
        assert isinstance(c,Contract) , 'Need a Contract object to subscribe'
        tws.reqMktData(subId,c,"",False)

    #------start a loop that must be interrupted with Ctrl-C
    print('Press Ctr-C to stop loop')

    try:
        while True:
            time.sleep(2) # wait a little
            logger.flush() # commit data to file
            sys.stdout.write('.') # print a dot to the screen
                
                
    except KeyboardInterrupt:
        print('Interrupted with Ctrl-c')    
    
    logger.close()             
    tws.disconnect()
    print('All done')    
Ejemplo n.º 55
0
 def __init__(self, contract, date, barsize, outfile):
   self.outfile = outfile
   self.contract = contract
   self.date = date
   #self.t = t
   self.barsize = barsize
   #self.duration = str(duration) + ' S'
   self.tick_id = 1
   self.con = ibConnection(port=7496, clientId=996)
   self.con.register(self.process_data, message.historicalData)
   #self.con.register(self.error_handler, 'Error')
   self.con.connect()
   time.sleep(1)
   end_datetime = self.date
   self.con.reqHistoricalData(tickerId=self.tick_id, contract=self.contract, endDateTime=end_datetime, durationStr='1 D', barSizeSetting=barsize, whatToShow='TRADES', useRTH=0, formatDate=1)
   self.data_received = False
    def __init__(self,debug=False):
        self._log = logger.getLogger('DLD')        
        self._log.debug('Initializing data dwonloader. Pandas version={0}, ibpy version:{1}'.format(pandas.__version__,ib.version))

        self.tws = ibConnection()
        self._dataHandler = _HistDataHandler(self.tws)
        
        if debug:
            self.tws.registerAll(self._debugHandler)
            self.tws.unregister(self._debugHandler,message.HistoricalData)
            
        self._log.debug('Connecting to tws')
        self.tws.connect() 
        
        self._timeKeeper = TimeKeeper() # keep track of past requests
        self._reqId = 1 # current request id
Ejemplo n.º 57
0
    def __init__(self,debug=False):
        self._log = logging.getLogger('DLD')        
        self._log.debug('Initializing data dwonloader. Pandas version={0}, ibpy version:{1}'.format(pd.__version__,ib.__version__))

        self.tws = ibConnection()
        self._dataHandler = _HistDataHandler(self.tws)
        
        if debug:
            self.tws.enableLogging() # show debugging output from ibpy
           
            
        self._log.debug('Connecting to tws')
        self.tws.connect() 
        
        self._timeKeeper = TimeKeeper() # keep track of past requests
        self._reqId = 1 # current request id
Ejemplo n.º 58
0
def getPrevDayStat(sym, sec='STK', exch='SMART'):
	con = ibConnection(clientId=1050)
	con.registerAll(watchAll)
	con.unregister(watchAll, message.historicalData)
	con.register(dataWatcher, message.historicalData)
	con.unregister(watchAll, message.error)
	con.register(errHandler, message.error)

	con.connect()
	time.sleep(1)
	contractTuple = (sym, sec, exch, 'USD', '', 0.0, '')
	
	endSecs = time.time()-(5-time.daylight)*60*60  # to NY EST via gmtime
	NYtime = time.gmtime(endSecs)
	
	# combined dateStr+timeStr format is 'YYYYMMDD hh:mm:ss TMZ'
	dateStr = time.strftime('%Y%m%d', NYtime)
	timeStr = time.strftime(' %H:%M:%S EST', NYtime)
	dataWatcher.pricesWatched =[0,0,0,0]

	dataWatcher.finished = False # true when historical data is done
	con.reqHistoricalData(0,
					  contract(contractTuple),
					  dateStr+timeStr, # last requested bar date/time
					  '2 D',  # quote duration, units: S,D,W,M,Y
					  '1 day',  # bar length
					  'TRADES',  # what to show
					  0, 1 )
	countSecs = 0
	while not dataWatcher.finished and countSecs < 5: # wait up to 20 seconds
		time.sleep(1)
		countSecs += 1
	if dataWatcher.finished==False:
		con.reqHistoricalData(0,
						  contract(contractTuple),
						  dateStr+timeStr, # last requested bar date/time
						  '1 D',  # quote duration, units: S,D,W,M,Y
						  '1 day',  # bar length
						  'TRADES',  # what to show
						  0, 1 )
		countSecs = 0
		while not dataWatcher.finished and countSecs < 5: # wait up to 20 seconds
			time.sleep(1)
			countSecs += 1	
	con.disconnect()
	print dataWatcher.pricesWatched
	return dataWatcher.pricesWatched