-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrade_one_crypto.py
106 lines (91 loc) · 3.97 KB
/
trade_one_crypto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import time
import pandas as pd
from src.datafetch.datafetch import DataFetch
from src.features.utils import feature_pipeline
from src.kraken.krakenclient import KrakenClient
from src.logger.slackclient import SlackClient
import pickle
import click
def execute_order_and_log(order_type, pair_name, volume, logger, kraken_client):
try:
output = kraken_client.execute_limit_market_order(
order_type=order_type, volume=volume, pair_name=pair_name)
logger.send_message(
text=str(output),
channel="#trading-finalized-orders",
title="Finalized order")
except Exception as e:
logger.send_message(
text=str(e),
channel="#errors",
title="Errors")
@click.command()
@click.option(
"--pair_name",
type=click.Choice(
["xlmeur", "bcheur","compeur","xdgeur", "etheur", "algoeur", "bateur", "adaeur","xrpeur"]),
prompt="Pair name to trade"
)
@click.option('--model_dir', prompt="Directory of the model")
@click.option('--threshold', type=float, prompt="Threshold for the model")
@click.option('--volume', type=float, prompt="Volume to trade")
def main(pair_name, model_dir, threshold, volume):
api_public_key = open("API_Public_Key").read().strip()
api_private_key = open("API_Private_Key").read().strip()
slack_url = open("slack_url").read().strip()
next_action = "buy"
kraken_client = KrakenClient(api_private_key=api_private_key, api_public_key=api_public_key)
slack_client = SlackClient(slack_url)
datafetch = DataFetch(pair_name, platform_client=kraken_client)
# Load model
with open(model_dir ,'rb') as f:
model = pickle.load(f)
while True:
# Fetch data
df = datafetch.fetch_data(interval=1)
# Preprocess it
df, _=feature_pipeline(df, include_target=False)
# Make predictions
columns_features = [col for col in df.columns if col.startswith("feature")]
df["preds"] = model.predict(df[columns_features])
df["next_action"] = next_action
# introduce lag of -1 to avoid values per minute that may change
last_pred = df.tail(1).preds.values[0] #df.iloc[-1].preds #df.tail(1).preds.values[0]
last_date = df.tail(1).date.values[0] #df.iloc[-1].date #df.tail(1).date.values[0]
last_open = df.tail(1).open.values[0] #df.iloc[-1].open #df.tail(1).open.values[0]
# log
try:
df_log = pd.read_csv(f"run_{pair_name}_{threshold}_{volume}.csv")
except FileNotFoundError:
df_log = pd.DataFrame()
df_log.to_csv(f"run_{pair_name}_{threshold}_{volume}.csv", index=False)
#base_columns = ["open", "close", "low", "high", "vwap", "volume", "preds"]
#feature_columns = [col for col in df.columns if col.startswith("feature")]
df_log = pd.concat([df_log, df.tail(2)])
#df_log[base_columns+feature_columns]= df_log[base_columns+feature_columns].astype("float32").copy()
df_log.drop_duplicates().to_csv(f"run_{pair_name}_{threshold}_{volume}.csv", index=False)
print(f"Prediction of {pair_name} for {last_date} is {last_pred}")
print(f"Open at {last_open}")
if (-last_pred > threshold) and (next_action=="buy"):
print("Buying")
execute_order_and_log(
order_type="buy",
pair_name=pair_name,
volume=volume,
logger=slack_client,
kraken_client=kraken_client)
next_action = "sell"
elif (-last_pred < -threshold) and (next_action=="sell"):
print("Selling")
execute_order_and_log(
order_type="sell",
pair_name=pair_name,
volume=volume,
logger=slack_client,
kraken_client=kraken_client)
next_action = "buy"
else:
print("No action")
time.sleep(60)
if __name__ == "__main__":
main()