-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
140 lines (116 loc) · 4.59 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
# -*- coding: utf8 -*-
import datetime
import time
import sys
import win32com.client
from sqlalchemy.engine.url import URL
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from settings import DATABASE, A_USERNAME, A_PASSWORD, PAPERS, POOL_RECYCLE
from models import TradeType, AllTrade, Queue
def get_engine(drivername, username, password, host, port, database):
url = URL(DATABASE['DRIVERNAME'], DATABASE['USERNAME'], DATABASE['PASSWORD'],
DATABASE['HOST'], DATABASE['PORT'], DATABASE['DATABASE'],
DATABASE['QUERY'])
engine = create_engine(url, pool_recycle=POOL_RECYCLE)
return engine
def connect_terminal(A_USERNAME, A_PASSWORD):
terminal = win32com.client.Dispatch("ADLite.AlfaDirect")
terminal.UserName = A_USERNAME
terminal.Password = A_PASSWORD
terminal.Connected = True
return terminal
def check_trade_types(terminal_res, session_db):
trades_types_str = terminal_res.GetLocalDBData("trade_types",
"*",
"trd_type_code > 0")
trades_types_t = trades_types_str.split("\r\n")
trades_types_row = session_db.query(TradeType).all()
for num, row in enumerate(trades_types_row):
if row.trd_type_code != trades_types_t[num].split("|")[0]:
return False
return True
def get_paper_no(p_code, terminal_res):
condition = "p_code = '%s'" % p_code
response = terminal_res.GetLocalDBData("papers", '*', condition)
number = int(response.split("|")[0])
return number
def write_trades(num, i_last_update, terminal_res, session_db):
query_trades = "paper_no = %s AND i_last_update > %s" % (num, i_last_update,)
trades_str = terminal_res.GetLocalDBData("all_trades", '*', query_trades)
if len(trades_str) == 0:
raise ValueError('Not data in table "Trade_Types"')
for trade_row_str in trades_str.split("\r\n"):
if len(trade_row_str) == 0:
continue
trade_info = trade_row_str.split("|")
i_last_update = trade_info[5]
del trade_info[13]
session_db.add(AllTrade(*trade_info))
session_db.commit()
print "inserted trades", datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
return i_last_update
def write_queue(num, terminal_res, session_db):
query = "paper_no = %s" % num
queue_str = terminal_res.GetLocalDBData("queue", '*', query)
if len(queue_str) == 0:
raise ValueError('Not data in table "Queue"')
for queue_row_str in queue_str.split("\r\n"):
if len(queue_row_str) == 0:
continue
queue_info = queue_row_str.split("|")
queue_info[0] = num
del queue_info[5:]
session_db.add(Queue(*queue_info))
session_db.commit()
print "inserted queue", datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
return
def reconnect_ter(terminal_res):
if terminal_res.Connected == False:
terminal_res.Connected = True
print 'reconnected...'
return terminal_res
def dispatch():
terminal = connect_terminal(A_USERNAME, A_PASSWORD)
engine = get_engine(DATABASE['DRIVERNAME'], DATABASE['USERNAME'],
DATABASE['PASSWORD'], DATABASE['HOST'],
DATABASE['PORT'], DATABASE['DATABASE'])
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
if not check_trade_types(terminal, session):
raise Exception("Trades_types not valid")
else:
print "trade_types is valid"
paper_nums = dict([[get_paper_no(v, terminal), '0',] for v in PAPERS])
last_updated_time = datetime.datetime.now()
while 1:
current_time = datetime.datetime.now()
td = current_time - last_updated_time
if td < datetime.timedelta(seconds=1):
print 'sleep 1 second'
time.sleep(1)
continue
else:
last_updated_time = current_time
for num, i_last_update in paper_nums.items():
try:
i = write_trades(num, i_last_update, terminal, session)
paper_nums[num] = i
except ValueError, e:
print 'not data trades: ', e
reconnect_ter(terminal)
try:
write_queue(num, terminal, session)
except ValueError, e:
print 'not data queue: ', e
reconnect_ter(terminal)
continue
while 1:
try:
dispatch()
except KeyboardInterrupt:
print 'exit'
sys.exit()
#except:
# print 'some error'