Beispiel #1
0
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))
Beispiel #2
0
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(argv):
	chart = BotChart("poloniex","BTC_XMR",300)

	strategy = BotStrategy()

	for candlestick in chart.getPoints():
		strategy.tick(candlestick)
Beispiel #4
0
def main(argv):
    # chart = BotChart("poloniex","BTC_ETH",1800,'2018-01-01 14:00:00','2018-03-12 20:53:20')

    pair = "USDT_ETH"
    debut = '2016-11-02 14:00:00'
    fin = '2018-08-14 20:53:20'
    period = 14400

    chart = BotChart("poloniex", pair, period, debut, fin)

    # on va stocker les bougies de period 5mn, 15mn, et 1 jour
    # chart_m5 = BotChart("poloniex",pair,900,debut,fin)
    # chart_m15 = BotChart("poloniex",pair,1800,debut,fin)
    # chart_d1 = BotChart("poloniex",pair,86400,debut,fin)
    # strategy = stratStochastique(chart_m5,chart_m15,chart_d1)

    strategy = stratRsi(period)
    # strategy = stratRsi2()

    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
Beispiel #5
0
def main(argv):
    showTradeDetails = False
    startingBal = 100
    endTime = time.time()
    startTime = endTime - 3600 * 24 * 2
    period = 900  # period values can be 300, 900, 1800, 7200, 14400, and 86400
    usdtPairs = ["USDT_REP", "BTC_REP"]
    btcPairs = [
        "USDT_BCH", "USDT_BTC", "USDT_DASH", "USDT_ETC", "USDT_ETH",
        "USDT_LTC", "USDT_NXT", "USDT_REP", "USDT_STR", "USDT_XMR", "USDT_XRP",
        "USDT_ZEC", "BTC_REP", "BTC_XMR"
    ]

    pairs = btcPairs
    for pair in pairs:
        chart = BotChart(pair, period, endTime, startTime)
        strategy = BotStrategy(startingBal)

        i = 0
        for candlestick in chart.getPoints():
            strategy.candlesticks.append(candlestick)
            if i > 24:
                strategy.evaluatePositions()
            i += 1

        strategy.showPositions(startingBal, showTradeDetails)
        print("Start: " + time.strftime('%m/%d/%Y %H:%M:%S',
                                        time.localtime(chart.startTime)))
        print(
            "End  : " +
            time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(chart.endTime)))
        print("Currency: " + chart.pair)
Beispiel #6
0
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))
Beispiel #7
0
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))
Beispiel #8
0
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))
Beispiel #9
0
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')
Beispiel #10
0
def main(argv):

    start_time = time.time()

    pairs = ["USDT_BTC"]  #, "USDT_ETH", "USDT_LTC"]
    exchanges = ["poloniex"]
    charts = []
    strategies = []
    #modes = ["RSI", "BBAND", "MACD", "ALL"]
    #modes = ["RSI", "BBAND", "MACD"]
    modes = ["MACD"]

    for pair in pairs:
        for exchange in exchanges:
            charts.append(BotChart(exchange, pair, 1800))
            for mode in modes:
                strategies.append(
                    BotStrategy(exchange + '-' + pair, mode, 10, 10000, 0,
                                1000, 0.01, 0.1, True))
                # Parameters: max trades, initial fiat, initial holding, trade amount, stop loss, target

    for i, chart in enumerate(charts):
        for j, mode in enumerate(modes):
            strategy = strategies[len(modes) * i + j]
            for candlestick in chart.getPoints():
                candlestick['priceAverage'] = candlestick['weightedAverage']
                strategy.tick(candlestick)

            strategy.showProfit()
            strategy.showPositions()
            strategy.drawGraph()

    print("\n--- %s seconds ---" % (time.time() - start_time))
Beispiel #11
0
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):

    start_time = time.time()

    pairs = ["USDT_BTC", "USDT_ETH", "USDT_LTC"]
    exchanges = ["poloniex"]
    charts = []

    for pair in pairs:
        for exchange in exchanges:
            charts.append(BotChart(exchange, pair, 1800))

    portfolio_head = ['pair', 'allocation', 'value']
    portfolio_allocation = ['USDT_BTC', 50, 400], ['USDT_ETH', 30,
                                                   300], ['USDT_LTC', 20, 180]
    portfolio = []

    for p in portfolio_allocation:
        portfolio.append(dict(zip(portfolio_head, p)))

    print('portfolio:', portfolio)
    rebal = needReBalance(portfolio)
    print('Needs rebalance?', rebal)
    if rebal:
        print(reBalance(portfolio))

    chart_zip = zip(charts)

    for c in charts:
        print(c['weightedAverage'])

    exit()
    #for c in charts:
    for candlestick in zip(charts.getPoints()):
        print(candlestick['weightedAverage'])

    exit()

    for charts[0], charts[1], charts[2] in zip(charts[0], charts[1],
                                               charts[2]):
        print(float(charts[0].getpoint()['weightedAverage']))
        print(float(charts[1].getpoint()['weightedAverage']))
        print(float(charts[2].getpoint()['weightedAverage']))

    exit()

    for i, chart in enumerate(charts):
        for candlestick in chart.getPoints():
            tick(portfolio, candlestick)

    print("\n--- %s seconds ---" % (time.time() - start_time))
Beispiel #13
0
def main(argv):
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument("-p",
                            "--period",
                            help="Period length in seconds, 14400 by default",
                            type=int,
                            choices=[7200, 14400, 86400],
                            default=7200)
        parser.add_argument("-c",
                            "--currency",
                            help="Currency pair | Ex: BTC_ETH",
                            default='BTC_ETH')
        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')
        args = vars(parser.parse_args())
    except:
        print("ArgumentParser Error type -h for help")
        sys.exit(2)

    pair = args["currency"]
    period = args["period"]
    debut = args['start']
    fin = args['end']
    chart = BotChart("poloniex", pair, period, debut, fin)
    strategy = SLSTM.SLSTM()
    for candlestick in chart.get_points():
        strategy.tick(candlestick)
    graphe = PlotGraphe(chart, strategy)
    graphe.plotChart()
    print("Result = " + str(strategy.get_result()) + " BTC")
    try:
        sigma = chart.getSigma() * float(chart.compteur)**0.5
        perf = graphe.perf
        sharpe_ratio = perf / sigma
        print("\n Performance: " + str(perf))
        print("\n Ratio de Sharpe: " + str(sharpe_ratio) + "\n")
    except Exception as e:
        pass
Beispiel #14
0
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")
Beispiel #15
0
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()
Beispiel #16
0
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))
Beispiel #17
0
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))
Beispiel #18
0
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
Beispiel #19
0
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))
Beispiel #20
0
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))
Beispiel #21
0
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'])
Beispiel #22
0
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()
Beispiel #23
0
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 warnings
with warnings.catch_warnings():
    warnings.filterwarnings('ignore', category=FutureWarning)
    import numpy as np
    from botchart import BotChart
    from keras.models import load_model
    from keras.models import Sequential
    from keras.layers import Dense
    from keras.layers import LSTM
    from keras.layers import Dropout
    import matplotlib
    import matplotlib.pyplot as plt

# Data preprocessing : scaling, reshaping
chart = BotChart('poloniex', 'BTC_ETH', 7200, '2014-11-02 14:00:00',
                 '2016-12-14 20:53:20')
list_opens = []
list
for val in chart.data:
    list_opens.append(val.open)
test_size = int(0.1 * len(list_opens))
opens = (np.array(list_opens)).reshape(-1, 1)
timestep = 60

x_train = []
y_train = []
for i in range(timestep, len(opens) - test_size):
    x_train.append(opens[i - timestep:i])
    y_train.append(opens[i])

x_train, y_train = np.array(x_train), np.array(y_train)
Beispiel #25
0
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))
Beispiel #26
0
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
Beispiel #27
0
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))
#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)
Beispiel #29
0
    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
        '''