forked from nick-nh/qlua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
robotOptimize.lua
1257 lines (1114 loc) · 56.9 KB
/
robotOptimize.lua
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
-------------------------------------------
--Îïòèìèçàöèÿ
test_startTradeTime = 1018 -- Íà÷àëî òîðãîâëè äëÿ òåñòà
test_endTradeTime = 1842 -- Îêîí÷àíèå òîðãîâëè äëÿ òåñòà
RFR = 0 --7.42 --áåçðèñêîâà ñòàâêà äëÿ ðàñ÷åòà êîýôô. Øàðïà
stopSignal = false
doneOptimization = 0
optimizationInProgress = false
needReoptimize = false
beginIndex = 1
endIndex = 1
beginIndexallProfit = 0
shortProfit = 0
longProfit = 0
lastDealPrice = 0
stopLevelPrice = 0
lastTradeDirection = 0
dealsCount = 0
dealsLongCount = 0
dealsShortCount = 0
algoResults = nil
profitDealsLongCount = 0
profitDealsShortCount = 0
slDealsLongCount = 0
tpDealsLongCount = 0
slDealsShortCount = 0
tpDealsShortCount = 0
ratioProfitDeals = 0
initalAssets = 0
deals = {}
resultsTables = {}
logDeals = false
function readOptimizedParams()
local func, err = loadfile(PARAMS_FILE_NAME)
if not func then
myLog(NAME_OF_STRATEGY.." Îøèáêà ïðè çàãðóçêå ôàéëà ïàðàìåòðîâ "..PARAMS_FILE_NAME..", err: "..tostring(err))
return nil
else
return func()
end
end
function saveOptimizedParams(settings)
local ParamsFile = io.open(PARAMS_FILE_NAME,"w")
myLog(NAME_OF_STRATEGY..'----- Çàïèñü îïòèìàëüíûõ óñòàíîâîê ïðåñåòà '..presets[curPreset].Name)
for k,v in pairs(globalSettings) do
if settings[k]~=nil then v = settings[k] end
if type(v) == 'string' then
ParamsFile:write(k..' = "'..tostring(v)..'"\n')
else
ParamsFile:write(k..' = '..tostring(v)..'\n')
end
end
for par, field in pairs(presets[curPreset].fields) do
local val = settings[par]
if val~=nil then
if type(val) == 'string' then
ParamsFile:write('Settings.'..par..' = "'..tostring(val)..'"\n')
else
ParamsFile:write('Settings.'..par..' = '..tostring(val)..'\n')
end
end
end
ParamsFile:flush()
ParamsFile:close()
end
function reoptimize()
ROBOT_STATE = 'ÎÏÒÈÌÈÇÀÖÈß'
BASE_ROBOT_STATE = 'ÎÏÒÈÌÈÇÀÖÈß'
if isTrade then
isTrade = false
end
maintable:SetValue('State', ROBOT_STATE, 0)
maintable:SetValue('START', 'START', 0)
maintable:SetColor('START', RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0))
SetAlgo()
setParameters()
lastSignalIndex = {}
myLog(NAME_OF_STRATEGY..' Ñòàðò ðåîïðòèìèçàöèè')
if virtualTrade then
if tpPrice~=0 then vtpPrice = tpPrice end
if slPrice~=0 then vslPrice = slPrice end
end
if iterateAlgo~=nil then
iterateAlgo()
end
needReoptimize = false
if virtualTrade then
if vtpPrice~=0 then tpPrice = vtpPrice end
if vslPrice~=0 then slPrice = vslPrice end
end
if serverTime < endTradeTime then
startTrade()
else
ROBOT_STATE = 'ÎÑÒÀÍÎÂËÅÍ'
BASE_ROBOT_STATE = 'ÎÑÒÀÍÎÂËÅÍ'
maintable:SetValue('State', ROBOT_STATE, 0)
end
if isTrade then
local currentTradeDirection = getTradeDirection(DS:Size()-1, calcAlgoValue, trend)
if currentTradeDirection < 0 then
CurrentDirect = 'SELL'
else
CurrentDirect = 'BUY'
end
if (OpenCount > 0 and currentTradeDirection == -1) or (OpenCount < 0 and currentTradeDirection == 1) then
myLog(NAME_OF_STRATEGY..' CurrentDirect = '..CurrentDirect)
myLog(NAME_OF_STRATEGY..' Îòêðûòà ïîçèöèÿ ïðîòèâ òðåíäà, ïåðåâîðà÷èâàåì')
ROBOT_STATE = 'ÏÅÐÅÂÎÐÎÒ'
end
if OpenCount == 0 then
ROBOT_STATE = 'Â ÏÐÎÖÅÑÑÅ ÑÄÅËÊÈ'
end
end
end
--- ÎÏÒÈÌÈÇÀÖÈß
function iterateAlgorithm(settingsTable)
local resultsTable = {}
isTrade = false
optimizationInProgress = true
endIndex = DS:Size()
if testSizeBars > 0 then
beginIndex = DS:Size()-testSizeBars
else
local days = 0
local firstDay = true
for i=1,endIndex do
local time = math.ceil((DS:T(endIndex-i+1).hour + DS:T(endIndex-i+1).min/100)*100)
local time1 = math.ceil((DS:T(endIndex-i).hour + DS:T(endIndex-i).min/100)*100)
local isTradeBegin = time >= startTradeTime and time1 < startTradeTime
--myLog(NAME_OF_STRATEGY..' time '..tostring(time)..' time1 '..tostring(time1))
if isTradeBegin then
days = days + 1
beginIndex = endIndex-i-1
if firstDay and serverTime < dayClearing then
days = days - 1
firstDay = false
end
end
if days == -1*testSizeBars then break end
end
end
myLog(NAME_OF_STRATEGY..'---------------------------------------------------')
myLog(NAME_OF_STRATEGY..' Start optimization '..presets[curPreset].Name)
for k,v in pairs(Settings) do
myLog(k..' '..tostring(v))
end
myLog(NAME_OF_STRATEGY..'-----------')
--local bars = endIndex - beginIndex
myLog(NAME_OF_STRATEGY..' testSizeBars '..tostring(testSizeBars))
myLog(NAME_OF_STRATEGY..' beginIndex '..tostring(beginIndex)..' - '..toYYYYMMDDHHMMSS(DS:T(beginIndex))..' endIndex '..tostring(endIndex)..' - '..toYYYYMMDDHHMMSS(DS:T(endIndex)))
--Âîññòàíàâëèâàåì íàñòðîéêè ñòîï-ëîññà è òåéê-ïðîôèòà ïî óìîë÷àíèþ èç ïðåñåòà, ÷òîáû èçáåæàòü âëèÿíèÿ ïðîøëûõ ðåçóëüòàòîâ
if presets[curPreset].TAKE_PROFIT ~= 0 then
globalSettings.TAKE_PROFIT = presets[curPreset].TAKE_PROFIT
TAKE_PROFIT = presets[curPreset].TAKE_PROFIT
end
if presets[curPreset].STOP_LOSS ~= 0 then
globalSettings.STOP_LOSS = presets[curPreset].STOP_LOSS
STOP_LOSS = presets[curPreset].STOP_LOSS
end
myLog('SL '..tostring(STOP_LOSS)..' TP '..tostring(TAKE_PROFIT))
resultsTable = iterateTable(settingsTable, resultsTable)
if not isRun then return end
if #resultsTable > 1 then
--ArraySortByColl(resultsTable, 3)
table.sort(resultsTable, function(a,b) return a[1]<b[1] end)
end
local saveSettings_string = (#presets[curPreset].saveSettings_string==0 and '' or presets[curPreset].saveSettings_string..';')..optimizedSettings_string
local optimizedSettings = {}
for par in allWords(saveSettings_string, ';') do
optimizedSettings[#optimizedSettings+1] = par
end
saveSettings_string = "line; INTERVAL; testSizeBars; allProfit; maxDown; lastDealSignal; trend; "..saveSettings_string
if #resultsTable > 0 and iterateSLTP and SetStop then
myLog(NAME_OF_STRATEGY.." list before iterate SL/TP")
myLog(NAME_OF_STRATEGY.." ----------------------------------------------------------")
local resultString = resultsTable[#resultsTable]
local bestSettings = resultString[#resultString]
myLog(saveSettings_string)
local linesToIterateSLTP = 25
for i=0,math.min(#resultsTable-1, linesToIterateSLTP) do
resultString = resultsTable[#resultsTable - i]
local settings = resultString[#resultString]
paramsString = tostring(#resultsTable-i).."; "..tostring(INTERVAL).."; "..tostring(testSizeBars)
for j=1,4 do
paramsString = paramsString..'; '..tostring(resultString[j])
end
for k=1, #optimizedSettings do
--myLog(optimizedSettings[k]..' global '..tostring(globalSettings[optimizedSettings[k]])..' settings '..tostring(bestSettings[optimizedSettings[k]]))
if settings[optimizedSettings[k]]~=nil then
paramsString = paramsString..'; '..tostring(settings[optimizedSettings[k]])
else
paramsString = paramsString..'; '..tostring(globalSettings[optimizedSettings[k]])
end
end
myLog(paramsString)
end
local lines = math.min(linesToIterateSLTP, #resultsTable)
local settingsTableSLTP = getSettingsSLTP(resultsTable, lines)
local i = 1
while i <= lines do
table.remove(resultsTable, #resultsTable)
i = i+1
end
--for i=1,#settingsTableSLTP do
-- myLog("i "..tostring(i).." periodATR "..tostring(settingsTableSLTP[i].periodATR).." kATR "..tostring(settingsTableSLTP[i].kATR).." alpha "..tostring(settingsTableSLTP[i].alpha).." shift "..tostring(settingsTableSLTP[i].shift))
--end
resultsTable = iterateTable(settingsTableSLTP, resultsTable)
table.sort(resultsTable, function(a,b) return a[1]<b[1] end)
end
if #resultsTable ~=0 then
local resultString = resultsTable[#resultsTable]
local bestSettings = resultString[#resultString]
local maxProfit = resultString[1]
local minDrawDown = resultString[2]
local algoLine =resultString[3]
local trendLine = resultString[4]
local bestOnTrend = (trendLine < 0 and DS:C(DS:Size()) < algoLine) or (trendLine > 0 and DS:C(DS:Size()) > algoLine) or algoLine == 0
local minProfit = maxProfit*0.95
local isSearch = true
local line = #resultsTable - 1
--local needNewBest = minDrawDown>6
local needNewBest = minDrawDown>20
myLog(NAME_OF_STRATEGY.." ----------------------------------------------------------")
myLog(saveSettings_string)
myLog(NAME_OF_STRATEGY.." best")
paramsString = tostring(#resultsTable).."; "..tostring(INTERVAL).."; "..tostring(testSizeBars)
for j=1,4 do
paramsString = paramsString.."; "..tostring(resultString[j])
end
for k=1, #optimizedSettings do
if bestSettings[optimizedSettings[k]]~=nil then
paramsString = paramsString..'; '..tostring(bestSettings[optimizedSettings[k]])
else
paramsString = paramsString..'; '..tostring(globalSettings[optimizedSettings[k]])
end
end
myLog(paramsString)
while isSearch and line >= 1 do
if not isRun then return end
CheckTradeSession()
if minProfit > resultsTable[line][1] and not needNewBest then
break
end
resultString = resultsTable[line]
trendLine = resultsTable[line][4]
algoLine = resultsTable[line][3]
local onTrend = (trendLine < 0 and DS:C(DS:Size()) < algoLine) or (trendLine > 0 and DS:C(DS:Size()) > algoLine) or algoLine == 0
if minDrawDown == resultsTable[line][2] and onTrend and not bestOnTrend then
minDrawDown = resultsTable[line][2]
--if minDrawDown<=6 then needNewBest = false end
bestSettings = resultsTable[line][#resultsTable[line]]
bestOnTrend = true
myLog(NAME_OF_STRATEGY.." new best line "..tostring(line))
paramsString = tostring(line).."; "..tostring(INTERVAL).."; "..tostring(testSizeBars)
for j=1,4 do
paramsString = paramsString.."; "..tostring(resultString[j])
end
for k=1, #optimizedSettings do
if bestSettings[optimizedSettings[k]]~=nil then
paramsString = paramsString..'; '..tostring(bestSettings[optimizedSettings[k]])
else
paramsString = paramsString..'; '..tostring(globalSettings[optimizedSettings[k]])
end
end
myLog(paramsString)
end
if minDrawDown > resultsTable[line][2] and onTrend then
minDrawDown = resultsTable[line][2]
--if minDrawDown<=6 then needNewBest = false end
bestSettings = resultsTable[line][#resultsTable[line]]
myLog(NAME_OF_STRATEGY.." new best line "..tostring(line))
paramsString = tostring(line).."; "..tostring(INTERVAL).."; "..tostring(testSizeBars)
for j=1,4 do
paramsString = paramsString.."; "..tostring(resultString[j])
end
for k=1, #optimizedSettings do
if bestSettings[optimizedSettings[k]]~=nil then
paramsString = paramsString..'; '..tostring(bestSettings[optimizedSettings[k]])
else
paramsString = paramsString..'; '..tostring(globalSettings[optimizedSettings[k]])
end
end
myLog(paramsString)
end
line = line - 1
end
--íå íàøëè ëó÷øèé ðåçóëüòàò ñ ïðèåìëåìîé ïðîñàäêîé. Áåðåì ëó÷øèé ïî ïðèáûëè.
if needNewBest then
resultString = resultsTable[#resultsTable]
bestSettings = resultString[#resultString]
myLog(NAME_OF_STRATEGY.." ----------------------------------------------------------")
myLog(NAME_OF_STRATEGY.." Íå íàøëè ëó÷øèé ðåçóëüòàò ñ ïðèåìëåìîé ïðîñàäêîé")
myLog(NAME_OF_STRATEGY.." new best line "..tostring(#resultsTable))
end
myLog(NAME_OF_STRATEGY.." ----------------------------------------------------------")
myLog(NAME_OF_STRATEGY.." list")
for i=0,math.min(#resultsTable-1, 40) do
resultString = resultsTable[#resultsTable - i]
local settings = resultString[#resultString]
paramsString = tostring(#resultsTable-i).."; "..tostring(INTERVAL).."; "..tostring(testSizeBars)
for j=1,4 do
paramsString = paramsString..'; '..tostring(resultString[j])
end
for k=1, #optimizedSettings do
--myLog(optimizedSettings[k]..' global '..tostring(globalSettings[optimizedSettings[k]])..' settings '..tostring(settings[optimizedSettings[k]]))
if settings[optimizedSettings[k]]~=nil then
paramsString = paramsString..'; '..tostring(settings[optimizedSettings[k]])
else
paramsString = paramsString..'; '..tostring(globalSettings[optimizedSettings[k]])
end
end
myLog(paramsString)
end
for k,v in pairs(bestSettings) do
if globalSettings[k]~= nil then
assert(loadstring(k..'='..tostring(v)))()
globalSettings[k] = v
end
end
setTableAlgoParams(bestSettings, presets[curPreset])
maintable:SetValue('STOP_LOSS', tostring(STOP_LOSS), STOP_LOSS)
maintable:SetValue('TAKE_PROFIT', tostring(TAKE_PROFIT), TAKE_PROFIT)
optimizationInProgress = false
saveOptimizedParams(bestSettings)
return
end
optimizationInProgress = false
myLog(NAME_OF_STRATEGY.." Íåò ïîëîæèòåëüíûõ ðåçóëüòàòîâ îïòèìèçàöèè")
message("Íåò ïîëîæèòåëüíûõ ðåçóëüòàòîâ îïòèìèçàöèè")
end
function iterateTable(settingsTable, resultsTable)
local localCount = 0
local rescount = 0
local allCount = #settingsTable
for i,v in ipairs(settingsTable) do
if not isRun then return end
if stopSignal then
stopSignal = false
break
end
localCount = localCount + 1
doneOptimization = round(localCount*100/allCount, 0)
SetState("OPTIMIZATION "..tostring(doneOptimization).."%", doneOptimization)
CheckTradeSession()
allProfit = 0
shortProfit = 0
longProfit = 0
lastDealPrice = 0
lastTradeDirection = 0
lastStopShiftIndex = 0
dealsCount = 0
dealsLongCount = 0
dealsShortCount = 0
profitDealsLongCount = 0
profitDealsShortCount = 0
slDealsLongCount = 0
tpDealsLongCount = 0
slDealsShortCount = 0
tpDealsShortCount = 0
ratioProfitDeals = 0
initalAssets = 0
settingsTask = v
settingsTask.beginIndex = beginIndex
settingsTask.endIndex = endIndex
settingsTask.beginIndexToCalc = math.max(1, beginIndex - 1000)
optimizeAlgorithm()
local profitRatio, avg, sigma, maxDrawDown, sharpe, AHPR, ZCount = calculateSigma(deals)
--myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
--myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî ëîíãàì "..tostring(longProfit))
--myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî øîðòàì "..tostring(shortProfit))
--myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
--myLog(NAME_OF_STRATEGY.." ================================================")
dealsLP = tostring(dealsLongCount).."/"..tostring(profitDealsLongCount)
dealsSP = tostring(dealsShortCount).."/"..tostring(profitDealsShortCount)
if dealsLongCount + dealsShortCount > 0 then
ratioProfitDeals = round((profitDealsLongCount + profitDealsShortCount)*100/(dealsLongCount + dealsShortCount), 2)
end
if profitRatio > 0 then
rescount = rescount + 1
--resultsTable[rescount] = {allProfit, profitRatio, longProfit, shortProfit, dealsLP, dealsSP, ratioProfitDeals, avg, sigma, maxDrawDown, sharpe, AHPR, ZCount, settingsTask}
resultsTable[rescount] = {allProfit, maxDrawDown, calcAlgoValue[endIndex], trend[endIndex], settingsTask}
end
end
return resultsTable
end
function getSettingsSLTP(resultsTable, lines)
local param4Min = STOP_LOSS
local param4Max = STOP_LOSS
local param4Step = 5
local param5Min = TAKE_PROFIT
local param5Max = TAKE_PROFIT
local param5Step = 5
if STOP_LOSS~=0 then
param4Min = 25
param4Max = 75
param4Step = 5
end
if TAKE_PROFIT~=0 then
param5Min = 80
param5Max = 230
param5Step = 5
end
local settingsTable = {}
local allCount = 0
for i=0,math.min(#resultsTable-1, lines) do
local resultString = resultsTable[#resultsTable - i]
for param4 = param4Min, param4Max, param4Step do
for param5 = param5Min, param5Max, param5Step do
allCount = allCount + 1
settingsTable[allCount] = {}
for i,v in pairs(resultString[#resultString]) do
settingsTable[allCount][i] = v
end
settingsTable[allCount].STOP_LOSS = param4
settingsTable[allCount].TAKE_PROFIT = param5
--myLog(NAME_OF_STRATEGY..' **** SL '..tostring(settingsTable[allCount].SLSec)..' TP '..tostring(settingsTable[allCount].TPSec))
end
end
end
return settingsTable
end
function calculateSigma(deals)
local sigma = 0
local avg = 0
local maxDrawDown = 0
local equity = initalAssets or 0
local maxEquity = initalAssets or 0
local profitRatio = 0
local dispDeals = {}
local maxDelta = 0
--Sharpe ratio
local sharpe = 0
local HPRDeals = {}
local sigmaHPR = 0
local avgHPR = 0
local dealsCount = 0
local seriesCount = 0
local lastProfit = nil
local ZCount = 0
--myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
--myLog(NAME_OF_STRATEGY.." equity "..tostring(equity))
for i,index in pairs(deals["index"]) do
if deals["dealProfit"][i] ~= nil then
dealsCount = dealsCount + 1
avg = avg + deals["dealProfit"][i]
dispDeals[i] = deals["dealProfit"][i]
local oldEquity = equity
equity = equity + deals["dealProfit"][i]
--myLog(NAME_OF_STRATEGY.." index "..tostring(index).." equity "..tostring(equity))
if oldEquity > 0 and equity < 0 then
HPRDeals[i] = 0
elseif oldEquity < 0 and equity > 0 then
HPRDeals[i] = 1000
else
HPRDeals[i] = equity/oldEquity
end
--myLog(NAME_OF_STRATEGY.." HPRDeals[i] "..tostring(HPRDeals[i]))
avgHPR = avgHPR + HPRDeals[i]
maxEquity = math.max(maxEquity, equity)
--myLog(NAME_OF_STRATEGY.." maxEquity "..tostring(maxEquity))
if equity < maxEquity then
maxDelta = math.max(maxEquity - equity, maxDelta)
maxDrawDown = math.max(round(maxDelta*100/maxEquity, 2), maxDrawDown)
--myLog(NAME_OF_STRATEGY.." maxDrawDown "..tostring(maxDrawDown))
end
if lastProfit ~= nil then
if lastProfit > 0 and deals["dealProfit"][i] <= 0 then
seriesCount = seriesCount + 1
elseif lastProfit <= 0 and deals["dealProfit"][i] > 0 then
seriesCount = seriesCount + 1
end
end
lastProfit = deals["dealProfit"][i]
end
end
if dealsCount > 0 then
avg = round(avg/dealsCount, 5)
avgHPR = round(avgHPR/dealsCount, 5)
else
avg = 0
avgHPR = 0
end
--myLog(NAME_OF_STRATEGY.." avgHPR "..tostring(avgHPR))
for i,_ in pairs(dispDeals) do
sigma = sigma + math.pow(dispDeals[i] - avg, 2)
sigmaHPR = sigmaHPR + math.pow(HPRDeals[i] - avgHPR, 2)
--myLog(NAME_OF_STRATEGY.." HPR_Avg "..tostring(math.pow(HPRDeals[i] - avgHPR, 2)))
end
--myLog(NAME_OF_STRATEGY.." DispHPR "..tostring(sigmaHPR))
if dealsCount > 1 then
sigma = round(math.sqrt(sigma/(dealsCount-1)), 2)
sigmaHPR = round(math.sqrt(sigmaHPR/(dealsCount-1)), 5)
--myLog(NAME_OF_STRATEGY.." sigmaHPR "..tostring(sigmaHPR))
sharpe = round((avgHPR - (1 + RFR/100))/sigmaHPR, 2)
else
sigma = 0
sigmaHPR = 0
end
if initalAssets ~= 0 then
profitRatio = round((equity - initalAssets)*100/initalAssets, 2)
end
if seriesCount > 0 then
local P = 2*(profitDealsLongCount + profitDealsShortCount)*(dealsLongCount - profitDealsLongCount + dealsShortCount - profitDealsShortCount)
ZCount=round((dealsCount*(seriesCount-0.5)-P)/math.sqrt((P*(P-dealsCount))/(dealsCount-1)), 2)
end
return profitRatio, avg, sigma, maxDrawDown, sharpe, round(avgHPR, 2), ZCount
end
function optimizeAlgorithm()
if initalAssets == 0 and CLASS_CODE == "SPBFUT" then
initalAssets = tonumber(getParamEx(CLASS_CODE, SEC_CODE, "BUYDEPO").param_value) --/priceKoeff
end
--if beginIndex == 1 then
-- beginIndex = DS:Size()-testSizeBars
--end
if endIndex == 1 then
endIndex = DS:Size()
end
if beginIndex <= 0 or beginIndex == endIndex then beginIndex = 1 end
if initAlgo~=nil then
initAlgo()
end
lastTradeDirection = 0
slPrice = 0
tpPrice = 0
slIndex = 0
TRAILING_ACTIVATED = false
TransactionPrice = 0
for k,v in pairs(settingsTask) do
if globalSettings[k]~= nil then
assert(loadstring(k..'='..tostring(v)))()
globalSettings[k] = v
end
end
deals = {
["index"] = {},
["openLong"] = {},
["openShort"] = {},
["closeLong"] = {},
["closeShort"] = {},
["dealProfit"] = {}
}
for index = settingsTask.beginIndexToCalc, settingsTask.endIndex do
calculateAlgo(index, settingsTask)
simpleTrade(index, calcAlgoValue, trend, deals, settingsTask)
end
end
function simpleTrade(index, calcAlgoValue, calcTrend, deals)
if index <= beginIndex then return nil end
local equitySum = initalAssets or 0
local t = DS:T(index)
local dealTime = false
local time = math.ceil((t.hour + t.min/100)*100)
if time >= test_startTradeTime then
dealTime = true
end
if time >= test_endTradeTime then
dealTime = false
end
if CLASS_CODE == 'QJSIM' or CLASS_CODE == 'TQBR' then
dealTime = true
end
tradeSignal = getTradeSignal(index, calcAlgoValue, calcTrend)
if not dealTime or os.time(DS:T(index)) == test_startTradeTime then
lastTradeDirection = getTradeDirection(index-1, calcAlgoValue, calcTrend)
end
local closeDeal = false
if calcTrend ~= nil then
closeDeal = calcTrend[index-1] == 0
end
if (not dealTime or closeDeal) and lastDealPrice ~= 0 and (deals["openShort"][dealsCount] ~= nil or deals["openLong"][dealsCount] ~= nil) then
if initalAssets == 0 then
initalAssets = DS:O(index)/priceKoeff
equitySum = initalAssets
end
if deals["openShort"][dealsCount] ~= nil then
dealsCount = dealsCount + 1
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY.." index "..tostring(index).." time "..toYYYYMMDDHHMMSS(DS:T(index))..' dealsCount '..tostring(dealsCount))
end
local tradeProfit = round(lastDealPrice - DS:O(index), SCALE)/priceKoeff
shortProfit = shortProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
if tradeProfit > 0 then
profitDealsShortCount = profitDealsShortCount + 1
end
deals["index"][dealsCount] = index
deals["closeShort"][dealsCount] = DS:O(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå øîðòà "..tostring(deals["openShort"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî øîðòàì "..tostring(shortProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
TRAILING_ACTIVATED = false
lastDealPrice = 0
slPrice = 0
slIndex = 0
tpPrice = 0
end
if deals["openLong"][dealsCount] ~= nil then
dealsCount = dealsCount + 1
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY.." index "..tostring(index).." time "..toYYYYMMDDHHMMSS(DS:T(index))..' dealsCount '..tostring(dealsCount))
end
local tradeProfit = round(DS:O(index) - lastDealPrice, SCALE)/priceKoeff
longProfit = longProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
if tradeProfit > 0 then
profitDealsLongCount = profitDealsLongCount + 1
end
deals["index"][dealsCount] = index
deals["closeLong"][dealsCount] = DS:O(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå ëîíãà "..tostring(deals["openLong"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî ëîíãàì "..tostring(longProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
TRAILING_ACTIVATED = false
lastDealPrice = 0
slPrice = 0
slIndex = 0
tpPrice = 0
end
end
--if dealTime and slIndex ~= 0 and (index - slIndex) == reopenPosAfterStop then
if dealTime and slIndex ~= 0 and slIndex+2>=index then
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY..' index '..tostring(index).." òåñò ïîñëå ñòîïà time "..toYYYYMMDDHHMMSS(DS:T(slIndex)))
end
local currentTradeDirection = getTradeDirection(index, calcAlgoValue, calcTrend, DS)
local spread = round(DS:H(index) - DS:L(index), SCALE)
local close_up = round((DS:C(index) - DS:L(index))/spread, SCALE) > 0.6
local close_dw = round((DS:H(index) - DS:C(index))/spread, SCALE) > 0.6
if currentTradeDirection == 1 and deals["closeLong"][dealsCount]~=nil then
--if deals["closeLong"][dealsCount]<DS:O(index) then
if DS:C(index-2)<DS:C(index) and DS:C(index-2)<DS:C(index-1) and DS:C(index-1)<DS:C(index) and DS:O(index-1)<DS:C(index-1) and DS:O(index)<DS:C(index) and close_up then
--if DS:C(index-3)<DS:C(index-1) and DS:C(index-2)<DS:C(index) and DS:C(index-1)<DS:C(index) then
if logDeals then
myLog(NAME_OF_STRATEGY.." ïåðåîòêðûòèå ëîíãà ïîñëå ñòîïà time "..toYYYYMMDDHHMMSS(DS:T(slIndex)))
end
lastTradeDirection = currentTradeDirection
reopenAfterStop = true
end
end
if currentTradeDirection == -1 and deals["closeShort"][dealsCount]~=nil then
--if deals["closeShort"][dealsCount]>DS:O(index) then
if DS:C(index-2)>DS:C(index) and DS:C(index-2)>DS:C(index-1) and DS:C(index-1)>DS:C(index) and DS:O(index-1)>DS:C(index-1) and DS:O(index)>DS:C(index) and close_dw then
--if DS:C(index-3)<DS:C(index-1) and DS:C(index-2)<DS:C(index) and DS:C(index-1)<DS:C(index) then
if logDeals then
myLog(NAME_OF_STRATEGY.." ïåðåîòêðûòèå øîðòà ïîñëå ñòîïà time "..toYYYYMMDDHHMMSS(DS:T(slIndex)))
end
lastTradeDirection = currentTradeDirection
reopenAfterStop = true
end
end
slIndex = index
end
if (tradeSignal == 1 or lastTradeDirection == 1) and dealTime and not closeDeal then
dealsCount = dealsCount + 1
if initalAssets == 0 then
initalAssets = DS:O(index)/priceKoeff
equitySum = initalAssets
end
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY.." index "..tostring(index).." time "..toYYYYMMDDHHMMSS(DS:T(index))..' dealsCount '..tostring(dealsCount))
myLog(NAME_OF_STRATEGY.." tradeSignal "..tostring(tradeSignal).." lastTradeDirection "..tostring(lastTradeDirection).." openShort "..tostring(deals["openShort"][dealsCount-1])..' openLong '..tostring(deals["openLong"][dealsCount-1]))
end
lastTradeDirection = 0
if deals["openShort"][dealsCount-1] ~= nil then
local tradeProfit = round(lastDealPrice - DS:O(index), SCALE)/priceKoeff
shortProfit = shortProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
slPrice = 0
slIndex = 0
tpPrice = 0
if tradeProfit > 0 then
profitDealsShortCount = profitDealsShortCount + 1
end
deals["index"][dealsCount] = index
deals["closeShort"][dealsCount] = DS:O(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå øîðòà "..tostring(deals["openShort"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî øîðòàì "..tostring(shortProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
end
if isLong then
dealsLongCount = dealsLongCount + 1
lastDealPrice = DS:O(index)
TRAILING_ACTIVATED = false
TransactionPrice = lastDealPrice
if STOP_LOSS~=0 then
--slPrice = lastDealPrice - STOP_LOSS*priceKoeff
local atPrice = calcAlgoValue[index-1]
local shiftSL = (kATR*ATR[index-1] + SL_ADD_STEPS*SEC_PRICE_STEP)
if (atPrice - shiftSL) >= TransactionPrice then
atPrice = TransactionPrice
end
if fixedstop then
shiftSL = STOP_LOSS*priceKoeff
atPrice = TransactionPrice
end
slPrice = round(atPrice - shiftSL, SCALE)
if reopenAfterStop then dealMaxStop = reopenDealMaxStop else dealMaxStop = maxStop end
if (lastDealPrice - slPrice) > dealMaxStop*priceKoeff then slPrice = lastDealPrice - dealMaxStop*priceKoeff end
reopenAfterStop = false
slIndex = 0
lastStopShiftIndex = index
end
if TAKE_PROFIT~=0 then
tpPrice = round(lastDealPrice + TAKE_PROFIT*priceKoeff, SCALE)
end
deals["index"][dealsCount] = index
deals["openLong"][dealsCount] = DS:O(index)
if logDeals then
myLog(NAME_OF_STRATEGY.." Ïîêóïêà ïî öåíå "..tostring(lastDealPrice).." SL "..tostring(slPrice).." TP "..tostring(tpPrice))
myLog(NAME_OF_STRATEGY.." STOP_LOSS "..tostring(STOP_LOSS).." TAKE_PROFIT "..tostring(TAKE_PROFIT).." kATR "..tostring(kATR).." ATR "..tostring(ATR[index-1]).." calcAlgoValue "..tostring(calcAlgoValue[index-1]))
end
else
lastDealPrice = 0
TRAILING_ACTIVATED = false
end
end
if (tradeSignal == -1 or lastTradeDirection == -1) and dealTime and not closeDeal then
dealsCount = dealsCount + 1
if initalAssets == 0 then
initalAssets = DS:O(index)/priceKoeff
end
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY.." index "..tostring(index).." time "..toYYYYMMDDHHMMSS(DS:T(index)))
myLog(NAME_OF_STRATEGY.." tradeSignal "..tostring(tradeSignal).." lastTradeDirection "..tostring(lastTradeDirection).." openShort "..tostring(deals["openShort"][dealsCount-1])..' openLong '..tostring(deals["openLong"][dealsCount-1]))
end
lastTradeDirection = 0
if deals["openLong"][dealsCount-1] ~= nil then
local tradeProfit = round(DS:O(index) - lastDealPrice, SCALE)/priceKoeff
longProfit = longProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
slPrice = 0
slIndex = 0
tpPrice = 0
if tradeProfit > 0 then
profitDealsLongCount = profitDealsLongCount + 1
end
deals["index"][dealsCount] = index
deals["closeLong"][dealsCount] = DS:O(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå ëîíãà "..tostring(deals["openLong"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî ëîíãàì "..tostring(longProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
end
if isShort then
dealsShortCount = dealsShortCount + 1
lastDealPrice = DS:O(index)
TRAILING_ACTIVATED = false
TransactionPrice = lastDealPrice
if STOP_LOSS~=0 then
--slPrice = lastDealPrice + STOP_LOSS*priceKoeff
local atPrice = calcAlgoValue[index-1]
local shiftSL = (kATR*ATR[index-1] + SL_ADD_STEPS*SEC_PRICE_STEP)
if (atPrice + shiftSL) <= TransactionPrice then
atPrice = TransactionPrice
end
if fixedstop then
shiftSL = STOP_LOSS*priceKoeff
atPrice = TransactionPrice
end
slPrice = round(atPrice + shiftSL, SCALE)
if reopenAfterStop then dealMaxStop = reopenDealMaxStop else dealMaxStop = maxStop end
if (slPrice - lastDealPrice) > dealMaxStop*priceKoeff then slPrice = lastDealPrice + dealMaxStop*priceKoeff end
reopenAfterStop = false
slIndex = 0
lastStopShiftIndex = index
end
if TAKE_PROFIT~=0 then
tpPrice = round(lastDealPrice - TAKE_PROFIT*priceKoeff, SCALE)
end
deals["index"][dealsCount] = index
deals["openShort"][dealsCount] = DS:O(index)
if logDeals then
myLog(NAME_OF_STRATEGY.." Ïðîäàæà ïî öåíå "..tostring(lastDealPrice).." SL "..tostring(slPrice).." TP "..tostring(tpPrice))
myLog(NAME_OF_STRATEGY.." STOP_LOSS "..tostring(STOP_LOSS).." TAKE_PROFIT "..tostring(TAKE_PROFIT).." kATR "..tostring(kATR).." ATR "..tostring(ATR[index-1]).." calcAlgoValue "..tostring(calcAlgoValue[index-1]))
end
else
lastDealPrice = 0
TRAILING_ACTIVATED = false
end
end
checkSL_TP(index, calcAlgoValue, calcTrend, deals, equitySum)
if index == endIndex and (deals["openShort"][dealsCount] ~= nil or deals["openLong"][dealsCount] ~= nil) then
if logDeals then
myLog(NAME_OF_STRATEGY.." --------------------------------------------------")
myLog(NAME_OF_STRATEGY.." last index "..tostring(index).." time "..toYYYYMMDDHHMMSS(DS:T(index)))
end
if initalAssets == 0 then
initalAssets = DS:O(index)/priceKoeff
equitySum = initalAssets
end
if deals["openShort"][dealsCount] ~= nil then
dealsCount = dealsCount + 1
local tradeProfit = round(lastDealPrice - DS:C(index), SCALE)/priceKoeff
shortProfit = shortProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
if tradeProfit > 0 then
profitDealsShortCount = profitDealsShortCount + 1
end
deals["index"][dealsCount] = index
deals["closeShort"][dealsCount] = DS:C(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå øîðòà "..tostring(deals["openShort"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî øîðòàì "..tostring(shortProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
end
if deals["openLong"][dealsCount] ~= nil then
dealsCount = dealsCount + 1
local tradeProfit = round(DS:O(index) - lastDealPrice, SCALE)/priceKoeff
longProfit = longProfit + tradeProfit
allProfit = allProfit + tradeProfit
equitySum = equitySum + tradeProfit
if tradeProfit > 0 then
profitDealsLongCount = profitDealsLongCount + 1
end
deals["index"][dealsCount] = index
deals["closeLong"][dealsCount] = DS:C(index)
deals["dealProfit"][dealsCount] = tradeProfit
if logDeals then
myLog(NAME_OF_STRATEGY.." Çàêðûòèå ëîíãà "..tostring(deals["openLong"][dealsCount-1]).." ïî öåíå "..tostring(DS:O(index)))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ñäåëêè "..tostring(tradeProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü ïî ëîíãàì "..tostring(longProfit))
myLog(NAME_OF_STRATEGY.." Ïðèáûëü âñåãî "..tostring(allProfit))
myLog(NAME_OF_STRATEGY.." equity "..tostring(equitySum))
end
end
end
end
function checkSL_TP(index, calcAlgoValue, calcTrend, deals, equitySum)