Ejemplo n.º 1
0
def test_trade(binance, model):

    os.system("cls")  #Clear Screen
    dt_now = datetime.datetime.now()
    print(dt_now.strftime("%Y-%m-%d %H:%M:%S"))

    symbol = "BTCUSDT"
    amount = 0.0002

    base_balance = 0.002
    quote_balance = 100
    price = binance.get_current_price(symbol)

    model.load_weights(
        const.CHECKPOINT_PATH.format(time_length=const.TIME_LENGTH))

    ready = False

    df_test = make_dataset.make_current_data(binance, symbol, 0, 0)
    test_data, test_target = make_dataset.make_dataset(df_test)
    test_loss, test_acc = model.evaluate(test_data, test_target, verbose=2)
    print("Test accuracy:", test_acc)

    while True:

        loop = True
        while loop:
            sleep(5)
            dt_now = datetime.datetime.now()
            if dt_now.minute % 5 == 4 and dt_now.second >= 45 and dt_now.second <= 55 and ready == True:
                print(dt_now.strftime("%Y-%m-%d %H:%M:%S"))
                loop = False
                ready = False
            elif dt_now.minute % 5 == 0 and ready == False:
                ready = True

        df = make_dataset.make_current_data(binance, symbol, 0, 0)
        df = df.iloc[len(df) - const.TIME_LENGTH:, :]
        input_data = np.array(df).reshape(1, const.TIME_LENGTH,
                                          len(df.columns))

        predicted = model.predict(input_data)[-1]
        print(predicted)
        result = np.argmax(predicted)

        price = binance.get_current_price(symbol)
        print("Price:" + str(price))
        print("Balance:" + str((base_balance * price) + quote_balance) +
              " Base:" + str(base_balance) + " Quote:" + str(quote_balance))
        if result == 0:
            print("SELL")
            binance.create_test_order(symbol, 0.0002, "SELL")
            base_balance, quote_balance = sell(base_balance, quote_balance,
                                               amount, price)
        elif result == 2:
            print("BUY")
            binance.create_test_order(symbol, 0.0002, "BUY")
            base_balance, quote_balance = buy(base_balance, quote_balance,
                                              amount, price)
        print("")
Ejemplo n.º 2
0
def simulation(binance,model):

    df_list = {}

    for symbol in const.PAIR_SYMBOLS:
        df_list[symbol] = make_dataset.make_current_data(binance,symbol,12,10)
        #mpf.plot(df_list[symbol], type='candle')

    symbol = "BTCUSDT"

    first_base_balance = 0.002
    first_quote_balance = 100
    base_balance = first_base_balance
    quote_balance = first_quote_balance
    price = df_list[symbol].iloc[0,0]
    #price = float(binance.get_ticker("BTCUSDT")["lastPrice"])

    data,_ = make_dataset.make_dataset(df_list[symbol])
    print(df_list[symbol])
    print(data)



    model.load_weights(const.CHECKPOINT_PATH)
    prediction = pd.DataFrame(model.predict(data))
    #prediction = prediction.idxmax(axis=1)
    prediction = prediction.iloc[:,0].tolist()


    
    first_balance = (base_balance*price)+quote_balance


    for i in range(len(prediction)):
        print("Period:" + str(i))
        price = df_list[symbol].iloc[i+const.TIME_LENGTH,0]
        print("Price:"+str(price))
        print("Balance:"+str((base_balance*price)+quote_balance) + " Base:" + str(base_balance) + " Quote:" + str(quote_balance))
        if prediction[i] < -0.05:
            print("SELL")
            base_balance, quote_balance = sell(base_balance, quote_balance,0.0002,price)
        elif prediction[i] > 0.05:
            print("BUY")
            base_balance, quote_balance = buy(base_balance, quote_balance,0.0002,price)
        print("")



    print("Start:" + str(first_balance) + "  Last" + str((base_balance*price)+quote_balance))
    print("Result:" + str((base_balance*price)+quote_balance-first_balance))
    print("Without Trading:" + str((first_base_balance*price + first_quote_balance)-first_balance))

    print()

    x=range(len(prediction))
    plt.plot(x, df_list[symbol].iloc[-len(prediction):,1], prediction)
    plt.legend(["actual", "predict"], loc="upper left")
    plt.show()
Ejemplo n.º 3
0
def main():

    #with open("ApiKeyFuturesTestnet.txt") as f:
    with open("ApiKey.txt") as f:
        api_key = f.readline().rstrip('\n')
        api_secret = f.readline().rstrip('\n')

    binance = BinanceAPI(api_key, api_secret)

    df = make_dataset.make_current_data(binance, "LTCUSDT", 0,
                                        0)  #to get column size

    #model = tf.keras.models.Sequential()
    #model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(200, activation="tanh"), input_shape=(const.TIME_LENGTH, len(df.columns))))
    #model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(50, activation="swish"), input_shape=(const.TIME_LENGTH, len(df.columns))))
    #model.add(tf.keras.layers.LSTM(32, activation="tanh", recurrent_activation="sigmoid", return_sequences = True))
    #model.add(tf.keras.layers.LSTM(16, activation="tanh", recurrent_activation="sigmoid"))
    #model.add(tf.keras.layers.Dense(500, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.2))
    #model.add(tf.keras.layers.Dense(250, activation="swish"))
    #model.add(tf.keras.layers.Dense(125, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.2))
    #model.add(tf.keras.layers.Dense(75, activation="swish"))
    #model.add(tf.keras.layers.Dense(50, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.2))
    #model.add(tf.keras.layers.Dense(25, activation="swish"))
    #model.add(tf.keras.layers.Dense(4, activation="softmax"))
    #optimizer = tf.keras.optimizers.Adam(lr=0.001)
    #model.compile(optimizer=optimizer, loss="sparse_categorical_crossentropy", metrics = ['accuracy'])

    model = make_model(len(df.columns))

    print("0:CollectData 1:Train 2:Simulation")
    mode = input(">")
    if mode == "0":
        collect_info.collect_info(binance)
    elif mode == "1":
        train.train(binance, model)
    elif mode == "2":
        simulation.simulation(binance, model)
def simulation(binance, agent):
    df = make_dataset.make_current_data(binance, "BTCUSDT", 12, 10)
    df = df[[
        "OrigClose", "Close", "Volume", "TradeCount", "BOLL_UP", "BOLL_DOWN",
        "MACD", "MACD_SIGNAL", "SAR", "RSI12", "WMA99"
    ]]
    df = df.fillna(0)
    orig_close = df["OrigClose"]
    df = df.applymap(lambda x: 100 * x)
    df["OrigClose"] = orig_close

    environment_py = TradingEnv(df)
    environment_py.set_init_balance(1000)
    environment_py.set_mode(1)
    environment_py.set_data(df)
    environment = tf_py_environment.TFPyEnvironment(environment_py)

    policy_state = agent.policy.get_initial_state(1)
    time_step = environment.reset()
    action_history = []
    return_sum = 0

    for _ in range(len(df)):

        action_step = agent.policy.action(time_step, policy_state)
        action_history.append(action_step.action.numpy()[0])
        time_step = environment.step(action_step.action)
        policy_state = action_step.state
        return_sum += time_step.reward

    print("Result:" + str(return_sum.numpy()[0]))

    x = range(0, len(df))
    fig = plt.figure()
    ax1 = fig.add_subplot(2, 1, 1)
    ax2 = fig.add_subplot(2, 1, 2)
    ax1.plot(x, df["OrigClose"])
    ax2.plot(x, action_history)
    plt.show()
Ejemplo n.º 5
0
def collect_info(binance):

    df_list = {}
    df_list_test = {}

    print("collecting data")

    symbol = "LTCUSDT"

    df_list[symbol] = make_dataset.make_current_data(binance, symbol,
                                                     128 * 2 + 70, 70)
    df_list[symbol].to_csv("..\\Data\\" + symbol + "_data.csv")

    img = make_dataset.make_current_image_data(binance, symbol, 128 * 2 + 70,
                                               70)
    np.save("..\\Data\\" + symbol + "_image_data", img)

    for symbol in const.PAIR_SYMBOLS:
        base_asset = binance.get_base_asset(symbol)
        quote_asset = binance.get_quote_asset(symbol)

    for i in const.BALANCE_SYMBOLS:
        print(i + " Available : " + binance.get_balance(i)["free"])
Ejemplo n.º 6
0
def collect_info(binance):

    df_list = {}
    df_list_test = {}

    print("collect data")

    for symbol in const.PAIR_SYMBOLS:
        if os.path.exists("..\\Data\\" + symbol + "_data.csv"):
            df_list[symbol] = pd.read_csv("..\\Data\\" + symbol + "_data.csv",
                                          index_col=0,
                                          parse_dates=True)
            mpf.plot(df_list[symbol], type='candle')
        else:
            df_list[symbol] = make_dataset.make_current_data(
                binance, symbol, 400, 10)
            df_list[symbol].to_csv("..\\Data\\" + symbol + "_data.csv")

    for symbol in const.PAIR_SYMBOLS:
        base_asset = binance.get_base_asset(symbol)
        quote_asset = binance.get_quote_asset(symbol)

    for i in const.BALANCE_SYMBOLS:
        print(i + " Available : " + binance.get_balance(i)["free"])
Ejemplo n.º 7
0
def simulation_c(binance,model):

    df_list = {}

    for symbol in const.PAIR_SYMBOLS:
        df_list[symbol] = make_dataset.make_current_data(binance,symbol,520,420)
        #mpf.plot(df_list[symbol], type='candle')

    symbol = "BTCUSDT"

    first_base_balance = 0.0
    first_quote_balance = 100
    base_balance = first_base_balance
    quote_balance = first_quote_balance
    price = df_list[symbol].iloc[0,0]
    #price = float(binance.get_ticker("BTCUSDT")["lastPrice"])

    data, target = make_dataset.make_classification_dataset(df_list[symbol])
    print(df_list[symbol])
    print(data)



    model.load_weights(const.CHECKPOINT_PATH)
    prediction = pd.DataFrame(model.predict(data))
    prediction = prediction.idxmax(axis=1)
    #prediction = prediction.iloc[:,0].tolist()


    
    first_balance = (base_balance*price)+quote_balance
    last_balance = (base_balance*price)+quote_balance
    prev_action = 1

    total_lose = 0
    total_win = 0

    for i in range(len(prediction)):
        print("Period:" + str(i))
        price = df_list[symbol].iloc[i+const.TIME_LENGTH-1,0] #data does not include [i+const.TIME_LENGTH]
        if prev_action == 0:
            base_balance, quote_balance = buy(base_balance, quote_balance,0.001,price)
            print("stop")
        elif prev_action == 2:
            base_balance, quote_balance = sell(base_balance, quote_balance,0.001,price)
        if (base_balance*price)+quote_balance-last_balance > 0:
            total_win += 1
        elif (base_balance*price)+quote_balance-last_balance < 0:
            total_lose += 1
        print("Price:"+str(price))
        print("Balance:"+str((base_balance*price)+quote_balance))
        print("Profit:" + str((base_balance*price)+quote_balance-first_balance))
        last_balance = (base_balance*price)+quote_balance
        if prediction[i] == 0:
            print("SELL")
            base_balance, quote_balance = sell(base_balance, quote_balance,0.001,price)
            prev_action = 0
        elif prediction[i] == 2:
            print("BUY")
            base_balance, quote_balance = buy(base_balance, quote_balance,0.001,price)
            prev_action = 2
        else:
            prev_action = 1
        print("")



    print("Start:" + str(first_balance) + "  Last" + str((base_balance*price)+quote_balance))
    print("Result:" + str((base_balance*price)+quote_balance-first_balance))
    print("Without Trading:" + str((first_base_balance*price + first_quote_balance)-first_balance))
    print("Total Lose:" + str(total_lose))
    print("Total Win:" + str(total_win))

    print()



    fig = plt.figure()
    ax1 = fig.add_subplot(2, 1, 1)
    ax2 = fig.add_subplot(2, 1, 2)
    x=range(len(prediction))
    ax1.plot(x, df_list[symbol].iloc[-len(prediction):,1])
    ax2.plot(x, prediction)
    plt.show()
Ejemplo n.º 8
0
def main():

    with open("ApiKeyFutures.txt") as f:
        api_key = f.readline().rstrip('\n')
        api_secret = f.readline().rstrip('\n')

    #with open("ApiKeyFuturesTestnet.txt") as f:
    #    api_key = f.readline().rstrip('\n')
    #    api_secret = f.readline().rstrip('\n')

    binance = BinanceAPI(api_key, api_secret);


    df = make_dataset.make_current_data(binance,"BTCUSDT",0,0) #to get column size

    model = tf.keras.models.Sequential()
    #model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(200, activation="tanh"), input_shape=(const.TIME_LENGTH, len(df.columns))))
    #model.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(50, activation="swish"), input_shape=(const.TIME_LENGTH, len(df.columns))))
    #model.add(tf.keras.layers.LSTM(100, activation="tanh", recurrent_activation="sigmoid", return_sequences = True))
    model.add(tf.keras.layers.LSTM(100, activation="tanh", recurrent_activation="sigmoid"))
    #model.add(tf.keras.layers.Dense(500, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.2))
    #model.add(tf.keras.layers.Dense(250, activation="swish"))
    #model.add(tf.keras.layers.Dense(125, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.2))
    #model.add(tf.keras.layers.Dense(75, activation="swish"))
    model.add(tf.keras.layers.Dense(50, activation="swish"))
    #model.add(tf.keras.layers.Dropout(0.1))
    model.add(tf.keras.layers.Dense(25, activation="swish"))
    model.add(tf.keras.layers.Dense(1, activation="linear"))
    optimizer = tf.keras.optimizers.Adam(lr=0.001)
    #optimizer = tf.keras.optimizers.Adam(lr=0.0005)
    #loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    #model.compile(optimizer=optimizer, loss=loss, metrics=["accuracy"])
    model.compile(optimizer=optimizer, loss="mse", metrics = ['mae', 'mse'])


    model_c = tf.keras.models.Sequential()
    model_c.add(tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(50, activation="swish"), input_shape=(const.TIME_LENGTH, len(df.columns))))
    model_c.add(tf.keras.layers.LSTM(100, activation="tanh", recurrent_activation="sigmoid"))
    model_c.add(tf.keras.layers.Dense(75, activation="swish"))
    model_c.add(tf.keras.layers.Dense(50, activation="swish"))
    model_c.add(tf.keras.layers.Dropout(0.2))
    model_c.add(tf.keras.layers.Dense(25, activation="swish"))
    model_c.add(tf.keras.layers.Dense(3, activation="softmax"))
    optimizer_c = tf.keras.optimizers.Adam(lr=0.001)
    #loss_c = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    model_c.compile(optimizer=optimizer_c, loss="sparse_categorical_crossentropy", metrics = ['accuracy'])

    print("0:CollectData 1:Train 1C:Train_classification_model 2:Simulation 2C:Simulation_classification 3:TestTrade 4:Trade")
    print("A:TestIndicators B:TestRainforcementLearn C:PracticalTrade1")
    mode = input(">")
    if mode == "0":
        collect_info.collect_info(binance)
    elif mode == "1":
        train.train(binance,model)
    elif mode == "1C":
        train.train_c(binance,model_c)
    elif mode == "2":
        simulation.simulation(binance,model)
    elif mode == "2C":
        simulation.simulation_c(binance,model_c)
    elif mode == "3":
        test_trade.test_trade(binance,model)
    elif mode == "A":
        technical_indicators.test(binance)
    elif mode == "B":
        reinforcement_learn_test.test(binance,model)
    elif mode == "C":
        practical_trade.practical_trade(binance)
Ejemplo n.º 9
0
def train(binance, model):

    df_list = {}
    df_list_test = {}

    for symbol in const.PAIR_SYMBOLS:
        df_list[symbol] = pd.read_csv("..\\Data\\" + symbol + "_data.csv",
                                      index_col=0,
                                      parse_dates=True)
        #df_list[symbol] = pd.read_csv("..\\Data\\SinSample1.csv", index_col=0, parse_dates=True)
        #df_list[symbol] = tf.keras.utils.normalize(df_list[symbol], axis=0, order=2)

    #df_list_merged = pd.concat(df_list, axis=1)

    df_test = make_dataset.make_current_data(binance, "BTCUSDT", 0, 0)
    #df_test = pd.read_csv("..\\Data\\SinSample1.csv", index_col=0, parse_dates=True)

    data, target = make_dataset.make_dataset(df_list["BTCUSDT"])
    data_test, target_test = make_dataset.make_dataset(df_test)

    print(target_test)
    checkpoint_dir = os.path.dirname(const.CHECKPOINT_PATH)
    checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
        const.CHECKPOINT_PATH,
        verbose=1,
        save_weights_only=True,
        save_freq=3000)
    lr_change_callback = tf.keras.callbacks.LearningRateScheduler(scheduler)

    early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_mae',
                                                  patience=4)

    tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="log",
                                                          histogram_freq=1)

    epochs = 50
    batch_size = 64

    #tuner = kt.Hyperband(model_builder,
    #                 objective = "val_accuracy",
    #                 max_epochs = 10,
    #                 factor = 3,
    #                 directory = "HyperparameterTunerData",
    #                 project_name = "tunerData")
    #tuner.search(data, target, epochs=3, validation_data=(data_test, target_test))
    #tuner.results_summary()

    print(target)

    stack = model.fit(data,
                      target,
                      batch_size=batch_size,
                      epochs=epochs,
                      callbacks=[
                          checkpoint_callback, lr_change_callback, early_stop,
                          tensorboard_callback
                      ],
                      validation_data=(data_test, target_test))
    model.summary()

    x = range(len(stack.history["mae"]))
    plt.plot(x, stack.history["mae"])
    plt.plot(x, stack.history["val_mae"])
    plt.legend(["mae", "val_mae"], loc="upper left")
    plt.title("loss")
    plt.show()

    #p_data, _ = make_dataset.make_dataset(df_list_test)
    #predicted = model.predict(p_data)
    #predicted = np.pad(predicted,[[0,const.TIME_LENGTH],[0,0]],"edge")
    #df = pd.DataFrame(predicted)
    #for i in range(100):
    #    print(df.iloc[i,:])
    #df = df.idxmax(axis=1)
    #df = df.columns.get_loc(df.idxmax(axis=1))
    #addplot = mpf.make_addplot(df)
    #mpf.plot(df_list["BTCUSDT"], type='candle', addplot = addplot)

    test_acc = model.evaluate(data_test, target_test, verbose=2)
    print("Test accuracy:", test_acc)

    prediction = pd.DataFrame(model.predict(data_test))
    x = range(len(prediction))
    plt.plot(x, df_test.iloc[-len(prediction):, 1], prediction)
    plt.legend(["actual", "predict"], loc="upper left")
    plt.show()
Ejemplo n.º 10
0
def simulation(binance, model):

    df_list = {}

    for symbol in const.PAIR_SYMBOLS:
        df_list[symbol] = make_dataset.make_current_data(
            binance, symbol, 12, 10)
        #mpf.plot(df_list[symbol], type='candle')

    symbol = "LTCUSDT"

    first_base_balance = 1.0
    first_quote_balance = 100
    base_balance = first_base_balance
    quote_balance = first_quote_balance
    price = df_list[symbol].iloc[0, 0]
    #price = float(binance.get_ticker("BTCUSDT")["lastPrice"])

    data, target = make_dataset.make_dataset(df_list[symbol])
    print(df_list[symbol])
    print(data)

    model.load_weights(const.CHECKPOINT_PATH)
    prediction = pd.DataFrame(model.predict(data))
    prediction = prediction.idxmax(axis=1)

    first_balance = (base_balance * price) + quote_balance

    for i in range(len(prediction)):
        print("Period:" + str(i))
        price = df_list[symbol].iloc[i + const.TIME_LENGTH, 0]
        print("Price:" + str(price))
        print("Balance:" + str((base_balance * price) + quote_balance) +
              " Base:" + str(base_balance) + " Quote:" + str(quote_balance))
        if prediction[i] == 0:
            print("SELL")
            base_balance, quote_balance = sell(base_balance, quote_balance,
                                               0.0002, price)
        elif prediction[i] == 3:
            print("BUY")
            base_balance, quote_balance = buy(base_balance, quote_balance,
                                              0.0002, price)
        print("")

    print("Start:" + str(first_balance) + "  Last" +
          str((base_balance * price) + quote_balance))
    print("Result:" +
          str((base_balance * price) + quote_balance - first_balance))
    print("Without Trading:" +
          str((first_base_balance * price + first_quote_balance) -
              first_balance))

    print()

    fig = plt.figure()
    ax1 = fig.add_subplot(4, 1, 1)
    ax2 = fig.add_subplot(4, 1, 2)
    ax3 = fig.add_subplot(4, 1, 3)
    ax4 = fig.add_subplot(4, 1, 4)
    x = range(len(prediction))
    result = []
    win_num = 0
    total_num = 0
    for i in range(len(prediction)):
        if prediction[i] == 0 or prediction[i] == 3:
            total_num += 1
            if (prediction[i] == 0 and (target[i] == 0 or target[i] == 1)) or (
                    prediction[i] == 3 and (target[i] == 2 or target[i] == 3)):
                result.append(1)
                win_num += 1
            else:
                result.append(-1)
        else:
            result.append(0)
    print("Accuracy:" + str(win_num / total_num))
    ax1.plot(x, df_list[symbol].iloc[-len(prediction):, 1])
    ax1.set_title("Price")
    ax2.plot(x, target)
    ax2.set_title("Actual")
    ax3.plot(x, prediction)
    ax3.set_title("Prediction")
    ax4.plot(x, result)
    ax4.set_title("Result")
    plt.show()
Ejemplo n.º 11
0
def train(binance, model):

    df_list = {}
    df_list_test = {}

    symbol = "LTCUSDT"
    df_list[symbol] = pd.read_csv("..\\Data\\" + symbol + "_data.csv",
                                  index_col=0,
                                  parse_dates=True)
    orig_img = np.load("..\\Data\\" + symbol + "_image_data.npy")

    #df_list_merged = pd.concat(df_list, axis=1)

    df_test = make_dataset.make_current_data(binance, "LTCUSDT", 0, 0)
    orig_img_test = make_dataset.make_current_image_data(
        binance, "LTCUSDT", 0, 0)

    data, data_img, target = make_dataset.make_dataset(df_list["LTCUSDT"],
                                                       orig_img)
    data_test, data_img_test, target_test = make_dataset.make_dataset(
        df_test, orig_img_test)

    print(data_img.shape)
    print(data.shape)

    print(target_test)
    checkpoint_dir = os.path.dirname(const.CHECKPOINT_PATH)
    checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
        const.CHECKPOINT_PATH,
        verbose=1,
        save_weights_only=True,
        save_freq=1000)
    lr_change_callback = tf.keras.callbacks.LearningRateScheduler(scheduler)

    early_stop = tf.keras.callbacks.EarlyStopping(monitor="val_accuracy",
                                                  patience=30)

    tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="log",
                                                          histogram_freq=1)

    epochs = 100
    batch_size = 8

    #tuner = kt.Hyperband(model_builder,
    #                 objective = "val_accuracy",
    #                 max_epochs = 10,
    #                 factor = 3,
    #                 directory = "HyperparameterTunerData",
    #                 project_name = "tunerData")
    #tuner.search(data, target, epochs=3, validation_data=(data_test, target_test))
    #tuner.results_summary()

    print(target)

    stack = model.fit([data, data_img],
                      target,
                      batch_size=batch_size,
                      epochs=epochs,
                      callbacks=[
                          checkpoint_callback, lr_change_callback, early_stop,
                          tensorboard_callback
                      ],
                      validation_data=([data_test,
                                        data_img_test], target_test))
    model.summary()

    x = range(len(stack.history["accuracy"]))
    plt.plot(x, stack.history["accuracy"])
    plt.plot(x, stack.history["val_accuracy"])
    plt.legend(["accuracy", "val_accuracy"], loc="upper left")
    plt.title("accuracy")
    plt.show()

    #p_data, _ = make_dataset.make_dataset(df_list_test)
    #predicted = model.predict(p_data)
    #predicted = np.pad(predicted,[[0,const.TIME_LENGTH],[0,0]],"edge")
    #df = pd.DataFrame(predicted)
    #for i in range(100):
    #    print(df.iloc[i,:])
    #df = df.idxmax(axis=1)
    #df = df.columns.get_loc(df.idxmax(axis=1))
    #addplot = mpf.make_addplot(df)
    #mpf.plot(df_list["LTCUSDT"], type='candle', addplot = addplot)

    test_acc = model.evaluate([data_test, data_img_test],
                              target_test,
                              verbose=2)
    print("Test accuracy:", test_acc)

    fig = plt.figure()
    ax1 = fig.add_subplot(4, 1, 1)
    ax2 = fig.add_subplot(4, 1, 2)
    ax3 = fig.add_subplot(4, 1, 3)
    ax4 = fig.add_subplot(4, 1, 4)
    prediction = pd.DataFrame(model.predict([data_test, data_img_test]))
    prediction = prediction.idxmax(axis=1)
    x = range(len(prediction))
    result = []
    win_num = 0
    for i in range(len(prediction)):
        if target_test[i] == prediction[i] or (
            (target_test[i] == 1 or target_test[i] == 2) and
            (prediction[i] == 1 or prediction[i] == 2)):
            result.append(1)
            win_num += 1
        else:
            result.append(0)
    print("Accuracy:" + str(win_num / len(prediction)))
    ax1.plot(x, df_test.iloc[-len(prediction):, 1])
    ax1.set_title("Price")
    ax2.plot(x, target_test)
    ax2.set_title("Actual")
    ax3.plot(x, prediction)
    ax3.set_title("Prediction")
    ax4.plot(x, result)
    ax4.set_title("Result")
    plt.show()
Ejemplo n.º 12
0
def practical_trade(binance):

    symbol = "BTCUSDT"
    base_asset = binance.get_base_asset(symbol)
    quote_asset = binance.get_quote_asset(symbol)

    amount = 0.001

    current_balance = binance.get_futures_balance(quote_asset)
    price = binance.get_current_price(symbol)

    wait_time = 0
    prev_action = 0
    stop_time = 0

    prev_price = 0

    trade_history = []

    touched_boll = 0

    while True:

        wait_time -= 1

        df = make_dataset.make_current_data(binance, symbol, 0, 0)
        if df is None:
            if prev_action == 1:
                trade_history.append(
                    "BUY  " + dt_formed + "  Balance:" +
                    str(binance.get_futures_balance(quote_asset)))
                binance.create_futures_order(symbol, amount, "BUY")
                stop_time = 0
                prev_action = 0
            if prev_action == 2:
                trade_history.append(
                    "SELL " + dt_formed + "  Balance:" +
                    str(binance.get_futures_balance(quote_asset)))
                binance.create_futures_order(symbol, amount, "SELL")
                stop_time = 0
                prev_action = 0
            continue
        df = df.iloc[-1, :]

        os.system("cls")  #Clear Screen
        dt_now = datetime.datetime.now()
        dt_formed = dt_now.strftime("%Y-%m-%d %H:%M:%S")
        print(dt_formed)

        current_balance = binance.get_futures_balance(quote_asset)
        price = binance.get_current_price(symbol)
        if price is None:
            if prev_action == 1:
                trade_history.append("BUY  " + dt_formed + "  Balance:" +
                                     str(current_balance))
                binance.create_futures_order(symbol, amount, "BUY")
                stop_time = 0
                prev_action = 0
            if prev_action == 2:
                trade_history.append("SELL " + dt_formed + "  Balance:" +
                                     str(current_balance))
                binance.create_futures_order(symbol, amount, "SELL")
                stop_time = 0
                prev_action = 0
            continue
        print("Price:" + str(price))
        print(quote_asset + " Available : " + str(current_balance))

        dif = df["Close"] - df["Open"]

        print("Dif:" + str(dif) + " WaitTime:" + str(wait_time) +
              " StopTime:" + str(stop_time))

        if wait_time < 0 and prev_action == 0:
            if df["BOLL_UP"] < price:
                touched_boll = 1
            elif df["BOLL_DOWN"] > price:
                touched_boll = 2
            if touched_boll == 1 < price and df["SAR"] > price:
                trade_history.append("SELL " + dt_formed + "  Balance:" +
                                     str(current_balance))
                wait_time = 100
                prev_action = 1
                prev_price = price
                binance.create_futures_order(symbol, amount, "SELL")
                touched_boll = 0
            elif touched_boll == 2 > price and df["SAR"] < price:
                trade_history.append("BUY  " + dt_formed + "  Balance:" +
                                     str(current_balance))
                wait_time = 100
                prev_action = 2
                prev_price = price
                binance.create_futures_order(symbol, amount, "BUY")
                touched_boll = 0

        #close position after some time
        #if wait_time <= 0:
        #    if prev_action == 1 and stop_time >= 3:
        #        trade_history.append("BUY  " + dt_formed + "  Balance:" + str(current_balance))
        #        binance.create_futures_order(symbol, amount, "BUY")
        #        prev_action = 0
        #    if prev_action == 2 and stop_time >= 3:
        #        trade_history.append("SELL")
        #        binance.create_futures_order(symbol, amount, "SELL")
        #        prev_action = 0

        #close position if there is loss
        if (prev_action == 1 and dif > 0) or (prev_action == 2 and dif < 0):
            stop_time += 1
        else:
            stop_time = 0

        if stop_time >= 18:
            if prev_action == 1:
                trade_history.append("BUY  " + dt_formed + "  Balance:" +
                                     str(current_balance))
                binance.create_futures_order(symbol, amount, "BUY")
            if prev_action == 2:
                trade_history.append("SELL")
                binance.create_futures_order(symbol, amount, "SELL")
            stop_time = 0
            prev_action = 0

        if prev_action == 1 and df["SAR"] < price:
            trade_history.append("BUY  " + dt_formed + "  Balance:" +
                                 str(current_balance))
            binance.create_futures_order(symbol, amount, "BUY")
            stop_time = 0
            prev_action = 0
        if prev_action == 2 and df["SAR"] > price:
            trade_history.append("SELL " + dt_formed + "  Balance:" +
                                 str(current_balance))
            binance.create_futures_order(symbol, amount, "SELL")
            stop_time = 0
            prev_action = 0

        #stop_loss
        if prev_action == 1 and (price - prev_price) > price / 700:
            trade_history.append("BUY  " + dt_formed + "  Balance:" +
                                 str(current_balance))
            binance.create_futures_order(symbol, amount, "BUY")
            stop_time = 0
            prev_action = 0
        if prev_action == 2 and (price - prev_price) < -price / 700:
            trade_history.append("SELL " + dt_formed + "  Balance:" +
                                 str(current_balance))
            binance.create_futures_order(symbol, amount, "SELL")
            stop_time = 0
            prev_action = 0

        print("\nHistory:")
        for i in trade_history:
            print(i)

        sleep(3)  #it takes 2 second to calculate