-
Notifications
You must be signed in to change notification settings - Fork 0
/
trade.py
140 lines (109 loc) Β· 5.11 KB
/
trade.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import os
import time
from datetime import datetime
from dotenv import load_dotenv # pip install python-dotenv
import cbpro # pip install cbpro
import base64
import json
class Trade:
# initialize APIs and objects
API_KEY = os.environ.get("CBPRO_API_KEY")
SECRET = os.environ.get("CBPRO_SECRET")
PASSPHRASE = os.environ.get("CBPRO_PASSPHRASE")
SB_API_KEY = os.environ.get("CBPROSAND_API_KEY")
SB_SECRET = os.environ.get("CBPROSAND_SECRET")
SB_PASSPHRASE = os.environ.get("CBPROSAND_PASSPHRASE")
encoded = json.dumps(SECRET).encode()
b64_secret = base64.b64encode(encoded)
sb_encoded = json.dumps(SB_SECRET).encode()
sb_b64_secret = base64.b64encode(sb_encoded)
cbpro_client = cbpro.PublicClient()
def __init__(self, ticker, trade_strategy, investment):
self.ticker = ticker
self.side = "buy" if (trade_strategy == "BUY") else "sell"
self.investment = investment
self.order_success = False
self.holding_qty = 10
def paper(self):
"""Takes the recommended strategy of BUY or SELL and executes trade with Coinbase Pro Sandbox."""
auth_client = cbpro.AuthenticatedClient(
key=self.SB_API_KEY, b64secret=self.sb_b64_secret, passphrase=self.SB_PASSPHRASE
)
try:
current_ticker_info_response = self.cbpro_client.get_product_ticker(product_id=self.ticker)
except:
print(f"\nπ€: Boooops. Something went wrong. Unable to place order.")
try:
current_price = float(current_ticker_info_response['price'])
except Exception as e:
print(f"π€: Error obtaining ticker data. {e}")
order_size = round(self.investment / current_price, 5) if self.side == "buy" else self.holding_qty
print(f"π€: Placing order {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}: "
f"{self.ticker}, {self.side}, {current_price}, {order_size}, {int(time.time() * 1000)}"
)
try:
order_response = auth_client.place_limit_order(
product_id=self.ticker, side=self.side, price=current_price, size=order_size
)
# order_response = auth_client.place_market_order(product_id='BTC-USD',
# side='buy',
# funds=str(self.investment))
print(order_response)
except Exception as e:
print(f"π€: Error placing order. {e}")
time.sleep(4)
try:
check = order_response['id']
check_order = auth_client.get_order(order_id=check)
except Exception as e:
print(f"π€: Unable to check order. {e}")
if check_order['status'] == 'done':
print("π€: Order has been placed successfully BOOPboopboop!")
print(check_order)
self.holding_qty = order_size if self.side == "buy" else self.holding_qty
self.order_success = True
else:
print("π€: Order was not matched.")
return self.order_success
def execute(self):
"""Takes the recommended strategy of BUY or SELL and executes trade with Coinbase Pro."""
auth_client = cbpro.AuthenticatedClient(
key=self.API_KEY, b64secret=self.b64_secret, passphrase=self.PASSPHRASE
)
try:
current_ticker_info_response = self.cbpro_client.get_product_ticker(product_id=self.ticker)
except:
print(f"\nπ€: Boooops. Something went wrong. Unable to place order.")
try:
current_price = float(current_ticker_info_response['price'])
except Exception as e:
print(f"π€: Error obtaining ticker data. {e}")
order_size = round(self.investment / current_price, 5) if self.side == "buy" else self.holding_qty
print(f"π€: Placing order {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}: "
f"{self.ticker}, {self.side}, {current_price}, {order_size}, {int(time.time() * 1000)}"
)
try:
order_response = auth_client.place_limit_order(
product_id=self.ticker, side=self.side, price=current_price, size=order_size
)
except Exception as e:
print(f"π€: Error placing order. {e}")
try:
check = order_response["id"]
check_order = auth_client.get_order(order_id=check)
except Exception as e:
print(f"π€: Unable to check order. {e}")
if check_order['status'] == "done":
print("π€: Order has been placed successfully BOOPboopboop!")
print(check_order)
self.holding_qty = order_size if self.side == "buy" else self.holding_qty
self.order_success = True
else:
print("π€: Order was not matched.")
return self.order_success
def cancel_all_orders(self):
auth_client = cbpro.AuthenticatedClient(
key=self.API_KEY, b64secret=self.b64_secret, passphrase=self.PASSPHRASE
)
auth_client.cancel_all(product_id=self.ticker)
return