class MyListener(MessageListener): upperBoundaries = {} lowerBoundaries = {} currentPriceRanges = {} candlesHourly = {} candlesMinutely = {} xmpp = [] aqsPrice = None xmppListener = None jid = '*****@*****.**' password = '******' targetjid = '*****@*****.**' def __init__(self): super(MessageListener, self).__init__() self.xmppListener = XMPPMessageListener(self) self.xmpp = XmppBot(self.jid, self.password, self.xmppListener) self.xmpp.process() if self.xmpp.connect(): self.logger.info("Done") else: self.logger.info("Unable to connect.") return def setAqsPrice(self, aqsPrice): self.aqsPrice = aqsPrice def serverTime(self, serverTime): return # called as soon as the socket got connected to the trading servers. def connected(self): # now that we are connected, let's send the login message. self.aqSocket.login(brokeraqUid, brokeraqPwd, "PRICE") def init(self, instrumentId): self.logger.info('Initializing ' + instrumentId) # let's fetch ten days of hourly history. endDate = date.today().strftime('%Y%m%d') startDate = (date.today() - timedelta(days=10)).strftime('%Y%m%d') self.candlesHourly[instrumentId] = onlinearchive.history( instrumentId, 'HOURS_1', startDate, endDate) length = len(self.candlesHourly[instrumentId]) lastClose = self.candlesHourly[instrumentId]['C'][length - 1] tradingRange = self.calculateTradingRange( self.candlesHourly[instrumentId][length - 10:length]) # let's store the current price range for later reuse. self.currentPriceRanges[instrumentId] = tradingRange self.upperBoundaries[instrumentId] = lastClose + tradingRange self.lowerBoundaries[instrumentId] = lastClose - tradingRange print 'Fetched ', len( self.candlesHourly[instrumentId]), ' candles from history archive.' return def loggedIn(self): self.logger.info("Breakout watcher ready!") self.xmpp.outgoingQueue.put( [self.targetjid, 'Breakout watcher ready!']) # let's subscribe to all instruments on the server (not many at the moment) i = 0 members = [ attr for attr in dir(Symbols()) if not callable(attr) and not attr.startswith("__") ] for s in members: i = i + 1 symbol = getattr(Symbols(), s) self.init(symbol) self.aqSocket.subscribe(symbol, TimeFrames.HOURS_1) self.aqSocket.subscribe(symbol, TimeFrames.MINUTES_1) def calculateTradingRange(self, candles): # length = len(candles) # oVector = candles['O'] hVector = candles['H'] lVector = candles['L'] # cVector = candles['C'] slotRanges = hVector - lVector meanRange = slotRanges.mean() return meanRange def ohlc(self, ohlc): self.logger.info('OHLC.') # mdiId stands for market data instrument ID. tf = ohlc.timeFrame # let's check the time frame in minutes ... if tf == 60: # ok, hourly candle received. tempDf = pd.DataFrame( { 'O': ohlc.open, 'H': ohlc.high, 'L': ohlc.low, 'C': ohlc.close, 'V': ohlc.volume }, index=[ohlc.timestamp]) tempDf.index = pd.to_datetime(tempDf.index) # let's append this new candle ... self.candlesHourly[ohlc.mdiId] = self.candlesHourly[ ohlc.mdiId].append(tempDf) # now, let's update the uper and lower threshold length = len(self.candlesHourly[ohlc.mdiId]) # let's calculate the average trading range over the last five hours tradingRange = self.calculateTradingRange( self.candlesHourly[ohlc.mdiId][length - 10:length]) # let's store the current price range for later reuse. self.currentPriceRanges[ohlc.mdiId] = tradingRange self.upperBoundaries[ohlc.mdiId] = ohlc.close + tradingRange self.lowerBoundaries[ohlc.mdiId] = ohlc.close - tradingRange if tf == 1: if self.currentPriceRanges[ohlc.mdiId] is not None: # ok, minute candle received. upperBoundary = self.upperBoundaries[ohlc.mdiId] lowerBoundary = self.lowerBoundaries[ohlc.mdiId] percDistUp = (upperBoundary / ohlc.close - 1.0) * 100.0 percDistDown = (lowerBoundary / ohlc.close - 1.0) * 100.0 print datetime.datetime.now( ), "\t", ohlc.mdiId, '\tClose:', ohlc.close, '\tUpper boundary:', upperBoundary, '(', percDistUp, ')\tLower boundary:', lowerBoundary, '(', percDistDown, ')' if ohlc.close > upperBoundary: self.logger.info("UPWARDS BREAKOUT %s" % ohlc.mdiId) # let's also pull up the breakout point self.upperBoundaries[ ohlc.mdiId] = ohlc.close + self.currentPriceRanges[ ohlc.mdiId] self.xmpp.outgoingQueue.put( [self.targetjid, ohlc.mdiId + ' UPWARDS BREAKOUT']) if ohlc.close < lowerBoundary: self.logger.info("DOWNWARDS BREAKOUT %s" % ohlc.mdiId) # let's pull it down ... self.lowerBoundaries[ ohlc.mdiId] = ohlc.close - self.currentPriceRanges[ ohlc.mdiId] self.xmpp.outgoingQueue.put( [self.targetjid, ohlc.mdiId + ' DOWNWARDS BREAKOUT']) return
class CrossOverMonitor(MessageListener): currentDirections = {} candles = {} xmpp = [] aqsPrice = None xmppListener = None jid = '@jabber.org' password = '' targetjid = '' def __init__(self): super(CrossOverMonitor, self).__init__() self.xmppListener = XMPPMessageListener(self) self.xmpp = XmppBot(self.jid, self.password, self.xmppListener) if self.xmpp.connect(): self.xmpp.process(block=False) print("Done") else: print("Unable to connect.") return def setAqsPrice(self, aqsPrice): self.aqsPrice = aqsPrice def serverTime(self, serverTime): return def connected(self): self.aqsPrice.login(brokeraqUid, brokeraqPwd, "PRICE") def init(self, instrumentId): # let's fetch ten days of hourly history. endDate = date.today().strftime('%Y%m%d') startDate = (date.today() - timedelta(days=10)).strftime('%Y%m%d') self.candles[instrumentId] = onlinearchive.history( instrumentId, 'HOURS_1', startDate, endDate) print 'Fetched ', len( self.candles[instrumentId]), ' candles from history archive.' return def loggedIn(self): print "Logged in!" self.xmpp.outgoingQueue.put([self.targetjid, 'Bot is up and running']) self.init(Symbols.EURUSD) self.aqsPrice.subscribe(Symbols.EURUSD, TimeFrames.HOURS_1) self.init(Symbols.OILUSD) self.aqsPrice.subscribe(Symbols.OILUSD, TimeFrames.HOURS_1) self.init(Symbols.EURCHF) self.aqsPrice.subscribe(Symbols.EURCHF, TimeFrames.HOURS_1) self.init(Symbols.USDCHF) self.aqsPrice.subscribe(Symbols.USDCHF, TimeFrames.HOURS_1) self.init(Symbols.XAGUSD) self.aqsPrice.subscribe(Symbols.XAGUSD, TimeFrames.HOURS_1) # checks if a series crossed. def crossing(self, series1, series2): if len(series1) == len(series2) and len(series1) > 1: length = len(series1) if series1[length - 2] > series2[length - 2] and series1[ length - 1] < series2[length - 1]: print 'SHORT' return -1 if series1[length - 2] < series2[length - 2] and series1[ length - 1] > series2[length - 1]: print 'LONG' return 1 return 0 def ohlc(self, ohlc): print 'ohlc received for ', ohlc.mdiId, ': ', ohlc.close tempDf = pd.DataFrame( { 'O': ohlc.open, 'H': ohlc.high, 'L': ohlc.low, 'C': ohlc.close, 'V': ohlc.volume }, index=[ohlc.timestamp]) tempDf.index = pd.to_datetime(tempDf.index) # let's append this new candle ... self.candles[ohlc.mdiId] = self.candles[ohlc.mdiId].append(tempDf) # now, let's calculate the ewma values. ewma20 = pd.ewma(self.candles[ohlc.mdiId]['C'], span=20) ewma50 = pd.ewma(self.candles[ohlc.mdiId]['C'], span=50) lastEma20Val = ewma20[len(ewma20) - 1] lastEma50Val = ewma50[len(ewma50) - 1] print "EMAs: ", lastEma20Val, " - ", lastEma50Val if lastEma20Val > lastEma50Val: self.currentDirections[ohlc.mdiId] = 'LONG' else: self.currentDirections[ohlc.mdiId] = 'SHORT' if self.crossing(ewma20, ewma50) > 0: # let's trigger some action ... self.xmpp.outgoingQueue.put([self.targetjid, 'LONG ' + ohlc.mdiId]) return if self.crossing(ewma20, ewma50) < 0: # let's trigger some action ... self.xmpp.outgoingQueue.put( [self.targetjid, 'SHORT ' + ohlc.mdiId]) return return
class MyListener(MessageListener): upperBoundaries = {} lowerBoundaries = {} currentPriceRanges = {} candlesHourly = {} candlesMinutely = {} xmpp = [] aqsPrice = None xmppListener = None jid = '*****@*****.**' password = '******' targetjid = '*****@*****.**' def __init__(self): super(MessageListener, self).__init__() self.xmppListener = XMPPMessageListener(self) self.xmpp = XmppBot(self.jid, self.password, self.xmppListener) self.xmpp.process() if self.xmpp.connect(): self.logger.info("Done") else: self.logger.info("Unable to connect.") return def setAqsPrice(self, aqsPrice): self.aqsPrice = aqsPrice def serverTime(self, serverTime): return # called as soon as the socket got connected to the trading servers. def connected(self): # now that we are connected, let's send the login message. self.aqSocket.login(brokeraqUid, brokeraqPwd, "PRICE") def init(self, instrumentId): self.logger.info('Initializing ' + instrumentId) # let's fetch ten days of hourly history. endDate = date.today().strftime('%Y%m%d') startDate = (date.today() - timedelta(days=10)).strftime('%Y%m%d') self.candlesHourly[instrumentId] = onlinearchive.history(instrumentId, 'HOURS_1', startDate, endDate) length = len(self.candlesHourly[instrumentId]) lastClose = self.candlesHourly[instrumentId]['C'][length - 1] tradingRange = self.calculateTradingRange(self.candlesHourly[instrumentId][length - 10:length]) # let's store the current price range for later reuse. self.currentPriceRanges[instrumentId] = tradingRange self.upperBoundaries[instrumentId] = lastClose + tradingRange self.lowerBoundaries[instrumentId] = lastClose - tradingRange print 'Fetched ', len(self.candlesHourly[instrumentId]), ' candles from history archive.' return def loggedIn(self): self.logger.info("Breakout watcher ready!") self.xmpp.outgoingQueue.put([self.targetjid, 'Breakout watcher ready!']) # let's subscribe to all instruments on the server (not many at the moment) i = 0 members = [attr for attr in dir(Symbols()) if not callable(attr) and not attr.startswith("__")] for s in members: i = i + 1 symbol = getattr(Symbols(), s) self.init(symbol) self.aqSocket.subscribe(symbol, TimeFrames.HOURS_1) self.aqSocket.subscribe(symbol, TimeFrames.MINUTES_1) def calculateTradingRange(self, candles): # length = len(candles) # oVector = candles['O'] hVector = candles['H'] lVector = candles['L'] # cVector = candles['C'] slotRanges = hVector - lVector meanRange = slotRanges.mean() return meanRange def ohlc(self, ohlc): self.logger.info('OHLC.') # mdiId stands for market data instrument ID. tf = ohlc.timeFrame # let's check the time frame in minutes ... if tf == 60: # ok, hourly candle received. tempDf = pd.DataFrame({'O': ohlc.open, 'H':ohlc.high, 'L':ohlc.low, 'C':ohlc.close, 'V':ohlc.volume}, index=[ohlc.timestamp]) tempDf.index = pd.to_datetime(tempDf.index) # let's append this new candle ... self.candlesHourly[ohlc.mdiId] = self.candlesHourly[ohlc.mdiId].append(tempDf) # now, let's update the uper and lower threshold length = len(self.candlesHourly[ohlc.mdiId]) # let's calculate the average trading range over the last five hours tradingRange = self.calculateTradingRange(self.candlesHourly[ohlc.mdiId][length - 10:length]) # let's store the current price range for later reuse. self.currentPriceRanges[ohlc.mdiId] = tradingRange self.upperBoundaries[ohlc.mdiId] = ohlc.close + tradingRange self.lowerBoundaries[ohlc.mdiId] = ohlc.close - tradingRange if tf == 1: if self.currentPriceRanges[ohlc.mdiId] is not None: # ok, minute candle received. upperBoundary = self.upperBoundaries[ohlc.mdiId] lowerBoundary = self.lowerBoundaries[ohlc.mdiId] percDistUp = (upperBoundary / ohlc.close - 1.0) * 100.0 percDistDown = (lowerBoundary / ohlc.close - 1.0) * 100.0 print datetime.datetime.now(), "\t", ohlc.mdiId, '\tClose:', ohlc.close, '\tUpper boundary:', upperBoundary, '(', percDistUp, ')\tLower boundary:', lowerBoundary, '(', percDistDown, ')' if ohlc.close > upperBoundary: self.logger.info("UPWARDS BREAKOUT %s" % ohlc.mdiId) # let's also pull up the breakout point self.upperBoundaries[ohlc.mdiId] = ohlc.close + self.currentPriceRanges[ohlc.mdiId] self.xmpp.outgoingQueue.put([self.targetjid, ohlc.mdiId + ' UPWARDS BREAKOUT']) if ohlc.close < lowerBoundary: self.logger.info("DOWNWARDS BREAKOUT %s" % ohlc.mdiId) # let's pull it down ... self.lowerBoundaries[ohlc.mdiId] = ohlc.close - self.currentPriceRanges[ohlc.mdiId] self.xmpp.outgoingQueue.put([self.targetjid, ohlc.mdiId + ' DOWNWARDS BREAKOUT']) return
class CrossOverMonitor(MessageListener): currentDirections = {} candles = {} xmpp = [] aqsPrice = None xmppListener = None jid = '@jabber.org' password = '' targetjid = '' def __init__(self): super(CrossOverMonitor, self).__init__() self.xmppListener = XMPPMessageListener(self) self.xmpp = XmppBot(self.jid, self.password, self.xmppListener) if self.xmpp.connect(): self.xmpp.process(block=False) print("Done") else: print("Unable to connect.") return def setAqsPrice(self, aqsPrice): self.aqsPrice = aqsPrice def serverTime(self, serverTime): return def connected(self): self.aqsPrice.login(brokeraqUid, brokeraqPwd, "PRICE") def init(self, instrumentId): # let's fetch ten days of hourly history. endDate = date.today().strftime('%Y%m%d') startDate = (date.today() - timedelta(days=10)).strftime('%Y%m%d') self.candles[instrumentId] = onlinearchive.history(instrumentId, 'HOURS_1', startDate, endDate) print 'Fetched ', len(self.candles[instrumentId]), ' candles from history archive.' return def loggedIn(self): print "Logged in!" self.xmpp.outgoingQueue.put([self.targetjid, 'Bot is up and running']) self.init(Symbols.EURUSD) self.aqsPrice.subscribe(Symbols.EURUSD, TimeFrames.HOURS_1) self.init(Symbols.OILUSD) self.aqsPrice.subscribe(Symbols.OILUSD, TimeFrames.HOURS_1) self.init(Symbols.EURCHF) self.aqsPrice.subscribe(Symbols.EURCHF, TimeFrames.HOURS_1) self.init(Symbols.USDCHF) self.aqsPrice.subscribe(Symbols.USDCHF, TimeFrames.HOURS_1) self.init(Symbols.XAGUSD) self.aqsPrice.subscribe(Symbols.XAGUSD, TimeFrames.HOURS_1) # checks if a series crossed. def crossing(self, series1, series2): if len(series1) == len(series2) and len(series1) > 1: length = len(series1) if series1[length - 2] > series2[length - 2] and series1[length - 1] < series2[length - 1]: print 'SHORT' return -1 if series1[length - 2] < series2[length - 2] and series1[length - 1] > series2[length - 1]: print 'LONG' return 1 return 0 def ohlc(self, ohlc): print 'ohlc received for ', ohlc.mdiId, ': ', ohlc.close tempDf = pd.DataFrame({'O': ohlc.open, 'H':ohlc.high, 'L':ohlc.low, 'C':ohlc.close, 'V':ohlc.volume}, index=[ohlc.timestamp]) tempDf.index = pd.to_datetime(tempDf.index) # let's append this new candle ... self.candles[ohlc.mdiId] = self.candles[ohlc.mdiId].append(tempDf) # now, let's calculate the ewma values. ewma20 = pd.ewma(self.candles[ohlc.mdiId]['C'], span=20) ewma50 = pd.ewma(self.candles[ohlc.mdiId]['C'], span=50) lastEma20Val = ewma20[len(ewma20) - 1] lastEma50Val = ewma50[len(ewma50) - 1] print "EMAs: ", lastEma20Val, " - ", lastEma50Val if lastEma20Val > lastEma50Val: self.currentDirections[ohlc.mdiId] = 'LONG' else: self.currentDirections[ohlc.mdiId] = 'SHORT' if self.crossing(ewma20, ewma50) > 0: # let's trigger some action ... self.xmpp.outgoingQueue.put([self.targetjid, 'LONG ' + ohlc.mdiId]) return if self.crossing(ewma20, ewma50) < 0: # let's trigger some action ... self.xmpp.outgoingQueue.put([self.targetjid, 'SHORT ' + ohlc.mdiId]) return return