예제 #1
0
 def tickPrice(self, tickerId, field, price, canAutoExecute):
     msg = EWrapperMsgGenerator.tickPrice(tickerId, field, price, 
                                          canAutoExecute)
     dt = datetime.now().isoformat()
     try:
         key, index = self.tickerId_to_symbolKey[tickerId]
         bid_histogram = self.bid_histograms[key]
         ask_histogram = self.ask_histograms[key]
         last_histogram = self.last_histograms[key]
         symExp = '_'.join(key)
         if field == 1:
             bid_histogram.datafile = '%s/BID_%s.dat' % (symExp, dt)
             bid_histogram.update_price(price, index)
             print bid_histogram.plot_histogram(fname='%s/BID_%s.jpg'\
                                               % (symExp, dt), timestamp=dt)
         elif field == 2:
             ask_histogram.datafile = '%s/ASK_%s.dat' % (symExp, dt)
             ask_histogram.update_price(price, index)
             print ask_histogram.plot_histogram(fname='%s/ASK_%s.jpg'\
                                               % (symExp, dt), timestamp=dt)
         elif field == 4:
             last_histogram.datafile = '%s/LAST_%s.dat' % (symExp, dt)
             last_histogram.update_price(price, index)
             print last_histogram.plot_histogram(fname='%s/LAST_%s.jpg'\
                                               % (symExp, dt), timestamp=dt)
     except KeyError:
         pass
     self.datahandler(tickerId, msg)
예제 #2
0
파일: client.py 프로젝트: gazzman/ib
 def updatePortfolio(self, contract, position, marketPrice, marketValue, 
                     averageCost, unrealizedPNL, realizedPNL, accountName):
     msg = EWrapperMsgGenerator.updatePortfolio(contract, position, 
                                                marketPrice, marketValue, 
                                                averageCost, unrealizedPNL, 
                                                realizedPNL, accountName)
     self.msghandler('updatePort: ' + msg)
예제 #3
0
    def data_handler(self, reqId, date, open_, high, low, close, volume, count, 
                     WAP, hasGaps=False):
        showbase = self.req_map[reqId]
        try:
            base = '%s_%s' % showbase
        except TypeError:
            base = showbase

        if self.port is None:
            msg = EWrapperMsgGenerator.historicalData(reqId, date, open_, high, 
                                                      low, close, volume, 
                                                      count, WAP, hasGaps)
            print self.mdata['underlying'], base, msg
        else:
            bar = [('open', open_), ('high', high), ('low', low), 
                   ('close', close), ('hasgaps', hasGaps)]
            if 'trade' in base:
                bar += [('volume', volume), ('count', count), ('wap', WAP)]
            data = self.mdatastring + ['timestamp=%s' % date]
            data += ['%s_%s=%s' % (base, name, data) for name, data in bar]

            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((self.host, self.port))
            sock.sendall('%s,%s\n' % (self.dbinfo, ','.join(data)))
            sock.close()
예제 #4
0
파일: client.py 프로젝트: gazzman/ib
 def error(self, *args):
     ''' We either get an (int, int, str), (Exception, ), or (str, )
     '''
     errmsg = EWrapperMsgGenerator.error(*args)
     errmsg = ' '.join(errmsg.split('\n'))
     if len(args) == 3:
         (req_id, err_code, err_msg) = args
         if err_code == 200:
             self.failed_contracts[req_id] = (err_code, err_msg)
         elif req_id >= 0: self.req_errs[req_id] = (err_code, err_msg)
         if err_code == 162: self.logger.warn(errmsg) # historical data
         elif err_code == 200: self.logger.warn(errmsg) # no contract
         elif err_code == 202: self.logger.info(errmsg) # cancel order
         elif err_code == 399: self.logger.warn(errmsg) # after-hours
         elif err_code == 502:
             self.logger.warn(errmsg) # no connection
             raise Exception('%s | %s | %s' % (req_id, err_code, err_msg))
         elif err_code < 1100: self.logger.error(errmsg)
         elif err_code < 2100: self.logger.critical(errmsg)
         else: self.logger.warn(errmsg)
     elif type(args[0]) is (Exception or java.io.EOFException):
         self.logger.error(args[0])
         raise args[0]
     elif type(args[0]) is str: self.logger.error(errmsg)
     else:
         m = 'Unexpected result from AnyWrapperMsgGenerator: %s, %s'
         self.logger.error(m, str(args[0]), str(type(args[0])))
예제 #5
0
파일: client.py 프로젝트: gazzman/ib
 def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, 
             impliedFuture, holdDays, futureExpiry, dividendImpact, 
             dividendsToExpiry):
     msg = EWrapperMsgGenerator.tickEFP(tickerId, tickType, basisPoints, 
                                        formattedBasisPoints, impliedFuture, 
                                        holdDays, futureExpiry, 
                                        dividendImpact, dividendsToExpiry) 
     self.datahandler(tickerId, msg)
예제 #6
0
파일: client.py 프로젝트: gazzman/ib
 def tickOptionComputation(self, tickerId, field, impliedVol, delta, 
                           optPrice, pvDividend, gamma, vega, theta, 
                           undPrice):
     msg = EWrapperMsgGenerator.tickOptionComputation(tickerId, field, 
                                                      impliedVol, delta, 
                                                      optPrice, pvDividend, 
                                                      gamma, vega, theta, 
                                                      undPrice)
     self.datahandler(tickerId, msg)
예제 #7
0
파일: client.py 프로젝트: gazzman/ib
 def execDetails(self, reqId, contract, execution):
     msg = EWrapperMsgGenerator.execDetails(reqId, contract, execution)
     self.executions[execution.m_execId] = (reqId, contract, execution)
     if execution.m_orderId == sys.maxint: oid = 0
     else: oid = execution.m_orderId
     msg = 'Client %2i executed oid %4i: %s %3i %5s %s at price %7.3f,'
     msg += ' avgprice %7.3f'
     msg_data = (execution.m_clientId, oid, execution.m_side,
                 execution.m_cumQty, contract.m_symbol, contract.m_secType,
                 execution.m_price, execution.m_avgPrice)
     self.msghandler(msg % msg_data, req_id=reqId)
예제 #8
0
    def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, 
                    count):
        for reversal in self.req_to_rev[reqId]:
            rev_id, pos = reversal
            self.rev_to_data[rev_id][pos] = (close, time)
            data = self.rev_to_data[rev_id]
            self.logger.debug('Processing %s: %s', str(reversal), str(data))
            times = [x[1] for x in data]
            if times[0] == times[1] == times[2]: 
                prices = [x[0] for x in data]
                self.evaluate_and_enter_reversal(rev_id, prices)

        msg = EWrapperMsgGenerator.realtimeBar(reqId, time, open_, high, low, 
                                               close, volume, wap, count)
        fnm = '%i_%s.csv' % (self.realtime_bars[reqId]['contract'].m_conId,
                             self.realtime_bars[reqId]['show'])
        self.datahandler(fnm, reqId, msg)
예제 #9
0
 def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, 
                 count):
     msg = EWrapperMsgGenerator.realtimeBar(reqId, time, open_, high, low, 
                                            close, volume, wap, count)
     timestamp = timemod.strftime('%Y%m%d %H:%M:%S', 
                                  timemod.localtime(time))
     if not args.port:
         print >> sys.stderr, msg
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.connect((args.host, args.port))
         sock.sendall('%s,%s,%s,0 %s\n' % (args.database, 
                                           args.schema, 
                                           fnames[reqId], 
                                           msg.replace(str(time), 
                                                       timestamp)))
         sock.close()
예제 #10
0
 def tickPrice(self, tickerId, field, price, canAutoExecute):
     msg = EWrapperMsgGenerator.tickPrice(tickerId, field, price, 
                                          canAutoExecute)
     dt = datetime.now().isoformat()
     try:
         symExp, right, index = self.tickerId_to_symbolKey[tickerId]
         butterfly_prices = self.butterfly_prices[symExp]
         symExp = '_'.join(symExp)
         if field in [1, 2]:
             butterfly_prices.ocallfile = '%s/buttercalls_%s.dat' % (symExp, dt)
             butterfly_prices.oputfile = '%s/butterputs_%s.dat' % (symExp, dt)
             butterfly_prices.ufile = '%s/underlying_%s.dat' % (symExp, dt)
             butterfly_prices.update_price(price, right, index, field)
             print butterfly_prices.plot_prices(fname='%s/%s.jpg'\
                                               % (symExp, dt), timestamp=dt)
     except KeyError:
         pass
     self.datahandler(tickerId, msg)
예제 #11
0
    def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, 
                    count):
        msg = EWrapperMsgGenerator.realtimeBar(reqId, time, open_, high, low, 
                                               close, volume, wap, count)
        timestamp = timemod.strftime('%Y%m%d %H:%M:%S', 
                                     timemod.localtime(time))

        strike, right, show = self.show_req[reqId]        
        self.bars[(strike, right, show)] = (timestamp, open_, high, low, close, 
                                            volume, wap, count)

        if strike == -1 and show == 'TRADES':
            self.gen_strikes(close, self.interval)

        self.l = [self.bars[x][0] for x in self.show_req.values()]
        if self.l.count(timestamp) + self.l.count(None) == len(self.l):
            try:
                flies = self.compute_fly_prices()

                try:                
                    spot = self.bars[(-1, None, 'TRADES')]\
                           + (self.bars[(-1, None, 'BID')][4], 
                              self.bars[(-1, None, 'ASK')][4])
                except IndexError:
                    spot = self.bars[(-1, None, 'TRADES')] + (None, None)
                row = ['underlying=%s' % c.symbol, 'interval=%f' % c.interval]
                for field, data in zip(self.FIELDS, spot + flies):
                    row += ['%s=%s' % (field, str(data))]
                if not c.port:
                    for datapoint in row:
                        print datapoint
                else:
                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect((c.host, c.port))
                    sock.sendall('%s,%s,%s,%s\n' % (c.database, 
                                                    c.schema, 
                                                    c.tablename, 
                                                    ','.join(row)))
                    sock.close()
            except KeyError, err:
                self.logger.warn('Realtime bars (%f, %s, %s) not started yet', 
                                 *err.args[0])
                pass
예제 #12
0
파일: client.py 프로젝트: gazzman/ib
 def deltaNeutralValidation(self, reqId, underComp):
     msg = EWrapperMsgGenerator.deltaNeutralValidation(reqId, underComp)
     self.msghandler('deltaNeutralValid: ' + msg, req_id=reqId)
예제 #13
0
파일: client.py 프로젝트: gazzman/ib
 def tickSnapshotEnd(self, tickerId):
     msg = EWrapperMsgGenerator.tickSnapshotEnd(tickerId)
     self.fulfilled_tick_snapshots[tickerId] = datetime.now()
     del self.mkt_data[tickerId]
     self.msghandler(msg)
예제 #14
0
파일: client.py 프로젝트: gazzman/ib
 def tickString(self, tickerId, tickType, value):
     msg = EWrapperMsgGenerator.tickString(tickerId, tickType, value)
     self.datahandler(tickerId, msg)
예제 #15
0
파일: client.py 프로젝트: gazzman/ib
 def bondContractDetails(self, reqId, contractDetails):
     msg = EWrapperMsgGenerator.bondContractDetails(reqId, contractDetails)
     self.msghandler('bondConDet: ' + msg, req_id=reqId)
예제 #16
0
파일: client.py 프로젝트: gazzman/ib
 def tickSize(self, tickerId, field, size):
     msg = EWrapperMsgGenerator.tickSize(tickerId, field, size)
     self.datahandler(tickerId, msg)
예제 #17
0
파일: client.py 프로젝트: gazzman/ib
 def contractDetailsEnd(self, reqId):
     msg = EWrapperMsgGenerator.contractDetailsEnd(reqId)
     self.fulfilled_contracts[reqId] = datetime.now()
     self.msghandler(msg)
예제 #18
0
파일: client.py 프로젝트: gazzman/ib
 def scannerDataEnd(self, reqId):
     msg = EWrapperMsgGenerator.scannerDataEnd(reqId)
     self.msghandler('scannerDataEnd: ' + msg, req_id=reqId)
예제 #19
0
파일: client.py 프로젝트: gazzman/ib
 def updateNewsBulletin(self, msgId, msgType, message, origExchange):
     msg = EWrapperMsgGenerator.updateNewsBulletin(msgId, msgType, message, 
                                                   origExchange)
     self.msghandler('updateNewsBull: ' + msg)
예제 #20
0
파일: client.py 프로젝트: gazzman/ib
 def scannerParameters(self, xml):
     msg = EWrapperMsgGenerator.scannerParameters(xml)
     self.msghandler('scannerParams: ' + msg)
예제 #21
0
파일: client.py 프로젝트: gazzman/ib
 def scannerData(self, reqId, rank, contractDetails, distance, benchmark, 
                 projection, legsStr):
     msg = EWrapperMsgGenerator.scannerData(reqId, rank, contractDetails, 
                                            distance, benchmark, 
                                            projection, legsStr)
     self.msghandler('scannerData: ' + msg, req_id=reqId)
예제 #22
0
파일: client.py 프로젝트: gazzman/ib
 def execDetailsEnd(self, reqId):
     msg = EWrapperMsgGenerator.execDetailsEnd(reqId)
     self.fulfilled_execution_req[reqId] = datetime.now()
     self.msghandler(msg, req_id=reqId)
예제 #23
0
파일: client.py 프로젝트: gazzman/ib
 def currentTime(self, time):
     msg = EWrapperMsgGenerator.currentTime(time)
     self.msghandler(msg)
예제 #24
0
파일: client.py 프로젝트: gazzman/ib
 def historicalData(self, reqId, date, open_, high, low, close, volume, 
                    count, WAP, hasGaps):
     msg = EWrapperMsgGenerator.historicalData(reqId, date, open_, high, 
                                               low, close, volume, count, 
                                               WAP, hasGaps)
     self.datahandler(reqId, msg, date)
예제 #25
0
파일: client.py 프로젝트: gazzman/ib
 def marketDataType(self, reqId, marketDataType):
     msg = EWrapperMsgGenerator.marketDataType(reqId, marketDataType)
     self.msghandler('marketDataType: ' + msg, req_id=reqId)
예제 #26
0
파일: client.py 프로젝트: gazzman/ib
 def tickPrice(self, tickerId, field, price, canAutoExecute):
     msg = EWrapperMsgGenerator.tickPrice(tickerId, field, price, 
                                          canAutoExecute)
     self.datahandler(tickerId, msg)
예제 #27
0
파일: client.py 프로젝트: gazzman/ib
 def realtimeBar(self, reqId, time, open_, high, low, close, volume, wap, 
                 count):
     msg = EWrapperMsgGenerator.realtimeBar(reqId, time, open_, high, low, 
                                            close, volume, wap, count)
     self.datahandler(reqId, msg)
예제 #28
0
파일: client.py 프로젝트: gazzman/ib
 def updateMktDepthL2(self, tickerId, position, marketMaker, operation, 
                      side, price, size):
     msg = EWrapperMsgGenerator.updateMktDepthL2(tickerId, position, 
                                                 marketMaker, operation, 
                                                 side, price, size)
     self.msghandler('updateMktDepthL2: ' + msg)
예제 #29
0
파일: client.py 프로젝트: gazzman/ib
 def nextValidId(self, orderId):
     self.nextId = orderId
     msg = EWrapperMsgGenerator.nextValidId(orderId)
     self.logger.info('nextValidID: ' + msg)
예제 #30
0
파일: client.py 프로젝트: gazzman/ib
 def fundamentalData(self, reqId, data):
     msg = EWrapperMsgGenerator.fundamentalData(reqId, data)
     self.datahandler(reqId, msg)