def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1491048000 self.endTime = 1491591200 self.data = [] if (exchange == "poloniex"): self.conn = poloniex('key goes here','Secret goes here') if backtest: poloData = self.conn.api_query("returnChartData",{"currencyPair":self.pair,"start":self.startTime,"end":self.endTime,"period":self.period}) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append(BotCandlestick(self.period,datum['open'],datum['close'],datum['high'],datum['low'],datum['weightedAverage'])) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName="+self.pair+"&tickInterval="+self.period+"&_="+str(self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"] if (exchange == "binance"): if backtest: APIkey = 'gcMugP0qdU5JBPoueFXgIY6I4gSEsDVwIb89ZC0oJzmDSgPVUW1gBlDiZmy9zHOl' Secretkey = 'F05pow8F5pxMyIBDEcj6Q3uWNf6CPLfJRDr3bCDrvnYpn7sYElayH3iGY0RiKyox' client = Client(APIkey, Secretkey) binandata = client.get_historical_klines(symbol=self.pair, interval=self.period, start_str="1 Jul, 2019", end_str="2 Jul, 2019") for datas in binandata: if len(datas) != 0: weightAve = (float(datas[4])+float(datas[2])+float(datas[3])/ float(3)) self.data.append(BotCandlestick(self.period,datas[1],datas[4],datas[2],datas[3], weightAve))
def main(argv): chart = BotChart( "poloniex", "BTC_GRC", 60, False) # the period is for back testing, so actually obsolete strategy = BotStrategy() # strategy_FLDC = BotStrategy_FLDC() candlesticks = [] developingCandlestick = BotCandlestick(period=60) while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if developingCandlestick.isClosed(): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) # strategy_FLDC.tick() developingCandlestick = BotCandlestick(period=60) # strategy.evaluatePositions_raw_gap() time.sleep(int(30))
def main(argv): #Trades using the btc to xmr currency chart = BotChart("poloniex","BTC_XMR",300,False) #Function from bot strategy, which is a class containeing various datas #such as opening price for the tick, closing price for the tick. strategy = BotStrategy() #Empty array holding the candlestick data candlesticks = [] developingCandlestick = BotCandlestick() #Loop that continues indefinately while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) #Sleep function so that we dont overload the server with requests. Which #can result in the account or our ip getting banned. developingCandlestick.tick(chart.getCurrentPrice()) #check if it is closing price, if it is the append to the array if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))
def main(argv): pair = "USDT_ETH" debut = '2017-08-01 14:00:00' fin = '2018-08-01 20:53:20' period = 14400 chart = BotChart("poloniex", pair, period, backtest=False) strategy = stratRsi2() candlesticks = [] developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))
def main(argv): startTime = False endTime = False try: opts, args = getopt.getopt(argv, "hp:c:n:s:e:", ["period=", "currency=", "points="]) except getopt.GetoptError: print 'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>' sys.exit() elif opt in ("-p", "--period"): if (int(arg) in [300, 900, 1800, 7200, 14400, 86400]): period = arg else: print 'Poloniex requires periods in 300,900,1800,7200,14400, or 86400 second increments' sys.exit(2) elif opt in ("-c", "--currency"): pair = arg elif opt in ("-n", "--points"): lengthOfMA = int(arg) elif opt in ("-s"): startTime = arg elif opt in ("-e"): endTime = arg if (startTime): chart = BotChart("poloniex", "BTC_PIVX", 300) strategy = BotStrategy() for candlestick in chart.getPoints(): strategy.tick(candlestick) else: chart = BotChart("poloniex", "BTC_PIVX", 300, False) strategy = BotStrategy() candlesticks = [] developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))
def returnChartData(self, pair, period, start, end): data = [] if self.exchange == 'poloniex': if (period not in [300, 900, 1800, 7200, 14400, 86400]): self.output.fail( 'Poloniex requires periods in seconds: 300,900,1800,7200,14400, or 86400' ) sys.exit(2) poloData = self.api.returnChartData(pair, period=int(period), start=int(start), end=int(end)) #TODO: check for error for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low'] and datum['date'] and datum['volume'] and datum['weightedAverage']): data.append( BotCandlestick(period, float(datum['open']), float(datum['close']), float(datum['high']), float(datum['low']), float(datum['weightedAverage']), float(datum['volume']), float(datum['date']))) elif self.exchange == 'kraken': if (period not in [1, 5, 15, 30, 60, 240, 1440, 10080, 21600]): self.output.fail( 'Kraken requires periods in minutes: 1, 5, 15, 30, 60, 240, 1440, 10080, 21600' ) sys.exit(2) krakenData = self.api.query_public('OHLC', data={ 'pair': pair, 'since': start, 'interval': period }) # check for error if len(krakenData['error']) > 0: for e in krakenData['error']: self.output.fail(e) sys.exit() for datum in krakenData['result'][pair]: data.append( BotCandlestick(period, float(datum[1]), float(datum[4]), float(datum[2]), float(datum[3]), float(datum[5]), float(datum[0]))) else: self.output.fail("Not a valid exchange") sys.exit(2) return data
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1491048000 self.endTime = 1491591200 self.data = [] if (exchange == "poloniex"): self.conn = poloniex('key goes here','Secret goes here') if backtest: poloData = self.conn.api_query("returnChartData",{"currencyPair":self.pair,"start":self.startTime,"end":self.endTime,"period":self.period}) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append(BotCandlestick(self.period,datum['open'],datum['close'],datum['high'],datum['low'],datum['weightedAverage'])) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName="+self.pair+"&tickInterval="+self.period+"&_="+str(self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def __init__(self, pair, period, endTime, startTime, backtest=True): self.pair = pair self.period = period self.endTime = endTime self.startTime = startTime self.data = [] self.conn = poloniex('key goes here', 'Secret goes here') if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime - 12 * 900, "end": self.endTime, "period": self.period }) for datum in poloData: if datum['open'] and datum['close'] and datum[ 'high'] and datum['low'] and datum['date']: self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'], datum['date']))
def __init__(self, exchange, pair, period, backtest=True ): # TODO: pass in start and end timestamps for backtesting self.output = BotLog() self.exchange = exchange self.pair = pair self.period = period self.startTime = time.time( ) - SECONDS_IN_DAY * 2 # TODO: use passed in start and end timestamps self.endTime = time.time( ) # Backtest up to now TODO: move this to __init__ param so it can be changed self.data = [] if self.exchange == "kraken" and backtest: logger.info("Fetching historical OHLC data for back testing...") kraken_data = OHLC(pair='XXBTZUSD', since=self.startTime, interval=self.period) historical_kraken_data = kraken_data['result'][self.pair] for datum in historical_kraken_data: if datum[1] and datum[4] and datum[2] and datum[3] and datum[5]: # list entries: (0: <timestamp>, 1: <open>, 2: <high>, 3: <low>, 4: <close>, 5: <vwap>, 6: <volume>, 7: <count>) self.data.append( BotCandlestick(self.period, datum[1], datum[4], datum[2], datum[3], datum[5]))
def heikinashi(self, currentCandle, previousCandle=False): if not previousCandle: o = (currentCandle.open+currentCandle.close)/2 else: o = (previousCandle.open+previousCandle.close)/2 c = (currentCandle.open+currentCandle.high+currentCandle.low+currentCandle.close)/4 h = max((o, c, currentCandle.high)) l = min((o, c, currentCandle.low)) return BotCandlestick(currentCandle.date,o,h,l,c,0)
def main(argv): chart = LiveBotChart() strategy = BotStrategy(50) strategy.candlesticks = chart.preliminaryCandlesticks() developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(1) developingCandlestick.tick(chart.getCurrentPrice()) if developingCandlestick.isClosed(): strategy.candlesticks.append(developingCandlestick) strategy.evaluatePositions() developingCandlestick = BotCandlestick() time.sleep(1)
def main(argv): pairs = ["USDT_BTC"] #, "USDT_ETH", "USDT_LTC"] exchanges = ["poloniex"] charts = [] strategies = [] #modes = ["DROP", "RSI", "BBAND", "MACD", ALL"] modes = ["MACD"] period = 300 for pair in pairs: for exchange in exchanges: charts.append(BotChart(exchange, pair, period)) for mode in modes: strategies.append( BotStrategy(exchange + '-' + pair, mode, 20, 10000, 0, 1000, 0.01, 0.15, False)) candlesticks = [] developingCandlestick = BotCandlestick(period) for i, chart in enumerate(charts): for j, mode in enumerate(modes): while True: strategy = strategies[len(modes) * i + j] try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib.error.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick(period) strategy.showProfit() strategy.showPositions() strategy.drawGraph() time.sleep(int(30))
def main(argv): chart = BotChart("poloniex","BTC_LTC",300,False) strategy = BotStrategy() candlesticks = [] developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))
def __init__(self, exchange, pair, period, backtest, output, startTime=1483228800, endTime=1514764800): self.exchange = exchange self.pair = pair self.period = period self.startTime = startTime # 01 JAN 2017 #self.startTime = 1504224000 # 01 SEP 2017 #self.endTime = 1506729600 # 30 SEP 2017 self.endTime = endTime # 1 Jan 2018 self.data = [] if (self.exchange == "poloniex"): self.conn = poloniex('key goes here', 'Secret goes here') if backtest in ["backtest", "warm"]: data = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) #data = json.loads(open("./data/btc-usd-data.json", "r").readline()) for d in data: if (d['open'] and d['close'] and d['high'] and d['low']): self.data.append( BotCandlestick(output, d['date'], self.period, d['open'], d['close'], d['high'], d['low'], d['weightedAverage'])) if (self.exchange == "bittrex"): if backtest == "backtest": url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = requests.get(url) rawdata = response.json() self.data = rawdata["result"]
def preliminaryCandlesticks(self): poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) for datum in poloData: if datum['open'] and datum['close'] and datum['high'] and datum[ 'low'] and datum['date']: self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'], datum['date'])) return self.data
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period # hard coded self.startTime = 1491048000 self.endTime = 1491591200 # where weare going to save the historical data self.data = [] # poloniex if (exchange == "poloniex"): self.conn = poloniex('key goes here', 'Secret goes here') if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): #se il dato non c e mette tutto a zero! se uno e zero non lo considero altrimenti lo aggiungo self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'])) # bittrex if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1526500085 self.endTime = 1526502085 self.data = [] if (exchange == "poloniex"): self.conn = poloniex( '5NTVQ4P4-AIUEPN28-E57OXVUV-7C19OZCJ', 'b4182fec0b5c578563b6ebe9367c41d6609e06af8ef2960f0159a5338980e426ed3939c9e53f9afbcf3be279f26eb3a800da2c6b785dd2680764be16ee523323' ) if backtest: poloData = self.conn.api_query( "returnChartData", { "currencyPair": self.pair, "start": self.startTime, "end": self.endTime, "period": self.period }) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'])) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + self.pair + "&tickInterval=" + self.period + "&_=" + str( self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"]
def __init__(self, backTest=True): self.pair = shared.exchange['pair'] self.backTest = bool(backTest) self.output = BotLog() self.tempCandle = None self.data = [] # API self.api = BotApi() if backTest: from_timestamp = self.api.exchange.parse8601( shared.strategy['start_date']) try: print(self.api.exchange.milliseconds(), 'Fetching candles starting from', self.api.exchange.iso8601(from_timestamp)) ohlcvs = self.api.exchange.fetch_ohlcv( shared.exchange['pair'], timeframe=shared.strategy['timeframe'], since=from_timestamp) print(self.api.exchange.milliseconds(), 'Fetched', len(ohlcvs), 'candles') for ohlcv in ohlcvs: self.data.append( BotCandlestick( float(ohlcv[0]) / 1000, float(ohlcv[1]), float(ohlcv[2]), float(ohlcv[3]), float(ohlcv[4]), float(ohlcv[5]))) except (self.api.ExchangeError, self.api.AuthenticationError, self.api.ExchangeNotAvailable, self.api.RequestTimeout) as error: print('Got an error', type(error).__name__, error.args) exit(2)
def main(argv): # default: period = 300 backTest = False animation = False csvName = "defaultLog.csv" try: # getopt.getopt returns two elements, opts which consists of pairs (options and values) # the second (args) is the list of program arguments left after the option list was stripped # (this is a trailing slice of args) opts, args = getopt.getopt(argv, "p:c:n:s:e:bha", [ "period=", "currency=", "points=", "name=" "startTime=", "endTime=", "backTest", "animation", "help" ]) except getopt.GetoptError: print( "Start3.py -p <period> -c <currency pairs> -n <period of moving average> -s <startTime> -e <endTime>" ) sys.exit(2) for opt, arg in opts: print(opt, arg) if opt == '-h': print( "Start3.py -p <period> -c <currency pairs> -n <period of moving average> -s <startTime> -e <endTime>" ) sys.exit() elif opt in ("-c", "--currency"): pairs = arg.split(",") elif opt in ("-n", "--points"): lengthofMA = int(arg) elif opt in ("-b", "--backTest"): backTest = True elif opt in ("-s", "--startTime"): startTime_datetime = datetime.strptime(arg, '%Y-%m-%d') startTime_timestamp = datetime.timestamp(startTime_datetime) elif opt in ("-e", "--endTime"): endTime_datetime = datetime.strptime(arg, '%Y-%m-%d') endTime_timestamp = datetime.timestamp(endTime_datetime) elif opt in ("-a", "--animation"): animation = True elif opt in ("-b", "--backTest"): backTest = True elif opt in ("--name"): csvName = arg elif opt in ("-p", "--period"): if arg in [ "60", "180", "300", "900", "1800", "3600", "7200", "14400", "21600", "28800", "43200", "86400", "259200", "1209600" ]: period = int(arg) elif arg in [ "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1M" ]: period_dict = {"1m": 60, "3m": 180, "5m": 300, "15m": 900, "30m": 1800, "1h": 3600, \ "2h": 7200, "4h": 14400, "6h": 21600, "8h": 28800, "12h": 43200, "1d": 86400, \ "3d": 259200, "1w": 1209600} period = period_dict[arg] else: print( "Binance requires periods in 60,180,300, 900, 1800, 3600, 7200, 14400, 21600,28800,43200,86400,259200,1209600 or\ 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M") sys.exit(2) print(period) api = API() #TODO: delete pair editing checker = BotChecker() pairs = checker.pairs if backTest: log = BotLog() log.logToCsv(csvName) chart = BotChart(period=period, log=log, api=api, checker=checker) history, timestamps = chart.loadHistory( startTime_timestamp=startTime_timestamp, endTime_timestamp=endTime_timestamp) strategy = BotStrategy(api=api, period=period, log=log, checker=checker, stopLoss=0, startBalance=100) for timestamp in timestamps: strategy.tick(history, timestamp, initialize_live=False, duration=None) print("{} days passed".format((timestamp - timestamps[0]) / 86400)) # log.tick() # logging to csv log.csvLog() log.histogram() log.scatter() else: log = BotLog() chart = BotChart(period=period, log=log, api=api, checker=checker) strategy = BotStrategy(api=api, period=period, log=log, checker=checker, stopLoss=0, startBalance=100) intermediateStep = time.time() data, timestamps = chart.loadHistory( startTime_timestamp=intermediateStep - 86400 * 15, endTime_timestamp=intermediateStep, firstTime=True, duringLive=False) duration = len(timestamps) counter = 0 for timestamp in timestamps: # loading history into BotStrategy (past indicators etc.) strategy.tick(data, timestamp, initialize_live=True) counter += 1 if ((counter / duration) * 100 % 5) == 0: print( f"{(counter / duration) * 100} % progress of preloading the 15 days, " f"since starting loading 15 days at: {intermediateStep}, {(time.time() - intermediateStep) / 60} minutes are over" ) # load data that is missing since the first part of loading history takes very long beginning = time.time() data, timestamps = chart.loadHistory( startTime_timestamp=intermediateStep, endTime_timestamp=beginning, firstTime=False, duringLive=False) for timestamp in timestamps: strategy.tick(data, timestamp, initialize_live=True) print(f"The second loading took {time.time() - beginning} seconds") # starting creating candlesticks and liveTrading if not animation: liveData = {} developingCandlestick = BotCandlestick(period=period, log=log, checker=checker) check = 0 counter = 0 while True: counter += 1 startCandlestick = time.time() candlestickClosed = False print(f"!!!! {counter}. ROUND !!!!") check = 0 for pair in pairs: developingCandlestick.tick(pair, chart.getCurrentTicker()) #print("The pair: ", pair, "has ", developingCandlestick.counter[pair], " number of ticks") if developingCandlestick.isClosed(pair): check += 1 print( f"counter is: {check}, len pairs is: {len(pairs)}, if equal the candlestick gets closed" ) if check == len(pairs): # meaning all are closed candlestickClosed = True time_of_closed_candlestick = time.time() liveData[time_of_closed_candlestick] = {} time.sleep(5) data, timestamps = chart.loadHistory( startTime_timestamp=startCandlestick - period, endTime_timestamp=time_of_closed_candlestick, firstTime=False, duringLive=True) for pair in pairs: # add the self made candlestick to the dictionary with the past data liveData[time_of_closed_candlestick][ pair] = developingCandlestick.candlestick[pair] liveData[time_of_closed_candlestick][pair][ 'volume'] = data[timestamps[-1]][pair][ 'volume'] # assigning 1 tick old volume strategy.tick(liveData, time_of_closed_candlestick, initialize_live=False) # create new candlestick developingCandlestick = BotCandlestick( period, log, checker) counter = 0 if not candlestickClosed: time_used = time.time() - startCandlestick try: time.sleep(np.ceil(30 - time_used)) except: pass
def __init__(self, exchange, pair, period, backtest=True): self.pair = pair self.period = period self.startTime = 1491048000 self.endTime = 1491591200 self.data = [] if (exchange == "poloniex"): self.conn = poloniex('key goes here','Secret goes here') if backtest: poloData = self.conn.api_query("returnChartData",{"currencyPair":self.pair,"start":self.startTime,"end":self.endTime,"period":self.period}) for datum in poloData: if (datum['open'] and datum['close'] and datum['high'] and datum['low']): self.data.append(BotCandlestick(self.period,datum['open'],datum['close'],datum['high'],datum['low'],datum['weightedAverage'])) if (exchange == "bittrex"): if backtest: url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName="+self.pair+"&tickInterval="+self.period+"&_="+str(self.startTime) response = urllib.urlopen(url) rawdata = json.loads(response.read()) self.data = rawdata["result"] def getPoints(self): return self.data def getCurrentPrice(self): currentValues = self.conn.api_query("returnTicker")
def main(argv): startTime = False endTime = False live = False movingAverageLength = 20 try: opts, args = getopt.getopt(argv,"ht:c:n:s:e",["timeframe=","currency=","exchange=","live"]) except getopt.GetoptError: print('trading-bot.py -t <timeframe> -c <currency pair>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('trading-bot.py -t <timeframe> -c <currency pair>') sys.exit() elif opt in ("-s"): startTime = str(arg) elif opt in ("-e"): endTime = str(arg) elif opt in ("-t", "--timeframe"): timeframe = str(arg) shared.strategy['timeframe'] = timeframe elif opt in ("-c", "--currency"): pair = str(arg) shared.exchange['pair'] = pair shared.exchange['market'] = pair.split("/")[1] shared.exchange['coin'] = pair.split("/")[0] elif opt in ("--exchange"): exchange = str(arg) shared.exchange['name'] = exchange elif opt == "--live": print("You're going live... All loss are your reponsability only!") live = True # startTime specified: we are in backtest mode if (startTime): chart = BotChart(timeframe, startTime, endTime) strategy = BotStrategy() strategy.showPortfolio() for candlestick in chart.getPoints(): strategy.tick(candlestick) chart.drawChart(strategy.candlesticks, strategy.trades, strategy.movingAverages) strategy.showPortfolio() else: chart = BotChart(timeframe, False, False, False) strategy = BotStrategy(False, live) strategy.showPortfolio() candlestick = BotCandlestick() x = 0 while True: try: currentPrice = chart.getCurrentPrice() candlestick.tick(currentPrice) strategy.tick(candlestick) except ccxt.NetworkError as e: print(type(e).__name__, e.args, , 'Exchange error (ignoring)') except ccxt.ExchangeError as e: print(type(e).__name__, e.args, , 'Exchange error (ignoring)') except ccxt.DDoSProtection as e: print(type(e).__name__, e.args, 'DDoS Protection (ignoring)') except ccxt.RequestTimeout as e: print(type(e).__name__, e.args, 'Request Timeout (ignoring)') except ccxt.ExchangeNotAvailable as e: print(type(e).__name__, e.args, 'Exchange Not Available due to downtime or maintenance (ignoring)') except ccxt.AuthenticationError as e: print(type(e).__name__, e.args, 'Authentication Error (missing API keys, ignoring)') drawingCandles = copy.copy(strategy.candlesticks) if not candlestick.isClosed(): drawingCandles.append(copy.copy(candlestick)) drawingCandles[-1].close = candlestick.currentPrice chart.drawChart(drawingCandles, strategy.trades, strategy.movingAverages) if candlestick.isClosed(): candlestick = BotCandlestick() x+=1 time.sleep(int(10))
def main(argv): live = False try: opts, args = getopt.getopt(argv, "", ["live"]) except getopt.GetoptError: print('trading-bot.py') sys.exit(2) for opt, arg in opts: if opt == "--live": print("You're going live... Losses are your responsibility only!") live = True # START_DATE specified: we are in backtest mode if shared.strategy['start_date']: chart = BotChart() strategy = BotStrategy() strategy.showPortfolio() for candlestick in chart.getPoints(): strategy.tick(candlestick) chart.drawChart(strategy.candlesticks, strategy.trades, strategy.movingAverages) strategy.showPortfolio() else: chart = BotChart(False) strategy = BotStrategy(False, live) strategy.showPortfolio() candlestick = BotCandlestick() x = 0 while True: try: currentPrice = chart.getCurrentPrice() candlestick.tick(currentPrice) strategy.tick(candlestick) except ccxt.NetworkError as e: print(type(e).__name__, e.args, 'Exchange error (ignoring)') except ccxt.ExchangeError as e: print(type(e).__name__, e.args, 'Exchange error (ignoring)') except ccxt.DDoSProtection as e: print(type(e).__name__, e.args, 'DDoS Protection (ignoring)') except ccxt.RequestTimeout as e: print(type(e).__name__, e.args, 'Request Timeout (ignoring)') except ccxt.ExchangeNotAvailable as e: print( type(e).__name__, e.args, 'Exchange Not Available due to downtime or maintenance (ignoring)' ) except ccxt.AuthenticationError as e: print( type(e).__name__, e.args, 'Authentication Error (missing API keys, ignoring)') drawingCandles = copy.copy(strategy.candlesticks) if not candlestick.isClosed(): drawingCandles.append(copy.copy(candlestick)) drawingCandles[-1].close = candlestick.currentPrice chart.drawChart(drawingCandles, strategy.trades, strategy.movingAverages) if candlestick.isClosed(): candlestick = BotCandlestick() x += 1 time.sleep(shared.exchange['interval'])
def main(argv): startTime = False endTime = False try: opts, args = getopt.getopt(argv,"hp:c:n:s:e:a:",["period=","currency=","points="]) except getopt.GetoptError: print 'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>' sys.exit(2) print(opts) for opt, arg in opts: if opt == '-h': print 'trading-bot.py -p <period length> -c <currency pair> -n <period of moving average>' sys.exit() elif opt in ("-p", "--period"): if (int(arg) in [300,900,1800,7200,14400,86400]): period = arg else: print 'Poloniex requires periods in 300,900,1800,7200,14400, or 86400 second increments' sys.exit(2) elif opt in ("-c", "--currency"): pair = arg elif opt in ("-n", "--points"): lengthOfMA = int(arg) elif opt in ("-s"): startTime = arg elif opt in ("-e"): endTime = arg elif opt in ("-a"): auto = arg if (startTime): chart = BotChart("poloniex","BTC_XMR",300,True,startTime,endTime) chart2 = BotChart("poloniex","USDT_BTC",300,True,startTime,endTime) chart3 = BotChart("poloniex","USDC_BTC",300,True,startTime,endTime) chart4 = BotChart("poloniex","BTC_ETH",300,True,startTime,endTime) strategy = BotStrategy() strategy2 = BotStrategy() strategy3 = BotStrategy() strategy4 = BotStrategy() print("start1") for candlestick in chart.getPoints(): total = strategy.tick(candlestick) print("Total is: " + str(total)) print("start2") for candlestick in chart2.getPoints(): total = strategy2.tick(candlestick) print("Total is: " + str(total)) print("start3") for candlestick in chart3.getPoints(): total = strategy3.tick(candlestick) print("Total is: " + str(total)) print("start4") for candlestick in chart4.getPoints(): total = strategy4.tick(candlestick) print("Total is: " + str(total)) elif(auto): time = BotTime(10) endTime = time.startDate() startTime = time.endDate() chart = BotChart("poloniex","BTC_XMR",300,True,startTime,endTime) chart2 = BotChart("poloniex","USDT_BTC",300,True,startTime,endTime) chart3 = BotChart("poloniex","USDC_BTC",300,True,startTime,endTime) chart4 = BotChart("poloniex","BTC_ETH",300,True,startTime,endTime) strategy = BotStrategy() strategy2 = BotStrategy() strategy3 = BotStrategy() strategy4 = BotStrategy() print("chart1") for candlestick in chart.getPoints(): total = strategy.tick(candlestick) print("Total is: " + str((total*6972.90))) print("chart2") for candlestick in chart2.getPoints(): total = strategy2.tick(candlestick) print("Total is: " + str((total*0.80))) print("chart3") for candlestick in chart3.getPoints(): total = strategy3.tick(candlestick) print("Total is: " + str((total*0.80))) print("chart4") for candlestick in chart4.getPoints(): total = strategy4.tick(candlestick) print("Total is: " + str((total*6972.90))) else: chart = BotChart("poloniex","BTC_XMR",300,False) strategy = BotStrategy() candlesticks = [] developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))
def main(argv): pairs = [] try: opts, args = getopt.getopt(argv, "hm:p:c:", ["mode=", "period=", "currency="]) except getopt.GetoptError: print( "bot.py -m <backtest | paper | live> -p <period length in sec> -c <currency pair>" ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( "bot.py -m <backtest | paper | live> -p <period length in sec> -c <currency pair>" ) sys.exit() elif opt in ("-m", "--mode"): if (arg == "backtest"): mode = arg elif (arg == "paper"): mode = arg elif (arg == "live"): mode = arg else: print("Requires mode to be 'backtest', 'paper' or 'live'") sys.exit(2) elif opt in ("-p", "--period"): if (int(arg) in [300, 900, 1800, 7200, 14400, 86400]): period = int(arg) else: print( "Requires periods to be 300, 900, 1800, 7200, 14400, or 86400 second increments" ) sys.exit(2) elif opt in ("-c", "--currency"): pairs.append(arg) start_time = time.time() output = BotLog() exchanges = ["poloniex"] #pairs = ["USDT_BTC", "USDT_ETH", "USDT_LTC", "USDT_ZEC"] #modes = ["RSI"] #modes = ["BBAND"] #modes = ["BBAND", "MACD2", "ALL"] algos = ["MACD"] #modes = ["RSI", "BBAND", "MACD2", "MACD", "DROP", "ALL"] charts = [] strategies = [] target = 0.04 stoploss = 0.18 for pair in pairs: for exchange in exchanges: if (mode == "backtest"): charts.append(BotChart(exchange, pair, period, mode, output)) else: charts.append( BotChart(exchange, pair, period, "warm", output, int(time.time() - (24 * 60 * 60)), int(time.time()))) for algo in algos: if (mode == "backtest"): strategies.append( BotStrategy(exchange + "-" + pair, algo, pair, 1, 5000, 0, int(5000 - 1), stoploss, target, mode, output)) # Parameters: max trades, initial fiat, initial holding, trade amount, stop loss, target else: strategies.append( BotStrategy(exchange + "-" + pair, algo, pair, 1, 5000, 0, int(5000 - 1), stoploss, target, "warm", output)) if (mode == "backtest"): for i, chart in enumerate(charts): for j, algo in enumerate(algos): strategy = strategies[len(algos) * i + j] for candlestick in chart.getPoints(): strategy.tick(candlestick) strategy.showPositions() strategy.showProfit() strategy.drawGraph() output.log("\n--- %s seconds ---" % (time.time() - start_time)) else: candlesticks = [] developingCandlestick = BotCandlestick(output, int(time.time()), period) for i, chart in enumerate(charts): for j, algo in enumerate(algos): strategy = strategies[len(algos) * i + j] for candlestick in chart.getPoints(): strategy.tick(candlestick) strategy.drawGraph() strategy.backtest = mode while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib.error.URLError: time.sleep(int(period / 10)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick( output, int(time.time()), period) strategy.showPositions() strategy.showProfit() strategy.drawGraph() time.sleep(int(period / 10)) output.close()
def __init__(self, exchange, pair, period, startTime, endTime, backtest=True): self.botHTML = BotHTML() self.vars = botVariables() self.api_key = self.vars.api_key_poloniex self.api_secret = self.vars.api_secret_poloniex self.avPeriod = self.vars.movingAvPeriod self.indicators = BotIndicators() self.pair = pair self.period = period self.startTime = startTime self.endTime = endTime self.data = [] self.prices = [] self.poloData = [] self.trades = [] if (exchange == "poloniex"): print('Ecxhange with Poloniex') self.conn = poloniex.Poloniex(self.api_key, self.api_secret) if backtest: print("Checking the data from " + datetime.datetime.fromtimestamp(int(startTime)).strftime( '%Y-%m-%d %H:%M:%S') + " to " + datetime.datetime.fromtimestamp(int(endTime)).strftime( '%Y-%m-%d %H:%M:%S')) self.poloData = self.conn.returnChartData( self.pair, self.period, self.startTime, self.endTime) #A:poloData is an list (checked with the funtion type(), where each item of the list contains 6 values of the period for datum in self.poloData: #datum is a dict = {key1:value1, key2:value2, ... } if (datum['open'] and datum['close'] and datum['high'] and datum['low']): #putting all this data to the BotCandlestick object self.data.append( BotCandlestick(self.period, datum['open'], datum['close'], datum['high'], datum['low'], datum['weightedAverage'], datum['date'])) if (exchange == "binance"): # Remember to install binance python script with --> pip install python-binance print('Ecxhange with Binance') if backtest: # create the Binance client, no need for api key client = Client("", "") klines = client.get_historical_klines( self.vars.pairBinance, getattr(client, self.vars.periodBinance), self.vars.startTimeBinance, self.vars.endTimeBinance) for kline in klines: self.data.append( BotCandlestick( self.period, kline[1], kline[4], kline[2], kline[3], str((float(kline[1]) + float(kline[2]) + float(kline[4]) + float(kline[3])) / 4), int(((kline[0]) + (kline[6])) / 2000))) #because in miliseconds """
def main(argv): startTime = False endTime = False forwardTest = True movingAverageLength = 20 try: opts, args = getopt.getopt( argv, "hp:c:n:s:e", ["period=", "currency=", "exchange=", "live"]) except getopt.GetoptError: print('trading-bot.py -p <period length> -c <currency pair>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('trading-bot.py -p <period length> -c <currency pair>') sys.exit() elif opt in ("-s"): startTime = float(arg) elif opt in ("-e"): endTime = float(arg) elif opt in ("-p", "--period"): period = int(arg) elif opt in ("-c", "--currency"): pair = str(arg) shared.exchange['pair'] = pair shared.exchange['market'] = pair.split("_")[0] shared.exchange['coin'] = pair.split("_")[1] elif opt in ("--exchange"): if str(arg) not in ['', 'poloniex', 'kraken']: print("Only poloniex and kraken are supported for now") sys.exit() exchange = str(arg) shared.exchange['name'] = exchange elif opt == "--live": print( "You're going live... All losts are your reponsability only!") forwardTest = False if shared.exchange['name'] == "kraken": shared.exchange['pair'] = str(shared.exchange['coin']) + str( shared.exchange['market']) # startTime specified: we are in backtest mode if (startTime): chart = BotChart(period, startTime, endTime) strategy = BotStrategy() strategy.showPortfolio() for candlestick in chart.getPoints(): strategy.tick(candlestick) chart.drawChart(strategy.candlesticks, strategy.movingAverages, strategy.trades) strategy.showPortfolio() else: chart = BotChart(period, False, False, False) strategy = BotStrategy(False, forwardTest) strategy.showPortfolio() candlestick = BotCandlestick(float(period)) x = 0 while True: try: currentPrice = chart.getCurrentPrice() except Exception as e: print(e) print("Error fetching current price") return try: candlestick.tick(currentPrice) except Exception as e: print(e) print("Error fetching tick") return strategy.tick(candlestick) drawingCandles = copy.copy(strategy.candlesticks) if not candlestick.isClosed(): drawingCandles.append(copy.copy(candlestick)) drawingCandles[-1].close = candlestick.currentPrice chart.drawChart(drawingCandles, strategy.movingAverages, strategy.trades) if candlestick.isClosed(): candlestick = BotCandlestick(float(period)) x += 1 time.sleep(int(10))
output.log("{}... Continuing".format(err[0])) statsd.histogram( 'main_loop.urllib2.ssl.SSLError', err, tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) continue except Exception as err: # Something else happened but we still want ot log it, send it to DD, and keep going. output.log("Unexpected error: {}".format(sys.exc_info()[0])) statsd.histogram( 'main_loop.unknown_exception', err, tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) time.sleep(30) continue # When close price is present if developing_candlestick.isClosed(): # Add the closed candlestick to the list candlesticks.append(developing_candlestick) # Enact the strategy strategy.tick(developing_candlestick) # Create a new candlestick developing_candlestick = BotCandlestick(period) time.sleep(float(poll_time)) if __name__ == "__main__": main(sys.argv[1:])
def main(argv): """ Main entry point """ # Logging output = BotLog() supported_exchanges = ['kraken'] exchange = 'kraken' pair = "XXBTZUSD" # Bitcoin/USD pair on Kraken period = 5 # Time frame interval in minutes, e.g. width of candlestick. poll_time = 1 # How often an API query is made when using real time data. script_help = '\n\t-c --currency <currency pair>\n\t-x --exchange <name of the exchange {exchanges}>\n\t-t --poll <poll period length in minutes>\n\nHistorical Mode\n\t-p --period <period of frame>\n\t-s --start <start time in unix timestamp>\n\t-e --end <end time in unix timestamp>\n'.format( exchanges=supported_exchanges) start_time = False end_time = False try: opts, args = getopt.getopt( argv, "h:x:p:c:t:s:e:y:", ["exchange=", "period=", "currency=", "poll=", "start=", "end="]) except getopt.GetoptError: output.log(sys.argv[0] + script_help) sys.exit(2) for opt, arg in opts: if opt == ("-h", "--help"): output.log(sys.argv[0] + script_help) sys.exit() elif opt in ("-s", "--start"): start_time = arg elif opt in ("-e", "--end"): end_time = arg elif opt in ("-x", "--exchange"): if arg in supported_exchanges: exchange = arg else: output.log( 'Supported exchanges are {}'.format(supported_exchanges)) sys.exit(2) elif opt in ("-p", "--period"): if exchange.lower() == 'kraken': # Kraken uses minutes for getting historical data. mins = [1, 5, 15, 30, 60, 240, 1440, 10080, 21600] if (int(arg) in mins): period = int(arg) else: output.log( 'Kraken requires intervals 1, 5, 15, 30, 60, 240, 1440, 10080, 21600 minute intervals' ) sys.exit(2) else: period = int(arg) elif opt in ("-c", "--currency"): pair = arg elif opt in ("-t", "--poll"): poll_time = arg ################ Strategy in use ################ strategy = MACDStrategy(pair, period) strategy_name = strategy.get_name() ################################################# # Log bot startup event to DataDog statsd.event(title='Bot started', text='{}:{} started on {} trading {} using {}'.format( BOT_ID, BOT_NAME, exchange, pair, strategy_name), alert_type='success', tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) trade_session_details = "{bg}Trading {pair} on {exchange} with {strat}" \ " @ {period} minute period{White}".format(pair=pair, exchange=exchange.upper(), strat=strategy_name, period=period, bg=On_Cyan, White=White) if start_time: # Backtesting chart = BotChart(exchange, pair, period) for candlestick in chart.get_points(): strategy.tick(candlestick) output.log(trade_session_details) else: # Live Trading output.log(trade_session_details) chart = BotChart(exchange, pair, period, backtest=False) candlesticks = [] developing_candlestick = BotCandlestick(period) progress_counter = 0 while True: # Log trade details every so often if progress_counter == 50: output.log(trade_session_details) progress_counter = 0 progress_counter += 1 try: developing_candlestick.tick( chart.get_current_price_and_vol()[0]) except urllib2.URLError, err: # If network or site is down output.log("{}... Continuing".format(err[0])) # TODO: These calls to statsd should be Rollbar. Set up Rollbar statsd.histogram( 'main_loop.urllib2.URLError', err, tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) continue except ValueError, err: # For screwy JSON output.log('{}... Continuing'.format(err[0])) statsd.histogram( 'main_loop.ValueError', err, tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) continue except urllib2.ssl.SSLError, err: # For read timeouts output.log("{}... Continuing".format(err[0])) statsd.histogram( 'main_loop.urllib2.ssl.SSLError', err, tags=['bot_name:{}.bot_id:{}'.format(BOT_NAME, BOT_ID)]) continue
def main(argv): # debut = '2016-11-02 14:00:00' # fin = '2018-08-14 20:53:20' try: parser = argparse.ArgumentParser() parser.add_argument("-p", "--period", help="Period length in seconds, 14400 by default", type=int, choices=[300, 900, 1800, 7200, 14400, 86400], default=14400) parser.add_argument("-c", "--currency", help="Currency pair | Ex: USDT_ETH", default='USDT_ETH') parser.add_argument("-b", "--backtest", help="Mode Backtest", action="store_true") parser.add_argument( "-s", "--start", help= "Start time in YYYY-MM-DD HH:MM:SS (for backtesting), '2016-11-02 14:00:00' by default", default='2016-11-02 14:00:00') parser.add_argument( "-e", "--end", help= "End time in YYYY-MM-DD HH:MM:SS (for backtesting), '2018-12-14 20:53:20' by default", default='2018-12-14 20:53:20') parser.add_argument("-S", "--short", help="Enable Short Mode", action="store_true") args = vars(parser.parse_args()) except: print "ArgumentParser Error type -h for help" sys.exit(2) pair = args["currency"] period = args["period"] short_mode = args["short"] if (args["backtest"]): debut = args['start'] fin = args['end'] chart = BotChart("poloniex", pair, period, debut, fin) strategy = stratRsi(period=period, short_mode=short_mode) for candlestick in chart.getPoints(): strategy.tick(candlestick) graphe = PlotGraphe(chart, strategy) graphe.plotChart() try: sigma = chart.getSigma() * float(chart.compteur)**0.5 perf = graphe.perf sharpeRatio = perf / sigma print("\n Perforance: " + str(perf)) print("\n Ratio de Sharpe: " + str(sharpeRatio) + "\n") except Exception as e: pass else: chart = BotChart("poloniex", pair, period, backtest=False) strategy = stratRsi(period, short_mode, backtest=False) candlesticks = [] developingCandlestick = BotCandlestick() while True: try: developingCandlestick.tick(chart.getCurrentPrice()) except urllib2.URLError: time.sleep(int(30)) developingCandlestick.tick(chart.getCurrentPrice()) if (developingCandlestick.isClosed()): candlesticks.append(developingCandlestick) strategy.tick(developingCandlestick) developingCandlestick = BotCandlestick() time.sleep(int(30))