-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathorderstreamer.py
More file actions
257 lines (226 loc) · 9.05 KB
/
orderstreamer.py
File metadata and controls
257 lines (226 loc) · 9.05 KB
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
import requests
import hashlib
import localsettings
import time
import urllib
import hmac
from datetime import datetime, timedelta
from dbtools.models import RealOrder, Trade
from dbtools.db import Session
from sqlalchemy import or_, and_
import telegram_send
import threading
import math
"""
payload = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC', # Good Till Cancel
'quantity': 0.0015,
'price': 9800,
# 'newClientOrderId': 'xwdfrtest'
}
payload['timestamp'] = int(time.time()) * 1000
# payload.update({'timestamp': int(time.time()) * 1000})
payload_str = urllib.parse.urlencode(payload).encode('utf-8')
sign = hmac.new(
key=localsettings.SECRET_KEY,
# key=settings.SECRET_KEY,
msg=payload_str,
digestmod=hashlib.sha256
).hexdigest()
payload_str = payload_str.decode("utf-8") + "&signature=" + str(sign)
headers = {"X-MBX-APIKEY": localsettings.API_KEY, "Content-Type": "application/json"}
response = requests.request(method='POST', url='https://api.binance.com/api/v3/order',
data=payload_str, headers=headers)
print(response)
print(response.json())
"""
class OrderManager:
last_trade_price = 0
repeated_buy_count = 0
repeated_sell_count = 0
buy_sell = 0
cash = localsettings.initialcash
btc = localsettings.initialbtc
@staticmethod
def sign(params):
params['timestamp'] = (int(time.time()) * 1000)
params['recvWindow'] = 50000
params_str = urllib.parse.urlencode(params).encode('utf-8')
sign = hmac.new(
key=localsettings.SECRET_KEY,
msg=params_str,
digestmod=hashlib.sha256
).hexdigest()
return params_str.decode("utf-8") + "&signature=" + str(sign)
@staticmethod
def get_header():
return {"X-MBX-APIKEY": localsettings.API_KEY, "Content-Type": "application/json"}
@staticmethod
def send_order(order):
order['price'] = round(order['price'], 2)
order['quantity'] = round(order['quantity'], 6)
response = requests.request(method='POST', url='https://api.binance.com/api/v3/order',
data=OrderManager.sign(params=order), headers=OrderManager.get_header())
print("order sent in {}".format(datetime.now()))
if response.status_code == 200:
print("order placed in {}".format(datetime.now()))
return response.json()
else:
print(order)
print("ERROR {}:".format(order['side']), response.json())
@staticmethod
def cancel_order(symbol, order_id):
params = {
'symbol': symbol,
'orderId': order_id,
}
print("sent request to cancel order {}".format(params['orderId']))
response = requests.request(method='DELETE', url='https://api.binance.com/api/v3/order',
data=OrderManager.sign(params=params), headers=OrderManager.get_header())
if response.status_code == 200:
return response.json()
print("successfully deleted")
@staticmethod
def cancel_all_orders(symbol):
params = {
'symbol': symbol,
}
response = requests.request(method='DELETE', url='https://api.binance.com/api/v3/openOrders',
data=OrderManager.sign(params=params), headers=OrderManager.get_header())
if response.status_code == 200:
return response.json()
@staticmethod
def get_order(symbol, order_id):
params = {
'symbol': symbol,
'orderId': order_id,
}
response = requests.request(method='GET', url='https://api.binance.com/api/v3/order',
params=OrderManager.sign(params=params), headers=OrderManager.get_header())
if response.status_code == 200:
return response.json()
@staticmethod
def get_now():
return datetime.utcnow() + timedelta(hours=2, minutes=0)
@staticmethod
def send_telegram_message(msg):
price = float(msg['p'])
traded_volume = float(msg['z'])
side = msg['S']
message_text = f"{msg['x']}, {side}, {traded_volume}BTC in {price}$"
if float(msg['z']) >= localsettings.strategy_volume:
message_text += f"\n wallet update: btc({round(OrderManager.btc, 2)}), cash({round(OrderManager.cash, 2)})"
telegram_send.send(messages=[message_text])
@staticmethod
def update_order(msg):
print(msg)
print(OrderManager.get_now())
OrderManager.insert_trade(msg)
info = {
'binance_id': str(msg['i']),
'symbol': msg['s'],
'price': float(msg['p']),
'volume': float(msg['q']),
'traded_volume': float(msg['z']),
'status': msg['x'],
'insert_time': OrderManager.get_now()
}
session = Session()
orders = session.query(RealOrder).filter(RealOrder.binance_id == info['binance_id'])
to_balance = False
if orders.count() > 0:
order = orders.first()
order.traded_volume = info['traded_volume']
order.status = info['status']
if order.traded_volume == order.volume:
order.status = 'DONE'
OrderManager.last_trade_price = order.price
to_balance = True
side = msg['S']
if side == 'BUY':
OrderManager.buy_sell += 1
OrderManager.btc += float(msg['z'])
OrderManager.cash -= float(msg['p'])*float(msg['z'])
OrderManager.repeated_buy_count += 1
OrderManager.repeated_sell_count = 0
elif side == 'SELL':
OrderManager.buy_sell -= 1
OrderManager.btc -= float(msg['z'])
OrderManager.cash += float(msg['p'])*float(msg['z']) * 0.999
OrderManager.repeated_sell_count += 1
OrderManager.repeated_buy_count = 0
print("order {} at {} is done".format(info['binance_id'], order.price))
order.update_time = OrderManager.get_now()
else:
order = RealOrder(**info)
session.add(order)
session.commit()
telegram_thread = threading.Thread(target=OrderManager.send_telegram_message, args=[msg])
telegram_thread.start()
if to_balance:
OrderManager.balance_strategy(order)
session.close()
@staticmethod
def insert_trade(msg):
info = {
'binance_id': str(msg['i']),
'symbol': msg['s'],
'price': float(msg['p']),
'volume': float(msg['q']),
'traded_volume': float(msg['z']),
'status': msg['x'],
'insert_time': OrderManager.get_now()
}
session = Session()
trade = Trade(**info)
session.add(trade)
session.commit()
session.close()
@staticmethod
def balance_strategy(order):
print("inside balance order")
session = Session()
# OrderManager.cancel_all_orders(order.symbol)
other_side_orders = session.query(RealOrder).filter(or_(RealOrder.status == 'NEW', RealOrder.status == 'TRADE'))
print("before if")
if other_side_orders.count() > 0:
print("inside if")
other_side_order = other_side_orders.first()
print("other side order is {}".format(other_side_order.binance_id))
OrderManager.cancel_order(symbol=order.symbol, order_id=int(other_side_order.binance_id))
session.commit()
session.close()
buy_step = 1
# if OrderManager.repeated_buy_count >= 2:
# buy_step = 2**(int(math.log2(OrderManager.repeated_buy_count))-1)
if OrderManager.buy_sell >= 2:
buy_step = 2**(int(math.log2(OrderManager.buy_sell))-1)
sell_step = 1
# if OrderManager.repeated_sell_count >= 2:
# sell_step = 2**(int(math.log2(OrderManager.repeated_sell_count))-1)
if OrderManager.buy_sell <= -2:
sell_step = 2**(int(math.log2(-1 * OrderManager.buy_sell))-1)
OrderManager.send_order({
'side': 'BUY',
'type': 'LIMIT',
'timeInForce': 'GTC', # Good Till Cancel
'price': order.price * (1-buy_step*localsettings.strategy_percent),
'quantity': localsettings.strategy_volume*(1+0.001),
'symbol': "BTCUSDT",
})
#plunging price
#if OrderManager.last_trade_price != order.price * (1-localsettings.strategy_percent):
#print("sell order sent at: {}".format(datetime.now()))
OrderManager.send_order({
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC', # Good Till Cancel
'price': order.price * (1+sell_step*localsettings.strategy_percent),
'quantity': localsettings.strategy_volume,
'symbol': "BTCUSDT",
})
#else:
#print("order skipped at: {}".format(datetime.now()))