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): chart = BotChart("poloniex", "BTC_XMR", 300) strategy = BotStrategy() print strategy.spreadsheet for candlestick in chart.getPoints(): strategy.tick(candlestick) #Create Worbook with an active sheet m_wb = Workbook() wslist = m_wb.active wslist.title = 'Charts' list = strategy.spreadsheet for row_list in list: wslist.append(row_list) # Save dt = str(datetime.now()) wb_name = 'CryptoChartInfo' + dt[0:10] + '.xlsx' m_wb.save(wb_name) print('it worked')
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 main(argv): chart = BotChart("poloniex","BTC_XMR",300) strategy = BotStrategy() for candlestick in chart.getPoints(): strategy.tick(candlestick)
def trial(toPerform, curr): global pair global chart global prevPair global now global mcl global trained_mcl global chartData now += 1 num = "_".join(map(str, ("-".join(map(str, a)) for a in toPerform))) strategyDetails = {} for z in toPerform: if z[0] == "currency": pair = tradeCurrencies[z[1] - 1] strategyDetails[z[0]] = z[1] print("{} | {}/{} | {}".format(str(num), now, total, str(datetime.datetime.now())[:10])) if strat in ["4"]: if ('lookback-mc' in strategyDetails or 'advance' in strategyDetails or 'learnProgTotal' in strategyDetails) or mcl == "": mcl = MachineStrat(strat, strategyDetails) if not mcl.trained: learnProgTotal = 1400 if not 'learnProgTotal' in strategyDetails else strategyDetails[ 'learnProgTotal'] chart = BotChart(functions, pair) chart.getHistorical(period, startTime - period * (learnProgTotal + 30), endTime) totalChartData = chart.getPoints() trainingSet = totalChartData["weightedAverage"][:learnProgTotal] chartData = totalChartData[learnProgTotal:] trained_mcl = mcl.train(trainingSet) else: if pair != prevPair: chart = BotChart(functions, pair) chart.getHistorical(period, startTime, endTime) chartData = chart.getPoints() prevPair = pair strategy = BotStrategy(period, functions, totalBalance, num, strategyDetails, strat, trained_mcl) for index, candlestick in chartData.iterrows(): strategy.tick(candlestick) strategy.closeAllTrades() totalAssets, totalFees, totalTime, marketProf = strategy.calculateCurrentPosition( ) totalProfit = strategy.balance global trialResults timeEf = totalTime / (int(strategy.currentDateOrig) - int(strategy.startDate)) trialResults.append([ num, toPerform.copy(), totalProfit, (marketProf) * totalBalance, totalTime, timeEf ])
def main(): strategy = BotStrategy() #implementation starts strategy.tick() strategy.evaluatePositions() strategy.TradeDatabase.closecon() #disposes all connections to save memory #graphing EMAs and MACD indicator: strategy.output.macdrsiplot(strategy.graphdataPoints, strategy.EMA9, strategy.MACD, strategy.cumulatedProfits)
def main(argv): #chart = BotChart("poloniex","BTC_ETH") strategy = BotStrategy() t_end = time.time() + (60 * 60 * 7) while time.time() < t_end: strategy.tick()
def main(): strategy = BotStrategy() #implementation starts while True: strategy.tick() strategy.evaluatePositions() #graphing EMAs and MACD indicator: strategy.output.macdrsiplot(strategy.graphdataPoints, strategy.EMA9, strategy.MACD, strategy.cumulatedProfits) time.sleep(60) #define timestamp period
def main(argv): chart = BotChart("poloniex","BTC_XMR",300,False) strategy = BotStrategy() while True: candlestick = chart.getCurrentPrice() strategy.tick(candlestick) time.sleep(int(10))
def main(argv): startTime = CONFIG["START"] endTime = CONFIG["END"] # pair = CONFIG['BASE'] + "/" + CONFIG['QUOTE'] exchange = CONFIG['EXCHANGE'] period = CONFIG['PERIOD'] pairs = CONFIG['PAIRS'] for pair in pairs: if(not CONFIG['VERBOSE']): print('Gathering', pair, 'ticker data from', exchange) chart = BotChart(startTime, endTime, exchange, pair, period) strategy = BotStrategy(pair) for candlestick in chart.getPoints(): strategy.tick(candlestick) print("Finished gathing data for " + pair + "\n")
def main(argv): #chart = BotChart("poloniex", "BTC_ETH", 300) chart = BotChart("poloniex", "BTC_XMR", 300) #chart = BotChart("poloniex", "BTC_DASH", 300) strategy = BotStrategy() for candlestick in chart.getPoints(): #print(candlestick) strategy.tick(candlestick) BotTrade.export() series = read_csv('export.csv', parse_dates=[0], index_col=0, squeeze=True, date_parser=parser) series.plot() pyplot.show()
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 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))
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): 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))
class Backtest(object): def __init__(self, pair, live=False, numberOfCharts=1, strat=0, klineint=0, ss="", es="", graphics=True, ma5=True, handl=True): #sets kline interval to what the selected strat uses stratintervals = [Client.KLINE_INTERVAL_30MINUTE] if klineint == 0: klineint = stratintervals[strat] #graphs = [Client.KLINE_INTERVAL_30MINUTE, Client.KLINE_INTERVAL_5MINUTE] #Set startstamp to the highest kline interval chart and then pass it to the other charts #this starts the graphs at the same time, will makes things 999999999x easier if numberOfCharts != 1: self.chart3 = BotChart(pair,300,klineint, stringy=ss, endstring=es) startstamp = self.chart3.timestamps[0] // 1000 self.chart2 = BotChart(pair,300,klineint, startstamp, stringy=ss, endstring=es) #startstamp = chart2.timestamps[0] // 1000 #print(startstamp) #Changed chart to global var so I can access list values if numberOfCharts == 1: self.chart = BotChart(pair,300,klineint, stringy=ss, endstring=es) else: self.chart = BotChart(pair,300,klineint, startstamp, stringy=ss, endstring=es) chartmax = self.chart.getMax() chartmin = self.chart.getMin() #Get how many times one interval goes into another by minutes intervals = {"1":[6],"2":[2],"3":[2]} intervals = [6,2] chartlen = len(self.chart.data) if numberOfCharts != 1: chartlen2 = len(self.chart2.data) chartlen3 = len(self.chart3.data) #either multiply chartlen by a factor (6) and subtract chart2len #to get the extra at the end or find the closest 30 minute and #see how many 5 minutes go into it from the current time #I'll start by doing the first interval = intervals[0] if numberOfCharts != 1: #need multiple extras extra1 = (len(self.chart.data) - 1) - (len(self.chart3.data) - 1) * 30 extra2 = (len(self.chart2.data) - 1) - (len(self.chart3.data) - 1) * 6 extra3 = 0 extra = [extra1, extra2, extra3] #delete these from valuelist chartlengths = [chartlen,chartlen2,chartlen3] timestamps = [self.chart.timestamps,self.chart2.timestamps,self.chart3.timestamps] data = [self.chart.data,self.chart2.data,self.chart3.data] ''' lmaxes = [chart.lmaxes,chart2.lmaxes,chart3.lmaxes] highs = [chart.highs,chart2.highs,chart3.highs] lows = [chart.lows,chart2.lows,chart3.lows] ''' else: extra = [0] chartlengths = [chartlen] timestamps = [self.chart.timestamps] print("data chart length",len(self.chart.data)) begin = time.time() #Might need some cleanup here #There's gotta be a better way #I think i should make prices be its own list like lmaxes and data etc - maybe do this with all the lists #there has to be multiple lists in valuelist because the lists become the same if they're not duplicated #valuelist = [[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]],[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]],[False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],0,0,[],1,0,[],False,False,True,0,[],[],True,[],0,0,[],[],[],[]]] valuelist = [False,0,Point(0,0),0,[],0,"",[],[],[],0,0,0,False, False,[-1],[-1],0,0,[],1,0,[],False,False,True,[],[],True,[],0,0,[],[],[],[],[]] print("chart.data:",self.chart.data) self.strategy = BotStrategy(strat, chartmax, chartmin, chartlengths, pair, numberOfCharts, self.chart.valuesAre, timestamps, extra, valuelist, intervals, int(self.chart.timestamps[0]), int(self.chart.timestamps[-1]), len(self.chart.timestamps),live,aggTrades=False,aggisNext=False, graphics=graphics, ma5on=ma5, handlon=handl) #Before doing this first migrate all data from graph to botstrategy #pass through all the different chart vars in strategy and scrap reinit #for candlestick in range(len(chart.data)): # if (chart.timestamps[candlestick] == chart2.timestamps[candlestick]): # strategy.tick(chart2.data[candlestick], 2) # strategy.tick(chart.data[candlestick], 1) print("extra",extra) #I think chart is supposed to have the most klines for candlestick in range(len(self.chart.data)): print("\nTick number:",candlestick) #print(len(self.chart.data)) #print(chart.timestamps[candlestick],chart2.timestamps[candlestick//5]) #if (chart.timestamps[candlestick] == chart2.timestamps[candlestick//2] ): #if (chart2.timestamps[candlestick//5] == chart3.timestamps[candlestick//30]): # strategy.tick(chart3.data[candlestick//30], "3") #strategy.tick(chart2.data[candlestick//2], "2", float(chart2.highs[candlestick//2]), float(chart2.lows[candlestick//2]), float(chart2.opens[candlestick//2])) if (candlestick == len(self.chart.data) - 1): # self.strategy.last = True #this is so dirty and I feel dirty for doing it #could mess up live run, move highs and lows to masterDick in botstrategy if so if graphics: self.strategy.graph.addLists("1", self.chart.highs, self.chart.lows) end = time.time() print("time taken:",end - begin) print("Candestick Data:",self.chart.data[candlestick]) self.strategy.tick(self.chart.data[candlestick], "1", float(self.chart.highs[candlestick]), float(self.chart.lows[candlestick]), float(self.chart.opens[candlestick]), float(self.chart.timestamps[candlestick])) #maybe run strategy.graph.listadd(params) every iteration-think of other strategies tho ''' self.charts = True strategy.reinit(self.charts) for candlestick in chart2.data: strategy.tick(candlestick, "2") ''' #this is the last chart ''' self.charts = True strategy.reinit(self.charts, chart3.lmaxes, chartlen3, chart3.data, chart3.timestamps) for candlestick in chart3.data: strategy.tick(candlestick) ''' def getstuff(self): return self.strategy.prevPrices, self.strategy.prevma5, self.strategy.prevma5list, self.strategy.prevma15, self.strategy.prevma15list, self.strategy.prevPrevEma, self.strategy.prevEma, self.strategy.prevk, self.strategy.prevfast, self.strategy.prevhighs, self.strategy.prevlows, self.strategy.prevrsi, self.strategy.prevpag, self.strategy.prevpal, self.strategy.prevPriceChg
class Trading_Gui: def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' _compcolor = '#d9d9d9' # X11 color: 'gray85' _ana1color = '#d9d9d9' # X11 color: 'gray85' _ana2color = '#d9d9d9' # X11 color: 'gray85' self.root = root self.style = ttk.Style() self.style.theme_use("vista") self.style.configure('.',background=_bgcolor) self.style.configure('.',foreground=_fgcolor) self.style.configure('.',font="TkDefaultFont") self.style.map('.',background= [('selected', _compcolor), ('active',_ana2color)]) self.strategy= [] self.showChart = False self.startTrading = False self.closeAll= False self.stopRunning= False self.numberOfExecutions= 0 self.numberOfTrades = 0 self.output = BotLog() self.liveChartObject= [] self.CheckVar = IntVar() top.geometry("990x518+446+155") top.title("Trading Gui") top.configure(background="#d9d9d9") self.TFrame1 = ttk.Frame(top) self.TFrame1.place(relx=0.01, rely=0.02, relheight=0.98, relwidth=0.11) self.TFrame1.configure(relief=GROOVE) self.TFrame1.configure(borderwidth="2") self.TFrame1.configure(relief=GROOVE) self.TFrame1.configure(width=95) self.Run = ttk.Button(self.TFrame1, command=self.main) self.Run.place(relx=0.11, rely=0.07, height=35, width=76) self.Run.configure(takefocus="") self.Run.configure(text='''Run''') self.Run.configure(width=76) self.Stop = ttk.Button(self.TFrame1, command=self.stopRun) self.Stop.place(relx=0.11, rely=0.17, height=35, width=76) self.Stop.configure(takefocus="") self.Stop.configure(text='''Stop''') self.Stop.configure(width=76) self.StartTrade = ttk.Button(self.TFrame1, command= self.useStartegy) self.StartTrade.place(relx=0.11, rely=0.27, height=35, width=76) self.StartTrade.configure(takefocus="") self.StartTrade.configure(text='''StartTrade''') self.StartTrade.configure(width=76) self.StopTrade = ttk.Button(self.TFrame1, command=self.stopTrade) self.StopTrade.place(relx=0.11, rely=0.37, height=35, width=76) self.StopTrade.configure(takefocus="") self.StopTrade.configure(text='''StopTrade''') self.StopTrade.configure(width=76) self.ShowChart = ttk.Button(self.TFrame1, command= self.chartOpen) self.ShowChart.place(relx=0.11, rely=0.47, height=35, width=76) self.ShowChart.configure(takefocus="") self.ShowChart.configure(text='''ShowChart''') self.ShowChart.configure(width=76) self.CloseChart = ttk.Button(self.TFrame1, command= self.chartClose) self.CloseChart.place(relx=0.11, rely=0.57, height=35, width=76) self.CloseChart.configure(takefocus="") self.CloseChart.configure(text='''CloseChart''') self.CloseChart.configure(width=76) self.ClosePos = ttk.Button(self.TFrame1, command= self.closeAllPositions) self.ClosePos.place(relx=0.11, rely=0.67, height=35, width=76) self.ClosePos.configure(takefocus="") self.ClosePos.configure(text='''ClosePos''') self.CheckVar.set(1) self.SaveTrades = Checkbutton(self.TFrame1, text="SaveHistory", variable=self.CheckVar, bg=_bgcolor) self.SaveTrades.place(relx=0.11, rely=0.77, height=35, width=80) self.Exit = ttk.Button(self.TFrame1, command= self.CloseWindow) self.Exit.place(relx=0.11, rely=0.9, height=35, width=76) self.Exit.configure(takefocus="") self.Exit.configure(text='''Exit''') self.Exit.configure(width=76) self.TFrame3 = Frame(top) self.TFrame3.place(relx=0.15, rely=0.05, relheight=0.1, relwidth=0.8) self.TFrame3.configure(relief=GROOVE) self.TFrame3.configure(borderwidth="2") self.TFrame3.configure(relief=GROOVE) self.TFrame3.configure(width=475) self.TFrame3.configure(takefocus="0") self.TLabel5 = Label(self.TFrame3) self.TLabel5.place(relx=0.01, rely=0.18, height=19, width=55) self.TLabel5.configure(font=('Helvetica', 8)) self.TLabel5.configure(foreground="#075bb8") self.TLabel5.configure(relief=FLAT) self.TLabel5.configure(text='''Ticker:''') self.ticker = Entry(self.TFrame3) self.ticker.insert(END, str("USDT_BTC")) self.ticker.place(relx=0.07, rely=0.18, relheight=0.44, relwidth=0.09) self.ticker.configure(font=('Helvetica', 10)) self.ticker.configure(background="white") self.ticker.configure(font="TkTextFont") self.ticker.configure(foreground="black") self.ticker.configure(highlightbackground="#d9d9d9") self.ticker.configure(highlightcolor="black") self.ticker.configure(insertbackground="black") self.ticker.configure(selectbackground="#c4c4c4") self.ticker.configure(selectforeground="black") self.ticker.configure(takefocus="0") self.TLabel4 = Label(self.TFrame3) self.TLabel4.place(relx=0.18, rely=0.18, height=19, width=75) self.TLabel4.configure(font=('Helvetica', 8)) self.TLabel4.configure(foreground="#075bb8") self.TLabel4.configure(relief=FLAT) self.TLabel4.configure(text='''StopLossEdge:''') self.StopLossEdge = Entry(self.TFrame3) self.StopLossEdge.insert(END, str(10)) self.StopLossEdge.place(relx=0.28, rely=0.18, relheight=0.44, relwidth=0.09) self.StopLossEdge.configure(font=('Helvetica', 10)) self.StopLossEdge.configure(background="white") self.StopLossEdge.configure(font="TkTextFont") self.StopLossEdge.configure(foreground="black") self.StopLossEdge.configure(highlightbackground="#d9d9d9") self.StopLossEdge.configure(highlightcolor="black") self.StopLossEdge.configure(insertbackground="black") self.StopLossEdge.configure(selectbackground="#c4c4c4") self.StopLossEdge.configure(selectforeground="black") self.StopLossEdge.configure(takefocus="0") self.TLabel5 = Label(self.TFrame3) self.TLabel5.place(relx=0.39, rely=0.2, height=19, width=65) self.TLabel5.configure(font=('Helvetica', 8)) self.TLabel5.configure(foreground="#075bb8") self.TLabel5.configure(relief=FLAT) self.TLabel5.configure(takefocus="0") self.TLabel5.configure(text='''EntryEdge:''') self.EntryEdge = Entry(self.TFrame3) self.EntryEdge.insert(END, str(1)) self.EntryEdge.place(relx=0.47, rely=0.15, relheight=0.44, relwidth=0.09) self.EntryEdge.configure(background="white") self.EntryEdge.configure(font="TkTextFont") self.EntryEdge.configure(foreground="black") self.EntryEdge.configure(highlightbackground="#d9d9d9") self.EntryEdge.configure(highlightcolor="black") self.EntryEdge.configure(insertbackground="black") self.EntryEdge.configure(selectbackground="#c4c4c4") self.EntryEdge.configure(selectforeground="black") self.EntryEdge.configure(takefocus="0") self.TLabel6 = Label(self.TFrame3) self.TLabel6.place(relx=0.58, rely=0.2, height=19, width=85) self.TLabel6.configure(font=('Helvetica', 8)) self.TLabel6.configure(foreground="#075bb8") self.TLabel6.configure(relief=FLAT) self.TLabel6.configure(takefocus="0") self.TLabel6.configure(text='''OpenTradesLimit:''') self.OpenTradesLimit = Entry(self.TFrame3) self.OpenTradesLimit.insert(END, str(4)) self.OpenTradesLimit.place(relx=0.69, rely=0.15, relheight=0.44, relwidth=0.09) self.OpenTradesLimit.configure(background="white") self.OpenTradesLimit.configure(font="TkTextFont") self.OpenTradesLimit.configure(foreground="black") self.OpenTradesLimit.configure(highlightbackground="#d9d9d9") self.OpenTradesLimit.configure(highlightcolor="black") self.OpenTradesLimit.configure(insertbackground="black") self.OpenTradesLimit.configure(selectbackground="#c4c4c4") self.OpenTradesLimit.configure(selectforeground="black") self.OpenTradesLimit.configure(takefocus="0") self.TLabel7 = Label(self.TFrame3) self.TLabel7.place(relx=0.79, rely=0.2, height=19, width=85) self.TLabel7.configure(font=('Helvetica', 8)) self.TLabel7.configure(foreground="#075bb8") self.TLabel7.configure(relief=FLAT) self.TLabel7.configure(takefocus="0") self.TLabel7.configure(text='''Maintenance:''') self.Maintenance = Entry(self.TFrame3) self.Maintenance.insert(END, str(1)) self.Maintenance.place(relx=0.89, rely=0.15, relheight=0.44, relwidth=0.09) self.Maintenance.configure(background="white") self.Maintenance.configure(font="TkTextFont") self.Maintenance.configure(foreground="black") self.Maintenance.configure(highlightbackground="#d9d9d9") self.Maintenance.configure(highlightcolor="black") self.Maintenance.configure(insertbackground="black") self.Maintenance.configure(selectbackground="#c4c4c4") self.Maintenance.configure(selectforeground="black") self.Maintenance.configure(takefocus="0") self.style.configure('Treeview.Heading', font="TkDefaultFont") self.Scrolledtreeview1 = ScrolledTreeView(top) self.Scrolledtreeview1.place(relx=0.15, rely=0.23, relheight=0.28, relwidth=0.6) self.Scrolledtreeview1.configure(columns="Col1 Col2 Col3 Col4 Col5") self.Scrolledtreeview1.configure(takefocus="0") self.Scrolledtreeview1.heading("#0",text="Id") self.Scrolledtreeview1.heading("#0",anchor="center") self.Scrolledtreeview1.column("#0",width="35") self.Scrolledtreeview1.column("#0",minwidth="20") self.Scrolledtreeview1.column("#0",stretch="1") self.Scrolledtreeview1.column("#0",anchor="w") self.Scrolledtreeview1.heading("Col1",text="Time") self.Scrolledtreeview1.heading("Col1",anchor="center") self.Scrolledtreeview1.column("Col1",width="150") self.Scrolledtreeview1.column("Col1",minwidth="20") self.Scrolledtreeview1.column("Col1",stretch="1") self.Scrolledtreeview1.column("Col1",anchor="w") self.Scrolledtreeview1.heading("Col2",text="Symbol") self.Scrolledtreeview1.heading("Col2",anchor="center") self.Scrolledtreeview1.column("Col2",width="80") self.Scrolledtreeview1.column("Col2",minwidth="20") self.Scrolledtreeview1.column("Col2",stretch="1") self.Scrolledtreeview1.column("Col2",anchor="w") self.Scrolledtreeview1.heading("Col3",text="Side") self.Scrolledtreeview1.heading("Col3",anchor="center") self.Scrolledtreeview1.column("Col3",width="80") self.Scrolledtreeview1.column("Col3",minwidth="20") self.Scrolledtreeview1.column("Col3",stretch="1") self.Scrolledtreeview1.column("Col3",anchor="w") self.Scrolledtreeview1.heading("Col4",text="Price") self.Scrolledtreeview1.heading("Col4",anchor="center") self.Scrolledtreeview1.column("Col4",width="80") self.Scrolledtreeview1.column("Col4",minwidth="20") self.Scrolledtreeview1.column("Col4",stretch="1") self.Scrolledtreeview1.column("Col4",anchor="w") self.Scrolledtreeview1.heading("Col5",text="Pnl") self.Scrolledtreeview1.heading("Col5",anchor="center") self.Scrolledtreeview1.column("Col5",width="80") self.Scrolledtreeview1.column("Col5",minwidth="20") self.Scrolledtreeview1.column("Col5",stretch="1") self.Scrolledtreeview1.column("Col5",anchor="w") self.menubar = Menu(top,font="TkMenuFont",bg='#bef7bb',fg=_fgcolor) top.configure(menu = self.menubar) self.Scrolledtreeview2 = ScrolledTreeView(top) self.style.configure("Scrolledtreeview2", font='helvetica 24') self.Scrolledtreeview2.place(relx=0.15, rely=0.61, relheight=0.32, relwidth=0.8) self.Scrolledtreeview2.configure(columns="Col1 Col2 Col3 Col4 Col5 Col6 Col7") self.Scrolledtreeview2.configure(takefocus="0") self.Scrolledtreeview2.heading("#0", text="Id") self.Scrolledtreeview2.heading("#0", anchor="center") self.Scrolledtreeview2.column("#0", width="35") self.Scrolledtreeview2.column("#0", minwidth="20") self.Scrolledtreeview2.column("#0", stretch="1") self.Scrolledtreeview2.column("#0", anchor="w") self.Scrolledtreeview2.heading("Col1", text="EntryTime") self.Scrolledtreeview2.heading("Col1", anchor="center") self.Scrolledtreeview2.column("Col1", width="150") self.Scrolledtreeview2.column("Col1", minwidth="20") self.Scrolledtreeview2.column("Col1", stretch="1") self.Scrolledtreeview2.column("Col1", anchor="w") self.Scrolledtreeview2.heading("Col2", text="ExitTime") self.Scrolledtreeview2.heading("Col2", anchor="center") self.Scrolledtreeview2.column("Col2", width="150") self.Scrolledtreeview2.column("Col2", minwidth="20") self.Scrolledtreeview2.column("Col2", stretch="1") self.Scrolledtreeview2.column("Col2", anchor="w") self.Scrolledtreeview2.heading("Col3", text="Symbol") self.Scrolledtreeview2.heading("Col3", anchor="center") self.Scrolledtreeview2.column("Col3", width="81") self.Scrolledtreeview2.column("Col3", minwidth="20") self.Scrolledtreeview2.column("Col3", stretch="1") self.Scrolledtreeview2.column("Col3", anchor="w") self.Scrolledtreeview2.heading("Col4", text="Side") self.Scrolledtreeview2.heading("Col4", anchor="center") self.Scrolledtreeview2.column("Col4", width="80") self.Scrolledtreeview2.column("Col4", minwidth="20") self.Scrolledtreeview2.column("Col4", stretch="1") self.Scrolledtreeview2.column("Col4", anchor="w") self.Scrolledtreeview2.heading("Col5", text="EntryPrice") self.Scrolledtreeview2.heading("Col5", anchor="center") self.Scrolledtreeview2.column("Col5", width="80") self.Scrolledtreeview2.column("Col5", minwidth="20") self.Scrolledtreeview2.column("Col5", stretch="1") self.Scrolledtreeview2.column("Col5", anchor="w") self.Scrolledtreeview2.heading("Col6", text="ExitPrice") self.Scrolledtreeview2.heading("Col6", anchor="center") self.Scrolledtreeview2.column("Col6", width="80") self.Scrolledtreeview2.column("Col6", minwidth="20") self.Scrolledtreeview2.column("Col6", stretch="1") self.Scrolledtreeview2.column("Col6", anchor="w") self.Scrolledtreeview2.heading("Col7", text="Pnl") self.Scrolledtreeview2.heading("Col7", anchor="center") self.Scrolledtreeview2.column("Col7", width="80") self.Scrolledtreeview2.column("Col7", minwidth="20") self.Scrolledtreeview2.column("Col7", stretch="1") self.Scrolledtreeview2.column("Col7", anchor="w") self.Label1 = Label(top) self.Label1.place(relx=0.15, rely=0.17, height=25, width=595) self.Label1.configure(font=('Helvetica', 10)) self.Label1.configure(anchor=N) self.Label1.configure(background="#b4c2fe") self.Label1.configure(compound="left") self.Label1.configure(cursor="bottom_left_corner") self.Label1.configure(disabledforeground="#a3a3a3") self.Label1.configure(foreground="#000000") self.Label1.configure(justify=LEFT) self.Label1.configure(relief=RIDGE) self.Label1.configure(text='''Opened Positions''') self.Label1.configure(textvariable=test_support) self.Label1.configure(width=459) self.Label2 = Label(top) self.Label2.place(relx=0.15, rely=0.55, height=25, width=788) self.Label2.configure(font=('Helvetica', 10)) self.Label2.configure(activebackground="#f9f9f9") self.Label2.configure(activeforeground="black") self.Label2.configure(anchor=N) self.Label2.configure(background="#b4c2fe") self.Label2.configure(compound="left") self.Label2.configure(cursor="bottom_left_corner") self.Label2.configure(disabledforeground="#a3a3a3") self.Label2.configure(foreground="#000000") self.Label2.configure(highlightbackground="#d9d9d9") self.Label2.configure(highlightcolor="black") self.Label2.configure(justify=LEFT) self.Label2.configure(relief=RIDGE) self.Label2.configure(text='''Trades''') self.Label2.configure(width=459) self.TFrame2 = Frame(top) self.TFrame2.place(relx=0.76, rely=0.23, relheight=0.22, relwidth=0.2) self.TFrame2.configure(relief=SUNKEN) self.TFrame2.configure(borderwidth="2") self.TFrame2.configure(relief=SUNKEN) self.TFrame2.configure(width=150) self.TFrame2.configure(takefocus="0") self.TotalPnl = Label(self.TFrame2) self.TotalPnl.place(relx=0.002, rely=0.17, height=29, width=86) self.TotalPnl.configure(font=('Helvetica', 11)) self.TotalPnl.configure(foreground="#075bb8") self.TotalPnl.configure(relief=FLAT) self.TotalPnl.configure(justify=RIGHT) self.TotalPnl.configure(takefocus="0") self.TotalPnl.configure(text='''TotalPnl:''') self.TradesCount = Label(self.TFrame2) self.TradesCount.place(relx=0.01, rely=0.63, height=29, width=106) self.TradesCount.configure(font=('Helvetica', 11)) self.TradesCount.configure(foreground="#075bb8") self.TradesCount.configure(relief=FLAT) self.TradesCount.configure(justify=RIGHT) self.TradesCount.configure(takefocus="0") self.TradesCount.configure(text='''TradesCount:''') self.tradesCount = Text(self.TFrame2) self.tradesCount.configure(font=('Helvetica', 10)) self.tradesCount.place(relx=0.52, rely=0.6, relheight=0.3, relwidth=0.4) self.tradesCount.configure(font=('Helvetica', 10)) self.tradesCount.configure(background="white") self.tradesCount.configure(font="TkTextFont") self.tradesCount.configure(foreground="black") self.tradesCount.configure(highlightbackground="#d9d9d9") self.tradesCount.configure(highlightcolor="black") self.tradesCount.configure(insertbackground="black") self.tradesCount.configure(selectbackground="#c4c4c4") self.tradesCount.configure(selectforeground="black") self.tradesCount.configure(takefocus="0") self.tradesCount.configure(width=104) self.totalPnl = Text(self.TFrame2, font= ('Times', '24', 'bold italic') ) self.totalPnl.place(relx=0.52, rely=0.1, relheight=0.3, relwidth=0.4) self.totalPnl.configure(font=('Helvetica', 10)) self.totalPnl.configure(background="white") self.totalPnl.configure(font="TkTextFont") self.totalPnl.configure(foreground="black") self.totalPnl.configure(highlightbackground="#d9d9d9") self.totalPnl.configure(highlightcolor="black") self.totalPnl.configure(insertbackground="black") self.totalPnl.configure(selectbackground="#c4c4c4") self.totalPnl.configure(selectforeground="black") self.totalPnl.configure(takefocus="0") self.totalPnl.configure(width=104) def stopRun(self): self.root.update() self.stopRunning= True self.output.log(crayons.red("System stop..........")) def CloseWindow(self) : self.root.destroy() def chartOpen(self) : self.liveChartObject = botChart() self.root.update() self.showChart= True def chartClose(self) : self.root.update() self.showChart= False plt.close() def useStartegy(self) : self.root.update() self.startTrading= True self.stopRunning= False self.output.log(crayons.green("Start trading..........")) def stopTrade(self) : self.root.update() try: opPos= self.strategy.openedPositions except: opPos= [] if len(opPos)>0: messagebox.showinfo("Warning", "There are opened position. Close all before stopping trading!") else: self.startTrading = False self.output.log(crayons.green("End trading..........")) def closeAllPositions(self) : self.root.update() self.closeAll = True def insertDataExecutions(self, executions): n= len(executions) if n>self.numberOfExecutions: newExecutions= executions[-(n-self.numberOfExecutions):] k= n for row in newExecutions: self.Scrolledtreeview1.insert('', 'end', text=str(k),\ values=( str(row[0]).split(" ")[-1], row[1], row[3], round(row[2],2), round(row[4],3))) k= k+1 self.numberOfExecutions= n def insertDataTrades(self, trades): n= len(trades) if n>self.numberOfTrades: newTrades= trades[-(n-self.numberOfTrades):] k= self.numberOfTrades for row in newTrades: self.Scrolledtreeview2.insert('', 'end', text=str(k),\ values=( str(row[0]).split(" ")[-1], str(row[1]).split(" ")[-1], row[2], \ row[5], round(row[3],2), round(row[4],2), round(row[6],3))) k= k+1 self.numberOfTrades= n def insertOpenData(self, openedPositions): self.Scrolledtreeview1.delete(*self.Scrolledtreeview1.get_children()) for i,row in enumerate(openedPositions): self.Scrolledtreeview1.insert('', 'end', text=str(i),\ values=( str(row[0]).split(" ")[-1], row[1], \ row[2], round(row[3], 2), round(row[4], 2)), tags=('new')) def saveTradeHistory(self, strategy): if self.CheckVar: data= strategy.showExecutions() if len(data)>0: data.to_csv("TradingHistory.csv", index=False) else: with open("TradingHistory.csv", 'w'): pass def main(self): period = 10 pair = "USDT_BTC" lengthMA = 50 error=False self.stopRunning= False self.numberOfTrades= 0 try: data = BotGetData(pair, period) historical = data.historicalData except Exception as e: historical = [] messagebox.showinfo("Error", e) error= True try: stopLossEdge= float(self.StopLossEdge.get()) except: messagebox.showinfo("Error", "Wrong StopLoss input. Must be integer.") error= True try: entryEdge= float(self.EntryEdge.get()) entryEdge= 0 except: messagebox.showinfo("Error", "Wrong StopLoss input. Must be numeric.") error= True try: openPosLimit= int(self.OpenTradesLimit.get()) if openPosLimit<=0: messagebox.showinfo("Error", "Wrong openPosLimit input. Must be integer>0.") openPosLimit= 1 except: messagebox.showinfo("Error", "Wrong openPosLimit input. Must be integer.") error= True try: timePosEdge= int(self.Maintenance.get()) if timePosEdge<0: messagebox.showinfo("Error", "Wrong Maintenance input. Must be integer>=0.") timePosEdge= 1 except: messagebox.showinfo("Error", "Wrong Maintenance input. Must be integer.") error= True if not error: prices = historical.Price.tolist() if (len(historical) > lengthMA): prices = prices[-lengthMA:] else: print("Not enough historical data for MA=" + str(lengthMA)) lengthMA = len(prices) self.strategy = BotStrategy(prices=prices, pair=pair, lengthMA=lengthMA, \ openPosLimit=openPosLimit, stopLossEdge=stopLossEdge, \ entryEdge=entryEdge, timePosEdge=timePosEdge) while True: try: if self.stopRunning: self.startTrading = False self.saveTradeHistory(strategy=self.strategy) self.Scrolledtreeview1.delete(*self.Scrolledtreeview1.get_children()) self.Scrolledtreeview2.delete(*self.Scrolledtreeview2.get_children()) self.strategy.closeAll() self.strategy.clearExecutions() break data.updateData() lastPairPrice = data.lastPrice prices.append(lastPairPrice) prices = prices[-lengthMA:] self.strategy.tick(lastPairPrice, self.startTrading) executions = self.strategy.allExecutions.execData trades = self.strategy.allTrades.tradesData histDataUpdated = chartHorizon(histDataUpdated=data.historicalData, interval=15) openedPositions= self.strategy.openedPositions self.insertDataTrades(trades) self.insertOpenData(openedPositions) self.tradesCount.delete(1.0, END) self.tradesCount.insert(END, str(len(trades))) self.totalPnl.delete(1.0, END) self.totalPnl.insert(END, str(round(self.strategy.totalPnl,1))) if self.closeAll: self.strategy.closeAll() self.saveTradeHistory(strategy=self.strategy) if self.showChart: self.liveChartObject.botLiveChart(x=histDataUpdated.Date, y=histDataUpdated.Price, \ tradesLive=executions, lastTradePnl=self.strategy.lastTradePnl, \ totalPnl=self.strategy.totalPnl, percentChange=data.percentChange) self.root.update() except Exception as e: messagebox.showinfo("Error", str(e)) self.strategy.closeAll() self.saveTradeHistory(strategy=self.strategy) break
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): global period global pair global startTime global endTime global totalBalance global liveTrading global environment global chart global strat global cont global trained_mcl output.log("------------STARTING BACKTESTER------------") # Handle all the incoming arguments try: opts, args = getopt.getopt(argv, "hp:c:s:e:b:v:u:l:", ["period=", "currency="]) except getopt.GetoptError: try: opts, args = getopt.getopt(argv, "r") except: print( 'backtest.py -p <period length> -c <currency pair> -s <start time> -e <end time> -u <strategy> -b <balance> -v <environment> -l <live>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'backtest.py -p <period length> -c <currency pair> -s <start time> -e <end time> -u <strategy> -b <balance> -v <environment> -l <live>' ) sys.exit() elif opt in ("-p", "--period"): if (int(arg) in [30, 300, 900, 1800, 7200, 14400, 86400]): period = int(arg) else: print( 'Poloniex requires periods in 300 (5mins),900 (15),1800 (30),7200 (2hr),14400(4hr), or 86400(24hr) second increments' ) sys.exit(2) elif opt in ("-s"): startTime = DateHelper.ut( datetime.datetime.strptime(arg, '%d/%m/%Y')) if "/" in arg else arg elif opt in ("-r"): cont = True elif opt in ("-v"): environment = arg elif opt in ("-e"): endTime = DateHelper.ut(datetime.datetime.strptime( arg, '%d/%m/%Y')) if "/" in arg else arg elif opt in ("-b"): totalBalance = int(arg) elif opt in ("-l"): liveTrading = True if int(arg) == 1 else False elif opt in ("-c"): if arg in currencies: pair = arg else: print("incorrect pair") sys.exit() elif opt in ("-u"): if len( list( set([str(i + 1) for i in range(numberOfStrats)]) & set(str(arg).split(',')))) > 0: strat = arg else: print("Bad strat params") sys.exit() # Instanstiate GUI for results createIndex = CreateIndex(environment) if not liveTrading and cont == False: #============================================================================== # [factor, lower limit, higher limit, step] is the format #============================================================================== # trialDetails = [['trailingstop',0,0.3,0.15],['maFactor',1,1.05,0.025],['lowMA',15,17,1],['highMA',35,55,10]] # trialDetails= [['stoplossDayCount', 0*86400/period, 30*86400/period, 5*86400/period],['stoploss', 0, 0.25, 0.05]] trialDetails = [['howSimReq', 0.87, 0.87, 0.01], ['lookback-mc', 9, 9, 1]] # trialDetails = [['highRSI',60,80,2],['lowRSI',20,40,2],['stoploss',0,0.4,0.04],['rsiperiod',10,20,2]] # trialDetails = [['upfactor',1,1.1,0.02],['downfactor',1,1.1,0.02],['lookback',28,40,1]] global total total = 1 for i in trialDetails: add = ((i[2] - i[1]) / i[3]) if isclose(add, round(add)): # fix this total *= (add + 1) else: print("bad params") sys.exit(2) performTrial(trialDetails, len(trialDetails), np.zeros(len(trialDetails))) output.logTrials(trialDetails, trialResults) # N dimensional views botgrapher.heatmap(trialResults) # 2 dimensional views if len(trialDetails) == 2: botgrapher.graph(trialResults) createIndex.CreatePages() else: trades = [] if cont == False: strategyDetails = {'howSimReq': 0.9, "lookback-mc": 7} param_to_store = strategyDetails param_to_store['strategy'] = strat param_to_store['pair'] = pair param_to_store['period'] = period functions.mysql_conn.storeAllParameters(param_to_store) else: strategyDetails = functions.mysql_conn.getAllParameters() stats = functions.mysql_conn.getStatistics() totalBalance = stats['balance'] trades = functions.mysql_conn.getAllOpenTrades() strat = strategyDetails['strategy'] pair = strategyDetails['pair'] period = int(strategyDetails['period']) del strategyDetails['strategy'] del strategyDetails['pair'] del strategyDetails['period'] if 'running_time' in stats: strategyDetails['running_time'] = stats['running_time'] print(strategyDetails) chart = BotChart(functions, pair) if (strat == "4"): print("Pretraining STARTED") learnProgTotal = 1400 if not 'learnProgTotal' in strategyDetails else strategyDetails[ 'learnProgTotal'] if (endTime == ""): endTime = DateHelper.ut(datetime.datetime.now()) if (startTime == ""): startTime = endTime - period * (learnProgTotal + 100) print("training from ~{} to {}".format(DateHelper.dt(startTime), DateHelper.dt(endTime))) chart.getHistorical(period, startTime, endTime) trainingSet = chart.getPoints() mcl = MachineStrat(strat, strategyDetails) trained_mcl = mcl.train( trainingSet["weightedAverage"][:learnProgTotal + 30]) lookback = 7 if not 'lookback-mc' in strategyDetails else int( strategyDetails['lookback-mc']) print("Pretraining finished") strategy = BotStrategy(period, functions, totalBalance, 0, strategyDetails, strat, trained_mcl, trades) if strat == "4": for index, candlestick in trainingSet[-lookback - 1:].iterrows(): strategy.tick(candlestick, True) while True: date = datetime.datetime.now() while ((date.hour % 4 == 0 and date.minute > 30) or (date.hour % 4 == 1 and date.minute < 25)) == False: date = datetime.datetime.now() print('checking for appropriate start time', date) time.sleep(60 * 5) start = time.time() currTick = dict(chart.getNext()) currTick['date'] = str(DateHelper.ut(datetime.datetime.now())) strategy.tick(currTick) createIndex.CreatePages() print('{}: Sleeping ...'.format(currTick['date'])) end = time.time() if int(period) - (end - start) > 0: time.sleep(int(period) - (end - start)) else: print("Calculation took too long. Continuing to next tick...")
#import sys, getopt from botchart import BotChart from botstrategy import BotStrategy # Select chart on which we want to backtest the strategy chart = BotChart("poloniex","BTC_XMR",300) # print first value of the timeseries print chart.getPoints()[0] # define Bot Strategy strategy = BotStrategy() # Apply strategy for candlestick in chart.getPoints(): strategy.tick(candlestick)
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