Skip to content

Commit 181e4f5

Browse files
committed
initial commit of basic version
0 parents  commit 181e4f5

37 files changed

+548
-0
lines changed

AutoTrader.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from VirtualAccount import VirtualAccount
2+
import numpy as np
3+
from Config import *
4+
import time
5+
6+
class AutoTrader:
7+
8+
def __init__(self,model):
9+
self.advisor = model
10+
self.account = VirtualAccount()
11+
self.trade_amount = 100
12+
13+
def buy(self):
14+
prev_bought_at = self.account.bought_btc_at # How much did I buy BTC for before
15+
if self.account.usd_balance - self.trade_amount >= 0:
16+
if prev_bought_at == 0 or self.account.last_transaction_was_sell or (prev_bought_at > self.account.btc_price): #or (self.account.btc_price/prev_bought_at -1 > 0.005):
17+
print(">> BUYING $",self.trade_amount," WORTH OF BITCOIN")
18+
self.account.btc_amount += self.trade_amount / self.account.btc_price
19+
self.account.usd_balance -= self.trade_amount
20+
self.account.bought_btc_at = self.account.btc_price
21+
self.account.last_transaction_was_sell = False
22+
else:
23+
print(">> Not worth buying more BTC at the moment")
24+
else:
25+
print(">> Not enough USD left in your account to buy BTC ")
26+
27+
def sell(self):
28+
if self.account.btc_balance - self.trade_amount >= 0:
29+
if self.account.btc_price > self.account.bought_btc_at: # Is it profitable?
30+
print(">> SELLING $",self.trade_amount," WORTH OF BITCOIN")
31+
self.account.btc_amount -= (self.trade_amount / self.account.btc_price)
32+
self.account.usd_balance += self.trade_amount
33+
self.account.last_transaction_was_sell = True
34+
else:
35+
print(">> Declining sale: Not profitable to sell BTC")
36+
else:
37+
print(">> Not enough BTC left in your account to buy USD ")
38+
39+
def runSimulation(self,samples,prices):
40+
print("> Trading Automatically for ",TESTING_MONTHS)
41+
day_count = 0
42+
for i in range(0,len(samples)):
43+
44+
if i % 24 == 0:
45+
day_count += 1
46+
print("#################################################################################################")
47+
print("# Account Balance: $", (self.account.usd_balance + self.account.btc_balance), " BTC: $",
48+
self.account.btc_balance, " USD: $", self.account.usd_balance, "")
49+
print("#################################################################################################")
50+
print("########################################## DAY ",day_count," #########################################")
51+
52+
53+
if i % 6 == 0: # Perform a prediction every 6 hours
54+
prediction = self.advisor.predict(np.array([samples[i]]))
55+
#btc_price = samples[i][len(samples[i])-1]
56+
btc_price = prices[i]
57+
58+
if self.account.btc_price != 0:
59+
self.account.btc_balance = self.account.btc_amount * btc_price
60+
61+
self.account.btc_price = btc_price
62+
63+
if prediction == 1:
64+
self.buy()
65+
else:
66+
self.sell()
67+
68+
self.account.btc_balance = self.account.btc_amount * btc_price
69+
70+
time.sleep(1) # Only for Visual Purposes
71+
72+
print("#################################################################################################")
73+
print("# Account Balance: $", (self.account.usd_balance + self.account.btc_balance), " BTC: $",
74+
self.account.btc_balance, " USD: $", self.account.usd_balance, "")
75+
print("#################################################################################################")

CoinbaseAPI.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import cbpro
2+
import json
3+
import datetime
4+
import time
5+
6+
class CoinbaseAPI:
7+
8+
public_clinet = None
9+
10+
def __init__(self):
11+
print("Coinbase API Initiated")
12+
self.public_client = cbpro.PublicClient()
13+
14+
# [ time, low, high, open, close, volume ],
15+
def getCoinHistoricData(self,coin_pair,start,end,granularity):
16+
print("> Collecting historic data for "+coin_pair," from ",start," to ",end," every ",granularity," sec")
17+
18+
data = []
19+
start_date = datetime.datetime.strptime(start, "%Y-%m-%d")
20+
end_date = datetime.datetime.strptime(end, "%Y-%m-%d")
21+
22+
while (start_date <= end_date):
23+
print("> Date: ",start_date)
24+
start_limit = start_date
25+
end_limit = start_date + datetime.timedelta(hours=1)
26+
27+
reversed_response = [] # Put in correct date order
28+
next_data = self.public_client.get_product_historic_rates(coin_pair, granularity=granularity,start=start_limit,end=end_limit)
29+
#print(self.public_client.get_products())
30+
for nd in next_data:
31+
reversed_response.append(nd)
32+
33+
data.append(list(reversed(reversed_response)))
34+
start_date += datetime.timedelta(minutes=61)
35+
time.sleep(3)
36+
37+
return data
38+
39+
# [ time, low, high, open, close, volume ],
40+
41+
"""
42+
time - bucket start time
43+
low - lowest price during the bucket interval
44+
high - highest price during the bucket interval
45+
open - opening price (first trade) in the bucket interval
46+
close - closing price (last trade) in the bucket interval
47+
volume - volume of trading activity during the bucket interval
48+
"""
49+
def getCoinCurrentData(self,coin_pair):
50+
data = self.public_client.get_product_historic_rates(coin_pair, granularity=60, start=datetime.datetime.today())
51+
52+
return data

Config.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
DATASET_DIR = "datasets/"
2+
COIN_PAIR = "BTC-USD"
3+
GRANULARITY = 60 # Data every 1 minute
4+
5+
TRAINING_MONTHS = ["2018_06","2018_07","2018_08","2018_09","2018_10","2018_11","2018_12","2019_01",
6+
"2019_02","2019_03","2019_04","2019_05","2019_06","2019_07","2019_08","2019_09",
7+
"2019_10","2019_11","2019_12","2020_01","2020_02","2020_03","2020_04","2020_05",
8+
"2020_06","2020_07","2020_08","2020_09"]
9+
10+
TESTING_MONTHS = ["2020_10"]
11+
12+
# Model and Auto Trader
13+
CHANGE_RATE_THRESHOLD = 0.005
14+
TRAINING_WINDOW = 360 # Window to use for training in minutes
15+
LABELING_WINDOW = 360 # How far ahead to look for labeling / prediction

Controller.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
from Dataset import Dataset
2+
from Model import Model
3+
from Config import *
4+
from AutoTrader import AutoTrader
5+
import argparse
6+
from CoinbaseAPI import CoinbaseAPI
7+
8+
if __name__ == '__main__':
9+
10+
print("\n\n\n ,.=ctE55ttt553tzs., \n",
11+
" ,,c5;z==!!:::: .::7:==it3>., \n",
12+
" ,xC;z!:::::: ::::::::::::!=c33x, \n",
13+
" ,czz!::::: ::;;..===:..::: ::::!ct3. \n",
14+
" ,C;/.:: : ;=c!:::::::::::::::.. !tt3. \n",
15+
" /z/.: :;z!:::::J :E3. E:::::::.. !ct3. \n",
16+
" ,E;F ::;t::::::::J :E3. E::. ::. \ztL \n",
17+
" ;E7. :c::::F****** **. *==c;.. :: Jttk \n",
18+
" .EJ. ;::::::L \:. ::. Jttl \n",
19+
" [:. :::::::::773. JE773zs. I:. ::::. It3L \n",
20+
" ;:[ L:::::::::::L |t::!::J |:::::::: :Et3 \n",
21+
" [:L !::::::::::::L |t::;z2F .Et:::.:::. ::[13 CRYPTO \n",
22+
" E:. !::::::::::::L =Et::::::::! ::|13 TRADING \n",
23+
" E:. (::::::::::::L ....... \:::::::! ::|i3 AI \n",
24+
" [:L !:::: ::L |3t::::!3. ]::::::. ::[13 \n",
25+
" !:( .::::: ::L |t::::::3L |:::::; ::::EE3 \n",
26+
" E3. :::::::::;z5. Jz;;;z=F. :E:::::.::::II3[ \n",
27+
" Jt1. :::::::[ ;z5::::;.::::;3t3 \n",
28+
" \z1.::::::::::l...... .. ;.=ct5::::::/.::::;Et3L \n",
29+
" \z3.:::::::::::::::J :E3. Et::::::::;!:::::;5E3L \n",
30+
" \cz\.:::::::::::::J E3. E:::::::z! ;Zz37` \n",
31+
" \z3. ::;:::::::::::::::;=' ./355F \n",
32+
" \z3x. ::~=======' ,c253F \n",
33+
" \ z3=. ..c5t32^ \n",
34+
" =zz3==... ...=t3z13P^ \n",
35+
" `*=zjzczIIII3zzztE3>*^` \n\n\n")
36+
37+
38+
print("\n> Welcome to Crypto-Trading AI")
39+
40+
parser = argparse.ArgumentParser()
41+
parser.add_argument("--collect_coins",action="store_true")
42+
parser.add_argument("--train_and_trade", action="store_true")
43+
parser.add_argument("--start")
44+
parser.add_argument("--end")
45+
args = parser.parse_args()
46+
47+
dataset = Dataset()
48+
49+
if args.collect_coins:
50+
start_date = args.start if args.start else "2020-01-01"
51+
end_date = args.end if args.end else "2020-02-02"
52+
tokens = start_date.split("-")
53+
month = tokens[0] + "_" + tokens[1] + "_"
54+
55+
coinbaseAPI = CoinbaseAPI()
56+
historic_data = coinbaseAPI.getCoinHistoricData(COIN_PAIR, start=start_date, end=end_date,granularity=GRANULARITY)
57+
dataset.storeRawCoinHistoricData(month,COIN_PAIR,historic_data)
58+
59+
print("> Using Coinbase API to build dataset for ",COIN_PAIR)
60+
61+
elif args.train_and_trade:
62+
print("> Creating Training Data for ", COIN_PAIR)
63+
data = dataset.loadCoinData(COIN_PAIR, TRAINING_MONTHS)
64+
x_train, y_train, _ = dataset.createTrainTestSets(COIN_PAIR, data, training_window=TRAINING_WINDOW, labeling_window=LABELING_WINDOW)
65+
66+
print("> Creating Testing Data for ", COIN_PAIR)
67+
data = dataset.loadCoinData(COIN_PAIR, TESTING_MONTHS)
68+
x_test, y_test, prices = dataset.createTrainTestSets(COIN_PAIR, data, training_window=TRAINING_WINDOW, labeling_window=LABELING_WINDOW)
69+
70+
test_model = Model("AutoTraderAI", x_train)
71+
test_model.train(x_train, y_train, batch_size=64, epochs=10)
72+
# test_model.evaluate(x_test,y_test)
73+
74+
auto_trader = AutoTrader(test_model)
75+
auto_trader.runSimulation(x_test, prices)
76+
else:
77+
print("> The biggest mistake you can make in life is to waste your time. – Jerry Bruckner")
78+
print("> P.S. Use an argument next time: --collect_coins or --train_and_trade")
79+
80+
81+
82+
83+
84+
85+
86+

0 commit comments

Comments
 (0)