-
Notifications
You must be signed in to change notification settings - Fork 0
/
account.py
298 lines (276 loc) · 12.5 KB
/
account.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import config
import ccxt
from rsi_indicator import rsi
from tradingviewscraper import check_signals
from redmail import gmail
gmail.username = config.email
gmail.password = config.password
import time
from datetime import datetime, timedelta
STOP_LOSS = .03
TAKE_PROFIT = .05
class Account:
def __init__(self, exch = ccxt.gemini({'apiKey':config.apiKey, 'secret':config.apiSecret})):
self.exch = exch
self.balance = self.getBalanceInUSD()
self.active_trades = self.getActiveTrades()
self.recently_purchased = {}
def getBalanceInUSD(self):
exchange = self.exch
balances = exchange.fetch_balance()['free']
balance = 0
for token, value in balances.items():
if float(value) != 0:
if token != 'USDT' or token != 'USD':
request = token + '/USDT'
try:
price = float(exchange.fetchTicker(request)['last'])
except:
try:
request = token + '/BTC'
price = float(exchange.fetchTicker(request)['last'])
val_btc = (float(value)) * price
price = float(exchange.fetchTicker('BTC/USDT')['last'])
balance += val_btc * price
except:
try:
request = token + '/ETH'
price = float(exchange.fetchTicker(request)['last'])
val_btc = (float(value)) * price
price = float(exchange.fetchTicker('ETH/USDT')['last'])
balance += val_btc * price
except:
balance += float(value)
else:
balance += price * float(value)
else:
balance += float(value)
return balance
def _recent_trade(self, symbol='ETH/USD'):
trades = self.exch.fetch_my_trades(symbol)
latest_timestamp = float('-inf')
for trade in trades:
if latest_timestamp < trade['timestamp']:
latest_timestamp = trade['timestamp']
print(trade)
latest = datetime.utcfromtimestamp(latest_timestamp/1000)
dnow = datetime.now()
print('latest', latest, type(latest))
print('datetime now', dnow, type(dnow))
timediff = dnow - latest
if timediff.total_seconds()/60 > 60 * 12: # 12 hours
return False
return True
def _should_sell(self, symbol='ETH'):
if symbol in self.active_trades.keys():
if self.active_trades[symbol]['total_gain_fees'] < STOP_LOSS * -1:
print("Should sell, total loss + fees is below above 3%")
return True
elif self.active_trades[symbol]['total_gain_fees'] > TAKE_PROFIT:
print("Should sell, total gain + fees is below above 5%")
return True
else:
print("Hold, parameters not met.")
return False
print("Should not sell")
return False
def getBalanceUSD(self):
exchange = self.exch
balances = exchange.fetch_balance()['free']
balance = 0
for token, value in balances.items():
if float(value) != 0:
balance += float(value)
return balance
def average_purchase_price(self, symbol='ETH/USD'):
exchange = self.exch
associated_trades = exchange.fetchMyTrades(symbol=symbol)
avg_sum = 0
shares_owned = 0
for trade in associated_trades:
if trade['side'] == 'buy':
avg_sum += trade['amount'] * trade['price']
shares_owned += trade['amount']
elif trade['side'] == 'sell':
avg_sum -= trade['amount'] * trade['price']
shares_owned -= trade['amount']
return avg_sum / shares_owned
def shares_outstanding(self, symbol='ETH/USD'):
exchange = self.exch
associated_trades = exchange.fetchMyTrades(symbol=symbol)
shares_owned = 0
for trade in associated_trades:
if trade['side'] == 'buy':
shares_owned += trade['amount']
elif trade['side'] == 'sell':
shares_owned -= trade['amount']
return shares_owned
def total_fees(self, symbol='ETH/USD'):
exchange = self.exch
associated_trades = exchange.fetchMyTrades(symbol=symbol)
fee = 0
for trade in associated_trades:
if trade['fee']['currency'] == 'USD':
fee += trade['fee']['cost']
else:
request = trade['fee']['currency'] + '/USD'
fee = trade['fee']['cost'] * float(exchange.fetch_ticker(request)['last'])
return fee
def getActiveTrades(self):
active_trades = {}
for key, value in self.exch.fetch_balance().items():
if key == 'info' or key == 'free' or key == 'USD' or key == 'used' or key == 'total': continue
check_entry = key + '/USD'
entry = self.average_purchase_price(check_entry)
latest_price = float(self.exch.fetchTicker(check_entry)['last'])
total_fees = self.total_fees(check_entry)
active_trades[key] = {
'amount': self.shares_outstanding(check_entry),
'entry': entry,
'total_fees': total_fees,
'latest_price': latest_price,
'total_gain': (latest_price/entry)-1,
'total_gain_fees': (latest_price/(entry + total_fees))-1
}
return active_trades
def rsi_value(self, symbol='ETH/USD'):
_rsi = rsi(exchange=self.exch, symbol=symbol)
# 30 is the sweet spot and 70 is the max tolerance ... if it's 30 or below 1, if it's 70 or above -1
rsi_value = _rsi['RSI_14'].iloc[-1]
return rsi_value
def rsi_indicator(self, symbol='ETH/USD'):
_rsi = rsi(exchange=self.exch, symbol=symbol)
# 30 is the sweet spot and 70 is the max tolerance ... if it's 30 or below 1, if it's 70 or above -1
rsi_value = self.rsi_value( symbol='ETH/USD')
indicator = 0
if rsi_value <= 30: indicator = 1
elif rsi_value >= 70: indicator = -1
elif rsi_value <= 50:
indicator = abs(1-(abs (30-rsi_value)/20) )*1
elif rsi_value <70:
indicator = abs(1-( abs(rsi_value-70) / 20)) * -1
return indicator
def place_buy_market_order(self, symbol, amt):
last_price = self.exch.fetchTicker(symbol)['last']
try:
order = self.exch.create_limit_order(symbol=symbol, side='buy', amount=amt, price=last_price)
except Exception as e:
print(f"\t{e}\n\t\tInvalid Limit Order Quantity.")
gmail.send(
subject=f"CMon: Buy Order FAILED {symbol}. Amount: {amt}",
sender=f"{config.email}",
receivers=[f"{config.email}"],
# A plot in body
html=f"""Market buy order FAILED for {symbol}. Amount: {amt}."""
)
return {'status': f'Invalid Limit Order Quantity: {e}'}
return order
def place_sell_market_order(self, symbol, amt):
last_price = self.exch.fetchTicker(symbol)['last']
try:
order = self.exch.create_limit_order(symbol=symbol, side='sell', amount=amt, price=last_price)
except Exception as e:
print(f"\t{e}\n\t\tInvalid Limit Order Quantity.")
gmail.send(
subject=f"CMon: Sell Order FAILED {symbol}. Amount: {amt}",
sender=f"{config.email}",
receivers=[f"{config.email}"],
# A plot in body
html=f"""Market Sell order FAILED for {symbol}. Amount: {amt}."""
)
return {'status': f'Invalid Limit Order Quantity: {e}'}
return order
def tvs_enter_trade(self, check_signals):
# first look for opportunities in tradingview scraper
tvscraper = check_signals.query("decision == 'BUY'")
purchased = []
if tvscraper.empty:
print("No trades to enter.")
return None
for index,row in tvscraper.iterrows():
if row['with'] == 'USDT' or row['with'] == 'USD':
free_balance = self.getBalanceUSD()
elif row['with'] in self.active_trades.keys():
free_balance = self.active_trades[row['with']]['amount']
symbol = f'{row["buy"]}/{row["with"]}'
print('symbol', symbol, 'free balance', free_balance)
if free_balance != 0 and not self._recent_trade(symbol): # if it's not a recent trade then execute trade
weight = row['total weight']
# we want to get the total ((100/4) / 5 ) * weight
amount_free_to_use = (((1/4)/5) * weight) * free_balance
print(amount_free_to_use)
# convert from the amount we want to use to the specified amount
amt = amount_free_to_use/ self.exch.fetchTicker(symbol)['last']
print('buy', symbol, 'with', amt)
order = self.place_buy_market_order(symbol, amt)
if order['status'] == 'filled':
gmail.send(
subject=f"CMon: Buy Order Filled {symbol}. Amount: {amt}",
sender=f"{config.email}",
receivers=[f"{config.email}"],
# A plot in body
html=f"""
Market buy order filled for {symbol}. Amount: {amt}.
"""
)
purchased.append(symbol)
print("Market buy order filled")
else:
print("Market buy order failed")
return purchased
def tvs_exit_trade(self, check_signals):
# first look for opportunities in tradingview scraper
tvscraper = check_signals.query("decision == 'SELL'")
sold = []
if tvscraper.empty:
print("No trades to exit.")
return None
for index,row in tvscraper.iterrows():
print("symbol", row['buy'], "in active trades", self.active_trades.keys())
if row['buy'] == 'USDT' or row['buy'] == 'USD':
free_balance = self.getBalanceUSD()
elif row['buy'] in self.active_trades.keys():
free_balance = self.active_trades[row['buy']]['amount']
else:
print(f"Don't have security {row['buy']}. Cannot sell.")
continue
symbol = f'{row["buy"]}/{row["with"]}'
print('symbol', symbol, 'free balance', free_balance)
if free_balance != 0 and self._should_sell(symbol): # if we should sell then go forward
amount_free_to_use = free_balance
# convert from the amount we want to use to the specified amount
amt = amount_free_to_use / self.exch.fetchTicker(symbol)['last']
print('sell', symbol, 'with', amt)
order = self.place_sell_market_order(symbol, amt)
if order['status'] == 'filled':
gmail.send(
subject=f"CMon: Sell Order Filled {symbol}. Amount: {amt}",
sender=f"{config.email}",
receivers=[f"{config.email}"],
# A plot in body
html=f"""
Market Sell order filled for {symbol}. Amount: {amt}.
"""
)
sold.append(symbol)
print("Market Sell order filled")
else:
print("Market Sell order failed")
return sold
def runTvsBot():
acct = Account()
while True:
print('account value:', acct.balance)
print('get balance usd:', acct.getBalanceUSD())
print('active trades:', acct.active_trades)
print('rsi indicator:', acct.rsi_indicator())
print('rsi value:', acct.rsi_value())
indicators_df = check_signals()
print('entered into trades trade where:', acct.tvs_enter_trade(indicators_df))
print('exited trades where:', acct.tvs_exit_trade(indicators_df))
print("sleeping for 5 minutes")
time.sleep(300)
def main():
runTvsBot()
if __name__ == '__main__':
main()