def createTab(self, value): """ Create or display a tab from a value @param value string or model item @return None """ for handler in self.createHandlers: try: if handler(value): break except (Exception, ), exc: msg = 'Exception (debug): %r:%s (h:%s)' logging.debug(msg, exc, exc, handler, )
def importSession(self, session, filename, types): """ Initiates session import. @param session Session instance @param filename name of file with serialized messages @param types sequence of message types to import @return None """ importer = session.importMessages(str(filename), types) loader = importer() try: self.count = loader.next() self.last = self.count - 1 if not self.count: raise StopIteration() except (StopIteration, ): self.loader = self.count = self.last = None logging.debug('Warning messages not imported from "%s"', filename) else: self.importProgress.setMaximum(self.last) self.importer = importer self.loader = loader
class SessionStrategyBuilder(QObject, BasicHandler): default_paramsHistoricalData = { ## change to use datetime "endDateTime": strftime("%Y%m%d %H:%M:%S PST", (2007, 1, 1, 0, 0, 0, 0, 0, 0)), "durationStr": "6 D", "barSizeSetting": "1 min", "whatToShow": "TRADES", #"BID_ASK", # "TRADES" "useRTH": 1, # 0 for not "formatDate": 2, # 2 for seconds since 1970/1/1 } def __init__(self, parent=None): QObject.__init__(self, parent) self.tickerItems = [] self.isActive = self.loadMessage = False self.threads = [] self.tickers = [] self.reflectSignals(Signals.contract.created) app = instance() if app: connect = self.connect connect(app, Signals.strategy.fileUpdated, self.externalFileUpdated) connect(app, Signals.strategy.requestActivate, self.requestActivation) @classmethod def paramsHistoricalData(cls, **kwds): cls.default_paramsHistoricalData.update(kwds) return cls.default_paramsHistoricalData def makeAccountSeries(self, *k): s = Series() return s def makeContract(self, symbol, **kwds): contract = Contract() kwds['symbol'] = symbol attrs = [k for k in dir(contract) if k.startswith('m_')] for attr in attrs: kwd = attr[2:] if kwd in kwds: setattr(contract, attr, kwds[kwd]) ## set these even if they're already set contract.m_secType = kwds.get('secType', 'STK') contract.m_exchange = kwds.get('exchange', 'SMART') contract.m_currency = kwds.get('currency', 'USD') return contract def makeContracts(self): symids = self.symbols() for symbol, tickerId in symids.items(): yield tickerId, self.makeContract(symbol) def makeOrder(self, **kwds): order = Order() attrs = [k for k in dir(order) if k.startswith('m_')] for attr in attrs: kwd = attr[2:] if kwd in kwds: setattr(order, attr, kwds[kwd]) return order def makeTicker(self, tickerId): ticker = StrategyBuilderTicker() return ticker def makeTickerSeries(self, tickerId, field): s = Series() s.addIndex('ema-40', KAMA, s, 40) return s def symbols(self): syms = [(i.get('symbol'), i.get('tickerId')) for i in self.tickerItems] syms = [(k, v) for k, v in syms if k is not None and v is not None] return dict(syms) def load(self, source): if not hasattr(source, 'read'): source = open(source) try: instance = load(source) except (Exception, ), exc: raise Exception('Exception "%s" loading strategy.' % exc) for item in instance: methName = 'load_%s' % item.get('type', 'Unknown') call = getattr(self, methName, None) try: call(item) except (TypeError, ): logging.debug('Could not load strategy item: %s', item) for tickerId, contract in self.makeContracts(): self.emit(Signals.contract.created, tickerId, contract)
def on_session_Error(self, message): logging.debug(str(message))
class SessionReplay(QDialog, Ui_SessionReplayWidget): """ Dialog for controlling the replay of a session. After the dialog instance is constructed, clients should call the 'setSession' to associate the dialog with a session. Clients should use 'exec_()' to display the dialog, not 'show'. """ def __init__(self, interval=50, parent=None): """ Initializer. @param interval=50 milliseconds between message delivery @param parent=None ancestor of this dialog """ QDialog.__init__(self, parent) self.setupUi(self) self.interval = interval self.session = None self.filename = None self.types = None self.loader = None self.importer = None self.timer = QTimer() def exec_(self): """ Dialog main loop. @return QDialog.DialogCode result """ connect = self.connect setInterval = self.timer.setInterval connect(self.timerSlider, Signals.intValueChanged, setInterval) connect(self.timerSpin, Signals.intValueChanged, setInterval) connect(self.timer, Signals.timeout, self.on_timer_timeout) self.timer.start(self.interval) return QDialog.exec_(self) def on_restartButton_clicked(self): """ Signal handler for restart button clicked signals. """ if self.importer: self.timer.setInterval(self.timerSpin.value()) self.loader = self.importer() def on_timer_timeout(self): """ Signal handler for the delivery timer timeout signal. If the instance has a session but no loader, it will attempt to import the session object and initiate the replay. If a loader is present (possibly added by importSession), the the next message is requested from the loader. @return None """ if self.session and not self.loader: try: self.importSession(self.session, self.filename, self.types) except (Exception, ), ex: QMessageBox.critical( self, 'Import Exception', 'Exception "%s" during import. ' 'Import not completed.' % ex) self.close() if self.loader: try: msgid = self.loader.next() except (StopIteration, ): self.timer.setInterval(max(self.timer.interval(), 50)) else: self.importProgress.setValue(msgid) if msgid == self.last: logging.debug('Imported %s messages from file "%s".', self.count, self.filename)