-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
96 lines (74 loc) · 2.61 KB
/
bot.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
import websocket
import json
import pprint
import talib
import numpy
import config
from binance.client import Client
from binance.enums import *
SOCKET = "wss://stream.binance.com:9443/ws/ethusdt@kline_1m"
RSI_PERIOD = 14
RSI_OVERBOUGHT = 70
RSI_OVERSOLD = 30
TRADE_SYMBOL = 'ETHUSD'
TRADE_QUANTITY = 0.05
closes = []
in_position = False
client = Client(config.API_KEY, config.API_SECRET, tld='us')
def order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET):
try:
print("sending order")
order = client.create_order(
symbol=symbol, side=side, type=order_type, quantity=quantity)
print(order)
except Exception as e:
print("an exception occured - {}".format(e))
return False
return True
def on_open(ws):
print('opened connection')
def on_close(ws):
print('closed connection')
def on_message(ws, message):
global closes, in_position
print('received message')
json_message = json.loads(message)
pprint.pprint(json_message)
candle = json_message['k']
is_candle_closed = candle['x']
close = candle['c']
if is_candle_closed:
print("candle closed at {}".format(close))
closes.append(float(close))
print("closes")
print(closes)
if len(closes) > RSI_PERIOD:
np_closes = numpy.array(closes)
rsi = talib.RSI(np_closes, RSI_PERIOD)
print("all rsis calculated so far")
print(rsi)
last_rsi = rsi[-1]
print("the current rsi is {}".format(last_rsi))
if last_rsi > RSI_OVERBOUGHT:
if in_position:
print("Overbought! Sell! Sell! Sell!")
# add binance sell logic here
order_succeeded = order(
SIDE_SELL, TRADE_QUANTITY, TRADE_SYMBOL)
if order_succeeded:
in_position = False
else:
print("It is overbought, but we don't own any. Nothing to do.")
if last_rsi < RSI_OVERSOLD:
if in_position:
print("It is oversold, but you already own it, nothing to do.")
else:
print("Oversold! Buy! Buy! Buy!")
# add binance buy order logic here
order_succeeded = order(
SIDE_BUY, TRADE_QUANTITY, TRADE_SYMBOL)
if order_succeeded:
in_position = True
ws = websocket.WebSocketApp(SOCKET, on_open=on_open,
on_close=on_close, on_message=on_message)
ws.run_forever()