-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
240 lines (203 loc) · 8.86 KB
/
main.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
# Python
import ccxt.pro
import asyncio
from asyncio import run, gather
from pprint import pprint
from ccxt.pro import exchanges
from configparser import ConfigParser
from utils.entities import Ticker, Order
config = ConfigParser()
config.read('./.config/config.cfg')
API_KEY = config.get('binance-test', 'apiKey')
API_SECRET = config.get('binance-test', 'secret')
async def place_delayed_order(exchange: ccxt.pro.Exchange, symbol, amount, price):
try:
order = await exchange.create_order(symbol, 'limit', 'buy', amount, price)
print(exchange.iso8601(exchange.milliseconds()), 'place_delayed_order')
pprint(order)
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_order_loop(exchange: ccxt.pro.Exchange, symbol: str):
your_delay = 1
await exchange.throttle(your_delay)
while True:
try:
orders = await exchange.watch_orders(symbol)
for order in orders:
if order['status'] == 'open' and order['filled'] == 0:
print('---------------------------Open Order NEW---------------------------')
pprint(order)
elif order['status'] == 'open' and order['filled'] == 0:
print('---------------------------Open Order PARTIALLY FILLED---------------------------')
pprint(order)
elif order['status'] == 'closed':
print('---------------------------Close Order---------------------------')
pprint(order)
elif order['status'] == 'canceled':
print('---------------------------Cancel Order---------------------------')
pprint(order)
# print(exchange.iso8601(exchange.milliseconds()), 'watch_orders_loop', len(orders), ' last orders cached')
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_orders_loop(exchange: ccxt.pro.Exchange, symbols: list):
loops = [watch_order_loop(exchange, symbol) for symbol in symbols]
# let them run, don't for all tasks cause they execute asynchronously
# don't print here
await asyncio.gather(*loops)
async def watch_balance_loop(exchange):
while True:
try:
balance = await exchange.watch_balance()
print(exchange.iso8601(exchange.milliseconds()), 'watch_balance_loop')
pprint(balance)
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_positions_loop(exchange:ccxt.Exchange):
while True:
try:
positions = await exchange.fetch_positions()
print(exchange.iso8601(exchange.milliseconds()), 'watch_positions_loop')
pprint(positions)
print('---------------------------------------------------------------')
await asyncio.sleep(1)
except Exception as e:
# break
print(e)
orderbooks = {}
def print_orderbook(exchange: ccxt.pro.Exchange, symbol, orderbook, limit: int = 5):
# this is a common handler function
# it is called when any of the orderbook is updated
# it has access to both the orderbook that was updated
# as well as the rest of the orderbooks
# ...................................................................
print('-------------------------------------------------------------')
print('Last updated:', exchange.iso8601(exchange.milliseconds()))
# ...................................................................
# print just one orderbook here
# print(orderbook['datetime'], symbol, orderbook['asks'][0], orderbook['bids'][0])
# ...................................................................
# or print all orderbooks that have been already subscribed-to
for symbol, orderbook in orderbooks.items():
print(orderbook['datetime'], symbol, orderbook['asks'][:limit], orderbook['bids'][:limit])
async def watch_orderbook_loop(exchange: ccxt.pro.Exchange, symbol):
# a call cost of 1 in the queue of subscriptions
# means one subscription per exchange.rateLimit milliseconds
your_delay = 1
await exchange.throttle(your_delay)
while True:
try:
orderbook = await exchange.watch_order_book(symbol)
orderbooks[symbol] = orderbook
print_orderbook(exchange, symbol, orderbook)
except Exception as e:
print(type(e).__name__, str(e))
async def watch_orderbooks_loop(exchange: ccxt.pro.Exchange, symbol_list):
loops = [watch_orderbook_loop(exchange, symbol) for symbol in symbol_list]
# let them run, don't for all tasks cause they execute asynchronously
# don't print here
await asyncio.gather(*loops)
async def watch_ticker_loop(exchange: ccxt.pro.Exchange, symbol: str):
while True:
try:
tickers = await exchange.watch_ticker(symbol)
print(exchange.iso8601(exchange.milliseconds()), 'watch_tickers_loop')
pprint(tickers)
print('---------------------------------------------------------------')
except Exception as e:
# break
print(e)
async def watch_tickers_loop(exchange: ccxt.pro.Exchange, symbols: list):
loops = [watch_ticker_loop(exchange, symbol) for symbol in symbols]
# let them run, don't for all tasks cause they execute asynchronously
# don't print here
await asyncio.gather(*loops)
async def main():
try:
exchange = ccxt.pro.binanceusdm({
'apiKey': API_KEY,
'secret': API_SECRET,
})
exchange.set_sandbox_mode(True)
symbol_1 = 'BTC/USDT:USDT'
symbol_2 = 'ETH/USDT:USDT'
loops = [
watch_tickers_loop(exchange, [symbol_1, symbol_2]),
# watch_orderbooks_loop(exchange, symbol_list=[symbol_1, symbol_2]),
# watch_orders_loop(exchange, [symbol_1, symbol_2]),
# watch_balance_loop(exchange),
# watch_positions_loop(exchange),
# place_delayed_order(exchange, symbol, amount, price)
]
await gather(*loops)
except KeyboardInterrupt:
print('Exiting...')
except Exception as e:
print(type(e).__name__, str(e))
finally:
await exchange.close()
if __name__ == '__main__':
asyncio.run(main())
# import ccxt.pro as ccxtpro
# from asyncio import get_event_loop, ensure_future
# from pprint import pprint
# print('CCXT Pro Version:', ccxtpro.__version__)
# class MyBinance(ccxtpro.binance):
# def on_connected(self, client, message=None):
# print('Connected to', client.url)
# ensure_future(create_order(self))
# async def on_partially_filled_order(self, client, order):
# print('--------------------------------------------------------------')
# print('Partially Filled Order:')
# pprint(order)
# async def on_filled_order(self, client, order):
# print('--------------------------------------------------------------')
# print('Filled Order:')
# pprint(order)
# async def on_canceled_order(self, client, order):
# print('--------------------------------------------------------------')
# print('Canceled Order:')
# pprint(order)
# async def create_order(exchange):
# symbol = 'BTC/USDT'
# type = 'limit'
# side = 'buy'
# amount = 123.45 # change for your values
# price = 54.321 # change for your values
# params = {}
# try:
# order = await exchange.create_order(symbol, type, side, amount, price, params)
# print('--------------------------------------------------------------')
# print('create_order():')
# pprint(order)
# except Exception as e:
# print(type(e).__name__, str(e))
# async def watch_orders(exchange):
# while True:
# try:
# orders = await exchange.watch_orders()
# for order in orders:
# if order['status'] == 'open':
# await exchange.on_partially_filled_order(exchange, order)
# elif order['status'] == 'closed':
# if order['filled'] == order['amount']:
# await exchange.on_filled_order(exchange, order)
# else:
# await exchange.on_canceled_order(exchange, order)
# except Exception as e:
# print(type(e).__name__, str(e))
# break
# await exchange.close()
# loop = get_event_loop()
# exchange = MyBinance({
# 'enableRateLimit': True,
# 'apiKey': 'YOUR_API_KEY',
# 'secret': 'YOUR_SECRET',
# 'asyncio_loop': loop,
# })
# loop.run_until_complete(watch_orders(exchange))