-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathautotrader.py
executable file
·1141 lines (964 loc) · 41.3 KB
/
autotrader.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: terryh.tp at gmail.com
# wxPython
import wx
from wx.lib.wordwrap import wordwrap
from wxobject import MyFrame, M, C, D, S
import os
import sys
import logging
import re
import datetime
import subprocess
import shlex
import tempfile
import multiprocessing
import multiprocessing.forking
# help pyinstaller, cx_Freeze to include
from ctypes import POINTER, WINFUNCTYPE, c_char_p, c_void_p, c_int, c_ulong
from ctypes.wintypes import BOOL, DWORD, BYTE, INT, LPCWSTR, UINT, ULONG
#import calendar
#from shutil import copyfile
# locale
#import gettext
#_ = gettext.ugettext
# third party module
from configobj import ConfigObj
#help pyinstaller to find
import pytz
#------------------------------------------
from tz import timezones
from wxutils import wxd_to_python, python_to_wxd, showMsg, ShowBusyCursor
from quote.utils import get_now, get_tz_hhmm
# Process
from quote.quoteworker import QuoteWriter
__version__ = u'0.2.1'
__appname__ = u'AutoTrader'
__author__ = u'TerryH'
app_realpath = os.path.realpath(sys.argv[0])
app_dir = os.path.dirname(app_realpath)
market_ini = os.path.join(app_dir, 'config', 'market.ini')
commodity_ini = os.path.join(app_dir, 'config', 'commodity.ini')
strategy_ini = os.path.join(app_dir, 'config', 'strategy.ini')
data_dir = os.path.join(app_dir, 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
re_alphanumeric = re.compile(r'^\w+$')
re_date = re.compile(r'^\d{4}-\d{2}-\d{2}$')
quote_module_dir = 'quote'
QUOTE_SOURCE = [u"", u'DDE']
# fixed name for quoteworker
QUOTE_WRITER_EXE = 'quoteworker.exe'
TRADER_EXE = 'trader.exe'
# support tracking trade time
SUPPORT_TIME = ['min1', 'min2', 'min3', 'min5', 'min15', 'min30', 'hour1',
'day1']
SUPPORT_TIME_NAME = ['1 Min', '2 Min', '3 Min', '5 Min', '15 Min',
'30 Min', '1 Hour', '1 Day']
#SUPPORT_TIME_NAME = ['1 Min':'min1',
# '2 Min':'min2',
# '3 Min':'min3',
# '5 Min':'min5',
# '15 Min':'min15',
# '30 Min':'min30',
# '1 Hour':'hour1',
# '1 Day':'day1'
# }
######################################################
# work around for pyinstaller one file execuable pack
# but now we use cx_Freeze
class _Popen(multiprocessing.forking.Popen):
def __init__(self, *args, **kw):
if hasattr(sys, 'frozen'):
# We have to set original _MEIPASS2 value from sys._MEIPASS
# to get --onefile mode working.
# Last character is stripped in C-loader. We have to add
# '/' or '\\' at the end.
os.putenv('_MEIPASS2', sys._MEIPASS + os.sep)
try:
super(_Popen, self).__init__(*args, **kw)
finally:
if hasattr(sys, 'frozen'):
# On some platforms (e.g. AIX) 'os.unsetenv()' is not
# available. In those cases we cannot delete the variable
# but only set it to the empty string. The bootloader
# can handle this case.
if hasattr(os, 'unsetenv'):
os.unsetenv('_MEIPASS2')
else:
os.putenv('_MEIPASS2', '')
class Process(multiprocessing.Process):
_Popen = _Popen
################################################################################
# start multiprocessing.Process outside wxApp main loop
# now in favor to subprocess.Popen via the following code block
def start_quote_process(quote_method, commodity='', commodity_ini=''):
quote_module = __import__(
"quote.%s" % quote_method, fromlist=[quote_method])
p = multiprocessing.Process(
target=quote_module.main, args=(commodity, commodity_ini))
p.start()
return p
def start_quote_workers(market_ini, commodity_ini, ccode):
p = QuoteWriter(market_ini, commodity_ini, ccode)
p.start()
return p
################################################################################
################################################################################
# start subprocess.Popen outside wxApp main loop
def sub_process_stdout(final_command):
#print final_command
p = subprocess.Popen(shlex.split(final_command), stdout=subprocess.PIPE)
return p
def sub_process(final_command):
#print final_command
p = subprocess.Popen(shlex.split(final_command))
return p
################################################################################
#------------------------------------------
class Mixin(object):
def collect_data(self):
raw_dict = {}
for k in self.field_keys:
if getattr(self.__dict__[k], 'GetValue', False):
raw_dict[k] = self.__dict__[k].GetValue()
elif getattr(self.__dict__[k], 'GetStringSelection', False):
raw_dict[k] = self.__dict__[k].GetStringSelection()
elif getattr(self.__dict__[k], 'GetPath', False):
raw_dict[k] = self.__dict__[k].GetPath()
return raw_dict
def loaditem(self, code=''):
if self.configobj and code in self.configobj:
for k in self.field_keys:
#print k
if self.configobj[code].get(k):
setvalue = self.configobj[code].get(k)
# casting
if setvalue == u'True':
setvalue = True
if setvalue == u'False':
setvalue = False
# datetime date to wx.DateTime
if (isinstance(setvalue, str) or isinstance(setvalue, unicode)) and re_date.search(setvalue):
setvalue = python_to_wxd(setvalue)
if getattr(self.__dict__[k], 'SetValue', False):
self.__dict__[k].SetValue(setvalue)
elif getattr(self.__dict__[k], 'SetStringSelection', False):
self.__dict__[k].SetStringSelection(setvalue)
elif getattr(self.__dict__[k], 'SetPath', False):
self.__dict__[k].SetPath(setvalue)
#------------------------------------------
class Strategy(S, Mixin):
def __init__(self, *args, **kwds):
S.__init__(self, *args, **kwds)
wx.EVT_CHAR_HOOK(self, self.onKey)
self.configobj = {}
self.inifile = strategy_ini
self.configobj = {}
self.c_obj = ConfigObj(commodity_ini, encoding='utf-8')
self.field_keys = ['strategyfile', 'historyfile', 'ccode',
'period', 'num', 'cost',
'start', 'end', 'sid', 'run'
]
self.require_fields = ['strategyfile', 'ccode', 'period', 'num']
self.ccode.SetItems([v.get('ccode') for k, v in self.c_obj.items()])
self.period.SetItems(SUPPORT_TIME_NAME)
self.loaddata()
def validate(self, raw_dict={}):
for key in self.require_fields:
if not raw_dict.get(key, False):
return False
# extra validate
if not raw_dict.get('num').isdigit():
return False
if raw_dict.get('cost', False) and not raw_dict.get('cost').isdigit():
return False
return True
def get_data_dir(self):
if self.ccode.GetValue():
ccode = self.ccode.GetValue()
dir_name = "%s_%s" % (self.c_obj[ccode].get(
'mcode'), self.c_obj[ccode].get('ccode'))
history_dir = os.path.join(data_dir, dir_name)
if history_dir and not os.path.exists(history_dir):
os.makedirs(history_dir)
return history_dir
return ''
def onSubmit(self, event):
raw_dict = self.collect_data()
if not self.validate(raw_dict):
dlg = wx.MessageDialog(self,
_("You must at least have strategy file, commodity code, trading time period and max number of bars will use in strategy."),
_("Strategy"),
wx.OK | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
else:
dlg = wx.MessageDialog(self,
_("Are you sure want to update?"),
_("Strategy"),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
sid = self.sid.GetValue()
if not sid:
# let's find a new sid, forget about race, lock, and looping
start_id = 1
if not sid:
sid = self.get_new_id()
raw_dict['sid'] = sid
# wx.DateTime
if raw_dict.get('start'):
raw_dict['start'] = wxd_to_python(
raw_dict.get('start')).strftime('%Y-%m-%d')
if raw_dict.get('end'):
raw_dict['end'] = wxd_to_python(
raw_dict.get('end')).strftime('%Y-%m-%d')
if sid not in self.configobj:
# insert
self.configobj[sid] = {}
for key in self.field_keys:
self.configobj[sid][key] = raw_dict.get(key, '')
self.configobj.write() # write ini file
self.Destroy()
def onValidate(self, event):
raw_dict = self.collect_data()
if 'strategyfile' in raw_dict:
final_command = r'%s --file "%s"' % (
TRADER_EXE, raw_dict['strategyfile'])
p = sub_process_stdout(final_command)
message = p.stdout.read().strip()
if message:
print "Go , haha ,cauch U", str(message), len(message), len(message.strip())
showMsg(self, message)
else:
showMsg(self, _("No error found"))
def onDelete(self, event):
if self.configobj and self.sid.GetValue():
sid = self.sid.GetValue()
dlg = wx.MessageDialog(self,
_('Are you sure?'),
_('Delete'),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
del self.configobj[sid] # delete & write back
self.configobj.write()
self.Destroy()
self.Destroy()
def onKey(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
self.Close()
event.Skip()
def onBackTest(self, event):
print "BackTest"
# you must specify the start date, end date or both
self.onSubmit(event)
self.loaddata()
sid = self.sid.GetValue()
raw_dict = self.configobj[sid]
# condition to run back test
_goBackTest = ((raw_dict.get('start') or raw_dict.get('end')) and
raw_dict.get('strategyfile') and raw_dict.get('historyfile'))
if _goBackTest:
# example command
# python trader.py -his FITX.txt --end 2010/10/13 -b 10 -f stest.py
command_list = [TRADER_EXE, '--file', r'"%s"' %
raw_dict['strategyfile']]
if raw_dict.get('start'):
command_list.append("--start")
command_list.append(raw_dict['start'])
if raw_dict.get('end'):
command_list.append("--end")
command_list.append(raw_dict['end'])
# must have
command_list.append("--history")
command_list.append(r'"%s"' % raw_dict['historyfile'])
final_command = " ".join(command_list)
p = sub_process_stdout(final_command)
message = p.stdout.read().strip()
#message = p.stdout.read()
if message:
# clean windows stdout line break
message = message.replace('\r', "")
fname = os.path.join(tempfile.gettempdir(), "autotrader.csv")
fp = open(fname, "w")
fp.write(message)
os.startfile(fname)
else:
dlg = wx.MessageDialog(self,
_("You must at least, config start date, end date or both, with history file"),
_("Back Test"),
wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal()
dlg.Destroy()
def get_new_id(self):
start_id = 1
sid = 0
while not sid:
if not str(start_id) in self.configobj:
sid = str(start_id)
return sid
start_id += 1
def loaddata(self):
self.configobj = ConfigObj(self.inifile, encoding='utf-8')
#------------------------------------------
class DDEWIN(D, Mixin):
def __init__(self, *args, **kwds):
D.__init__(self, *args, **kwds)
wx.EVT_CHAR_HOOK(self, self.onKey)
self.configobj = {}
self.field_keys = ['mcode', 'ccode',
'dde1_server', 'dde1_topic', 'dde1_time', 'dde1_price', 'dde1_volume',
'dde2_server', 'dde2_topic', 'dde2_time', 'dde2_price', 'dde2_volume'
] + SUPPORT_TIME
self.require_fields = ['dde1_server', 'dde1_topic',
'dde1_time', 'dde1_price', 'dde1_volume']
def validate(self, raw_dict={}):
for key in self.require_fields:
if not raw_dict.get(key, False):
return False
return True
def onSubmit(self, event):
raw_dict = self.collect_data()
if not self.validate(raw_dict):
dlg = wx.MessageDialog(self,
_("You must at least input DD1, time, price and volume, can refer from Excel."),
_("DDE"),
wx.OK | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
else:
dlg = wx.MessageDialog(self,
_("Are you sure want to update?"),
_("DDE"),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
# TODO
self.GetParent().update_quote(raw_dict, self.field_keys)
self.Destroy()
def onCancel(self, event):
self.Close()
def onDelete(self, event):
if self.configobj:
dlg = wx.MessageDialog(self,
_('Are you sure?'),
_('Delete'),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
self.GetParent().delete_quote()
self.Destroy()
self.Destroy()
def onKey(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
self.Close()
event.Skip()
#------------------------------------------
class Commodity(C, Mixin):
def __init__(self, *args, **kwds):
C.__init__(self, *args, **kwds)
wx.EVT_CHAR_HOOK(self, self.onKey)
self.field_keys = ['cname', 'ccode', 'mcode', 'cpov',
'csource', 'cdir']
self.require_fields = ['cname', 'ccode', 'mcode']
self.inifile = commodity_ini
self.configobj = {}
self.m_obj = ConfigObj(market_ini, encoding='utf-8')
self.markets = [(v.get('mname'), v.get('mcode')) for k,
v in self.m_obj.items()]
self.loaddata()
self.csource.SetItems(QUOTE_SOURCE)
self.mcode.SetItems([mcode for mname, mcode in self.markets])
def validate(self, raw_dict={}):
for key in self.require_fields:
if not raw_dict.get(key, False):
return False
if not re_alphanumeric.search(raw_dict.get('ccode')):
return False
return True
def onSubmit(self, event):
raw_dict = self.collect_data()
if not self.validate(raw_dict):
dlg = wx.MessageDialog(self,
_("You must at least input Commodity Name, Commodity Code (alphanumeric), and Quote Folder for real time data processing, better at a ram disk folder."),
_("Market"),
wx.OK | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
else:
dlg = wx.MessageDialog(self,
_("Are you sure want to update?") +
' ' + _("Remember to restart to ative changes."),
_("Market"),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
ccode = raw_dict['ccode'].upper()
raw_dict['ccode'] = ccode
if ccode not in self.configobj:
self.configobj[ccode] = {}
#print raw_dict
for key in self.field_keys:
self.configobj[ccode][key] = raw_dict.get(key, '')
self.configobj.write() # write ini file
self.Close()
def onSource(self, event):
if self.csource.GetStringSelection():
self.config.Enable()
else:
self.config.Enable(False)
def onConfig(self, event):
raw_dict = self.collect_data()
source = raw_dict.get('csource')
mcode = raw_dict.get('mcode')
ccode = raw_dict.get('ccode')
if source and source in QUOTE_SOURCE:
support_time = SUPPORT_TIME # FIXME, check this value
try:
exec('support_time = %s_SUPPORT_TIME' % source)
except:
pass # FIXME, better chance to load support field
try:
__import__("quote.%s" % (source), fromlist=[source])
dlg = DDEWIN(self) # FIXME, add more config
dlg.mcode.SetValue(mcode)
dlg.ccode.SetValue(ccode)
self.loaddata() # reload data again to make sure
if self.configobj.get(ccode):
dlg.configobj = self.configobj.get(ccode)
dlg.loaditem('quote')
dlg.ShowModal()
dlg.Destroy()
except ImportError:
self.GetParent().loginfo(_('No support quote module found.'))
def onHistory(self, event):
history_dir = self.check_history()
if history_dir:
if os.name == 'nt':
os.startfile(history_dir)
elif os.name == 'posix':
try:
os.system('xdg-open %s' % history_dir)
# try open histtory folder on linux
except:
pass # TODO
def check_history(self):
dir_name = ''
history_dir = ''
if self.ccode.GetValue() and self.mcode.GetStringSelection():
self.history.Enable()
dir_name = "%s_%s" % (self.mcode.GetStringSelection(
), self.ccode.GetValue().upper())
history_dir = os.path.join(data_dir, dir_name)
if history_dir and not os.path.exists(history_dir):
os.makedirs(history_dir)
return history_dir
else:
self.history.Enable(False)
return
def onMcode(self, event):
self.check_history()
def onDelete(self, event):
ccode = self.ccode.GetValue().upper()
if ccode and ccode in self.configobj:
dlg = wx.MessageDialog(self,
_('Are you sure?'),
_('Delete'),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
del self.configobj[ccode]
self.configobj.write()
self.Destroy()
def onKey(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
self.Close()
event.Skip()
def loaddata(self, m_obj={}):
self.configobj = ConfigObj(self.inifile, encoding='utf-8')
if m_obj:
self.m_obj = m_obj
def set_market_obj(self, m_obj={}):
if m_obj:
self.m_obj = m_obj
def update_quote(self, quote_obj={}, field_keys=[]):
if self.configobj and self.ccode.GetValue() and self.configobj.get(self.ccode.GetValue()):
cid = self.ccode.GetValue()
if not self.configobj[cid].get('quote', False):
self.configobj[cid]['quote'] = {}
for k in field_keys:
self.configobj[cid]['quote'][k] = quote_obj.get(k, '')
self.configobj.write()
def delete_quote(self):
if self.configobj and self.ccode.GetValue() and self.configobj.get(self.ccode.GetValue()):
del self.configobj[self.ccode.GetValue()]['quote']
self.configobj.write()
def loaditem(self, ccode=''):
super(Commodity, self).loaditem(ccode)
if self.csource.GetStringSelection():
self.config.Enable()
if self.ccode.GetValue() and self.mcode.GetStringSelection():
self.history.Enable()
#------------------------------------------
class Market(M, Mixin):
def __init__(self, *args, **kwds):
M.__init__(self, *args, **kwds)
wx.EVT_CHAR_HOOK(self, self.onKey)
self.field_keys = ['mname', 'mcode', 'mtimezone', 'mclear',
's1_start', 's1_end', 's2_start', 's2_end',
'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6'
]
self.require_fields = ['mname', 'mcode', 'mtimezone',
'mclear', 's1_start', 's1_end']
self.inifile = market_ini
self.configobj = {}
self.loaddata()
self.mtimezone.SetItems(timezones)
def validate(self, raw_dict={}):
for key in self.require_fields:
if not raw_dict.get(key, False):
return False
if not re_alphanumeric.search(raw_dict.get('mcode')):
return False
# special check for time 24HHMM
if raw_dict['mclear'] == u'00:00' or raw_dict['s1_end'] == u'00:00':
return False
return True
def onSubmit(self, event):
raw_dict = self.collect_data()
if not self.validate(raw_dict):
dlg = wx.MessageDialog(self,
_("You must at least input Market Name, Market Code (alphanumeric), Session Clear Time and Session 1 Time"),
_("Market"),
wx.OK | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
else:
dlg = wx.MessageDialog(self,
_("Are you sure want to update?"),
_("Market"),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
mcode = raw_dict['mcode'].upper()
raw_dict['mcode'] = mcode
if raw_dict['mcode'] not in self.configobj:
self.configobj[mcode] = {}
for key in self.field_keys:
self.configobj[mcode][key] = raw_dict.get(key, '')
self.configobj.write() # write ini file
self.Close()
def onCancel(self, event):
self.Close()
def onDelete(self, event):
mcode = self.mcode.GetValue().upper()
if mcode and mcode in self.configobj:
dlg = wx.MessageDialog(self,
_('Are you sure?'),
_('Delete'),
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
del self.configobj[mcode]
self.configobj.write()
self.Destroy()
def onKey(self, event):
keycode = event.GetKeyCode()
if keycode == wx.WXK_ESCAPE:
self.Close()
event.Skip()
def loaddata(self):
self.configobj = ConfigObj(self.inifile, encoding='utf-8')
#------------------------------------------
class FF(MyFrame):
def __init__(self, *args, **kwds):
MyFrame.__init__(self, *args, **kwds)
self.quote_process = {}
self.quote_workers = {}
self.trader = {}
self.strategy_process = {}
# main application timer
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onTimer, self.timer)
self.timer.Start(1000 * 10)
self.m_obj = {} # market
self.c_obj = {} # commodity
self.s_obj = {} # strategy
self.market_ini = market_ini
self.commodity_ini = commodity_ini
self.strategy_ini = strategy_ini
self.data_ids = ['username', 'password', 'cert',
'certpass', 'autostart', ] # 'sctrl','actrl']
self.logfilename = os.path.join(app_dir, "autotrader.log")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename=self.logfilename,
)
self.logger = logging.getLogger('')
# Market
self.mctrl.InsertColumn(0, _("Market Name"))
self.mctrl.InsertColumn(1, _("Market Code"))
self.mctrl.InsertColumn(2, _("Market Time Zone"))
# Commodity
self.cctrl.InsertColumn(0, _("Commodity Name"))
self.cctrl.InsertColumn(1, _("Commodity Code"))
self.cctrl.InsertColumn(2, _("Market Code"))
self.cctrl.InsertColumn(3, _("Quote Source"))
self.cctrl.InsertColumn(4, _("Quote Folder"))
# Strategy
self.sctrl.InsertColumn(0, _("Id"))
self.sctrl.InsertColumn(1, _("Commodity Code"))
self.sctrl.InsertColumn(2, _("Program File"))
self.sctrl.InsertColumn(3, _("Time Period"))
self.loaddata()
self.render_all()
# test
self.test = None
def onMarket(self, event):
dlg = Market(self)
dlg.ShowModal()
dlg.Destroy()
self.load_market()
self.render_market()
def onMarketActive(self, event):
item_index = event.m_itemIndex
mcode = self.mctrl.GetItem(item_index, 1).GetText()
dlg = Market(self)
dlg.loaditem(mcode)
dlg.ShowModal()
dlg.Destroy()
self.load_market()
self.render_market()
def onCommodity(self, event):
dlg = Commodity(self)
dlg.ShowModal()
dlg.Destroy()
self.loaddata()
self.render_commodity()
def onCommodityActive(self, event):
item_index = event.m_itemIndex
ccode = self.cctrl.GetItem(item_index, 1).GetText()
dlg = Commodity(self)
dlg.loaditem(ccode)
dlg.ShowModal()
dlg.Destroy()
self.load_commodity()
self.render_commodity()
def onStrategy(self, event):
dlg = Strategy(self)
dlg.ShowModal()
dlg.Destroy()
self.load_strategy()
self.render_strategy()
def onStrategyActive(self, event):
item_index = event.m_itemIndex
sid = self.sctrl.GetItem(item_index, 0).GetText()
dlg = Strategy(self)
dlg.loaditem(sid)
dlg.ShowModal()
dlg.Destroy()
self.load_strategy()
self.render_strategy()
def OnCheckItem(self, index, flag):
sid = self.sctrl.GetItem(index, 0).GetText()
#print index, flag, sid
if self.s_obj.get(sid, False):
# toggle run key value
if flag:
self.s_obj[sid]['run'] = True
else:
self.s_obj[sid]['run'] = ""
self.s_obj.write()
def onSave(self, event):
dd = {}
for k in self.data_ids:
item = getattr(self, k)
if hasattr(item, 'GetValue'):
if k == 'username':
dd[k] = item.GetValue().upper()
else:
dd[k] = item.GetValue()
elif hasattr(item, 'GetPath'):
dd[k] = item.GetPath()
self.data = dd
def onAbout(self, event):
info = wx.AboutDialogInfo()
info.Name = __appname__
info.Version = __version__
info.Copyright = __author__
info.Description = wordwrap(
_("An easy tool for you to trade any commodity you like.\nLicense: MIT for individual, GPL for none individual.\n Author: TerryH"),
350, wx.ClientDC(self))
info.WebSite = (u"http://terryh.tp.blogspot.com/", u"TerryH's Blog")
wx.AboutBox(info)
def onQuit(self, event):
dlg = wx.MessageDialog(self,
_('Are you sure?'),
_('Close'),
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_INFORMATION
)
val = dlg.ShowModal()
dlg.Destroy()
if val == wx.ID_YES:
# close all process
self.stop_process()
self.Destroy()
def onTimer(self, event):
"""
create process for quote service, strategy start or stop
"""
#self.loginfo('onTimer')
for k, v in self.c_obj.items():
if v.get('csource'):
ccode = v['ccode'] # commodity code
mcode = v['mcode'] # market code
source = v['csource']
mtimezone = self.m_obj[mcode]['mtimezone']
session_start = ''
session_end = ''
mclear = self.m_obj[mcode]['mclear']
s1_start = self.m_obj[mcode]['s1_start']
s1_end = self.m_obj[mcode]['s1_end']
s2_end = self.m_obj[mcode]['s2_end']
if mclear and mclear != '00:00':
session_start = mclear
elif s1_start and s1_start != '00:00':
session_start = mclear
if s2_end and s2_end != '00:00':
session_end = s2_end
elif s1_end and s1_end != '00:00':
session_end = s1_end
key = "%s_%s" % (mcode, ccode)
# commodity configureobj, get quote dir
com_data_dir = os.path.join(app_dir, 'data', mcode, ccode)
if v.get('cdir', False):
com_quote_dir = os.path.join(
v.get('cdir'), 'data', mcode, ccode)
else:
# parent folder data/mcode/ccode
com_quote_dir = com_data_dir
#self.loginfo(str(self.quote_process))
if self.should_running(session_start, session_end, mtimezone):
# check this quote should running
if key not in self.quote_process:
# not running quote process
#s_hour, s_minute = map(int, session_start.split(':',1))
#now = get_now(mtimezone)
#market_start_time = get_tz_hhmm(s_hour, s_minute, mtimezone)
# we must start app 1 minute before market open
#if (market_start_time-now).seconds < 60:
#quote_module = __import__("quote.%s" % source , fromlist=[source])
quote_exe = source + ".exe"
#--------------------------------------------------
# TODO nolonger use, REMOVE
# start_quote_process and start_quote_workers
#t = start_quote_process( source, ccode, self.commodity_ini )
#self.quote_process[key] = t
#w = start_quote_workers(self.market_ini, self.commodity_ini, ccode)
#self.quote_workers[key] = w
#--------------------------------------------------
#--------------------------------------------------
# FIXME, need to uncomment
# sub_quote_process and sub_quote_workers, add quote
# for file path in case path have space
final_command = '%s --config "%s" --commodity %s' % (
quote_exe, self.commodity_ini, ccode)
self.loginfo(final_command)
t = sub_process(final_command)
self.quote_process[key] = t
final_command = '%s --mini "%s" --cini "%s" --commodity %s' % (QUOTE_WRITER_EXE, self.market_ini, self.commodity_ini, ccode)
self.loginfo(final_command)
w = sub_process(final_command)
self.quote_workers[key] = w
#--------------------------------------------------
#--------------------------------------------------
# check srategy should running
for sk, sv in self.s_obj.items():
# we store Troe False as string, TODO s_obj not update
# after saved, but should be lock update after running
# trader. ???
if sv['ccode'] == ccode:
if sv['run'] == True:
# prepare command
period_code = SUPPORT_TIME[
SUPPORT_TIME_NAME.index(sv['period'])]
hisfile = os.path.join(
com_data_dir, "%s.csv" % (period_code))
quotefile = os.path.join(
com_quote_dir, "%s.ohlc" % (period_code))
#trader.py -his data\SMX\STW\min5.csv -q R:\TEMP\data\SMX\STW\min5.ohlc -f stest.py -g
final_command = r'%s --history "%s" --quote "%s" --file "%s" -g' % (TRADER_EXE, hisfile, quotefile, sv['strategyfile'])
# check exist or dead
if sk not in self.trader:
self.loginfo(final_command)
t = sub_process(final_command)
self.trader[sk] = t
else:
# have tarder running, let's poll it health
if self.trader[sk].poll() is not None:
# poll() == None mean running, maybe
# some thing wrong restart it.
self.trader.pop(sk)
self.loginfo(final_command)
t = sub_process(final_command)
self.trader[sk] = t
#--------------------------------------------------
def should_running(self, start, end, timezone):
if (start and end and timezone):
now = get_now(timezone)
hh, mm = map(int, start.split(':', 1))
tzstart = get_tz_hhmm(hh, mm, timezone)
hh, mm = map(int, end.split(':', 1))
tzend = get_tz_hhmm(hh, mm, timezone)
if end < start:
# trading time cross midnight
return now >= tzstart or now <= tzend
else:
return now >= tzstart and now <= tzend
return now >= tzstart
return False