-
Notifications
You must be signed in to change notification settings - Fork 18
/
trader_service.py
81 lines (62 loc) · 2.43 KB
/
trader_service.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
from asyncio import AbstractEventLoop
from trader.common.helpers import get_network_ip
from trader.common.logging_helper import LogLevels, set_all_log_level, setup_logging
from trader.container import Container
from trader.trading.trading_runtime import Trader
import asyncio
import click
import logging as log
import os
import signal
logging = setup_logging(module_name='trader_service')
@click.command()
@click.option('--simulation', required=False, default=False, help='load with historical data')
@click.option('--config', required=False, default='/home/trader/mmr/configs/trader.yaml',
help='trader.yaml config file location')
def main(simulation: bool,
config: str):
is_stopping = False
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
container = Container(config)
trader = container.resolve(Trader, simulation=simulation)
def stop_loop(loop: AbstractEventLoop):
nonlocal is_stopping
if loop.is_running() and not is_stopping:
is_stopping = True
loop.run_until_complete(trader.shutdown())
pending_tasks = [
task for task in asyncio.all_tasks() if not task.done()
]
if len(pending_tasks) > 0:
for task in pending_tasks:
logging.debug(task.get_stack())
logging.debug('waiting five seconds for {} pending tasks'.format(len(pending_tasks)))
loop.run_until_complete(asyncio.wait(pending_tasks, timeout=5))
loop.stop()
# SystemExit's out of the current asyncio loop
exit(0)
if simulation:
# ib_client = HistoricalIB(logger=logging)
raise ValueError('simulation not implemented yet')
try:
if os.environ.get('TRADER_NODEBUG'):
set_all_log_level(LogLevels.CRITICAL)
else:
loop.set_debug(enabled=True)
loop.add_signal_handler(signal.SIGINT, stop_loop, loop)
trader.connect()
ip_address = get_network_ip()
logging.debug('starting trading_runtime at network address: {}'.format(ip_address))
# start the trader
logging.debug('starting trader run() loop')
trader.run()
except KeyboardInterrupt:
logging.debug('KeyboardInterrupt')
stop_loop(loop)
exit()
except SystemExit:
logging.debug('SystemExit')
os._exit(0)
if __name__ == '__main__':
main()