-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathscriptMonitor.lua
More file actions
1675 lines (1466 loc) · 85.7 KB
/
Copy pathscriptMonitor.lua
File metadata and controls
1675 lines (1466 loc) · 85.7 KB
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
-- nick-h@yandex.ru
-- Glukk Inc ©
local w32 = require("w32")
CLASS_CODE = '' --класс в файле настроек
--CLASS_CODE = 'TQBR' -- Код класса
--CLASS_CODE = 'SPBFUT' -- Код класса
--CLASS_CODE = 'QJSIM'
SEC_CODE = '' -- бумаги в файле настроек
SEC_CODES = {}
INTERVAL = 15 -- --текущий интервал
START_TIME = '10:00:00' -- Начало торговли
STOP_TIME = '18:50:00' -- Окончание торговли
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
--/*РАБОЧИЕ ПЕРЕМЕННЫЕ РОБОТА (менять не нужно)*/
isRun = true -- Флаг поддержания работы скрипта
is_Connected = 0
PrevDayNumber = 0
trans_id = os.time() -- Задает начальный номер ID транзакций
trans_Status = nil -- Статус текущей транзакции из функции OnTransPeply
trans_result_msg = '' -- Сообщение по текущей транзакции из функции OnTransPeply
numberOfFixedColumns = 0 -- Число фиксированных колонок до периодов
numberOfVisibleColumns = 0 -- Число видимых колонок периодов
tableIndex = {} -- Индексы колонок созданной таблицы
openedDS = {}
t_id = nil
tv_id = nil
thist_id = nil
SeaGreen=12713921 -- RGB(193, 255, 193) нежно-зеленый
RosyBrown=12698111 -- RGB(255, 193, 193) нежно-розовый
SEC_PRICE_STEP = 0 -- ШАГ ЦЕНЫ ИНСТРУМЕНТА
DS = nil -- Источник данных графика (DataSource)
g_previous_time = os.time() -- помещение в переменную времени сервера в формате HHMMSS
SEC_CODE_INDEX = {} -- last interval index
isDayInterval = false -- есть дневной интервал
dayIntervalIndex = nil
UpdateDataSecQty = 10 -- Количество секунд ожидания подгрузки данных с сервера после возобновления подключения
-----------------------------
-- Основные функции --
-----------------------------
function DataSource(i,cell)
local seccode = SEC_CODES['sec_codes'][i]
local classcode = SEC_CODES['class_codes'][i]
local interval = INTERVALS['values'][cell]
if openedDS[i][interval] ~= nil then
return openedDS[i][interval]
end
local ds = CreateDataSource(classcode,seccode,interval)
if ds == nil then
message('NRTR monitor: ОШИБКА получения доступа к свечам! '..Error)
myLog('NRTR monitor: ОШИБКА получения доступа к свечам! '..Error)
-- Завершает выполнение скрипта
isRun = false
return
end
if ds:Size() == 0 then
ds:SetEmptyCallback()
SEC_CODES['isEmpty'][i] = true
end
openedDS[i][interval] = ds
return ds
end
do---- ДАТА/ВРЕМЯ
function is_date(val)
if not type(val) == "table" then return false end
local status = pcall(function() return os.time(val); end)
return status
end
-- Ждет подключения к серверу, после чего ждет еще UpdateDataSecQty секунд подгрузки пропущенных данных с сервера
function WaitUpdateDataAfterReconnect()
while isRun and isConnected() == 0 do sleep(100) end
if isRun then sleep(UpdateDataSecQty * 1000) end
-- Повторяет операцию если соединение снова оказалось разорвано
if isRun and isConnected() == 0 then WaitUpdateDataAfterReconnect() end
end
-- Возвращает текущую дату/время сервера в виде таблицы datetime
function GetServerDateTime()
local dt = {}
-- Пытается получить дату/время сервера
while isRun and dt.day == nil do
dt.day,dt.month,dt.year,dt.hour,dt.min,dt.sec = string.match(getInfoParam('TRADEDATE')..' '..getInfoParam('SERVERTIME'),"(%d*).(%d*).(%d*) (%d*):(%d*):(%d*)")
-- Если не удалось получить, или разрыв связи, ждет подключения и подгрузки с сервера актуальных данных
--if dt.day == nil or isConnected() == 0 then WaitUpdateDataAfterReconnect() end
if dt.day == nil or isConnected() == 0 then
return os.date('*t', os.time())
--WaitUpdateDataAfterReconnect()
end
end
-- Если во время ожидания скрипт был остановлен пользователем, возвращает таблицу datetime даты/времени компьютера, чтобы не вернуть пустую таблицу и не вызвать ошибку в алгоритме
if not isRun then return os.date('*t', os.time()) end
-- Приводит полученные значения к типу number
for key,value in pairs(dt) do dt[key] = tonumber(value) end
-- Возвращает итоговую таблицу
return dt
end
-- Приводит время из строкового формата ЧЧ:ММ:CC к формату datetime
function StrToTime(str_time)
if type(str_time) ~= 'string' then return os.date('*t') end
local sdt = GetServerDateTime()
while isRun and sdt.day == nil do sleep(100) sdt = GetServerDateTime() end
if not isRun then return os.date('*t') end
local dt = sdt
local h,m,s = string.match( str_time, "(%d%d):(%d%d):(%d%d)")
dt.hour = tonumber(h)
dt.min = tonumber(m)
dt.sec = s==nil and 0 or tonumber(s)
return dt
end
end--- ДАТА/ВРЕМЯ
-- Функция первичной инициализации скрипта (ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK в самом начале)
function OnInit()
dofile (getScriptPath().."\\monitorStepNRTR.lua") --stepNRTR алгоритм. Инициализация - initstepNRTR, расчет - stepNRTR
dofile (getScriptPath().."\\monitorEMA.lua") --EMA алгоритм. Инициализация - initEMA, расчет - EMA, allEMA
dofile (getScriptPath().."\\monitorRSI.lua") --EMA алгоритм. Инициализация - initRSI, расчет - RSI
dofile (getScriptPath().."\\monitorReg.lua") --Регрессия алгоритм. Инициализация - initReg, расчет - Reg
dofile (getScriptPath().."\\monitorVolume.lua") --RT алгоритм контроль повышенного объема. Инициализация - initVolume, расчет - Volume
dofile (getScriptPath().."\\monitorVSA.lua") --VSA алгоритм. Инициализация - initVSA, расчет - VSA
dofile (getScriptPath().."\\monitorRange.lua") --range
--Должен быть ниже модулей расчета
dofile (getScriptPath().."\\scriptMonitorPar.lua") --stepNRTR алгоритм. Инициализация - initstepNRTR, расчет - stepNRTR
logFile = io.open(FILE_LOG_NAME, "a+") -- открывает файл
local ParamsFile = io.open(PARAMS_FILE_NAME,"r")
if ParamsFile == nil then
isRun = false
message("Не удалость прочитать файл настроек!!!")
return false
end
--is_Connected = isConnected()
--
--if is_Connected ~= 1 then
-- isRun = false
-- message("Нет подключения к серверу!!!")
-- return false
--end
SEC_CODES['class_codes'] = {} -- CLASS_CODE
SEC_CODES['names'] = {} -- имена бумаг
SEC_CODES['sec_codes'] = {} -- коды бумаг
SEC_CODES['isMessage'] = {} -- выводить сообщения
SEC_CODES['isPlaySound'] = {} -- проигрывать звук
SEC_CODES['volume'] = {} -- рабочий объем
SEC_CODES['isEmpty'] = {} -- признак заказа данных
SEC_CODES['DS'] = {} -- данные по инструменту
SEC_CODES['calcAlgoValues'] = {} -- рассчитанные данные
SEC_CODES['dayATR'] = {} -- рассчитанные данные ATR
SEC_CODES['dayDS'] = {} -- данные для ATR
SEC_CODES['dayATR_Period'] = {} -- период данных ATR
SEC_CODES['D_minus5'] = {} -- цена 5 дней назад
SEC_CODES['lastTimeCalculated'] = {} -- время последнего рассчета
SEC_CODES['lastrealTimeCalculated'] = {} -- время последнего рассчета realtime алгоритма
myLog("______________________________________________________")
myLog("Читаем файл параметров")
local lineCount = 0
for line in ParamsFile:lines() do
--myLog("Строка параметров "..line)
lineCount = lineCount + 1
if lineCount > 1 and line ~= "" then
local per1, per2, per3, per4, per5, per6, per7 = line:match("%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*)")
SEC_CODES['class_codes'][lineCount-1] = per1
SEC_CODES['names'][lineCount-1] = per2
SEC_CODES['sec_codes'][lineCount-1] = per3
SEC_CODES['isMessage'][lineCount-1] = tonumber(per4)
SEC_CODES['isPlaySound'][lineCount-1] = tonumber(per5)
SEC_CODES['volume'][lineCount-1] = tonumber(per6)
SEC_CODES['isEmpty'][lineCount-1] = false
SEC_CODES['DS'][lineCount-1] = {}
SEC_CODES['calcAlgoValues'][lineCount-1] = {}
SEC_CODES['dayATR'][lineCount-1] = 0
SEC_CODES['dayDS'][lineCount-1] = nil
SEC_CODES['dayATR_Period'][lineCount-1] = tonumber(per7)
SEC_CODES['D_minus5'][lineCount-1] = 0
SEC_CODES['lastTimeCalculated'][lineCount-1] = {}
SEC_CODES['lastrealTimeCalculated'][lineCount-1] = {}
end
end
ParamsFile:close()
myLog("Intervals "..tostring(#INTERVALS["names"]))
myLog("Sec codes "..tostring(#SEC_CODES['sec_codes']))
CreateTable() -- Создает таблицу
myLog("realTime functions "..tostring(#realtimeAlgorithms["functions"]))
for i,v in ipairs(SEC_CODES['sec_codes']) do
SEC_CODE_INDEX[i] = {}
SEC_CODE = v
CLASS_CODE =SEC_CODES['class_codes'][i]
openedDS[i] = {}
if getSecurityInfo(CLASS_CODE, SEC_CODE) == nil then
isRun = false
message("Не удалость получить данные по инструменту: "..SEC_CODE.."/"..tostring(CLASS_CODE))
myLog("Не удалость получить данные по инструменту: "..SEC_CODE.."/"..tostring(CLASS_CODE))
return false
end
SEC_PRICE_STEP = getParamEx(CLASS_CODE, SEC_CODE, "SEC_PRICE_STEP").param_value
local status = getParamEx(CLASS_CODE, SEC_CODE, "last").param_value
local last_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"last").param_value)
local open_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"prevprice").param_value)
local highest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"high").param_value)
local lowest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"low").param_value)
local waprice = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"WAPRICE").param_value)
if last_price == 0 or last_price == nil then
last_price = open_price
end
SetCell(t_id, i, tableIndex["Текущая цена"], tostring(last_price), last_price) --i строка, 1 - колонка, v - значение
local lastchange = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"lastchange").param_value)
Str(i, tableIndex["%"], lastchange, 0, 0) --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex["Цена открытия"], tostring(open_price), open_price) --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex["VWAP"], tostring(waprice), wapprice) --i строка, 1 - колонка, v - значение
local delta = round(last_price-open_price,5)
SetCell(t_id, i, tableIndex["Дельта"], tostring(delta), delta) --i строка, 1 - колонка, v - значение
local openCount, awg_price = GetTotalnet(CLASS_CODE, SEC_CODE)
SetCell(t_id, i, tableIndex["Позиция"], tostring(openCount), openCount) --i строка, 1 - колонка, v - значение
if tonumber(awg_price)==0 then
SetCell(t_id, i, tableIndex["Средняя"], '', 0) --i строка, 1 - колонка, v - значение
White(i, tableIndex["Средняя"])
else
Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price) --i строка, 1 - колонка, v - значение
end
--Команды
if showTradeCommands == true then
SetCell(t_id, i, tableIndex["<"], "-") --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex["Объем сделки"], tostring(SEC_CODES['volume'][i]), SEC_CODES['volume'][i]) --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex[">"], "+") --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex["Команда BUY"], "BUY") --i строка, 1 - колонка, v - значение
Green(i, tableIndex["Команда BUY"])
SetCell(t_id, i, tableIndex["Команда SELL"], "SELL") --i строка, 1 - колонка, v - значение
Red(i, tableIndex["Команда SELL"])
if openCount~=0 then
Red(i, tableIndex["Команда CLOSE"])
SetCell(t_id, i, tableIndex["Команда CLOSE"], "CLOSE") --i строка, 0 - колонка, v - значение
else
White(i, tableIndex["Команда CLOSE"])
SetCell(t_id, i, tableIndex["Команда CLOSE"], "") --i строка, 0 - колонка, v - значение
end
end
for kk,algo in pairs(realtimeAlgorithms["functions"]) do
local initrf = realtimeAlgorithms["initAlgorithms"][kk]
if initrf~=nil then
initrf()
end
SEC_CODES['lastrealTimeCalculated'][i][kk] = g_previous_time
end
for cell,INTERVAL in pairs(INTERVALS["values"]) do
--myLog(SEC_CODE.." interval "..tostring(INTERVAL))
DS = DataSource(i,cell)
SEC_CODES['DS'][i][cell] = DS
SEC_CODES['lastTimeCalculated'][i][cell] = os.time()
SEC_CODE_INDEX[i][cell] = DS:Size()
--myLog("Всего свечей ".. SEC_CODE..", интервала "..INTERVALS["names"][cell].." "..tostring(SEC_CODE_INDEX[i][cell]))
if status ~= nil and status ~= 0 then
--interval algorithms
local initf = INTERVALS["initAlgorithms"][cell]
local calcf = INTERVALS["algorithms"][cell]
local signalf = INTERVALS["signalAlgorithms"][cell]
local settings = INTERVALS["settings"][cell]
calcAlgoValue = {}
if initf~=nil then
initf()
end
if calcf~=nil then
-- расчет параметров для каждого интервала
calcAlgoValue = calcf(i, DS:Size(), settings, DS, INTERVAL)
end
SEC_CODES['calcAlgoValues'][i][cell] = calcAlgoValue[DS:Size()] or 0
if signalf~=nil then
signalf(i, cell, settings, DS, false)
elseif calcf~=nil then
up_downTest(i, cell, settings, DS, false)
end
end
--ATR
if INTERVAL == INTERVAL_D1 and isDayInterval == false then
isDayInterval = true
dayIntervalIndex = cell
end
end
--ATR
getATR(i, dayIntervalIndex)
local lastATR = round(SEC_CODES['dayATR'][i], 5)
if highest_price ==0 then highest_price = open_price end
if lowest_price ==0 then lowest_price = open_price end
local atrDelta = math.max(math.abs(highest_price - open_price), math.abs(open_price-lowest_price))
if lastATR<math.abs(atrDelta) then
Red(i, tableIndex["D ATR"])
else
White(i, tableIndex["D ATR"])
end
--ATR
--W%
local changeW = round((last_price - SEC_CODES['D_minus5'][i])*100/SEC_CODES['D_minus5'][i], 2)
Str(i, tableIndex["%W"], changeW, 0, 0)
--W%
end
myLog("================================================")
myLog("Initialization finished")
end
function main() -- Функция, реализующая основной поток выполнения в скрипте
SetTableNotificationCallback(t_id, event_callback)
SetTableNotificationCallback(tv_id, volume_event_callback)
-- Цикл по дням
while isRun do
-- Ждет начала следующего дня
while isRun and GetServerDateTime().day == PrevDayNumber do sleep(100) end
-- Получает время в секундах для всех временных промежутков
local StartTime_sec = os.time(StrToTime(START_TIME))
local StopTime_sec = os.time(StrToTime(STOP_TIME))
-- Ждет начала торгового дня
while isRun and os.time(GetServerDateTime()) <= StartTime_sec do sleep(100) end
--myLog(' GetServerDateTime() '..tostring(os.time(GetServerDateTime()))..' StartTime_sec '..tostring(StartTime_sec)..' StopTime_sec '..tostring(StopTime_sec))
-- Цикл внутри дня
while isRun do -- Цикл будет выполнятся, пока isRun == true
-- Получает время сервера
local ServerDT = GetServerDateTime()
local ServerDT_sec = os.time(ServerDT)
-- Если торговый день закончился, выходит в цикл по дням
if ServerDT_sec >= StopTime_sec then PrevDayNumber = ServerDT.day break end
for i,v in ipairs(SEC_CODES['sec_codes']) do
if isRun == false then break end
SEC_CODE = v
CLASS_CODE =SEC_CODES['class_codes'][i]
-- Получает ШАГ ЦЕНЫ ИНСТРУМЕНТА, последнюю цену, открытые позиции
SEC_PRICE_STEP = getParamEx(CLASS_CODE, SEC_CODE, "SEC_PRICE_STEP").param_value
local status = getParamEx(CLASS_CODE, SEC_CODE, "last").param_value
local last_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"last").param_value)
local open_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"prevprice").param_value)
local highest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"high").param_value)
local lowest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"low").param_value)
local waprice = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"WAPRICE").param_value)
if last_price == 0 or last_price == nil then
last_price = open_price
end
local lp = GetCell(t_id, i, tableIndex["Текущая цена"]).value or last_price
if lp < last_price then
Highlight(t_id, i, tableIndex["Текущая цена"], SeaGreen, QTABLE_DEFAULT_COLOR,1000) -- подсветка мягкий, зеленый
elseif lp > last_price then
Highlight(t_id, i, tableIndex["Текущая цена"], RosyBrown, QTABLE_DEFAULT_COLOR,1000) -- подсветка мягкий розовый
end
SetCell(t_id, i, tableIndex["Текущая цена"], tostring(last_price), last_price) --i строка, 1 - колонка, v - значение
Str(i, tableIndex["VWAP"], waprice, last_price)
local lastchange = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"lastchange").param_value)
Str(i, tableIndex["%"], lastchange, 0, 0) --i строка, 1 - колонка, v - значение
SetCell(t_id, i, tableIndex["Цена открытия"], tostring(open_price), open_price) --i строка, 1 - колонка, v - значение
local delta = round(last_price-open_price,5)
SetCell(t_id, i, tableIndex["Дельта"], tostring(delta), delta) --i строка, 1 - колонка, v - значение
if IsWindowClosed(t_id) == false then
local awg_price = GetCell(t_id, i, tableIndex["Средняя"]).value or 0
if tonumber(awg_price)==0 then
White(i, tableIndex["Средняя"])
else
Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price)
end
end
local current_time=ServerDT_sec
--myLog(tostring(status))
if status ~= nil and status ~= "0.000000" then
for kk,algo in pairs(realtimeAlgorithms["functions"]) do
local realf = realtimeAlgorithms["functions"][kk]
if realf~=nil then
local lastrealTimeCalculated = SEC_CODES['lastrealTimeCalculated'][i][kk] or current_time
local newrealTimeToCalculate = current_time
local realperiod = realtimeAlgorithms["recalculatePeriod"][kk] or 0
if realperiod ~= 0 then
newrealTimeToCalculate = lastrealTimeCalculated + realperiod
if current_time>newrealTimeToCalculate then
--myLog(SEC_CODE.." realperiod "..tostring(realperiod).." lastrealTimeCalculated "..tostring(lastrealTimeCalculated))
--myLog("newrealTimeToCalculate "..tostring(newrealTimeToCalculate))
--myLog("current_time "..tostring(current_time))
SEC_CODES['lastrealTimeCalculated'][i][kk] = current_time
realf(i)
end
end
end
end
for cell,INTERVAL in pairs(INTERVALS["values"]) do
DS = SEC_CODES['DS'][i][cell]
local lastTimeCalculated = SEC_CODES['lastTimeCalculated'][i][cell]
local newTimeToCalculate = ServerDT_sec
local period = INTERVALS["recalculatePeriod"][cell] or 0
newTimeToCalculate = current_time
if period ~= 0 then
--newTimeToCalculate = lastTimeCalculated + 100*math.floor(period/60) + period%60
newTimeToCalculate = lastTimeCalculated + period*60
end
local timeCandle = DS:T(DS:Size())
--myLog(SEC_CODE.." - timeCandle "..tostring(os.time(timeCandle)).." - INTERVAL "..tostring(INTERVAL).." - period "..tostring(period))
--myLog(SEC_CODE.." - current_time "..tostring(current_time).." - lastTimeCalculated "..tostring(lastTimeCalculated).." - newTimeToCalculate "..tostring(newTimeToCalculate))
--myLog(SEC_CODE.." - current_time "..tostring(current_time))
--myLog(SEC_CODE.." - newtimeCandle "..tostring(os.time(timeCandle) + INTERVAL*60))
if SEC_CODE_INDEX[i][cell]<DS:Size() or (current_time>newTimeToCalculate and is_date(timeCandle) and current_time < (os.time(timeCandle) + INTERVAL*60)) then --new candle
--myLog(SEC_CODE.." - Перерасчет данных за интервал "..INTERVALS["names"][cell])
SEC_CODES['lastTimeCalculated'][i][cell] = current_time
--interval algorithms
local initf = INTERVALS["initAlgorithms"][cell]
local calcf = INTERVALS["algorithms"][cell]
local signalf = INTERVALS["signalAlgorithms"][cell]
local settings = INTERVALS["settings"][cell]
calcAlgoValue = {}
if initf~=nil then
initf()
end
if calcf~=nil then
--myLog(SEC_CODE.." - INTERVAL "..tostring(INTERVAL))
calcAlgoValue = calcf(i, DS:Size(), settings, DS)
end
SEC_CODES['calcAlgoValues'][i][cell] = calcAlgoValue[DS:Size()] or 0
if signalf~=nil then
signalf(i, cell, settings, DS, true)
elseif calcf~=nil then
up_downTest(i, cell, settings, DS, true)
end
SEC_CODE_INDEX[i][cell] = DS:Size() --last candle
end
end
end
--ATR
if SEC_CODES['D_minus5'][i]==0 or SEC_CODES['D_minus5'][i]==nil or SEC_CODES['dayATR'][i]==0 or SEC_CODES['dayATR'][i]==nil then
getATR(i, dayIntervalIndex)
end
local lastATR = round(SEC_CODES['dayATR'][i], 5)
if highest_price ==0 then highest_price = open_price end
if lowest_price ==0 then lowest_price = open_price end
local atrDelta = math.max(math.abs(highest_price - open_price), math.abs(open_price-lowest_price))
if lastATR<math.abs(atrDelta) then
Red(i, tableIndex["D ATR"])
else
White(i, tableIndex["D ATR"])
end
--ATR
--W%
local changeW = round((last_price - SEC_CODES['D_minus5'][i])*100/SEC_CODES['D_minus5'][i], 2)
Str(i, tableIndex["%W"], changeW, 0, 0)
--W%
end
sleep(100)
end
end
end
-- Функция ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK при остановке скрипта
function OnStop()
isRun = false
myLog("Script Stoped")
if t_id~= nil then
DestroyTable(t_id)
end
if tv_id~= nil then
DestroyTable(tv_id)
end
if thist_id~= nil then
DestroyTable(thist_id)
end
calcAlgoValue = nil
if logFile~=nil then logFile:close() end -- Закрывает файл
end
-----------------------------
-- РАБОТА С ТАБЛИЦЕЙ --
-----------------------------
function CreateTable() -- Функция создает таблицу
t_id = AllocTable() -- Получает доступный id для создания
-- Добавляет колонки
AddColumn(t_id, 0, "Инструмент", true, QTABLE_STRING_TYPE, 22)
tableIndex["Инструмент"] = 0
AddColumn(t_id, 1, "%", true, QTABLE_DOUBLE_TYPE, 9)
tableIndex["%"] = 1
AddColumn(t_id, 2, "Цена", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["Текущая цена"] = 2
AddColumn(t_id, 3, "%W", true, QTABLE_DOUBLE_TYPE, 9)
tableIndex["%W"] = 3
AddColumn(t_id, 4, "Открытие", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["Цена открытия"] = 4
AddColumn(t_id, 5, "VWAP", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["VWAP"] = 5
AddColumn(t_id, 6, "Дельта", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["Дельта"] = 6
AddColumn(t_id, 7, "D ATR", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["D ATR"] = 7
AddColumn(t_id, 8, "Поз.", true, QTABLE_INT_TYPE, 7)
tableIndex["Позиция"] = 8
AddColumn(t_id, 9, "Средняя", true, QTABLE_DOUBLE_TYPE, 13)
tableIndex["Средняя"] = 9
numberOfFixedColumns = 9
numberOfVisibleColumns = 0
local width = 0
for i,v in ipairs(INTERVALS["names"]) do
if INTERVALS["visible"][i] then
numberOfVisibleColumns = numberOfVisibleColumns + 1
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns, v, true, QTABLE_DOUBLE_TYPE, INTERVALS["width"][i])
tableIndex[i] = numberOfVisibleColumns+numberOfFixedColumns
width = width + INTERVALS["width"][i]
end
end
local columns = numberOfFixedColumns
if showTradeCommands == true then
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+1, "Цена", true, QTABLE_DOUBLE_TYPE, 15) --Price
tableIndex["Цена сделки"] = numberOfVisibleColumns+numberOfFixedColumns+1
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+2, "<", true, QTABLE_STRING_TYPE, 5) --Decrease volume
tableIndex["<"] = numberOfVisibleColumns+numberOfFixedColumns+2
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+3, "Vol", true, QTABLE_INT_TYPE, 7) --Volume
tableIndex["Объем сделки"] = numberOfVisibleColumns+numberOfFixedColumns+3
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+4, ">", true, QTABLE_STRING_TYPE, 5) --Increase volume
tableIndex[">"] = numberOfVisibleColumns+numberOfFixedColumns+4
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+5, "BUY", true, QTABLE_STRING_TYPE, 10) --BUY
tableIndex["Команда BUY"] = numberOfVisibleColumns+numberOfFixedColumns+5
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+6, "SELL", true, QTABLE_STRING_TYPE, 10) --SELL
tableIndex["Команда SELL"] = numberOfVisibleColumns+numberOfFixedColumns+6
AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+7, "CLOSE", true, QTABLE_STRING_TYPE, 10) --CLOSE ALL
tableIndex["Команда CLOSE"] = numberOfVisibleColumns+numberOfFixedColumns+7
columns = columns + 2.3
end
t = CreateWindow(t_id) -- Создает таблицу
SetWindowCaption(t_id, "Monitor") -- Устанавливает заголовок
SetWindowPos(t_id, 90, 60, 87*columns + width*5.8, #SEC_CODES['sec_codes']*17.2) -- Задает положение и размеры окна таблицы
-- Добавляет строки
for i,v in ipairs(SEC_CODES['names']) do
InsertRow(t_id, i)
SetCell(t_id, i, tableIndex["Инструмент"], v) --i строка, 0 - колонка, v - значение
end
tv_id = AllocTable() -- таблица ввода значения
thist_id = AllocTable() --таблица истории сделок
-- Добавляет колонки
AddColumn(thist_id, 0, "Инструмент", true, QTABLE_STRING_TYPE, 20)
AddColumn(thist_id, 1, "Номер сделки", true, QTABLE_INT_TYPE, 20)
AddColumn(thist_id, 2, "Дата сделки", true, QTABLE_STRING_TYPE, 29)
AddColumn(thist_id, 3, "Тип", true, QTABLE_STRING_TYPE, 15)
AddColumn(thist_id, 4, "Количество", true, QTABLE_INT_TYPE, 17)
AddColumn(thist_id, 5, "Цена", true, QTABLE_DOUBLE_TYPE, 17)
AddColumn(thist_id, 6, "Комментарий", true, QTABLE_STRING_TYPE, 130)
end
function Str(str, num, value, testvalue, dir) -- Функция выводит и окрашивает строки в таблице
if dir == nil then dir = 1 end
SetCell(t_id, str, num, tostring(value), value) -- Выводит значение в таблицу: строка, коллонка, значение
if (value < testvalue and dir == 1) or (value > testvalue and dir == 0) then Green(str, num) elseif value == testvalue then Gray(str, num) else Red(str, num) end -- Окрашивает строку в зависимости от значения профита
end
-----------------------------
-- Функции по раскраске строк/ячеек таблицы --
-----------------------------
function Green(Line, Col) -- Зеленый
if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку
SetColor(t_id, Line, Col, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0))
end
function Gray(Line, Col) -- Серый
if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку
SetColor(t_id, Line, Col, RGB(200,200,200), RGB(0,0,0), RGB(200,200,200), RGB(0,0,0))
end
function Red(Line, Col) -- Красный
if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку
SetColor(t_id, Line, Col, RGB(255,168,164), RGB(0,0,0), RGB(255,168,164), RGB(0,0,0))
end
function White(Line, Col) -- Белый
if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку
SetColor(t_id, Line, Col, RGB(255,255,255), RGB(0,0,0), RGB(255,255,255), RGB(0,0,0))
end
function cellSetColor(Line, Col, Color, textColor)
if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку
if Color == nil then Color = RGB(255,255,255) end -- Если цвет не указан, окрашивает в белый
if textColor == nil then textColor = RGB(0,0,0) end -- Если цвет не указан, цвет черный
SetColor(t_id, Line, Col, Color, textColor, Color, textColor)
end
-----------------------------
-- Обработка команд таблицы --
-----------------------------
function volume_event_callback(tv_id, msg, par1, par2)
if par1 == -1 then
return
end
if msg == QTABLE_CHAR then
if tostring(par2) == "8" then
local newPrice = string.sub(GetCell(tv_id, par1, 0).image, 1, string.len(GetCell(tv_id, par1, 0).image)-1)
SetCell(tv_id, par1, 0, tostring(newPrice))
SetCell(t_id, tstr, tcell, GetCell(tv_id, par1, 0).image, tonumber(GetCell(tv_id, par1, 0).image))
else
local inpChar = string.char(par2)
local newPrice = GetCell(tv_id, par1, 0).image..string.char(par2)
SetCell(tv_id, par1, 0, tostring(newPrice))
SetCell(t_id, tstr, tcell, GetCell(tv_id, par1, 0).image, tonumber(GetCell(tv_id, par1, 0).image))
end
end
end
function event_callback(t_id, msg, par1, par2)
if msg == QTABLE_LBUTTONDBLCLK and showTradeCommands == true then
if par2 == tableIndex["Инструмент"] then --Выводим сделки
createDealsTable(par1)
end
if par2 == tableIndex["Текущая цена"] or par2 == tableIndex["Цена открытия"] or par2 == tableIndex["Средняя"] or (par2 > numberOfFixedColumns and par2 <= numberOfVisibleColumns+numberOfFixedColumns) then --Берем цену
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
local newPrice = GetCorrectPrice(GetCell(t_id, par1, par2).value, TRADE_CLASS_CODE, TRADE_SEC_CODE)
local stringPrice = string.gsub(tostring(newPrice),',', '.')
local numberPrice = tonumber(stringPrice)
if numberPrice~=nil and numberPrice~=0 then
SetCell(t_id, par1, tableIndex["Цена сделки"], stringPrice, numberPrice) --i строка, 1 - колонка, v - значение
end
end
if par2 == tableIndex["Цена сделки"] and IsWindowClosed(tv_id) then --Вводим цену
tstr = par1
tcell = par2
AddColumn(tv_id, 0, "Значение", true, QTABLE_DOUBLE_TYPE, 25)
tv = CreateWindow(tv_id)
SetWindowCaption(tv_id, "Введите цену")
SetWindowPos(tv_id, 290, 260, 250, 100)
InsertRow(tv_id, 1)
SetCell(tv_id, 1, 0, GetCell(t_id, par1, tableIndex["Цена сделки"]).image, GetCell(t_id, par1, tableIndex["Цена сделки"]).value) --i строка, 0 - колонка, v - значение
end
if par2 == tableIndex["Объем сделки"] and IsWindowClosed(tv_id) then --Вводим объем
tstr = par1
tcell = par2
AddColumn(tv_id, 0, "Значение", true, QTABLE_INT_TYPE, 25)
tv = CreateWindow(tv_id)
SetWindowCaption(tv_id, "Введите объем")
SetWindowPos(tv_id, 290, 260, 250, 100)
InsertRow(tv_id, 1)
SetCell(tv_id, 1, 0, GetCell(t_id, par1, tableIndex["Объем сделки"]).image, GetCell(t_id, par1, tableIndex["Объем сделки"]).value) --i строка, 0 - колонка, v - значение
end
if par2 == tableIndex["Команда CLOSE"] then -- All Close
local TRADE_SEC_NAME = SEC_CODES['names'][par1]
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
local QTY_LOTS = GetCell(t_id, par1, tableIndex["Позиция"]).value
if QTY_LOTS == 0 or QTY_LOTS==nil then
message("Некорректно указан объем!!!")
return
end
if QTY_LOTS ~=0 then
local CurrentDirect = 'SELL'
message(TRADE_SEC_NAME.." Закрытие всей позиции, Объем: "..tostring(QTY_LOTS)..", по рынку")
MakeTransaction(CurrentDirect, QTY_LOTS, 0, TRADE_CLASS_CODE, TRADE_SEC_CODE)
end
end
if par2 == tableIndex["Команда BUY"] then --BUY volume
local TRADE_SEC_NAME = SEC_CODES['names'][par1]
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
local CurrentDirect = 'BUY'
local QTY_LOTS = GetCell(t_id, par1, tableIndex["Объем сделки"]).value
if QTY_LOTS == 0 or QTY_LOTS==nil then
message("Некорректно указан объем!!!")
return
end
local TRADE_PRICE = GetCell(t_id, par1, tableIndex["Цена сделки"]).value
local checkString = GetCell(t_id, par1, tableIndex["Цена сделки"]).image
if (TRADE_PRICE==nil or TRADE_PRICE==0) and string.len(checkString) ~= 0 then
message("Некорректно указана цена: "..tostring(TRADE_PRICE))
return
end
message(TRADE_SEC_NAME.." Покупка, Объем: "..tostring(QTY_LOTS)..", Цена: "..tostring(TRADE_PRICE))
MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE)
end
if par2 == tableIndex["Команда SELL"] then --SELL volume
local TRADE_SEC_NAME = SEC_CODES['names'][par1]
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
local CurrentDirect = 'SELL'
local QTY_LOTS = GetCell(t_id, par1, tableIndex["Объем сделки"]).value
if QTY_LOTS == 0 or QTY_LOTS==nil then
message("Некорректно указан объем!!!")
return
end
local TRADE_PRICE = GetCell(t_id, par1, tableIndex["Цена сделки"]).value
local checkString = GetCell(t_id, par1, tableIndex["Цена сделки"]).image
if (TRADE_PRICE==nil or TRADE_PRICE==0) and string.len(checkString) ~= 0 then
message("Некорректно указана цена: "..tostring(TRADE_PRICE))
return
end
message(TRADE_SEC_NAME.." Продажа, Объем: "..tostring(QTY_LOTS)..", Цена: "..tostring(TRADE_PRICE))
MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE)
end
if par2 == tableIndex["<"] then
local newVolume = GetCell(t_id, par1, tableIndex["Объем сделки"]).value - SEC_CODES['volume'][par1]
SetCell(t_id, par1, tableIndex["Объем сделки"], tostring(newVolume), newVolume) --i строка, 1 - колонка, v - значение
end
if par2 == tableIndex[">"] then
local newVolume = GetCell(t_id, par1, tableIndex["Объем сделки"]).value + SEC_CODES['volume'][par1]
SetCell(t_id, par1, tableIndex["Объем сделки"], tostring(newVolume), newVolume) --i строка, 1 - колонка, v - значение
end
end
if msg == QTABLE_CHAR and showTradeCommands == true then
--message("Клавиша "..tostring(par2))
if tostring(par2) == "8" then --BackSpace
SetCell(t_id, par1, tableIndex["Цена сделки"], "")
end
if tostring(par2) == "68" or tostring(par2) == "194" then --Shift+D
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_SEC_NAME = SEC_CODES['names'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
message("Удаляем все заявки "..TRADE_SEC_NAME)
KillAllOrders("orders", TRADE_CLASS_CODE, TRADE_SEC_CODE)
end
if tostring(par2) == "83" or tostring(par2) == "219" then --Shift+S
local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1]
local TRADE_SEC_NAME = SEC_CODES['names'][par1]
local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1]
message("Удаляем все стоп заявки "..TRADE_SEC_NAME)
KillAllOrders("stop_orders", TRADE_CLASS_CODE, TRADE_SEC_CODE)
end
if tostring(par2) == "65" or tostring(par2) == "212" then --sound --Shift+A
local curSound = SEC_CODES['isPlaySound'][par1]
if curSound == 1 then
SEC_CODES['isPlaySound'][par1] = 0
message("Выключаем звук у "..SEC_CODES['names'][par1])
else
SEC_CODES['isPlaySound'][par1] = 1
message("Включаем звук у "..SEC_CODES['names'][par1])
end
end
end
if (msg==QTABLE_CLOSE) then --закрытие окна
isRun = false
end
end
-----------------------------
-- Обработка команд таблицы --
-----------------------------
--Создание таблицы истоии сделок
function createDealsTable(iSec)
Clear(thist_id)
local secCode = SEC_CODES['sec_codes'][iSec]
local classCode = SEC_CODES['class_codes'][iSec]
local secTradesFilePath = TradesFilePath..ACCOUNT.."\\"..secCode..".csv"
TradesFile = io.open(secTradesFilePath,"r")
if TradesFile ~= nil then
if IsWindowClosed(thist_id) then
thist = CreateWindow(thist_id)
SetWindowCaption(thist_id, "Сделки")
SetWindowPos(thist_id, 290, 260, 1400, 800)
end
TradesFile:seek('set',0)
local tradeTable = {}
-- Перебирает строки файла, считывает содержимое в массив сделок
local Count = 0 -- Счетчик строк
for line in TradesFile:lines() do
Count = Count + 1
if Count > 1 and line ~= "" then
InsertRow(thist_id, Count - 1)
SetCell(thist_id, Count - 1, 0, SEC_CODES['names'][iSec])
local i = 0 -- счетчик элементов строки
local dateDeal = ''
local timeDeal = ''
local prefix = 1
for str in line:gmatch("[^;^\n]+") do
i = i + 1
if i == 3 then
SetCell(thist_id, Count - 1, 1, str, tonumber(str))
elseif i == 4 then
dateDeal = string.sub(str, 1, 4).."/"..string.sub(str, 5, 6).."/"..string.sub(str, 7, 8)
elseif i == 5 then
timeDeal = string.sub(str, 1, 2)..":"..string.sub(str, 3, 4)..":"..string.sub(str, 5, 6)
SetCell(thist_id, Count - 1, 2, dateDeal.." "..timeDeal)
elseif i == 6 then
if str == "B" then
SetCell(thist_id, Count - 1, 3, "Покупка")
prefix = 1
--SetColor(thist_id, Count - 1, QTABLE_NO_INDEX, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0))
else
SetCell(thist_id, Count - 1, 3, "Продажа")
prefix = -1
end
elseif i == 7 then
SetCell(thist_id, Count - 1, 4, str, tonumber(str))
tradeTable[Count] = prefix*tonumber(str)
elseif i == 8 then
SetCell(thist_id, Count - 1, 5, str, tonumber(str))
elseif i == 9 then
SetCell(thist_id, Count - 1, 6, str)
end
end
end
end
local netCount = GetTotalnet(classCode, secCode)
local netSell = 0
if netCount > 0 then
for tN=#tradeTable,1,-1 do
if netCount == 0 then
break
end
if tradeTable[tN] ~= nil then
if tradeTable[tN] < 0 then
netSell = netSell - tradeTable[tN]
end
if tradeTable[tN] > 0 and netSell ==0 then
SetColor(thist_id, tN - 1, QTABLE_NO_INDEX, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0))
netCount = math.max(netCount - tradeTable[tN], 0)
netSell = math.max(netSell - tradeTable[tN], 0)
end
if tradeTable[tN] > 0 and netSell ~=0 then
netSell = math.max(netSell - tradeTable[tN], 0)
end
end
end
end
else
message("Сделок по инструменту нет")
end
end
-------------------------------------
--Торговля--
-------------------------------------
-- Функция вызывается терминалом QUIK при получении ответа на транзакцию пользователя
function OnTransReply(trans_reply)
-- Если поступила информация по текущей транзакции
if trans_reply.trans_id == trans_id then
-- Передает статус в глобальную переменную
trans_Status = trans_reply.status
-- Передает сообщение в глобальную переменную
trans_result_msg = trans_reply.result_msg
if Status == 2 then
message("Ошибка при передаче транзакции в торговую систему. Так как отсутствует подключение шлюза Московской Биржи, повторно транзакция не отправляется")
myLog("Ошибка при передаче транзакции в торговую систему. Так как отсутствует подключение шлюза Московской Биржи, повторно транзакция не отправляется")
end
if trans_Status > 3 then
if trans_Status == 4 then messageText = "Транзакция не исполнена" end
if trans_Status == 5 then messageText = "Транзакция не прошла проверку сервера QUIK" end
if trans_Status == 6 then messageText = "Транзакция не прошла проверку лимитов сервера QUIK" end
if trans_Status == 7 then messageText = "Транзакция не поддерживается торговой системой" end
message('NRTR monitor: Транзакция вернула ошибку: '..messageText)
myLog('NRTR monitor: Транзакция вернула ошибку: '..messageText)
end
myLog("OnTransReply "..tostring(trans_id).." "..trans_result_msg)
end
--[[
for i=0,getNumberOf('orders')-1 do
local order = getItem('orders', i)
myLog("trans_id = " .. tostring(order["trans_id"]).." order: num = " .. tostring(order["order_num"]) .." qty=" ..tostring(order["qty"]).." value= "..tostring(order["value"]).." brokerref= "..tostring(order["brokerref"]))
end
]]--
end
function MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE)
return Trade(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE ,TRADE_SEC_CODE)
end
-- Совершает СДЕЛКУ указанного типа (Type) ["BUY", или "SELL"]
function Trade(Type, qnt, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE)
--Получает ID транзакции
trans_id = trans_id + 1
if TRADE_PRICE == nil then
TRADE_PRICE = 0
end
local TRADE_TYPE = 'M'-- по рынку (MARKET)
if TRADE_PRICE ~= 0 then
TRADE_TYPE = 'L'
end
local Operation = ''
--Устанавливает цену и операцию, в зависимости от типа сделки и от класса инструмента
TRADE_SEC_PRICE_STEP = tonumber(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, "SEC_PRICE_STEP").param_value)
if Type == 'BUY' then
Operation = 'B'
if TRADE_PRICE == 0 and TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then
TRADE_PRICE = getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'offer').param_value + 10*TRADE_SEC_PRICE_STEP
end -- по цене, завышенной на 10 мин. шагов цены
else
Operation = 'S'
if TRADE_PRICE == 0 and TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then
TRADE_PRICE = getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'bid').param_value - 10*TRADE_SEC_PRICE_STEP
end -- по цене, заниженной на 10 мин. шагов цены
end
-- Заполняет структуру для отправки транзакции
--TRADE_PRICE = GetCorrectPrice(TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE)
myLog("script Monitor: "..TRADE_TYPE.." Transaction "..Type..' '..TRADE_PRICE)
local Transaction={
['TRANS_ID'] = tostring(trans_id),
['ACTION'] = 'NEW_ORDER',
['CLASSCODE'] = TRADE_CLASS_CODE,
['SECCODE'] = TRADE_SEC_CODE,
['CLIENT_CODE'] = CLIENT_CODE,
['OPERATION'] = Operation, -- операция ("B" - buy, или "S" - sell)
['TYPE'] = TRADE_TYPE,
['QUANTITY'] = tostring(qnt), -- количество
['ACCOUNT'] = ACCOUNT,
['PRICE'] = tostring(TRADE_PRICE),