def rx_subscribe(node, data_class=String, parse=unpickle, buffer_size=1): source = ReplaySubject(buffer_size) rospy.Subscriber( node, data_class, lambda msg: source.on_next(parse(msg) if parse is not None else msg), queue_size=buffer_size) return source.as_observable()
def ib_bars_import(hint_date, hint_sym, bar_size="1 min", verbose=False): if bar_size == 5: bar_size=='5 mins' """ Hint_date => YYYYMMD format """ # Generate Event to wait for e = threading.Event() # Generate Observable for results retObservable = ReplaySubject() # Connect To IB global CONN, TICKER_ID conn = CONN # Register input processing function def processInput(x): tz = tzlocal.get_localzone() if isinstance(x, conn.messageTypes['historicalData']): if x.date.startswith("finished"): retObservable.on_completed() else: nextValue = dict([(k, getattr(x, k)) for k in x.keys() if k != "reqId"]) nextValue['date'] = tz.localize(datetime.strptime(nextValue['date'], '%Y%m%d %H:%M:%S')) nextValue['date'] = nextValue['date'].astimezone(pytz.utc).replace(tzinfo=None) retObservable.on_next(nextValue) elif isinstance(x, conn.messageTypes['error']): if "data farm connection is OK" in x.errorMsg: return print (x, file=sys.stderr) if x.errorCode != None: retObservable.on_error(Exception(x.errorMsg)); elif verbose: print (x) # Register it and connect conn.registerAll(processInput) # Request data from server endtime = "%s 17:20:00" % hint_date conn.reqHistoricalData( tickerId=TICKER_ID, contract=make_contract(hint_sym), endDateTime=endtime, durationStr='1800 S', barSizeSetting=bar_size, whatToShow='TRADES', useRTH=1, formatDate=1) TICKER_ID += 1 def on_complete(err=None): e.set() # Register on observable to hear "Complete" event. retObservable.subscribe(None, on_complete, on_complete) # Wait until data completed e.wait() return retObservable.as_observable()