示例#1
0
def load_BT_options(argv):
	'''
	funcion que carga opciones de usuario
	'''
	currencyPair, start, end = "BTC_DGB","2017-06-01 00:00:00","2017-06-01 00:00:00"
	period, strategy = 3600*4,"EMAvsSMA"
	try:
		opts, args = getopt.getopt(argv,"hp:c:n:s:e:f:s:",["period=","currency=","points="])
	except getopt.GetoptError:
		print ' Error trading-bot.py -p <period length> -c <currency pair> -s <start time> -e <end time> --> "YYYY:MM:DD hh:mm:ss"\
		 -f <input file bot.inp> -s <back testing strategy>'
		sys.exit(2)
	
	for opt, arg in opts:
		if opt == '-h':
			print 'trading-bot.py -p <period length> -c <currency pair> -s <start time> -e <end time> --> "YYYY:MM:DD hh:mm:ss"\
		 -f <input file> -s <back testing strategy>'
			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"):
			currencyPair = arg
		elif opt in ("-n", "--points"):
			lengthOfMA = int(arg)
		elif opt in ("-i"):
			ts = string2ts(arg)
			start = str(ts)
		elif opt in ("-e"):
			ts = string2ts(arg)
			end = str(ts)
		elif opt in ("-f"):
			dic = {}
			inputFile = open(arg).readlines()
			
			for line in inputFile:
			  if line != ['']:
				k = line.split('=')
				dic[k[0].strip()] = k[1].strip().strip('\n')
			currencyPair = dic["currencyPair"]
			start = string2ts(dic["start"])
			end = string2ts(dic["end"])
			period = int(dic["period"])
			strategy = dic["strategy"]
		elif opt in ("-s"):
			strategy = arg
	if len(opts) == 0:
		print "No proporcionó opciones. Se tomarán las predeterminadas."
	return currencyPair, start, end, period, strategy
示例#2
0
def load_PT_options(argv):
    '''
    funcion que carga opciones de usuario de paper trading
    '''
    currencyPair, start, end = "BTC_DGB","2017-06-01 00:00:00","2017-06-01 00:00:00"
    period, strategy = 300,"EMAvsSMA"
    try:
        opts, args = getopt.getopt(argv,"hp:c:n:s:e:f:s:",["period=","currency=","points="])
    except getopt.GetoptError:
        print '\t Error paperBot.py. The valid option are:\n -p <period length> -c <currency pair> -s <strategy> -h <help>'
        sys.exit(2)
    
    for opt, arg in opts:
        if opt == '-h':
            print 'paperBot.py -p <period length> -c <currency pair> -s <strategy>'
            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"):
            currencyPair = arg
        elif opt in ("-n", "--points"):
            lengthOfMA = int(arg)
        elif opt in ("-i"):
            ts = string2ts(arg)
            start = str(ts)
        elif opt in ("-e"):
            ts = string2ts(arg)
            end = str(ts)
        elif opt in ("-f"):
            dic = {}
            inputFile = open(arg).readlines()
            
            for line in inputFile:
              if line != ['']:
                k = line.split('=')
                dic[k[0].strip()] = k[1].strip().strip('\n')
            currencyPair = dic["currencyPair"]
            period = int(dic["period"])
            strategy = dic["strategy"]
        elif opt in ("-s"):
            strategy = arg
    if len(opts) == 0:
        print "\n\tYou did not provide options. The default ones will be assumed.\n"
        print "paperBot.py -p <period length> -c <currency pair> -s <strategy>"
    return currencyPair, period, strategy
示例#3
0
def prepareLiveData(pair="DGB_BTC",
                    start=string2ts("2017-06-01 00:00:00"),
                    end=string2ts("2017-09-01 00:00:00"),
                    period=3600 * 4):
    """
    funcion que trae los datos y 
    los devuleve en dataframe de pandas
    """

    from poloniex import Poloniex
    #import json
    #import pylab as plt

    poloKeys = open("../.kp").readlines()
    polo = Poloniex(poloKeys[0].strip(), poloKeys[1].strip())
    #print conn.returnBalances()['BTC']
    #polo = Poloniex()
    # historyData es una lista de diccionarios python
    # candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400
    historyData = polo.returnChartData(currencyPair=pair,
                                       start=start,
                                       end=end,
                                       period=period)

    # convirtiendo datos en data frame
    df = pd.DataFrame(historyData)

    #  convirtiendo string a float o int
    df["close"] = pd.to_numeric(df['close'])
    df["open"] = pd.to_numeric(df['open'])
    df["low"] = pd.to_numeric(df['low'])
    df["volume"] = pd.to_numeric(df['volume'])
    df["date"] = pd.to_datetime(df["date"].apply(ts2string))
    df['weightedAverage'] = pd.to_numeric(df['weightedAverage'])
    df['high'] = pd.to_numeric(df['high'])
    df['open'] = pd.to_numeric(df['open'])

    # calculando volatilidad en función del tamaño de las velas
    df["volatility"] = makeVolatility(df)

    # seleccionando la columna de fecha como indice
    df = df.set_index("date")

    return df, polo
示例#4
0
    def prepareData(self):
        """Trae el dataframe y el objeto poloniex correspondiente"""

        # definiendo end como la hora local actual
        self.tf = datetime.now()
        # convirtiendola a formato unix time (es equivalente a UTC)
        self.end = string2ts(self.tf.strftime('%Y-%m-%d %H:%M:%S'))

        # definiendo el tiempo inicial de la consulta
        self.to = self.tf-self.delta*self.len_data
        self.start = string2ts(self.to.strftime('%Y-%m-%d %H:%M:%S'))

        # trayendo y preparando datos
        self.df, self.polo = prepareLiveData(pair=self.pair, start=self.start,
                                             end=self.end, period=int(self.period))

        # fecha del último dato disponible
        self.tt = self.df.index[-1]
        # delay entre el tiempo actual y el último dato disponible
        self.de = self.tf - self.tt
示例#5
0
def prepareData(pair="DGB_BTC", start=string2ts("2017-06-01 00:00:00"), 
                 end=string2ts("2017-09-01 00:00:00"), period=3600*4):
	
	"""
	funcion que trae los datos y 
	los devuleve en dataframe de pandas
	"""

	from poloniex import Poloniex
	import json
	#import pylab as plt
	
	
	polo = Poloniex()

	# historyData es una lista de diccionarios python
	# candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400
	historyData = polo.returnChartData(currencyPair=pair,
						 start=start,
						 end=end,
						 period=period)

	# convirtiendo datos en data frame
	df = pd.DataFrame(historyData)

	#  convirtiendo string a float o int
	df["close"] =pd.to_numeric(df['close'])
	df["open"] =pd.to_numeric(df['open'])
	df["low"] =pd.to_numeric(df['low'])
	df["volume"] =pd.to_numeric(df['volume'])
	df["date"] = pd.to_datetime(df["date"].apply(ts2string))
	df['weightedAverage'] = pd.to_numeric(df['weightedAverage'])
	df['high'] = pd.to_numeric(df['high'])
	df['open'] = pd.to_numeric(df['open'])

	# seleccionando la columna de fecha como indice
	df = df.set_index("date")
	
	return df
示例#6
0
def load_PT_options(argv):
    '''
    funcion que carga opciones de usuario de paper trading
    '''
    pair, gain_rate, lose_rate, period = "BTC_DGB", 0.02, 0.01, 1
    try:
        opts, args = getopt.getopt(
            argv, "h:p:c:g:l:e:f:s:",
            ["period=", "currency=", "gain_rate=", "lose_rate="])
    except getopt.GetoptError:
        print '\t Error paperBot.py. The valid option are:\n -p <period length> -c <currency pair> -g <gain_rate> -l <lose_rate> -h <help>'
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print 'HFT_paperBot.py -c <currency pair> -p <period> -g <gain rate> -l <lose rate>'
            sys.exit()
        elif opt in ("-p", "--period"):
            period = arg
        elif opt in ("-c", "--currency"):
            pair = arg
        elif opt in ("-g", "--gain_rate"):
            gain_rate = float(arg)
        elif opt in ("-l", "--lose_rate"):
            lose_rate = float(arg)
        elif opt in ("-e"):
            ts = string2ts(arg)
            end = str(ts)
        elif opt in ("-f"):
            dic = {}
            inputFile = open(arg).readlines()

            for line in inputFile:
                if line != ['']:
                    k = line.split('=')
                    dic[k[0].strip()] = k[1].strip().strip('\n')
            currencyPair = dic["currencyPair"]
        elif opt in ("-s"):
            strategy = arg
    if len(opts) == 0:
        print "\n\tYou did not provide options. The default ones will be assumed.\n"
        print 'HFT_paperBot.py -c <currency pair> -p <period> -g <gain rate> -l <lose rate>'
    return pair, gain_rate, lose_rate, period
示例#7
0
def paper(pair, period, strategy, weight):
    """
    Traer los datos en vivo y devuelve SELL, WAIT o BUY,
    según la estrategia que se escoja    
    """

    # funciones necesarias para el manejo del tiempo
    from datetime import datetime, timedelta
    from time import sleep

    # en esta lista deben guardarse los nombres de todas las estrategias
    # de machine learning en strategy, para discriminar en base a estas
    # la cantindad de datos a traer
    ml_strategies = [
        "ml_logreg", "ml_randfor", "ml_knn", "ml_mlpc", "ml_bm", "ml_xgb",
        "ml_stacking", "ml_period"
    ]
    delta = timedelta(seconds=period)
    # máximo delay aceptado entre el tiempo actual y el del último dato
    delta2 = timedelta(seconds=200)
    # desfase para en la mayoría de los casos no entrar al while
    delta3 = timedelta(seconds=90)
    ml_strategy = False
    have_coin = False
    len_data = 0
    # en el caso de una estrategía de ML porcentaje de datos que se utilizanran
    # en el conjunto de datos de entrenamiento
    per = 0.95
    # dinero inicial con el que empieza el paperBot
    balance = []
    # definiendo el tiempo inicial de la consulta
    if strategy in ml_strategies:
        # para estrategias de machine learning se tomarán los últimos
        # 7000 datos
        len_data = 5000
        ml_strategy = True
    else:
        # para estrategias diferentes a las de ML se toman los últimos
        # 50 datos
        len_data = 40

    while True:
        try:
            # definiendo end como la hora local actual
            tf = datetime.now()
            # convirtiendola a formato unix time (es equivalente a UTC)
            end = string2ts(tf.strftime('%Y-%m-%d %H:%M:%S'))
            #start = end

            # definiendo el tiempo inicial de la consulta
            to = tf - delta * len_data
            start = string2ts(to.strftime('%Y-%m-%d %H:%M:%S'))

            # trayendo y preparando datos
            df, polo = prepareLiveData(pair=pair,
                                       start=start,
                                       end=end,
                                       period=int(period))
            #print "El total de datos descargados es: ",len(df)
            # corriendo estrategia. Generando vector w
            tt = df.index[-1]
            de = tf - tt

            # sincronizando tiempo del bot
            if de > delta2:
                # mientras la diferencia entre el la hora del último precio de cierre y
                # y la hora actual sea mayor a 120s
                while de > delta2:

                    # definiendo end como la hora local actual
                    tf = datetime.now()
                    # convirtiendola a formato unix time (es equivalente a UTC)
                    end = string2ts(tf.strftime('%Y-%m-%d %H:%M:%S'))
                    to = tf - delta * len_data
                    start = string2ts(to.strftime('%Y-%m-%d %H:%M:%S'))
                    # trayendo y preparando datos
                    df, polo = prepareLiveData(pair=pair,
                                               start=start,
                                               end=end,
                                               period=int(period))
                    tt = df.index[-1]
                    de = tf - tt
                    sys.stdout.write(
                        "\rSincronizando bot (delay máximo aceptado 200s, actual %ss). Esperando cierre de las %s. Último dato de cierre a las %s"
                        % (str((de).seconds), str(tt + delta), str(tt)))
                    sys.stdout.flush()
                    sleep(5)

            print "\n"

            #corriendo estrategia
            w, market_return = run_strategy(strategy, df, pair, ml_strategy,
                                            per)

            have_coin, coin_balance, btc_balance, order = run_live_signal(
                polo, str(df.index[-1]), w["orders"][-1], pair,
                df["close"][-1], have_coin, strategy, balance, weight)
            #print "%s %s %s %s %s\n"%(tf.strftime('%Y-%m-%d %H:%M:%S'),strategy,pair,w["orders"][-1],df["close"][-1])
            # calibrando tiempo de espera de acuerdo a emisión de próximo dato
            tf = datetime.now()
            to_sleep = tt + delta - tf + delta3
            # se recarga cada to_sleep segundos
            sleep(to_sleep.seconds)

        # Saliendo del programa
        except KeyboardInterrupt:

            yn = raw_input("\n\n\tDo you want to quit (y/n)? ")
            if yn == "y" or yn == "Y" or yn == "yes" or yn == "YES":
                print "\tSeleccionó salir. \n"

                # guardando el resumen del paper trading en un archivo de texto
                with open(
                        "paper_resume_%s_%s_%s.txt" % (pair, strategy, period),
                        "w") as paper_resume:
                    try:
                        print >> paper_resume, "\tBalance: %s" % (balance[-1])
                    except IndexError:
                        print "\tHasta pronto..."
                        sys.exit()
                    print >> paper_resume, "\tProfit: {}%".format(
                        round((balance[-1] - balance[0]) / balance[0] * 100,
                              2))

                print "\tBalance: %s" % (balance[-1])
                print "\tProfit: {}%".format(
                    round((balance[-1] - balance[0]) / balance[0] * 100, 2))
                print "\tHasta pronto..."
                bot_off(polo, order)
            elif yn == "n" or yn == "N" or yn == "no" or yn == "NO":
                print "\tSeleccionó seguir"
                pass
示例#8
0
def load_PT_options(argv):
    '''
    funcion que carga opciones de usuario de paper trading
    '''
    currencyPair, start, end = "BTC_DGB", "2017-06-01 00:00:00", "2017-06-01 00:00:00"
    period, strategy = 300, "EMAvsSMA"
    multi = None
    try:
        opts, args = getopt.getopt(argv, "hp:c:n:s:e:f:s:m:",
                                   ["period=", "currency=", "points="])
    except getopt.GetoptError:
        print '\t Error liveBot.py. The valid option are:\n -p <period length> -c <currency pair> -s <strategy> -m <int> -h <help>'
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print 'liveBot.py -p <period length> -c <currency pair> -s <strategy> -m <int>'
            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"):
            currencyPair = arg
        elif opt in ("-n", "--points"):
            lengthOfMA = int(arg)
        elif opt in ("-i"):
            ts = string2ts(arg)
            start = str(ts)
        elif opt in ("-e"):
            ts = string2ts(arg)
            end = str(ts)
        elif opt in ("-f"):
            dic = {}
            inputFile = open(arg).readlines()

            for line in inputFile:
                if line != ['']:
                    k = line.split('=')
                    dic[k[0].strip(" ")] = k[1].strip(" ").strip('\n')
            currencyPair = dic["currencyPair"]
            period = int(dic["period"])
            strategy = dic["strategy"]
            multi = dic["multi"]
        elif opt in ("-s"):
            strategy = arg
        elif opt in ("-m", "--multi"):
            multi = int(arg)
            bots = []
            # abriendo archivo como lista
            multi_file = open("multi_bot.inp").readlines()

            for line in multi_file:
                if line.strip("\n").strip(" ") != "":
                    pair = line.split(",")[0].strip(" ")
                    weight = line.split(",")[1].strip(" ")
                    strategy = line.split(",")[2].strip(" ")
                    period = line.split(",")[3].strip("\n").strip(" ")
                    bots.append({
                        "pair": pair,
                        "weight": weight,
                        "strategy": strategy,
                        "period": period
                    })

            currencyPair = bots[multi]["pair"]
            period = int(bots[multi]["period"])
            strategy = bots[multi]["strategy"]

    if len(opts) == 0:
        print "\n\tYou did not provide options. The default ones will be assumed.\n"
        print "paperBot.py -p <period length> -c <currency pair> -s <strategy> -w <weight>"
    return currencyPair, period, strategy, multi
示例#9
0
def paper(pair, period, strategy): 
    """
    Traer los datos en vivo y devuelve SELL, WAIT o BUY,
    según la estrategia que se escoja    
    """
    
    # funciones necesarias para el manejo del tiempo
    from datetime import datetime, timedelta
    from time import sleep
    
    # en esta lista deben guardarse los nombres de todas las estrategias
    # de machine learning en strategy, para discriminar en base a estas
    # la cantindad de datos a traer
    ml_strategies = ["ml_logreg", "ml_randfor",
      "ml_knn", "ml_mlpc",
      "ml_bm", "ml_xgb",
      "ml_stacking"]    
    delta = timedelta(seconds = period)
    
    # desfase para en la mayoría de los casos no entrar al while
    ml_strategy = False
    have_coin = False
    len_data = 0
    # en el caso de una estrategía de ML porcentaje de datos que se utilizanran 
    # en el conjunto de datos de entrenamiento
    per = 0.95
    # dinero inicial con el que empieza el paperBot
    init_balance = 100.0
    btc_balance = init_balance
    coin_balance = 0.0
    count = 0
    model = None
    test = None
    # definiendo el tiempo inicial de la consulta 
    if strategy.strip("2") in ml_strategies:
        # para estrategias de machine learning se tomarán los últimos
        # 7000 datos
        len_data = 10000
        ml_strategy = True
    else: 
        # para estrategias diferentes a las de ML se toman los últimos
        # 50 datos
        len_data = 40

    while True:
        try:
            count += 1
            # definiendo end como la hora local actual
            tf = datetime.now()
            # convirtiendola a formato unix time (es equivalente a UTC)
            end = string2ts(tf.strftime('%Y-%m-%d %H:%M:%S'))
            #start = end 
            
            # definiendo el tiempo inicial de la consulta 
            to = tf-delta*len_data
            print "\n\t to=%s"%to
            start = string2ts(to.strftime('%Y-%m-%d %H:%M:%S'))
                
            # trayendo y preparando datos
            df = prepareData(pair=pair, start=start, end=end, period=int(period))
            #print "El total de datos descargados es: ",len(df)
            # corriendo estrategia. Generando vector w

            w, market_return = run_strategy(strategy,df,pair, ml_strategy, per,
                                            count, la=11, prob=0.1)
            #print w[["w"]].tail(3)
            have_coin,coin_balance,btc_balance = run_paper_signal(str(df.index[-1]),
                                                w["w"][-1],pair,df["close"][-1],
                                                have_coin,coin_balance,btc_balance,
                                                strategy, period=period)
            #print "%s %s %s %s %s\n"%(tf.strftime('%Y-%m-%d %H:%M:%S'),strategy,pair,w["orders"][-1],df["close"][-1])
            
            
            #sys.stdout.write("\r\tPróxima actualización en: %s"%(to_sleep))
            #sys.stdout.flush()
            # se recarga cada period segundos
            sleep(period)
        
        # Saliendo del programa        
        except KeyboardInterrupt:
            
            yn = raw_input("\n\n\tDo you want to quit (y/n)? ")
            if yn == "y" or yn =="Y" or yn =="yes" or yn =="YES":
                print "\tSeleccionó salir. \n"
                balance = btc_balance+coin_balance*df["close"][-1]
                
                # guardando el resumen del paper trading en un archivo de texto
                with open("paper_resume_%s_%s_%s.txt"%(pair,strategy,period),"w") as paper_resume:
                    print >> paper_resume, "\tBalance: %s"%(balance)
                    print >> paper_resume, "\tProfit: {}%".format(round((balance-1)*100,2))
                
                print "\tBalance: %s"%(balance)
                print "\tProfit: {}%".format(round((balance-init_balance)/init_balance*100,2))
                print "\tHasta pronto..."
                sys.exit(1)
            elif yn == "n" or yn == "N" or yn == "no" or yn == "NO":
                print "\tSeleccionó seguir"
                pass