Exemple #1
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))
Exemple #2
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))
Exemple #3
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))
Exemple #4
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))
Exemple #5
0
def main(argv):
    chart = LiveBotChart()
    strategy = BotStrategy(50)
    strategy.candlesticks = chart.preliminaryCandlesticks()
    developingCandlestick = BotCandlestick()

    while True:
        try:
            developingCandlestick.tick(chart.getCurrentPrice())
        except urllib2.URLError:
            time.sleep(1)
            developingCandlestick.tick(chart.getCurrentPrice())

        if developingCandlestick.isClosed():
            strategy.candlesticks.append(developingCandlestick)
            strategy.evaluatePositions()
            developingCandlestick = BotCandlestick()

        time.sleep(1)
Exemple #6
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))
Exemple #7
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))
Exemple #8
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))
Exemple #9
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))
Exemple #10
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))
Exemple #11
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
Exemple #12
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))
Exemple #13
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()
Exemple #14
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'])
Exemple #15
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