-
Notifications
You must be signed in to change notification settings - Fork 0
/
binance_order_overview.py
368 lines (276 loc) · 11.5 KB
/
binance_order_overview.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
from binance.client import Client
from binance.um_futures import UMFutures
import time
import requests
import pandas as pd
import json
from pathlib import Path
from dhooks import Webhook
import decimal
import cli_inputs
from threading import Thread
import datetime as dt
import colorama
from colorama import Fore
colorama.init(autoreset=True)
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', 500)
def get_credentials(account):
root = Path(".")
file_path = f"{root}/credentials.json"
with open(file_path) as file:
file = file.read()
credentials = json.loads(file)
api_key = credentials[account]["binance_api_key"]
api_secret = credentials[account]["binance_api_secret"]
return api_key, api_secret
def auth(account):
api_key, api_secret = get_credentials(account=account)
binance_spot_client = Client(testnet=False, api_key=api_key, api_secret=api_secret)
binance_usdt_m_client = UMFutures(key=api_key, secret=api_secret)
return binance_spot_client, binance_usdt_m_client
def get_spot_balances(client, display:bool):
balances = client.get_account()["balances"]
products = client.get_all_tickers()
spot_positions = {}
coin_prices = {}
for row in products:
ticker = row["symbol"].replace("USDT", "")
price = float(row["price"]) # usd
coin_prices[ticker] = price
for balance in balances:
coin = balance["asset"]
coin_balance = float(balance["free"])
if coin_balance > 0:
if coin in coin_prices.keys() or coin in ["USDT", "USDC", "BUSD"]:
if coin in ["USDT", "USDC", "BUSD"]:
usd_value = coin_balance
else:
price = coin_prices[coin]
usd_value = round(coin_balance * price, 2)
if usd_value > 3:
spot_positions[coin] = {"coin_amount": coin_balance, "usd_value": usd_value}
if display:
print("Current positions:")
positions_df = pd.DataFrame.from_dict(spot_positions, orient="index")
print(positions_df.to_markdown())
return spot_positions
def get_spot_tickers(client):
products = client.get_all_tickers()
tickers = {}
for row in products:
symbol = row["symbol"]
ticker = row["symbol"]
if "USDT" in symbol:
symbol = symbol.replace("USDT", "")
tickers[symbol] = ticker
return tickers
def get_usdt_m_tickers(client):
ticker_data = client.ticker_24hr_price_change()
tickers = {}
for row in ticker_data:
symbol = row["symbol"]
ticker = row["symbol"]
if "USDT" in symbol:
symbol = symbol.replace("USDT", "")
if "10000" in symbol:
symbol = symbol.replace("10000", "")
elif "1000" in symbol:
symbol = symbol.replace("1000", "")
if "_" not in symbol:
tickers[symbol] = ticker
return tickers
def get_instrument_info_spot(client, ticker):
instrument_info = client.get_symbol_info(ticker)
min_notional = None
decimals = None
min_qty = None
max_qty = None
max_notional = None
tick_decimals = None
for row in instrument_info["filters"]:
if row["filterType"] == "NOTIONAL":
min_notional = float(row["minNotional"])
max_notional = float(row["maxNotional"])
elif row["filterType"] == "LOT_SIZE":
min_qty = float(row["minQty"])
max_qty = float(row["maxQty"])
min_qty_ = decimal.Decimal(row["minQty"]).normalize()
decimals = abs(min_qty_.as_tuple().exponent)
elif row["filterType"] == "PRICE_FILTER":
tick_size = decimal.Decimal(row["tickSize"]).normalize()
tick_decimals = abs(tick_size.as_tuple().exponent)
return min_notional, max_notional, decimals, tick_decimals ,min_qty, max_qty
def get_instrument_info_usdt_m(client, ticker):
symbol_info = client.exchange_info()["symbols"]
instrument_info = False
for i in symbol_info:
if i["symbol"] == ticker:
instrument_info = i
break
min_notional = None
min_qty = None
max_qty = None
decimals = None
tick_decimals = None
if instrument_info:
# print(instrument_info)
price_precision = instrument_info["pricePrecision"]
quantity_precision = instrument_info["quantityPrecision"]
decimals = quantity_precision
filters = instrument_info["filters"]
tick_size = decimal.Decimal(filters[0]["tickSize"]).normalize()
tick_decimals = abs(tick_size.as_tuple().exponent)
min_qty = float(filters[1]["minQty"])
max_qty = float(filters[1]["maxQty"])
min_notional = float(filters[5]["notional"])
# print(price_precision)
# print(quantity_precision)
# print(decimals)
# print(tick_size)
# print(tick_decimals)
# print(min_qty)
# print(max_qty)
# print(min_notional)
return min_notional, min_qty, max_qty, decimals, tick_decimals
def get_filled_orders_spot(client):
tickers = get_spot_tickers(client)
ticker = cli_inputs.select_ticker(tickers, spot=True)
lookback_window = cli_inputs.select_lookback_window()
orders = client.get_my_trades(symbol=ticker, limit=1000)
min_notional, max_notional, decimals, tick_decimals, min_qty, max_qty = get_instrument_info_spot(client, ticker)
start = dt.datetime.now() - dt.timedelta(hours=lookback_window)
cum_buy_qty = 0
buy_prc_times_qty = 0
cum_sell_qty = 0
sell_prc_times_qty = 0
filled_orders = []
for i in orders:
i["time"] = dt.datetime.fromtimestamp(i["time"]/1000)
if i["time"] >= start:
if i["isBuyer"]:
cum_buy_qty += float(i["qty"])
buy_prc_times_qty += float(i["qty"]) * float(i["price"])
else:
cum_sell_qty += float(i["qty"])
sell_prc_times_qty += float(i["qty"]) * float(i["price"])
if cum_buy_qty > 0:
filled_orders.append([ticker, "BUY", cum_buy_qty, round(buy_prc_times_qty / cum_buy_qty, tick_decimals)])
if cum_sell_qty > 0:
filled_orders.append([ticker, "SELL", cum_sell_qty, round(sell_prc_times_qty / cum_sell_qty, tick_decimals)])
# print(f"BUY >> executed qty: {cum_buy_qty} || avg price: {round(buy_prc_times_qty / cum_buy_qty, tick_decimals)}")
# print(f"SELL >> executed qty: {cum_sell_qty} || avg price: {round(sell_prc_times_qty / cum_sell_qty, tick_decimals)}")
final_df = pd.DataFrame(filled_orders, columns=["ticker", "side" ,"coins", "avg_price"])
final_df["usd_value"] = round(final_df["coins"] * final_df["avg_price"],2)
print(final_df.to_markdown())
def view_open_orders_spot(client):
pass
def get_filled_orders_usdt_m(client):
tickers = get_usdt_m_tickers(client)
ticker = cli_inputs.select_ticker(tickers, spot=False)
lookback_window = cli_inputs.select_lookback_window()
orders = client.get_account_trades(symbol="BTCUSDT", limit=1000)
min_notional, min_qty, max_qty, decimals, tick_decimals = get_instrument_info_usdt_m(client, ticker)
start = dt.datetime.now() - dt.timedelta(hours=lookback_window)
cum_buy_qty = 0
buy_prc_times_qty = 0
cum_sell_qty = 0
sell_prc_times_qty = 0
filled_orders = []
for i in orders:
i["time"] = dt.datetime.fromtimestamp(i["time"] / 1000)
if i["time"] >= start:
if i["buyer"]:
cum_buy_qty += float(i["qty"])
buy_prc_times_qty += float(i["qty"]) * float(i["price"])
else:
cum_sell_qty += float(i["qty"])
sell_prc_times_qty += float(i["qty"]) * float(i["price"])
if cum_buy_qty > 0:
filled_orders.append([ticker, "BUY", cum_buy_qty, round(buy_prc_times_qty / cum_buy_qty, tick_decimals)])
if cum_sell_qty > 0:
filled_orders.append([ticker, "SELL", cum_sell_qty, round(sell_prc_times_qty / cum_sell_qty, tick_decimals)])
# print(f"BUY >> executed qty: {cum_buy_qty} || avg price: {round(buy_prc_times_qty / cum_buy_qty, tick_decimals)}")
# print(f"SELL >> executed qty: {cum_sell_qty} || avg price: {round(sell_prc_times_qty / cum_sell_qty, tick_decimals)}")
final_df = pd.DataFrame(filled_orders, columns=["ticker", "side", "coins", "avg_price"])
final_df["usd_value"] = round(final_df["coins"] * final_df["avg_price"], 2)
print(final_df.to_markdown())
def orderOverview_binance_personal_SPOT(account):
spot_client, usdt_m_client = auth(account=account)
exit = False
while not exit:
print("\n")
print(Fore.LIGHTYELLOW_EX +"What do you want to do:"
"\n 1 >> display spot positions"
"\n 2 >> view filled orders"
"\n 3 >> view open limit orders"
"\n 4 >> cancel orders"
"\n 0 >> exit ")
mode = int(input("input number >>> "))
if mode == 0:
exit = True
print(Fore.LIGHTYELLOW_EX +f"Binance SPOT >> personal account - closing")
elif mode == 1:
print("\n")
get_spot_balances(spot_client, True)
elif mode == 2:
print("\n")
get_filled_orders_spot(spot_client)
elif mode == 3:
print("\n")
print("Not available yet")
elif mode == 4:
print("\n")
print("Not available yet")
# print(Fore.LIGHTCYAN_EX + "cancel options:"
# "\n 1 >> cancel all orders for specific side"
# "\n 2 >> cancel orders between 2 prices for specific side")
# price_mode = int(input(Fore.LIGHTCYAN_EX + "Input number >>> "))
def orderOverview_binance_personal_usdt_m(account):
spot_client, usdt_m_client = auth(account=account)
exit = False
while not exit:
print("\n")
print(Fore.LIGHTYELLOW_EX +"What do you want to do:"
"\n 1 >> view filled orders"
"\n 2 >> view open limit orders"
"\n 3 >> cancel orders"
"\n 0 >> exit ")
mode = int(input("input number >>> "))
if mode == 0:
exit = True
print(Fore.LIGHTYELLOW_EX +f"Binance SPOT >> personal account - closing")
elif mode == 1:
print("\n")
get_filled_orders_usdt_m(usdt_m_client)
elif mode == 2:
print("\n")
print("Not available yet")
elif mode == 3:
print("\n")
print("Not available yet")
# print(Fore.LIGHTCYAN_EX + "cancel options:"
# "\n 1 >> cancel all orders for specific side"
# "\n 2 >> cancel orders between 2 prices for specific side")
# price_mode = int(input(Fore.LIGHTCYAN_EX + "Input number >>> "))
def Order_overview():
exit = False
while not exit:
print("\n")
print(Fore.LIGHTYELLOW_EX + "Select account:"
"\n 1 >> Binance - personal_SPOT"
"\n 2 >> Binance - persoanl USDT-M"
"\n 0 >> exit terminal")
mode = int(input(Fore.LIGHTYELLOW_EX + "input number >>> "))
if mode == 0:
exit = True
print("\n")
print(Fore.LIGHTYELLOW_EX + "Terminal closing")
elif mode == 1:
print("\n")
orderOverview_binance_personal_SPOT(account="personal")
elif mode == 2:
print("\n")
orderOverview_binance_personal_usdt_m(account="personal")
# if __name__ == "__main__":
# main()