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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
"""
L2撤单策略
"""
# ---------------------------------S撤-------------------------------
 
# s级平均大单计算
# 计算范围到申报时间的那一秒
import json
import logging
import time
 
import constant
from code_attribute import big_money_num_manager, gpcode_manager, code_volumn_manager
import l2_data_util
from db import redis_manager_delegate as redis_manager
from db.redis_manager_delegate import RedisUtils
from l2.code_price_manager import Buy1PriceManager
from l2.huaxin import l2_huaxin_util
from l2.l2_data_manager import OrderBeginPosInfo
from l2.l2_transaction_data_manager import HuaXinBuyOrderManager, HuaXinSellOrderStatisticManager, BigOrderDealManager
from log_module import async_log_util
from trade.sell.sell_rule_manager import TradeRuleManager
 
from utils import tool
from l2.transaction_progress import TradeBuyQueue
from trade import trade_queue_manager, l2_trade_factor, trade_record_log_util, trade_manager, trade_data_manager
from l2 import l2_log, l2_data_source_util
from l2.l2_data_util import L2DataUtil, local_today_num_operate_map, local_today_datas, local_today_buyno_map, \
    local_today_canceled_buyno_map
from log_module.log import logger_buy_1_volumn, logger_l2_l_cancel, logger_l2_h_cancel, logger_l2_s_cancel, logger_debug
from utils.tool import CodeDataCacheUtil
 
 
def set_real_place_position(code, index, buy_single_index=None, is_default=True):
    # DCancelBigNumComputer().set_real_order_index(code, index)
    SCancelBigNumComputer().set_real_place_order_index(code, index, is_default)
    LCancelBigNumComputer().set_real_place_order_index(code, index, buy_single_index=buy_single_index,
                                                       is_default=is_default)
    HourCancelBigNumComputer().set_real_place_order_index(code, index, buy_single_index)
    NewGCancelBigNumComputer().set_real_place_order_index(code, index, buy_single_index, is_default)
    FCancelBigNumComputer().set_real_order_index(code, index, is_default)
    JCancelBigNumComputer().set_real_place_order_index(code, index, buy_single_index, is_default)
    NBCancelBigNumComputer().set_real_place_order_index(code, index, buy_single_index, is_default)
 
 
class BaseCancel:
    def set_real_place_order_index(self, code, index, buy_single_index, is_default):
        pass
        # 撤单成功
 
    def cancel_success(self, code):
        pass
 
        # 下单成功
 
    def place_order_success(self, code):
        pass
 
 
class L2DataComputeUtil:
    """
    L2数据计算帮助类
    """
 
    @classmethod
    def compute_left_buy_order(cls, code, start_index, end_index, limit_up_price, min_money=500000):
        """
        计算剩下的委托买单
        @param code: 代码
        @param start_index:起始索引(包含)
        @param end_index: 结束索引(包含)
        @param limit_up_price: 涨停价
        @param min_money: 最小的资金
        @return:笔数,手数
        """
        min_volume = min_money // int(limit_up_price * 100)
        total_datas = local_today_datas.get(code)
        canceled_buyno_map = local_today_canceled_buyno_map.get(code)
        total_count = 0
        total_num = 0
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val['num'] < min_volume:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     canceled_buyno_map)
            if left_count > 0:
                total_count += 1
                total_num += val["num"]
        return total_count, total_num
 
    @classmethod
    def compute_end_index(cls, code, start_index, end_index, limit_up_price, max_count, min_money=500000):
        """
        计算结束索引
        @param code: 代码
        @param start_index:起始索引(包含)
        @param end_index: 结束索引(包含)
        @param limit_up_price: 涨停价
        @param max_count: 最大数量
        @param min_money: 最小的资金
        @return:结束索引
        """
        min_volume = min_money // int(limit_up_price * 100)
        total_datas = local_today_datas.get(code)
        canceled_buyno_map = local_today_canceled_buyno_map.get(code)
        total_count = 0
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val['num'] < min_volume:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     canceled_buyno_map)
            if left_count > 0:
                total_count += 1
                if total_count >= max_count:
                    return i
        return end_index
 
 
class SCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __sCancelParamsManager = l2_trade_factor.SCancelParamsManager
    __s_cancel_real_place_order_index_cache = {}
    __s_down_watch_indexes_dict = {}
    __recompute_l_down_time_dict = {}
    # 最近处理的卖单号
    __latest_process_sell_order_no = {}
 
    # S慢砸包含的范围
    __s_slow_sell_watch_indexes_dict = {}
 
    # 成交进度位置
    __trade_progress_index_dict = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(SCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "s_cancel_real_place_order_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = json.loads(val)
                tool.CodeDataCacheUtil.set_cache(cls.__s_cancel_real_place_order_index_cache, code, val)
        finally:
            RedisUtils.realse(__redis)
 
    # 设置真实下单位置
    def __save_real_place_order_index(self, code, index, is_default):
        CodeDataCacheUtil.set_cache(self.__s_cancel_real_place_order_index_cache, code, (index, is_default))
        key = "s_cancel_real_place_order_index-{}".format(code)
        RedisUtils.setex_async(self.__db, key, tool.get_expire(), json.dumps((index, is_default)))
 
    def __get_real_place_order_index_info_cache(self, code):
        cache_result = CodeDataCacheUtil.get_cache(self.__s_cancel_real_place_order_index_cache, code)
        if cache_result[0]:
            return cache_result[1]
        return None
 
    def get_real_place_order_index_cache(self, code):
        cache_result = self.__get_real_place_order_index_info_cache(code)
        if cache_result:
            return cache_result[0]
        return None
 
    def __clear_data(self, code):
        CodeDataCacheUtil.clear_cache(self.__s_cancel_real_place_order_index_cache, code)
        CodeDataCacheUtil.clear_cache(self.__s_down_watch_indexes_dict, code)
        CodeDataCacheUtil.clear_cache(self.__trade_progress_index_dict, code)
        CodeDataCacheUtil.clear_cache(self.__s_slow_sell_watch_indexes_dict, code)
        ks = ["s_big_num_cancel_compute_data-{}".format(code), "s_cancel_real_place_order_index-{}".format(code)]
        for key in ks:
            RedisUtils.delete_async(self.__db, key)
 
    # 设置真实下单位置
    def set_real_place_order_index(self, code, index, is_default):
        self.__save_real_place_order_index(code, index, is_default)
        if not is_default:
            self.__compute_s_slow_sell(code)
 
    def set_transaction_index(self, code, buy_single_index, index):
        self.__trade_progress_index_dict[code] = index
        self.__compute_s_slow_sell(code)
 
    def clear_data(self):
        ks = ["s_big_num_cancel_compute_data-*", "s_cancel_real_place_order_index-*"]
        for key in ks:
            keys = RedisUtils.keys(self.__get_redis(), key)
            for k in keys:
                code = k.split("-")[1]
                self.__clear_data(code)
 
    # 撤单成功
    def cancel_success(self, code):
        self.__clear_data(code)
 
    # 下单成功
    def place_order_success(self, code):
        self.__clear_data(code)
 
    def __get_fast_threshold_value(self, code):
        """
        获取S快炸的阈值
        @param code:
        @return:(大单阈值, 800w内大单阈值)
        """
        max60, yesterday = code_volumn_manager.get_histry_volumn(code)
        if max60:
            num = max60[0]
            limit_up_price = gpcode_manager.get_limit_up_price(code)
            if limit_up_price:
                money_y = min(round((num * float(limit_up_price)) / 1e8, 1), 7.9)
                money = int(round(15 * money_y + 276.5))
                money_800 = int(round(money * 0.668))
                return money, money_800
        # 默认值
        return 299, 200
 
    # S前撤实现
    def __need_cancel_for_up(self, code, big_sell_order_info, total_datas):
        # 查询是否是真的真实下单位置
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        if trade_index is None:
            trade_index = 0
        real_order_index_info = self.__get_real_place_order_index_info_cache(code)
        if real_order_index_info is None or real_order_index_info[1]:
            return False, "没找到真实下单位"
        real_order_index = real_order_index_info[0]
        total_deal_money = sum([x[1] * x[2] for x in big_sell_order_info[1]])
        start_order_no = big_sell_order_info[1][0][3][1]
        # 防止分母位0
        total_num = 1
        # 获取正在成交的数据
        dealing_info = HuaXinBuyOrderManager.get_dealing_order_info(code)
        for i in range(trade_index, real_order_index):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if int(val['orderNo']) < start_order_no:
                continue
            if i == trade_index and dealing_info and str(total_datas[trade_index]["val"]["orderNo"]) == str(
                    dealing_info[0]):
                # 减去当前正在成交的数据中已经成交了的数据
                total_num -= dealing_info[1] // 100
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_num += val["num"]
 
        # 大于10w
        if total_deal_money >= 10 * 10000:
            cancel_result = self.__need_cancel_for_slow_sell(code, total_datas)
            if cancel_result[0]:
                return True, f"S慢砸:{cancel_result[1]}"
 
        if total_deal_money >= 100 * 10000:
            l2_log.s_cancel_debug(code, "准备更新L后囊括")
            start_order_no = big_sell_order_info[1][-1][4][1]
            latest_deal_time_ms = l2_huaxin_util.convert_time(big_sell_order_info[1][-1][4][0], with_ms=True)
            real_trade_index = None
            for i in range(trade_index, real_order_index):
                data = total_datas[i]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                if int(val['orderNo']) < start_order_no:
                    continue
                real_trade_index = i
                break
            if real_trade_index is None:
                l2_log.s_cancel_debug(code, f"没找到真实的成交进度:start_order_no-{start_order_no} 卖单-{big_sell_order_info}")
                return False, ""
            # 间隔1S以上才能重新囊括
            if code in self.__recompute_l_down_time_dict and tool.trade_time_sub_with_ms(latest_deal_time_ms,
                                                                                         self.__recompute_l_down_time_dict[
                                                                                             code]) < 1000:
                l2_log.s_cancel_debug(code,
                                      f"更新L后囊括:更新间隔在1s内,{latest_deal_time_ms}-{self.__recompute_l_down_time_dict[code]}")
                return False, ""
            self.__recompute_l_down_time_dict[code] = latest_deal_time_ms
            # 重新囊括L后
            # 撤单时间比早成交时间大就需要计算在里面
            LCancelBigNumComputer().re_compute_l_down_watch_indexes(code, big_sell_info=(
                real_trade_index, latest_deal_time_ms))
            l2_log.s_cancel_debug(code, f"更新L后囊括完成:{(real_trade_index, latest_deal_time_ms)}")
        return False, ""
 
    def __need_cancel_for_slow_sell(self, code, total_datas):
        """
        S慢撤的目的是判断较大金额卖占整个卖的比例不能太大
        @param code:
        @param total_datas:
        @return:
        """
        if code not in self.__s_slow_sell_watch_indexes_dict:
            return False, "S慢砸没有囊括"
        # 下单3分钟内有效
        real_place_order_info = self.__get_real_place_order_index_info_cache(code)
        if not real_place_order_info:
            return False, "没有获取到真实下单位"
        if tool.trade_time_sub(total_datas[-1]['val']['time'],
                               total_datas[real_place_order_info[0]]['val']['time']) > 180:
            return False, "超过守护时间"
 
        # 格式:[{监听index},当时正在成交的订单号,已经成交的手数]
        watch_info = self.__s_slow_sell_watch_indexes_dict.get(code)
        # 计算总买额
        total_num = 0
        for i in watch_info[0]:
            data = total_datas[i]
            val = data['val']
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_num += val['num']
                if val['orderNo'] == watch_info[1]:
                    total_num -= watch_info[2]
        # 过滤最小金额
        zyltgb = l2_trade_factor.L2TradeFactorUtil.get_zyltgb(code)
        zyltgb_unit_y = round(zyltgb / 100000000, 1)
        min_sell_money = int((zyltgb_unit_y / 2 + 5) * 10000)
        sell_orders = HuaXinSellOrderStatisticManager.get_latest_transaction_datas(code, min_sell_order_no=
        total_datas[real_place_order_info[0]]['val']['orderNo'], min_sell_money=min_sell_money)
        sell_order_num = sum([x[1] for x in sell_orders]) // 100
        rate = round(sell_order_num / total_num, 2)
        threshold_rate = constant.S_SLOW_RATE
        if gpcode_manager.MustBuyCodesManager().is_in_cache(code):
            threshold_rate = constant.S_SLOW_RATE_WITH_MUST_BUY
        if rate > threshold_rate:
            return True, f"慢砸成交比例:{rate}/0.49  成交:{sell_order_num}/{total_num}"
        else:
            return False, f"尚未触发撤单比例:{rate}"
 
    # 计算S后撤监听的数据范围
    def __compute_down_cancel_watch_index(self, code, big_sell_order_info, total_datas):
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        real_order_index_info = self.__get_real_place_order_index_info_cache(code)
        if real_order_index_info is None or real_order_index_info[1]:
            return
        real_order_index = real_order_index_info[0]
        start_order_no = big_sell_order_info[1][-1][4][1]
        latest_deal_time = l2_huaxin_util.convert_time(big_sell_order_info[1][-1][4][0], with_ms=True)
        if code in self.__s_down_watch_indexes_dict:
            # 更新囊括范围后1s内不能再次更新
            if tool.trade_time_sub_with_ms(latest_deal_time, self.__s_down_watch_indexes_dict[code][0]) <= 1000:
                return
 
        watch_index_info = []
        for i in range(trade_index, real_order_index):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if int(val['orderNo']) < start_order_no:
                continue
            if val['num'] * float(val['price']) < 5000:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                watch_index_info.append((i, val['num']))
        watch_index_info.sort(key=lambda x: x[1], reverse=True)
        watch_indexes = set([x[0] for x in watch_index_info[:5]])
        l2_log.s_cancel_debug(code, f"S后计算那概括范围:{watch_indexes}  最近成交的卖单信息:{big_sell_order_info[1][-1]}")
        if watch_indexes:
            # 保存卖单信息
            self.__s_down_watch_indexes_dict[code] = (latest_deal_time, watch_indexes)
 
    # 是否有大卖单需要撤
    def __need_cancel_for_big_sell_order(self, code, big_sell_order_info, order_begin_pos: OrderBeginPosInfo):
        # 需要排除成交时间在下单时间之前的
        total_deal_money = 0
        total_datas = local_today_datas.get(code)
        real_order_index_info = self.__get_real_place_order_index_info_cache(code)
        real_order_time_ms = None
        if real_order_index_info and not real_order_index_info[1]:
            real_order_index = real_order_index_info[0]
            real_order_time_ms = total_datas[real_order_index]["val"]["time"] + ".{0:0>3}".format(
                total_datas[real_order_index]["val"]["tms"])
 
        for x in big_sell_order_info[1]:
            deal_time = l2_huaxin_util.convert_time(x[4][0], with_ms=True)
            if real_order_time_ms:
                if tool.trade_time_sub_with_ms(deal_time, real_order_time_ms) >= 0:
                    m = x[1] * x[2]
                    total_deal_money += m
            else:
                m = x[1] * x[2]
                total_deal_money += m
 
        zyltgb = l2_trade_factor.L2TradeFactorUtil.get_zyltgb(code)
        zyltgb_unit_y = round(zyltgb / 100000000, 1)
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        limit_up_price = round(float(limit_up_price), 2)
        # 有超大单砸 S重砸
        threshold_big_deal = (2 * zyltgb_unit_y + 339) * 10000
        if total_deal_money >= threshold_big_deal:
            # S重砸必撤的金额满足以后,以前是无脑撤。现在优化一下,看成交进度位---真实下单位的区间额≤重砸金额*3.3倍,就撤。
            try:
                need_compute = False
                trade_index, is_default = TradeBuyQueue().get_traded_index(code)
                if trade_index is None:
                    trade_index = 0
                if real_order_index_info and not real_order_index_info[1]:
                    need_compute = True
 
                if need_compute:
                    total_count, total_num = L2DataComputeUtil.compute_left_buy_order(code, trade_index,
                                                                                      real_order_index_info[0],
                                                                                      limit_up_price)
                    if total_num == 0:
                        total_num = 1
 
                    threshold_rate = constant.S_FAST_BIG_RATE
                    if gpcode_manager.MustBuyCodesManager().is_in_cache(code):
                        threshold_rate = constant.S_FAST_BIG_RATE_WITH_MUST_BUY
 
                    if total_deal_money / (total_num * limit_up_price * 100) >= threshold_rate:
                        # 大单成交额占总剩余总囊括的30%
                        return True, f"1s内大于{threshold_big_deal}大卖单({total_deal_money})"
                else:
                    return True, f"1s内大于{threshold_big_deal}大卖单({total_deal_money})"
            except Exception as e:
                l2_log.info(code, logger_debug, f"S快计算出错:{str(e)}")
 
        # 判断是否为激进下单
        threash_money_w, threash_money_danger_w = self.__get_fast_threshold_value(code)
        total_fast_num = 0
        try:
 
            trade_index, is_default = TradeBuyQueue().get_traded_index(code)
            if trade_index is None:
                trade_index = 0
            if real_order_index_info and not real_order_index_info[1]:
                real_order_index = real_order_index_info[0]
                # 开始第一笔成交数据
                fdeal = big_sell_order_info[1][0][3]
                start_order_no = fdeal[1]
                sell_time_str = l2_huaxin_util.convert_time(fdeal[0], with_ms=False)
 
                total_num = 0
                # 获取正在成交的数据
                # 计算成交进度到真实下单位的纯买额
                dealing_info = HuaXinBuyOrderManager.get_dealing_order_info(code)
                for i in range(trade_index, real_order_index):
                    data = total_datas[i]
                    val = data['val']
                    if int(val['orderNo']) < start_order_no:
                        continue
                    if i == trade_index and dealing_info and str(
                            total_datas[trade_index]["val"]["orderNo"]) == str(
                        dealing_info[0]):
                        # 减去当前正在成交的数据中已经成交了的数据
                        total_num -= dealing_info[1] // 100
                        total_fast_num -= dealing_info[1] // 100
                    left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(
                        code,
                        i,
                        total_datas,
                        local_today_canceled_buyno_map.get(
                            code))
                    if left_count > 0:
                        total_num += val["num"]
                        total_fast_num += val['num']
                if total_num * float(limit_up_price) < 800 * 100 and tool.trade_time_sub(sell_time_str,
                                                                                         total_datas[real_order_index][
                                                                                             'val']['time']) < 15 * 60:
                    # 15分钟内真实成交位距离真实下单位,金额≤800万 ,大单阈值变为200w
                    threash_money_w = threash_money_danger_w
        except Exception as e:
            l2_log.s_cancel_debug(code, f"S撤激进下单计算大单卖阈值出错:{str(e)}")
        total_fast_money = int(total_fast_num * 100 * float(limit_up_price))
        if total_fast_money == 0:
            # 防止分母为0
            total_fast_money = 1
        rate = round(total_deal_money / total_fast_money, 2)
        threshold_rate = constant.S_FAST_RATE
        if gpcode_manager.MustBuyCodesManager().is_in_cache(code):
            threshold_rate = constant.S_FAST_RATE_WITH_MUST_BUY
 
        if total_deal_money >= threash_money_w * 10000 and rate >= threshold_rate:
            return True, f"近1s有大卖单({round(total_deal_money / 10000, 1)}万/{threash_money_w}万,成交占比:{total_deal_money}/{total_fast_money})"
        else:
            l2_log.s_cancel_debug(code,
                                  f"S快撤没达到撤单比例:成交金额({total_deal_money})/囊括金额({total_fast_money}),比例:{rate} 大单阈值:{threash_money_w}w")
        return False, f"无{threash_money_w}大单"
 
    #  big_sell_order_info格式:[总共的卖单金额, 大卖单详情列表]
    def set_big_sell_order_info_for_cancel(self, code, big_sell_order_info, order_begin_pos: OrderBeginPosInfo):
        if order_begin_pos is None or order_begin_pos.buy_exec_index is None or order_begin_pos.buy_exec_index < 0:
            return False, "还未下单"
 
        if big_sell_order_info[0] < 500000 or not big_sell_order_info[1]:
            return False, "无大单卖"
        l2_log.s_cancel_debug(code, f"主动卖:{big_sell_order_info}")
        try:
            need_cancel, cancel_msg = self.__need_cancel_for_big_sell_order(code, big_sell_order_info, order_begin_pos)
            if need_cancel:
                return need_cancel, cancel_msg
 
            total_datas = local_today_datas.get(code)
            need_cancel, cancel_msg = self.__need_cancel_for_up(code, big_sell_order_info, total_datas)
            if need_cancel:
                return need_cancel, cancel_msg
            # S后撤取消
            # if self.__latest_process_sell_order_no.get(code) != big_sell_order_info[1][-1][0]:
            #     # 不处理重复的卖单
            #     # 获取最新的成交时间
            #     latest_trade_time = l2_huaxin_util.convert_time(big_sell_order_info[1][-1][4][0])
            #     if tool.trade_time_sub(latest_trade_time,
            #                            total_datas[order_begin_pos.buy_single_index]['val']['time']) >= 180:
            #         self.__compute_down_cancel_watch_index(code, big_sell_order_info, total_datas)
            return False, "不满足撤单条件"
        finally:
            # self.__latest_process_sell_order_no[code] = big_sell_order_info[1][-1][0]
            pass
 
    # ----------------------------S慢砸范围计算------------------------------------
    def __compute_s_slow_sell(self, code):
        try:
            if code in self.__s_slow_sell_watch_indexes_dict:
                return
            real_place_order_info = self.__get_real_place_order_index_info_cache(code)
            if not real_place_order_info or real_place_order_info[1]:
                return
            trade_index = self.__trade_progress_index_dict.get(code)
            if trade_index is None:
                return
            start_index = trade_index
            end_index = real_place_order_info[0]
            total_datas = local_today_datas.get(code)
            watch_indexes = set()
            for i in range(start_index, end_index):
                data = total_datas[i]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                if val['num'] * float(val['price']) < 5000:
                    continue
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    watch_indexes.add(i)
 
            dealing_order_no = None
            dealed_num = 0
            # 格式:[监听的索引,正在成交索引,已成交的数量]
            dealing_info = HuaXinBuyOrderManager.get_dealing_order_info(code)
            if dealing_info:
                dealing_order_no = dealing_info[0]
                dealed_num = dealing_info[1] // 100
            watch_info = [watch_indexes, dealing_order_no, dealed_num]
            self.__s_slow_sell_watch_indexes_dict[code] = watch_info
            l2_log.s_cancel_debug(code, f"S慢砸监听范围:{watch_info}")
        except Exception as e:
            logger_l2_s_cancel.exception(e)
 
 
# --------------------------------H撤-------------------------------
class HourCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __tradeBuyQueue = TradeBuyQueue()
    __SCancelBigNumComputer = SCancelBigNumComputer()
 
    # 计算触发位置
    __start_compute_index_dict = {}
 
    # 成交位置
    __transaction_progress_index_dict = {}
    # 成交位置更新时间
    __transaction_progress_index_updatetime_dict = {}
    # 缓存
    __cancel_watch_indexs_cache = {}
 
    # L撤触发的代码
    __l_cancel_triggered_codes = set()
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(HourCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
 
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "h_cancel_watch_indexs-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = json.loads(val)
                if val:
                    val = set(val)
                else:
                    val = set()
                CodeDataCacheUtil.set_cache(cls.__cancel_watch_indexs_cache, code, val)
 
            keys = RedisUtils.keys(__redis, "h_cancel_transaction_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = int(val)
                CodeDataCacheUtil.set_cache(cls.__transaction_progress_index_dict, code, val)
        finally:
            RedisUtils.realse(__redis)
 
    # 保存成交位置到执行位置的揽括范围数据
    def __save_watch_index_set(self, code, buy_single_index, indexes):
        trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                           trade_record_log_util.CancelWatchIndexesInfo(
                                                               trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_H,
                                                               buy_single_index,
                                                               list(indexes)))
        CodeDataCacheUtil.set_cache(self.__cancel_watch_indexs_cache, code, indexes)
        key = f"h_cancel_watch_indexs-{code}"
        RedisUtils.setex_async(self.__db, key, tool.get_expire(),
                               json.dumps(list(indexes)))
 
    # 保存成交进度
    def __get_watch_index_set(self, code):
        key = f"h_cancel_watch_indexs-{code}"
        val = RedisUtils.get(self.__get_redis(), key)
        if val is None:
            return None
        val = json.loads(val)
        return val
 
    def __get_watch_index_set_cache(self, code):
        cache_result = CodeDataCacheUtil.get_cache(self.__cancel_watch_indexs_cache, code)
        if cache_result[0]:
            return cache_result[1]
        return set()
 
    def __save_transaction_index(self, code, index):
        CodeDataCacheUtil.set_cache(self.__transaction_progress_index_dict, code, index)
        key = f"h_cancel_transaction_index-{code}"
        RedisUtils.setex_async(self.__db, key, tool.get_expire(), index)
 
    def __clear_data(self, code):
        CodeDataCacheUtil.clear_cache(self.__cancel_watch_indexs_cache, code)
        CodeDataCacheUtil.clear_cache(self.__transaction_progress_index_dict, code)
        CodeDataCacheUtil.clear_cache(self.__start_compute_index_dict, code)
        self.__l_cancel_triggered_codes.discard(code)
        ks = [f"h_cancel_watch_indexs-{code}", f"h_cancel_transaction_index-{code}"]
        for key in ks:
            RedisUtils.delete_async(self.__db, key)
 
        # 计算观察索引,倒序计算
 
    def __compute_watch_index(self, code, buy_single_index):
        """
        @param code:
        @param buy_single_index:
        @return:
        """
        if buy_single_index is None:
            return
        if self.__cancel_watch_indexs_cache.get(code):
            return
        real_place_order_index = self.__SCancelBigNumComputer.get_real_place_order_index_cache(code)
        if not real_place_order_index:
            l2_log.h_cancel_debug(code, "尚未找到真实下单位置")
            return
        start_compute_index = self.__start_compute_index_dict.get(code)
        if not start_compute_index:
            l2_log.h_cancel_debug(code, "尚未找到开始计算位置")
            return
        transaction_index = self.__transaction_progress_index_dict.get(code)
        if transaction_index:
            # 不能计算成交进度以前的数据
            start_compute_index = transaction_index + 1  # max(transaction_index + 1, start_compute_index)
        total_datas = local_today_datas.get(code)
 
        # h撤计算必须超过3分钟
        if tool.trade_time_sub(total_datas[-1]["val"]["time"],
                               total_datas[real_place_order_index]["val"]["time"]) < 180:
            l2_log.h_cancel_debug(code, "180s内囊括计算H撤")
            return
        # -----------------计算H上-------------------
        watch_indexes_up = set()
        for i in range(real_place_order_index - 1, start_compute_index + 1, -1):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
                # 小金额过滤
            if float(val['price']) * val['num'] < 50 * 100:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                watch_indexes_up.add(i)
                if len(watch_indexes_up) >= 3:
                    # 最多取3笔
                    break
 
        # ------------------计算H下-----------------------
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        if not limit_up_price:
            return
        # 计算结束位置
        total_num = 0
        # 获取m值数据
        thresh_hold_money = Buy1PriceManager().get_latest_buy1_money(code)
        # 封单额的1/10
        thresh_hold_money = thresh_hold_money / 10
        thresh_hold_num = thresh_hold_money // (float(limit_up_price) * 100)
        end_index = real_place_order_index + 1
        watch_indexes = set()
        for i in range(real_place_order_index + 1, total_datas[-1]["index"]):
            # 看是否撤单
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if float(val['price']) * val['num'] < 50 * 100:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                watch_indexes.add(i)
                total_num += left_count * val["num"]
                count = len(watch_indexes)
                # 最小5笔,最大10笔
                if (total_num > thresh_hold_num and count >= 5) or count >= 10:
                    break
        if watch_indexes or watch_indexes_up:
            watch_indexes |= watch_indexes_up
            self.__save_watch_index_set(code, buy_single_index, watch_indexes)
            l2_log.h_cancel_debug(code, f"设置监听范围, 数据范围:{real_place_order_index}-{end_index} 监听范围-{watch_indexes}")
        # 设置真实下单位置
 
    def __need_compute_watch_indexes(self, code, transaction_index):
        """
        1.成交进度位距离真实下单位置<=5笔触发囊括
        2.成交到(下单那一刻的成交进度位)到(真实下单位置)的后1/10处也要触发囊括
        3.L撤无法生效触发囊括
        @param code:
        @param transaction_index:
        @return:
        """
 
        start_compute_index = self.__start_compute_index_dict.get(code)
        if start_compute_index is None:
            return False
        real_place_order_index = self.__SCancelBigNumComputer.get_real_place_order_index_cache(code)
        total_datas = local_today_datas.get(code)
        if real_place_order_index and real_place_order_index > transaction_index:
            # 成交位置离我们真实下单的位置只有5笔没撤的大单就需要计算H撤的囊括范围了
            total_left_count = 0
            for index in range(transaction_index + 1, real_place_order_index):
                data = total_datas[index]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                if float(val['price']) * val['num'] < 5000:
                    continue
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, index,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    total_left_count += 1
                    if total_left_count > 5:
                        break
            if total_left_count <= 5:
                return True
 
        # 成交位到开始计算位置没有买单之后
        for index in range(transaction_index + 1, start_compute_index):
            data = total_datas[index]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if float(val['price']) * val['num'] < 5000:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, index,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                # 中间还有未撤的买单
                return False
        return True
 
    # 设置成交进度
    def set_transaction_index(self, code, buy_single_index, index):
        try:
            # 每3s或者成交进度变化就囊括一次
            if index == self.__transaction_progress_index_dict.get(code):
                if code in self.__transaction_progress_index_updatetime_dict and time.time() - self.__transaction_progress_index_updatetime_dict.get(
                        code) < 3:
                    return
            self.__transaction_progress_index_dict[code] = index
            self.__transaction_progress_index_updatetime_dict[code] = time.time()
            if self.__need_compute_watch_indexes(code, index):
                self.__compute_watch_index(code, buy_single_index)
        except Exception as e:
            l2_log.h_cancel_debug(code, "设置成交进度位置出错:{}", str(e))
            async_log_util.exception(logger_l2_h_cancel, e)
 
    # 设置真实下单位置
    def set_real_place_order_index(self, code, index, buy_single_index):
        if buy_single_index is None:
            return
        try:
            # 计算触发位置
            min_num = int(5000 / (float(gpcode_manager.get_limit_up_price(code))))
            # 统计净涨停买的数量
            not_cancel_indexes = []
            total_datas = local_today_datas.get(code)
            for j in range(buy_single_index, index):
                data = total_datas[j]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                if val["num"] < min_num:
                    continue
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                         j,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    not_cancel_indexes.append(j)
            if not_cancel_indexes:
                temp_count = len(not_cancel_indexes)
                temp_index = int(temp_count * 9 / 10)
                if temp_index + 1 >= temp_count:
                    temp_index = temp_count - 1
                self.__start_compute_index_dict[code] = not_cancel_indexes[temp_index]
        except Exception as e:
            async_log_util.exception(logger_l2_h_cancel, e)
            l2_log.h_cancel_debug(code, "设置真实下单位置出错:{}", str(e))
 
    def need_cancel(self, code, buy_single_index, buy_exec_index, start_index, end_index, total_data,
                    buy_volume_index, volume_index,
                    is_first_code):
        if buy_single_index is None or buy_exec_index is None:
            return False, "尚未找到下单位置"
 
        if int(tool.get_now_time_str().replace(":", "")) > int("145000"):
            return False, None
        # 设置成交进度
        if code not in self.__transaction_progress_index_dict:
            return False, "没找到成交进度"
        watch_index_set = self.__get_watch_index_set_cache(code)
        if not watch_index_set:
            # 是否有涨停买撤
            need_compute = False
            # 有涨停买撤才会计算位置
            for i in range(start_index, end_index + 1):
                data = total_data[i]
                val = data['val']
                if L2DataUtil.is_limit_up_price_buy_cancel(val):
                    need_compute = True
                    break
            if need_compute:
                if self.__need_compute_watch_indexes(code, self.__transaction_progress_index_dict.get(code)):
                    self.__compute_watch_index(code, buy_single_index)
                    watch_index_set = self.__get_watch_index_set_cache(code)
        if not watch_index_set:
            return False, "没有监听索引"
        l2_log.cancel_debug(code, "H级是否需要撤单,数据范围:{}-{} ", start_index, end_index)
        if watch_index_set:
            cancel_num = 0
            total_num = 0
            for i in watch_index_set:
                if i is None:
                    l2_log.h_cancel_debug(code, f"空值:{watch_index_set}")
                    continue
                data = total_data[i]
                val = data['val']
                total_num += val['num'] * data['re']
                # 判断是否撤单
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                         total_data,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                cancel_num += val['num'] * (data['re'] - left_count)
            rate = round(cancel_num / total_num, 4)
            threshold_rate = constant.H_CANCEL_RATE_WITH_LDOWN_CANT_INVALID if code in self.__l_cancel_triggered_codes else constant.H_CANCEL_RATE
            try:
                must_buy = gpcode_manager.MustBuyCodesManager().is_in_cache(code)
                if must_buy:
                    threshold_rate = constant.H_CANCEL_RATE_WITH_MUST_BUY
            except Exception as e:
                async_log_util.error(logger_l2_h_cancel, str(e))
            if rate >= threshold_rate:
                l2_log.h_cancel_debug(code, f"撤单比例:{rate}")
                return True, total_data[-1]
        return False, None
 
    # 下单成功
    def place_order_success(self, code, buy_single_index, buy_exec_index, total_data):
        self.__clear_data(code)
 
    # 获取H撤监听的数据索引范围
    # 返回监听范围与已撤单索引
    def get_watch_index_dict(self, code):
        return {}, set()
 
    def start_compute_watch_indexes(self, code, buy_single_index):
        """
        L后撤无法生效触发的囊括
        @param code:
        @param buy_single_index:
        @return:
        """
        self.__l_cancel_triggered_codes.add(code)
        self.__compute_watch_index(code, buy_single_index)
 
 
# ---------------------------------D撤-------------------------------
# 计算 成交位->真实下单位置 总共还剩下多少手没有撤单
# 成交位变化之后重新计算
class DCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
 
    __instance = None
 
    # 下单位之后的封单中的大单
    __follow_big_order_cache = {}
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(DCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            pass
        finally:
            RedisUtils.realse(__redis)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    # 是否有撤买的规则
    def has_auto_cancel_rules(self, code):
        rules = self.get_auto_cancel_rules(code)
        return True if rules else False
 
    def get_auto_cancel_rules(self, code):
        try:
            rules = TradeRuleManager().list_can_excut_rules_cache([TradeRuleManager.TYPE_BUY_CANCEL], code)
            return rules
        except:
            return None
 
    def need_cancel(self, code, buy1_volume):
        rules = self.get_auto_cancel_rules(code)
        if rules:
            for r in rules:
                if r.buy1_volume >= buy1_volume:
                    # 量低于
                    return True, r.id_
        return False, None
 
    def compute_d_cancel_watch_index(self, code):
        # 计算D撤囊括范围
        # real_place_order_index = self.__SCancelBigNumComputer.get_real_place_order_index_cache(code)
        pass
 
    def __clear_data(self, code):
        if code in self.__follow_big_order_cache:
            self.__follow_big_order_cache.pop(code)
 
    def place_order_success(self, code, buy_single_index, buy_exec_index):
        self.__clear_data(code)
 
 
# ---------------------------------L撤-------------------------------
class LCancelRateManager:
    __block_limit_up_count_dict = {}
    __big_num_deal_rate_dict = {}
    __MustBuyCodesManager = gpcode_manager.MustBuyCodesManager()
 
    # 获取撤单比例,返回(撤单比例,是否必买)
    @classmethod
    def get_cancel_rate(cls, code, buy_exec_time, is_up=False, is_l_down_recomputed=False):
        try:
            must_buy = cls.__MustBuyCodesManager.is_in_cache(code)
            if must_buy:
                if is_up:
                    return constant.L_CANCEL_RATE_UP_WITH_MUST_BUY, True
                else:
                    return constant.L_CANCEL_RATE_WITH_MUST_BUY, True
        except Exception as e:
            async_log_util.error(logger_l2_l_cancel, str(e))
 
        base_rate = constant.L_CANCEL_RATE
        if is_up:
            base_rate = constant.L_CANCEL_RATE_UP
        try:
            block_rate = 0
            if code in cls.__block_limit_up_count_dict:
                count = cls.__block_limit_up_count_dict[code]
                rates = [0, 0.03, 0.06, 0.08, 0.12]
                if count >= len(rates):
                    block_rate = rates[-1]
                else:
                    block_rate = rates[count]
 
            deal_rate = 0
            if code in cls.__big_num_deal_rate_dict:
                deal_rate = round(cls.__big_num_deal_rate_dict[code] / 100)
 
            base_rate += block_rate
            base_rate += deal_rate
        except Exception as e:
            l2_log.l_cancel_debug(code, f"计算撤单比例出错:{e}")
        return round(base_rate, 2), False
 
    # 获取L后成交太快的撤单比例
    @classmethod
    def get_fast_deal_cancel_rate(cls, code):
        must_buy_cancel_rate = cls.__MustBuyCodesManager.get_cancel_rate_cache(code)
        if must_buy_cancel_rate is not None:
            return must_buy_cancel_rate
        return constant.L_CANCEL_FAST_DEAL_RATE
 
    # 设置板块涨停数量(除开自己)
    @classmethod
    def set_block_limit_up_count(cls, reason_codes_dict):
        for reason in reason_codes_dict:
            codes = reason_codes_dict[reason]
            for c in codes:
                cls.__block_limit_up_count_dict[c] = len(codes) - 1
 
    @classmethod
    def set_big_num_deal_info(cls, code, buy_money, sell_money):
        left_money_w = (buy_money - sell_money) // 10000
        if left_money_w > 0:
            rate = ((left_money_w + 300) // 900) * 2
        else:
            rate = ((left_money_w + 599) // 900) * 2
        if rate < -10:
            rate = -10
        if rate > 10:
            rate = 10
        cls.__big_num_deal_rate_dict[code] = rate
 
    @classmethod
    def compute_big_num_deal_info(cls, code):
        total_buy_money = BigOrderDealManager().get_total_buy_money(code)
        total_sell_money = BigOrderDealManager().get_total_sell_money(code)
        cls.set_big_num_deal_info(code, total_buy_money, total_sell_money)
 
 
# 计算成交位置之后的大单(特定笔数)的撤单比例
class LCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __last_trade_progress_dict = {}
    __real_place_order_index_dict = {}
    __cancel_watch_index_info_cache = {}
    # L后真实成交位之后的位置索引
    __cancel_l_down_after_place_order_index_cache = {}
    # 成交位附近临近大单索引
    __near_by_trade_progress_index_cache = {}
 
    __SCancelBigNumComputer = SCancelBigNumComputer()
 
    # L后囊括范围未撤单/未成交的总手数
    __total_l_down_not_deal_num_dict = {}
    # L后最近的成交数信息
    __l_down_latest_deal_info_dict = {}
 
    __last_l_up_compute_info = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(LCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
 
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "l_cancel_watch_index_info-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                if val:
                    val = json.loads(val)
                    val[2] = set(val[2])
                CodeDataCacheUtil.set_cache(cls.__cancel_watch_index_info_cache, code, val)
 
            keys = RedisUtils.keys(__redis, "l_cancel_real_place_order_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = json.loads(val)
                CodeDataCacheUtil.set_cache(cls.__real_place_order_index_dict, code, val)
 
            keys = RedisUtils.keys(__redis, "l_cancel_near_by_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                try:
                    val = set(json.loads(val))
                    CodeDataCacheUtil.set_cache(cls.__near_by_trade_progress_index_cache, code, val)
                except:
                    pass
            keys = RedisUtils.keys(__redis, "l_cancel_down_after_place_order_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                try:
                    val = json.loads(val)
                    CodeDataCacheUtil.set_cache(cls.__cancel_l_down_after_place_order_index_cache, code, val)
                except:
                    pass
 
 
        finally:
            RedisUtils.realse(__redis)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    def __set_watch_indexes(self, code, buy_single_index, re_compute: int, indexes):
        self.__cancel_watch_index_info_cache[code] = (buy_single_index, re_compute, indexes)
        RedisUtils.delete_async(self.__db, f"l_cancel_watch_index_info-{code}")
        RedisUtils.setex_async(self.__db, f"l_cancel_watch_index_info-{code}", tool.get_expire(),
                               json.dumps((buy_single_index, re_compute, list(indexes))))
        if indexes:
            trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                               trade_record_log_util.CancelWatchIndexesInfo(
                                                                   trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_DOWN,
                                                                   buy_single_index,
                                                                   list(indexes)))
 
    def __get_watch_indexes_cache(self, code):
        cache_result = CodeDataCacheUtil.get_cache(self.__cancel_watch_index_info_cache, code)
        if cache_result[0]:
            return cache_result[1]
        return None
 
    def __set_near_by_trade_progress_indexes(self, code, buy_single_index, indexes):
        if indexes:
            trade_record_log_util.add_cancel_watch_indexes_log(code,
                                                               trade_record_log_util.CancelWatchIndexesInfo(
                                                                   trade_record_log_util.CancelWatchIndexesInfo.CANCEL_TYPE_L_UP,
                                                                   buy_single_index,
                                                                   list(indexes)))
        self.__near_by_trade_progress_index_cache[code] = indexes
        RedisUtils.setex_async(self.__db, f"l_cancel_near_by_index-{code}", tool.get_expire(),
                               json.dumps(list(indexes)))
 
    def __get_near_by_trade_progress_indexes(self, code):
        val = RedisUtils.get(self.__get_redis(), f"l_cancel_near_by_index-{code}")
        if val is None:
            return None
        return set(json.loads(val))
 
    def __get_near_by_trade_progress_indexes_cache(self, code):
        cache_result = CodeDataCacheUtil.get_cache(self.__near_by_trade_progress_index_cache, code)
        if cache_result[0]:
            return cache_result[1]
        return None
 
    def __set_cancel_l_down_after_place_order_index(self, code, watch_index, index):
        if code not in self.__cancel_l_down_after_place_order_index_cache:
            self.__cancel_l_down_after_place_order_index_cache[code] = {}
        self.__cancel_l_down_after_place_order_index_cache[code][str(watch_index)] = index
        RedisUtils.setex_async(self.__db, f"l_cancel_down_after_place_order_index-{code}", tool.get_expire(),
                               json.dumps(self.__cancel_l_down_after_place_order_index_cache[code]))
 
    def __get_cancel_l_down_after_place_order_index_dict(self, code):
        return self.__cancel_l_down_after_place_order_index_cache.get(code)
 
    def del_watch_index(self, code):
        CodeDataCacheUtil.clear_cache(self.__cancel_watch_index_info_cache, code)
        RedisUtils.delete_async(self.__db, f"l_cancel_watch_index_info-{code}")
 
    def clear(self, code=None):
        if code:
            self.del_watch_index(code)
            if code in self.__real_place_order_index_dict:
                self.__real_place_order_index_dict.pop(code)
                RedisUtils.delete_async(self.__db, f"l_cancel_real_place_order_index-{code}")
            if code in self.__cancel_l_down_after_place_order_index_cache:
                self.__cancel_l_down_after_place_order_index_cache.pop(code)
                RedisUtils.delete_async(self.__db, f"l_cancel_down_after_place_order_index-{code}")
        else:
            keys = RedisUtils.keys(self.__get_redis(), f"l_cancel_watch_index_info-*")
            for k in keys:
                code = k.replace("l_cancel_watch_index_info-", "")
                if code in self.__last_trade_progress_dict:
                    self.__last_trade_progress_dict.pop(code)
                if code in self.__real_place_order_index_dict:
                    self.__real_place_order_index_dict.pop(code)
                self.del_watch_index(code)
            keys = RedisUtils.keys(self.__get_redis(), f"l_cancel_real_place_order_index-*")
            for k in keys:
                RedisUtils.delete(self.__get_redis(), k)
            # 清除L后真实下单位置之后囊括的索引
            self.__cancel_l_down_after_place_order_index_cache.clear()
            keys = RedisUtils.keys(self.__get_redis(), f"l_cancel_down_after_place_order_index-*")
            for k in keys:
                RedisUtils.delete(self.__get_redis(), k)
 
        # 重新计算L上
 
    # big_sell_info卖单信息,格式:[最近成交索引,最近成交时间(带毫秒)]
    def re_compute_l_down_watch_indexes(self, code, big_sell_info=None):
        watch_index_info = self.__cancel_watch_index_info_cache.get(code)
        if not watch_index_info or watch_index_info[1] > 0:
            return
        # 获取成交进度位与真实下单位置
        real_place_order_index_info = self.__real_place_order_index_dict.get(code)
        last_trade_progress_index = self.__last_trade_progress_dict.get(code)
        if big_sell_info:
            last_trade_progress_index = big_sell_info[0]
 
        if not real_place_order_index_info or last_trade_progress_index is None:
            return
        min_cancel_time_with_ms = None
        if big_sell_info:
            min_cancel_time_with_ms = big_sell_info[1]
        self.compute_watch_index(code, watch_index_info[0], last_trade_progress_index + 1,
                                 real_place_order_index_info[0],
                                 re_compute=1, min_cancel_time_with_ms=min_cancel_time_with_ms,
                                 msg=f"大单卖: 成交进度-{big_sell_info}" if big_sell_info is not None else '')
 
    # 计算观察索引,倒序计算
    # re_compute:是否是重新计算的
    # min_cancel_time_with_ms:最小撤单时间,大于等于此时间的撤单需要囊括进去
    def compute_watch_index(self, code, buy_single_index, start_index, end_index, re_compute=0,
                            min_cancel_time_with_ms=None, msg=""):
        try:
            l2_log.l_cancel_debug(code, f"计算L后囊括范围:{start_index}-{end_index}")
            total_datas = local_today_datas.get(code)
            if re_compute > 0 and tool.trade_time_sub(total_datas[-1]["val"]["time"],
                                                      total_datas[buy_single_index]["val"][
                                                          "time"]) < 2 * 60 and min_cancel_time_with_ms is None:
                # 封单额稳了以后,间隔超过2分钟才能重新计算
                l2_log.l_cancel_debug(code, f"要间隔2分钟过后才能重新计算")
                return
            if total_datas:
                # 计算的上截至位距离下截至位纯买额要小于2.5倍m值
                # thresh_hold_money = l2_trade_factor.L2PlaceOrderParamsManager.get_base_m_val(code)
                # thresh_hold_money = int(thresh_hold_money * 2.5)
                min_num = int(5000 / (float(gpcode_manager.get_limit_up_price(code))))
                # 统计净涨停买的数量
                not_cancel_indexes_with_num = []
                re_start_index = start_index
                MAX_COUNT = 5
                for j in range(start_index, end_index):
                    data = total_datas[j]
                    val = data['val']
                    if not L2DataUtil.is_limit_up_price_buy(val):
                        continue
 
                    if val["num"] < min_num:
                        continue
 
                    cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                          j,
                                                                                                          total_datas,
                                                                                                          local_today_canceled_buyno_map.get(
                                                                                                              code))
                    if not cancel_data:
                        not_cancel_indexes_with_num.append((j, val["num"]))
                    elif min_cancel_time_with_ms and tool.compare_time_with_ms(min_cancel_time_with_ms,
                                                                               L2DataUtil.get_time_with_ms(
                                                                                   cancel_data['val'])) <= 0:
                        not_cancel_indexes_with_num.append((j, val["num"]))
 
                min_num = 0
                if not_cancel_indexes_with_num:
                    temp_count = len(not_cancel_indexes_with_num)
                    # 取后1/5的数据
                    if temp_count >= 30:
                        temp_index = int(temp_count * 4 / 5)
                        re_start_index = not_cancel_indexes_with_num[temp_index][0]
                        MAX_COUNT = len(not_cancel_indexes_with_num[temp_index:])
                    else:
                        not_cancel_indexes_with_num.sort(key=lambda x: x[1])
                        if temp_count >= 10:
                            # 获取中位数
                            min_num = not_cancel_indexes_with_num[temp_count // 2][1]
                MIN_MONEYS = [300, 200, 100, 50]
                watch_indexes = set()
                for min_money in MIN_MONEYS:
                    for i in range(end_index, re_start_index - 1, -1):
                        try:
                            data = total_datas[i]
                            val = data['val']
                            if not L2DataUtil.is_limit_up_price_buy(val):
                                continue
                            # 小金额过滤
                            if float(val['price']) * val['num'] < min_money * 100:
                                continue
 
                            if val['num'] < min_num:
                                continue
 
                            cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                                  i,
                                                                                                                  total_datas,
                                                                                                                  local_today_canceled_buyno_map.get(
                                                                                                                      code))
                            if not cancel_data:
                                watch_indexes.add(i)
                                if len(watch_indexes) >= MAX_COUNT:
                                    break
 
                            elif min_cancel_time_with_ms and tool.compare_time_with_ms(min_cancel_time_with_ms,
                                                                                       L2DataUtil.get_time_with_ms(
                                                                                           cancel_data['val'])) <= 0:
                                watch_indexes.add(i)
                                if len(watch_indexes) >= MAX_COUNT:
                                    break
                        except Exception as e:
                            logger_l2_l_cancel.error(f"{code}: 范围: {start_index}-{end_index}  位置:{i}")
                            logger_l2_l_cancel.exception(e)
                    if len(watch_indexes) >= MAX_COUNT:
                        break
                if watch_indexes:
                    ##判断监听的数据中是否有大单##
                    has_big_num = False
                    for i in watch_indexes:
                        # 是否有大单
                        data = total_datas[i]
                        val = data['val']
                        if float(val['price']) * val['num'] > 100 * 100:
                            has_big_num = True
                            break
                    if not has_big_num:
                        # 无大单,需要找大单
                        for i in range(re_start_index, start_index, -1):
                            data = total_datas[i]
                            val = data['val']
                            # 涨停买,且未撤单
                            if not L2DataUtil.is_limit_up_price_buy(val):
                                continue
                            # 小金额过滤
                            if float(val['price']) * val['num'] < 100 * 100:
                                continue
                            cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                                  i,
                                                                                                                  total_datas,
                                                                                                                  local_today_canceled_buyno_map.get(
                                                                                                                      code))
                            if not cancel_data:
                                watch_indexes.add(i)
                                break
 
                            elif min_cancel_time_with_ms and tool.compare_time_with_ms(min_cancel_time_with_ms,
                                                                                       L2DataUtil.get_time_with_ms(
                                                                                           cancel_data['val'])) <= 0:
                                watch_indexes.add(i)
                                break
                    # 获取真实下单位后面10笔大单
                    try:
                        # 真实下单位置后面的数据就只看大单
                        MIN_NUM = int(5000 / (float(gpcode_manager.get_limit_up_price(code))))
                        real_place_order_info = self.__real_place_order_index_dict.get(code)
                        if real_place_order_info and not real_place_order_info[1]:
                            # 从真实下单位往后找
                            after_count = 0
                            for i in range(real_place_order_info[0] + 1, total_datas[-1]['index'] + 1):
                                if after_count > 10:
                                    break
                                data = total_datas[i]
                                val = data['val']
                                # 涨停买,且未撤单
                                if not L2DataUtil.is_limit_up_price_buy(val):
                                    continue
                                # 小金额过滤
                                if val['num'] < MIN_NUM:
                                    continue
                                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(
                                    code, i,
                                    total_datas,
                                    local_today_canceled_buyno_map.get(
                                        code))
                                if left_count > 0:
                                    after_count += 1
                                    if l2_data_util.is_big_money(val):
                                        watch_indexes.add(i)
                                        self.__set_cancel_l_down_after_place_order_index(code, i, after_count - 1)
                    except Exception as e:
                        pass
                    self.__set_watch_indexes(code, buy_single_index, re_compute, watch_indexes)
                    l2_log.l_cancel_debug(code,
                                          f"设置监听范围({msg}){'(重新计算)' if re_compute else ''}, 数据范围:{re_start_index}-{end_index} 监听范围-{watch_indexes}")
        except Exception as e:
            l2_log.l_cancel_debug(code, f"计算L后囊括范围出错:{str(e)}")
            async_log_util.exception(logger_l2_l_cancel, e)
 
    # 设置真实下单位置
    def set_real_place_order_index(self, code, index, buy_single_index=None, is_default=False):
        l2_log.l_cancel_debug(code, f"设置真实下单位-{index},buy_single_index-{buy_single_index}")
        self.__real_place_order_index_dict[code] = (index, is_default)
        RedisUtils.setex_async(self.__db, f"l_cancel_real_place_order_index-{code}", tool.get_expire(),
                               json.dumps((index, is_default)))
        if buy_single_index is not None:
            if code in self.__last_trade_progress_dict:
                # L撤从成交进度位开始计算
                self.compute_watch_index(code, buy_single_index,
                                         self.__last_trade_progress_dict[code], index)
            else:
                self.compute_watch_index(code, buy_single_index, buy_single_index, index)
 
        if self.__last_trade_progress_dict.get(code):
            self.__compute_trade_progress_near_by_indexes(code, buy_single_index,
                                                          self.__last_trade_progress_dict.get(code) + 1, index)
        else:
            self.__compute_trade_progress_near_by_indexes(code, buy_single_index, buy_single_index, index)
 
    # 重新计算L上
    def re_compute_l_up_watch_indexes(self, code, buy_single_index):
        if code not in self.__last_trade_progress_dict:
            return
        if code not in self.__real_place_order_index_dict:
            return
        if code not in self.__last_l_up_compute_info or time.time() - self.__last_l_up_compute_info[code][0] >= 3:
            self.__compute_trade_progress_near_by_indexes(code, buy_single_index,
                                                          self.__last_trade_progress_dict.get(code) + 1,
                                                          self.__real_place_order_index_dict.get(code)[0])
 
    # 计算范围内的成交位临近未撤大单
    def __compute_trade_progress_near_by_indexes(self, code, buy_single_index, start_index, end_index):
        if start_index is None or end_index is None:
            return
        total_datas = local_today_datas.get(code)
        MIN_MONEY = 99 * 100
        MAX_COUNT = 15
        watch_indexes = set()
        total_num = 0
        # thresh_hold_money = l2_trade_factor.L2PlaceOrderParamsManager.get_base_m_val(code)
        # threshold_num = thresh_hold_money // (float(gpcode_manager.get_limit_up_price(code)) * 100)
        for i in range(start_index, end_index):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            # 小金额过滤
            if float(val['price']) * val['num'] < MIN_MONEY:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_num += val['num'] * left_count
                watch_indexes.add(i)
                if len(watch_indexes) >= MAX_COUNT:
                    break
 
        changed = True
        if code in self.__last_l_up_compute_info:
            if self.__last_l_up_compute_info[code] == watch_indexes:
                changed = False
        # 保存数据
        if changed:
            l2_log.l_cancel_debug(code, f"L前监控范围:{watch_indexes} 计算范围:{start_index}-{end_index}")
            self.__set_near_by_trade_progress_indexes(code, buy_single_index, watch_indexes)
        self.__last_l_up_compute_info[code] = (time.time(), watch_indexes)
 
    # 计算L后还没成交的手数
    def __compute_total_l_down_not_deal_num(self, code):
        # 只有真实获取到下单位置后才开始计算
 
        try:
            if code in self.__total_l_down_not_deal_num_dict and time.time() - \
                    self.__total_l_down_not_deal_num_dict[code][
                        1] < 1:
                # 需要间隔1s更新一次
                return
            l_down_cancel_info = self.__cancel_watch_index_info_cache.get(code)
            if not l_down_cancel_info:
                return
 
            trade_progress = self.__last_trade_progress_dict.get(code)
            if trade_progress is None:
                return
 
            l_down_indexes = l_down_cancel_info[2]
            # 统计还未成交的数据
            total_left_num = 0
            total_datas = local_today_datas.get(code)
            for i in l_down_indexes:
                # 已经成交了的不计算
                if i < trade_progress:
                    continue
                data = total_datas[i]
                val = data['val']
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                         i,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    fnum = val["num"]
                    if i == trade_progress:
                        # 需要减去已经成交的数据
                        dealing_info = HuaXinBuyOrderManager.get_dealing_order_info(code)
                        if dealing_info:
                            if str(val["orderNo"]) == str(dealing_info[0]):
                                fnum -= dealing_info[1] // 100
                    total_left_num += fnum
            self.__total_l_down_not_deal_num_dict[code] = (total_left_num, time.time())
        except Exception as e:
            async_log_util.exception(logger_l2_l_cancel, e)
 
    # 设置成交位置,成交位置变化之后相应的监听数据也会发生变化
    def set_trade_progress(self, code, buy_single_index, index, total_datas):
        if self.__last_trade_progress_dict.get(code) == index:
            self.__compute_total_l_down_not_deal_num(code)
            return
        self.__last_trade_progress_dict[code] = index
        self.__compute_total_l_down_not_deal_num(code)
 
        if total_datas is None:
            return
 
        if not self.__is_l_down_can_cancel(code, buy_single_index):
            # L后已经不能守护
            l2_log.l_cancel_debug(code, f"L后已经无法生效:buy_single_index-{buy_single_index}")
            HourCancelBigNumComputer().start_compute_watch_indexes(code, buy_single_index)
 
        real_place_order_index_info = self.__real_place_order_index_dict.get(code)
        real_place_order_index = None
        if real_place_order_index_info:
            real_place_order_index = real_place_order_index_info[0]
 
        # 重新计算成交位置临近大单撤单
        self.__compute_trade_progress_near_by_indexes(code, buy_single_index, index + 1, real_place_order_index)
 
    # 已经成交的索引
    def add_deal_index(self, code, index, buy_single_index):
        """
        L后囊括范围成交一笔重新囊括1笔
        @param code:
        @param index:
        @param buy_single_index:
        @return:
        """
        watch_indexes_info = self.__get_watch_indexes_cache(code)
        if not watch_indexes_info:
            return
        watch_indexes = watch_indexes_info[2]
        if index not in watch_indexes:
            return
        if buy_single_index is None:
            return
        # 重新囊括1笔
        real_place_order_info = self.__real_place_order_index_dict.get(code)
        if real_place_order_info and real_place_order_info[0] > index:
            total_datas = local_today_datas.get(code)
            min_num = int(5000 / (float(gpcode_manager.get_limit_up_price(code))))
            for j in range(real_place_order_info[0] - 1, index, -1):
                data = total_datas[j]
                val = data['val']
                if data["index"] in watch_indexes:
                    continue
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                if val["num"] < min_num:
                    continue
 
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                         j,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    watch_indexes.add(data["index"])
                    l2_log.l_cancel_debug(code, f"L后有成交重新囊括:成交索引-{index} 囊括索引-{data['index']}")
                    break
            # 从真实下单位置往后囊括大单
            try:
                left_count_after = 0
                for j in range(real_place_order_info[0] + 1, total_datas[-1]["index"]):
                    data = total_datas[j]
                    val = data['val']
                    if left_count_after > 10:
                        break
                    if not L2DataUtil.is_limit_up_price_buy(val):
                        continue
                    if val["num"] < min_num:
                        continue
                    left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                             j,
                                                                                                             total_datas,
                                                                                                             local_today_canceled_buyno_map.get(
                                                                                                                 code))
                    if left_count > 0:
                        left_count_after += 1
                        if l2_data_util.is_big_money(val) and j not in watch_indexes:
                            watch_indexes.add(j)
                            self.__set_cancel_l_down_after_place_order_index(code, j, left_count_after - 1)
                            break
            except:
                pass
 
        self.__set_watch_indexes(code, watch_indexes_info[0], watch_indexes_info[1], watch_indexes)
 
    def __compute_need_cancel(self, code, buy_exec_index, start_index, end_index, total_data, is_first_code):
        """
        L后撤单;
        撤单计算规则:计算撤单比例时,将真实下单位置之后的数据按权重(离下单位最近的权重越大)加入分子,不加入分母(总囊括手数)计算
        @param code:
        @param buy_exec_index:
        @param start_index:
        @param end_index:
        @param total_data:
        @param is_first_code:
        @return:
        """
        watch_indexes_info = self.__get_watch_indexes_cache(code)
        if not watch_indexes_info:
            return False, None
        watch_indexes = set([int(i) for i in watch_indexes_info[2]])
        # 计算监听的总条数
        total_num = 0
        max_num = 0
        # 这是下单位置之后的索引: key为字符串
        after_place_order_index_dict = self.__get_cancel_l_down_after_place_order_index_dict(code)
        if after_place_order_index_dict is None:
            after_place_order_index_dict = {}
        for wi in watch_indexes:
            if str(wi) in after_place_order_index_dict:
                continue
            total_num += total_data[wi]["val"]["num"] * total_data[wi]["re"]
            if total_data[wi]["val"]["num"] > max_num:
                max_num = total_data[wi]["val"]["num"]
        # 判断撤单中是否有监听中的索引
        need_compute = False
        for i in range(start_index, end_index + 1):
            data = total_data[i]
            val = data["val"]
            if L2DataUtil.is_limit_up_price_buy_cancel(val):
                # 查询买入位置
                buy_index = l2_data_source_util.L2DataSourceUtils.get_buy_index_with_cancel_data_v2(data,
                                                                                                    local_today_buyno_map.get(
                                                                                                        code))
                if buy_index is not None and buy_index in watch_indexes:
                    need_compute = True
                    break
        if need_compute:
 
            # 计算撤单比例
            watch_indexes_list = list(watch_indexes)
            watch_indexes_list.sort()
            canceled_num = 0
            # 记录撤单索引
            canceled_indexes = []
            for wi in watch_indexes:
                cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                      wi,
                                                                                                      total_data,
                                                                                                      local_today_canceled_buyno_map.get(
                                                                                                          code))
                if cancel_data:
                    if str(wi) in after_place_order_index_dict:
                        # 真实下单位置之后的按照权重比例来计算
                        canceled_num += total_data[wi]["val"]["num"] * (
                                    10 - after_place_order_index_dict[str(wi)]) // 10
                    else:
                        canceled_num += total_data[wi]["val"]["num"]
 
                    canceled_indexes.append(cancel_data["index"])
                # if wi == watch_indexes_list[-1] and left_count == 0:
                #     # 离下单位置最近的一个撤单,必须触发撤单
                #     l2_log.l_cancel_debug(code, f"计算范围:{start_index}-{end_index},临近撤单:{wi}")
                #     return True, total_data[-1]
 
            rate = round(canceled_num / total_num, 3)
            thresh_hold_rate, must_buy = LCancelRateManager.get_cancel_rate(code,
                                                                            total_data[buy_exec_index]["val"]["time"])
            # 除开最大单的影响权重
            if not must_buy:
                temp_thresh_hold_rate = round((total_num - max_num) * 0.9 / total_num, 2)
                thresh_hold_rate = min(thresh_hold_rate, temp_thresh_hold_rate)
            l2_log.l_cancel_debug(code,
                                  f"L后计算范围:{start_index}-{end_index},已撤单比例:{rate}/{thresh_hold_rate}, 下单位之后的索引:{after_place_order_index_dict}")
            if rate >= thresh_hold_rate:
                canceled_indexes.sort()
                l2_log.l_cancel_debug(code, f"L后撤单,撤单位置:{canceled_indexes[-1]}")
                return True, total_data[canceled_indexes[-1]]
 
        return False, None
 
    def __compute_near_by_trade_progress_need_cancel(self, code, buy_exec_index, start_index, end_index, total_data,
                                                     is_first_code):
        # L前守护时间为3分钟
        if tool.trade_time_sub(total_data[-1]['val']['time'],
                               total_data[buy_exec_index]['val']['time']) > constant.L_CANCEL_UP_EXPIRE_TIME:
            return False, None
 
        watch_indexes = self.__get_near_by_trade_progress_indexes_cache(code)
        if not watch_indexes:
            return False, None
 
        # 监听范围小于5笔不生效
        if len(watch_indexes) < 5:
            return False, None
 
        # 计算监听的总条数
        # 权重
        WATCH_INDEX_WEIGHTS = [3, 2, 1]
        total_count_weight = 0
        for wi in range(0, len(watch_indexes)):
            if wi < len(WATCH_INDEX_WEIGHTS):
                total_count_weight += WATCH_INDEX_WEIGHTS[wi]
            else:
                total_count_weight += WATCH_INDEX_WEIGHTS[-1]
        # 判断撤单中是否有监听中的索引
        need_compute = False
        for i in range(start_index, end_index + 1):
            data = total_data[i]
            val = data["val"]
            if L2DataUtil.is_limit_up_price_buy_cancel(val):
                # 查询买入位置
                buy_index = l2_data_source_util.L2DataSourceUtils.get_buy_index_with_cancel_data_v2(data,
                                                                                                    local_today_buyno_map.get(
                                                                                                        code))
                if buy_index is not None and buy_index in watch_indexes:
                    need_compute = True
                    break
        if need_compute:
            watch_indexes_list = list(watch_indexes)
            watch_indexes_list.sort()
            # 计算撤单比例
            canceled_count_weight = 0
            canceled_indexes = []
            for wi in watch_indexes:
                canceled_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                        wi,
                                                                                                        total_data,
                                                                                                        local_today_canceled_buyno_map.get(
                                                                                                            code))
                if canceled_data:
                    canceled_indexes.append(canceled_data["index"])
                    # 获取索引权重
                    pos_index = watch_indexes_list.index(wi)
                    if pos_index < len(WATCH_INDEX_WEIGHTS):
                        canceled_count_weight += WATCH_INDEX_WEIGHTS[pos_index]
                    else:
                        canceled_count_weight += WATCH_INDEX_WEIGHTS[-1]
            rate = round(canceled_count_weight / total_count_weight, 3)
            thresh_cancel_rate, must_buy = LCancelRateManager.get_cancel_rate(code,
                                                                              total_data[buy_exec_index]["val"]["time"],
                                                                              is_up=True)
            l2_log.l_cancel_debug(code, f"计算范围:{start_index}-{end_index},成交位临近已撤单比例:{rate}/{thresh_cancel_rate}")
            if rate >= thresh_cancel_rate:
                # 计算成交进度位置到当前下单位置的纯买额
                real_place_order_index_info = self.__real_place_order_index_dict.get(code)
                trade_progress_index = self.__last_trade_progress_dict.get(code)
                if real_place_order_index_info and trade_progress_index:
                    total_num = 0
                    thresh_hold_money = l2_trade_factor.L2PlaceOrderParamsManager.get_base_m_val(code)
                    thresh_hold_money = thresh_hold_money * 3
                    # 阈值为2倍m值
                    thresh_hold_num = thresh_hold_money // (float(gpcode_manager.get_limit_up_price(code)) * 100)
                    for i in range(trade_progress_index + 1, real_place_order_index_info[0]):
                        data = total_data[i]
                        val = data['val']
                        if not L2DataUtil.is_limit_up_price_buy(val):
                            continue
                        canceled_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code,
                                                                                                                i,
                                                                                                                total_data,
                                                                                                                local_today_canceled_buyno_map.get(
                                                                                                                    code))
                        if not canceled_data:
                            # 没有撤单
                            total_num += val["num"] * data["re"]
                            if total_num > thresh_hold_num:
                                # 成交位到下单位还有足够的单没撤
                                l2_log.l_cancel_debug(code,
                                                      f"L上撤阻断: 成交位-{trade_progress_index} 真实下单位-{real_place_order_index_info[0]} 阈值-{thresh_hold_money}")
                                return False, None
 
                canceled_indexes.sort()
                l2_log.l_cancel_debug(code, f"L上撤单,撤单位置:{canceled_indexes[-1]}")
                return True, total_data[canceled_indexes[-1]]
 
        return False, None
 
    # L后是否还有可能撤单
    def __is_l_down_can_cancel(self, code, buy_exec_index):
        watch_indexes_info = self.__get_watch_indexes_cache(code)
        if not watch_indexes_info:
            return True
        trade_index = self.__last_trade_progress_dict.get(code)
        if trade_index is None:
            return True
        # 计算已经成交的比例
        total_datas = local_today_datas.get(code)
        total_deal_nums = 0
        total_nums = 1
        for index in watch_indexes_info[2]:
            data = total_datas[index]
            val = data["val"]
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                     index,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            total_nums += val["num"]
            if left_count > 0 and index < trade_index:
                total_deal_nums += val["num"]
        thresh_hold_rate, must_buy = LCancelRateManager.get_cancel_rate(code,
                                                                        total_datas[buy_exec_index]["val"]["time"])
        if total_deal_nums / total_nums > 1 - thresh_hold_rate - 0.05:
            return False
        return True
 
    def need_cancel(self, code, buy_exec_index, start_index, end_index, total_data, is_first_code):
        if buy_exec_index is None:
            return False, None, "尚未找到下单位置"
        # 守护S撤以外的数据
        if int(tool.get_now_time_str().replace(":", "")) > int("145700") and not constant.TEST:
            return False, None, ""
        # 下单位临近撤
        can_cancel, cancel_data = False, None
        try:
            can_cancel, cancel_data = self.__compute_need_cancel(code, buy_exec_index, start_index, end_index,
                                                                 total_data,
                                                                 is_first_code)
        except Exception as e:
            logger_l2_l_cancel.exception(e)
            raise e
        extra_msg = "L后"
        if not can_cancel:
            # 成交位临近撤
            try:
                can_cancel, cancel_data = self.__compute_near_by_trade_progress_need_cancel(code, buy_exec_index,
                                                                                            start_index, end_index,
                                                                                            total_data,
                                                                                            is_first_code)
                extra_msg = "L前"
            except Exception as e:
                logger_l2_l_cancel.exception(e)
                raise e
        return can_cancel, cancel_data, extra_msg
 
    def place_order_success(self, code):
        self.clear(code)
 
    def cancel_success(self, code):
        self.clear(code)
 
    def test(self):
        code = "000333"
        self.__set_cancel_l_down_after_place_order_index(code, 121, 0)
        time.sleep(6)
        self.__set_cancel_l_down_after_place_order_index(code, 121, 0),
        time.sleep(6)
        self.__set_cancel_l_down_after_place_order_index(code, 122, 1)
 
        print(self.__get_cancel_l_down_after_place_order_index_dict(code))
 
 
# 新F撤,根据成交数据来撤
class FCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __real_order_index_cache = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(FCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "f_cancel_real_order_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = json.loads(val)
                CodeDataCacheUtil.set_cache(cls.__real_order_index_cache, code, val)
        finally:
            RedisUtils.realse(__redis)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    def __set_real_order_index(self, code, index, is_default):
        CodeDataCacheUtil.set_cache(self.__real_order_index_cache, code, (index, is_default))
        RedisUtils.setex_async(self.__db, f"f_cancel_real_order_index-{code}", tool.get_expire(),
                               json.dumps((index, is_default)))
 
    def __del_real_order_index(self, code):
        CodeDataCacheUtil.clear_cache(self.__real_order_index_cache, code)
        RedisUtils.delete_async(self.__db, f"f_cancel_real_order_index-{code}")
 
    def __get_real_order_index(self, code):
        val = RedisUtils.get(self.__db, f"f_cancel_real_order_index-{code}")
        if val:
            val = json.loads(val)
            return val[0]
        return None
 
    def __get_real_order_index_cache(self, code):
        cache_result = CodeDataCacheUtil.get_cache(self.__real_order_index_cache, code)
        if cache_result[0]:
            return cache_result[1]
        return None
 
    def clear(self, code=None):
        if code:
            self.__del_real_order_index(code)
        else:
            keys = RedisUtils.keys(self.__get_redis(), "f_cancel_real_order_index-*")
            if keys:
                for k in keys:
                    code = k.split("-")[1]
                    self.__del_real_order_index(code)
 
    # 设置真实的下单位置
    def set_real_order_index(self, code, index, is_default):
        self.__set_real_order_index(code, index, is_default)
 
    def place_order_success(self, code):
        self.clear(code)
 
    def cancel_success(self, code):
        self.clear(code)
 
    def __get_fast_deal_threshold_value(self, code, place_order_time_str):
        """
        获取 F撤阈值
        @param code:
        @param place_order_time_str:下单时间
        @return:(金额(单位:W),笔数)
        """
        max60, yesterday = code_volumn_manager.get_histry_volumn(code)
        if max60:
            num = max60[0]
            limit_up_price = gpcode_manager.get_limit_up_price(code)
            if limit_up_price:
                money_y = round((num * float(limit_up_price)) / 1e8, 1)
                money = int(200 * money_y + 280)
                if tool.trade_time_sub(place_order_time_str, "10:00:00") <= 0:
                    # 10点前下单打7折
                    money = int(money * 0.7)
                count = int(money_y * 10) // 10 + 3
                return money, count
        # 默认值
        return 300, 3
 
    # 下单3分钟内距离下单位置不足3笔(包含正在成交)且不到300w就需要撤单
    def need_cancel_for_deal_fast(self, code, trade_index=None):
        if trade_index is None:
            trade_info = TradeBuyQueue().get_traded_index(code)
            if trade_info and not trade_info[1] and trade_info[0] is not None:
                trade_index = trade_info[0]
        if trade_index is None:
            return False, "没获取到成交进度位"
 
        # 判断是否具有真实的下单位置
        real_order_index_info = self.__get_real_order_index_cache(code)
        if not real_order_index_info:
            return False, "没找到真实下单位"
        if real_order_index_info[1]:
            return False, "真实下单位为默认"
        if real_order_index_info[0] <= trade_index:
            return False, "真实下单位在成交位之前"
        real_order_index = real_order_index_info[0]
        # 统计未撤订单的数量与金额
        total_datas = local_today_datas.get(code)
 
        # 是否是下单1分钟内
        if tool.trade_time_sub(tool.get_now_time_str(), total_datas[real_order_index]['val']['time']) > 1 * 60:
            return False, "下单超过60s"
 
        THRESHOLD_MONEY_W, THRESHOLD_COUNT = self.__get_fast_deal_threshold_value(code,
                                                                                  total_datas[real_order_index]['val'][
                                                                                      'time'])
 
        total_left_count = 0
        total_left_num = 0
        # 成交位到真实下单位剩余的未成交的单
        for i in range(trade_index, real_order_index_info[0]):
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 5000:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                     i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_left_count += left_count
                total_left_num += val["num"] * left_count
                if total_left_count > THRESHOLD_COUNT:
                    break
            if trade_index == i:
                dealing_info = HuaXinBuyOrderManager.get_dealing_order_info(code)
                if dealing_info and str(dealing_info[0]) == str(val["orderNo"]):
                    total_left_num -= dealing_info[1] // 100
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        if total_left_count <= 1 or (total_left_count <= THRESHOLD_COUNT and limit_up_price and total_left_num * float(
                limit_up_price) < THRESHOLD_MONEY_W * 100):
            return True, f"剩余笔数({total_left_count})/金额({round(total_left_num * float(limit_up_price) * 100)})不足,成交进度:{trade_index},真实下单位置:{real_order_index} 阈值:({THRESHOLD_MONEY_W},{THRESHOLD_COUNT}) "
        return False, f"不满足撤单条件: 成交进度-{trade_index} 真实下单位置-{real_order_index} total_left_count-{total_left_count} total_left_num-{total_left_num}"
 
    # 距离太近,封单不足,有大单50w大单砸下来就撤
    def need_cancel_for_p(self, code, big_sell_order_info, order_begin_pos):
        if not order_begin_pos or not order_begin_pos.buy_exec_index or order_begin_pos.buy_exec_index < 0:
            return False, "尚未下单"
 
        if big_sell_order_info[0] < 50 * 10000 or not big_sell_order_info[1]:
            return False, "不为大单"
        # 判断是否具有真实的下单位置
        real_order_index_info = self.__get_real_order_index_cache(code)
        if not real_order_index_info:
            return False, "没找到真实下单位"
        if real_order_index_info[1]:
            return False, "真实下单位为默认"
 
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        if trade_index is None:
            trade_index = 0
        real_order_index = real_order_index_info[0]
        if real_order_index_info[0] <= trade_index:
            return False, "真实下单位在成交位之前"
 
        start_order_no = big_sell_order_info[1][-1][4][1]
        real_trade_index = trade_index
        # 统计未撤订单的数量与金额
        total_datas = local_today_datas.get(code)
        for i in range(trade_index, real_order_index):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if int(val['orderNo']) < start_order_no:
                continue
            real_trade_index = i
            break
 
        # 是否是下单3分钟内
        if tool.trade_time_sub(total_datas[-1]['val']['time'], total_datas[real_order_index]['val']['time']) > 180:
            return False, "下单超过180s"
 
        total_left_count = 0
        total_left_num = 0
        # 成交位到真实下单位剩余的未成交的单
        for i in range(real_trade_index + 1, real_order_index_info[0]):
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 5000:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                     i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_left_count += left_count
                total_left_num += val["num"] * left_count
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        if total_left_count < 5 or total_left_num * float(limit_up_price) < 500 * 100:
            # 距离成交进度位5笔以内或500万以内
            # 计算我们后面的大单与涨停纯买额
            total_left_num = 0
            total_big_num_count = 0
            for i in range(real_order_index + 1, len(total_datas)):
                data = total_datas[i]
                val = data["val"]
                if not L2DataUtil.is_limit_up_price_buy(val):
                    continue
                money = val["num"] * float(val["price"])
                if money < 5000:
                    continue
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code,
                                                                                                         i,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    if money > 299 * 100:
                        total_big_num_count += 1
                    total_left_num += val["num"]
            left_money = total_left_num * float(limit_up_price)
            if total_big_num_count == 0 or left_money < 1000 * 100:
                # 实际下单位后方所有涨停纯买额≤1000万或没有任何大单(≥299万)
                return True, f"P撤:封单纯买额-{round(left_money / 100, 1)}万 大单数量-{total_big_num_count} 下单位-{real_order_index} 成交位-{real_trade_index}"
        return False, "不满足撤单条件"
 
    # w撤
    def need_cancel_for_w(self, code):
        real_order_index_info = self.__get_real_order_index_cache(code)
        if not real_order_index_info:
            return False, "没找到真实下单位"
        if real_order_index_info[1]:
            return False, "真实下单位为默认"
        place_order_count = trade_data_manager.PlaceOrderCountManager().get_place_order_count(code)
        if place_order_count > 1:
            return False, "不是初次下单"
 
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        if trade_index is None:
            return False, "没获取到成交进度位"
 
        real_order_index = real_order_index_info[0]
        total_datas = local_today_datas.get(code)
        if tool.trade_time_sub(total_datas[-1]['val']['time'], total_datas[real_order_index]['val']['time']) > 60:
            return False, "超过守护时间"
        limit_up_price = round(float(gpcode_manager.get_limit_up_price(code)), 2)
        end_index = L2DataComputeUtil.compute_end_index(code, real_order_index + 1, total_datas[-1]["index"],
                                                        limit_up_price, 10)
        # 从成交进度位到截至位置计算大单
        min_money = l2_data_util.get_big_money_val(limit_up_price)
        left_count, left_money = L2DataComputeUtil.compute_left_buy_order(code, trade_index, end_index, limit_up_price,
                                                                          min_money=min_money)
        if left_count < 1:
            return True, f"范围:{real_order_index}-{end_index}  大单数量:{left_count}"
        return False, "大单数量够"
 
 
# ---------------------------------G撤-------------------------------
class GCancelBigNumComputer:
    __real_place_order_index_dict = {}
    __trade_progress_index_dict = {}
    __watch_indexes_dict = {}
    __watch_indexes_by_dict = {}
    __expire_time_dict = {}
    # 最新处理的卖单
    __latest_process_sell_order_no_dict = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(GCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
 
    def set_real_place_order_index(self, code, index, buy_single_index, is_default):
        self.__real_place_order_index_dict[code] = (index, is_default)
        start_index = buy_single_index
        if code in self.__trade_progress_index_dict:
            start_index = self.__trade_progress_index_dict.get(code)
        total_datas = local_today_datas.get(code)
        # 设置生效截至时间
        self.__reset_expire_time(code, total_datas[index]['val']['time'])
        self.__commpute_watch_indexes(code, start_index, (index, is_default), from_real_order_index_changed=True)
 
    # 重新设置G撤守护时间
    def __reset_expire_time(self, code, now_time):
        self.__expire_time_dict[code] = tool.trade_time_add_second(now_time, 9)
 
    # 大有单卖
    # 暂时不启用
    def set_big_sell_order_info(self, code, big_sell_order_info):
        money = big_sell_order_info[0]
        if money < 50 * 10000:
            # 无大卖单
            return
        # 获取真实下单位置
        real_place_order_info = self.__real_place_order_index_dict.get(code)
        if not real_place_order_info:
            # 没有真实下单位置
            return
        if real_place_order_info[1]:
            # 不能是默认下单位置
            return
        trade_index = self.__trade_progress_index_dict.get(code)
        if trade_index is None:
            trade_index = 0
 
        # 下单9s之后才会重新触发
        total_datas = local_today_datas.get(code)
        if tool.trade_time_sub(total_datas[-1]['val']['time'],
                               total_datas[real_place_order_info[0]]['val']['time']) <= 9:
            return
 
        # 不重复处理同一卖单号
        if self.__latest_process_sell_order_no_dict.get(code) == big_sell_order_info[1][-1][0]:
            return
 
        # 查找真实成交位置
        real_order_index = real_place_order_info[0]
        start_order_no = big_sell_order_info[1][-1][4][1]
        real_trade_index = trade_index
        for i in range(trade_index, real_order_index):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if int(val['orderNo']) < start_order_no:
                continue
            real_trade_index = i
            break
        l2_log.g_cancel_debug(code, f"大单卖触发重新囊括,真实成交位置:{real_trade_index},卖信息:{big_sell_order_info}")
        self.__commpute_watch_indexes(code, real_trade_index, real_place_order_info, recompute=True)
        self.__reset_expire_time(code, total_datas[real_trade_index]['val']['time'])
        self.__latest_process_sell_order_no_dict[code] = big_sell_order_info[1][-1][0]
 
    def clear(self, code=None):
        if code:
            if code in self.__expire_time_dict:
                self.__expire_time_dict.pop(code)
            if code in self.__real_place_order_index_dict:
                self.__real_place_order_index_dict.pop(code)
            if code in self.__watch_indexes_dict:
                self.__watch_indexes_dict.pop(code)
            if code in self.__watch_indexes_by_dict:
                self.__watch_indexes_by_dict.pop(code)
            if code in self.__trade_progress_index_dict:
                self.__trade_progress_index_dict.pop(code)
 
        else:
            self.__real_place_order_index_dict.clear()
            self.__watch_indexes_dict.clear()
            self.__trade_progress_index_dict.clear()
            self.__watch_indexes_by_dict.clear()
 
    # recompute:是否重新计算
    def __commpute_watch_indexes(self, code, traded_index, real_order_index_info, from_real_order_index_changed=False,
                                 recompute=False):
        if traded_index is None or real_order_index_info is None:
            return
        real_order_index, is_default = real_order_index_info[0], real_order_index_info[1]
        origin_watch_index = self.__watch_indexes_dict.get(code)
        if origin_watch_index is None:
            origin_watch_index = set()
        # 不需要备用
        origin_watch_index_by = self.__watch_indexes_by_dict.get(code)
        if origin_watch_index_by is None:
            origin_watch_index_by = set()
 
        # 重新计算需要清除之前的数据
        if recompute:
            origin_watch_index.clear()
            origin_watch_index_by.clear()
 
        start_index = traded_index
        if traded_index in origin_watch_index or traded_index in origin_watch_index_by:
            # 正在成交的是已经囊括了的大单
            start_index = traded_index + 1
 
        total_datas = local_today_datas.get(code)
        watch_indexes = set()
        for i in range(start_index, real_order_index):
            # 判断是否有未撤的大单
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 29900 and val["num"] < 7999:
                continue
            # 是否已撤单
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                watch_indexes.add(i)
        if watch_indexes:
            # 还有300万以上的大单没有撤单
            if from_real_order_index_changed or recompute:
                # 真实下单位改变后才会更新
                final_watch_indexes = origin_watch_index | watch_indexes
                self.__watch_indexes_dict[code] = final_watch_indexes
                l2_log.g_cancel_debug(code, f"大单监听:{final_watch_indexes} 是否重新计算:{recompute}")
                # 有大单监听,需要移除之前的小单监听
                if code in self.__watch_indexes_by_dict:
                    self.__watch_indexes_by_dict[code].clear()
        else:
            l2_log.g_cancel_debug(code, f"没有大单监听,开始计算小单:{start_index}-{real_order_index}, 是否重新计算:{recompute}")
            # 没有300万以上的大单了,计算备用
            # 只有备用单成交了或者没有备用单,才会再次寻找备用单
            need_find_by = False
            if not origin_watch_index_by:
                need_find_by = True
            else:
                # 备用单是否成交
                need_find_by = True
                for i in origin_watch_index_by:
                    if i >= start_index:
                        # 只要有一个还没成交就不需要重新计算
                        need_find_by = False
                        break
            if need_find_by and (not is_default or not watch_indexes):
                l2_log.g_cancel_debug(code, f"启动小单备用监听:{start_index}-{real_order_index}")
                temp_list = []
                for i in range(start_index, real_order_index):
                    data = total_datas[i]
                    val = data["val"]
                    if not L2DataUtil.is_limit_up_price_buy(val):
                        continue
                    # 不能囊括已撤单
                    left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                             total_datas,
                                                                                                             local_today_canceled_buyno_map.get(
                                                                                                                 code))
                    if left_count <= 0:
                        continue
 
                    if val["num"] * float(val["price"]) < 5000:
                        continue
                    temp_list.append((val["num"], data))
                    if len(temp_list) > 15:
                        break
                temp_list.sort(key=lambda x: x[0], reverse=True)
                # 次大单的笔数1-3笔
                THRESH_COUNT = len(temp_list) // 5
                if THRESH_COUNT < 1:
                    THRESH_COUNT = 1
                if temp_list:
                    for i in range(THRESH_COUNT):
                        l2_log.g_cancel_debug(code, f"小单备用监听位置:{temp_list[i][1]['index']}")
                        watch_indexes.add(temp_list[i][1]["index"])
                    self.__watch_indexes_by_dict[code] = watch_indexes
 
    def set_trade_progress(self, code, buy_single_index, index):
        if self.__trade_progress_index_dict.get(code) != index:
            self.__trade_progress_index_dict[code] = index
            self.__commpute_watch_indexes(code, index, self.__real_place_order_index_dict.get(code))
 
    def need_cancel(self, code, buy_exec_index, start_index, end_index):
        if 1 > 0:
            return False, None, "G撤被注释掉"
 
        if code not in self.__real_place_order_index_dict:
            return False, None, "没有找到真实下单位"
        expire_time = self.__expire_time_dict.get(code)
        if not expire_time:
            return False, None, "尚未设置生效时间"
 
        real_place_order_index, is_default = self.__real_place_order_index_dict.get(code)
        total_datas = local_today_datas.get(code)
 
        if tool.trade_time_sub(total_datas[end_index]["val"]["time"], total_datas[buy_exec_index]['val']['time']) > 180:
            return False, None, "超过180s的生效时间"
 
        # 30s内有效
        if tool.trade_time_sub(total_datas[end_index]["val"]["time"], expire_time) > 0:
            return False, None, "超过生效时间"
 
        watch_indexes = self.__watch_indexes_dict.get(code)
        if watch_indexes is None:
            watch_indexes = set()
        watch_indexes_by = self.__watch_indexes_by_dict.get(code)
        if watch_indexes_by is None:
            watch_indexes_by = set()
        need_compute = False
        need_compute_by = False
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                continue
            if val["num"] * float(val["price"]) < 5000:
                continue
            buy_index = l2_data_source_util.L2DataSourceUtils.get_buy_index_with_cancel_data_v2(data,
                                                                                                local_today_buyno_map.get(
                                                                                                    code))
            if buy_index is not None and buy_index < real_place_order_index and (
                    buy_index in watch_indexes or buy_index in watch_indexes_by):
                if buy_index in watch_indexes_by:
                    need_compute_by = True
                    break
                    # 备用撤单,直接撤
                    # return True, data, f"次大单撤:{buy_index}"
                elif buy_index in watch_indexes:
                    # 大单撤需要重新计算大单撤单比例
                    need_compute = True
                    break
        if need_compute and watch_indexes:
            canceled_indexes = set()
            for index in watch_indexes:
                cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code, index,
                                                                                                      total_datas,
                                                                                                      local_today_canceled_buyno_map.get(
                                                                                                          code))
                if cancel_data:
                    canceled_indexes.add(cancel_data["index"])
            cancel_rate = round(len(canceled_indexes) / len(watch_indexes), 2)
            threshhold_rate = constant.G_CANCEL_RATE
            situation = trade_manager.MarketSituationManager().get_situation_cache()
            if situation == trade_manager.MarketSituationManager.SITUATION_GOOD:
                threshhold_rate = constant.G_CANCEL_RATE_FOR_GOOD_MARKET
            if cancel_rate > threshhold_rate:
                canceled_indexes_list = list(canceled_indexes)
                canceled_indexes_list.sort()
                return True, total_datas[canceled_indexes_list[-1]], f"撤单比例:{cancel_rate}"
        # 计算备用
        if need_compute_by and watch_indexes_by:
            canceled_indexes = set()
            for index in watch_indexes_by:
                cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code, index,
                                                                                                      total_datas,
                                                                                                      local_today_canceled_buyno_map.get(
                                                                                                          code))
                if cancel_data:
                    canceled_indexes.add(cancel_data["index"])
            cancel_rate = round(len(canceled_indexes) / len(watch_indexes_by), 2)
            threshhold_rate = constant.G_CANCEL_RATE
            situation = trade_manager.MarketSituationManager().get_situation_cache()
            if situation == trade_manager.MarketSituationManager.SITUATION_GOOD:
                threshhold_rate = constant.G_CANCEL_RATE_FOR_GOOD_MARKET
            if cancel_rate > threshhold_rate:
                canceled_indexes_list = list(canceled_indexes)
                canceled_indexes_list.sort()
                return True, total_datas[canceled_indexes_list[-1]], f"次大单撤单比例:{cancel_rate}"
 
        return False, None, ""
 
    # B撤单
    # 剩余一个大单撤半截就撤单
    def need_cancel_for_b(self, code, start_index, end_index):
        real_place_order_info = self.__real_place_order_index_dict.get(code)
        if not real_place_order_info or real_place_order_info[1]:
            # 没有真实下单位置
            return False, None, "没有真实下单位置"
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        if trade_index is None:
            return False, None, "未获取到成交进度位"
        total_datas = local_today_datas.get(code)
        buyno_map = local_today_buyno_map.get(code)
        cancel_half_index = None
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                continue
            orderNo = val['orderNo']
            buy_data = buyno_map.get(f"{orderNo}")
            if not buy_data:
                continue
            # 判断大单
            if buy_data["val"]["num"] * float(buy_data["val"]["price"]) < 29900:
                continue
            # 判断是否撤半截
            if buy_data["val"]["num"] > val["num"]:
                cancel_half_index = i
                break
        if cancel_half_index is None:
            return False, None, "没有撤半截"
        # 有大单撤半截桩
        # 计算是否还剩下大单
        total_big_num_count = 0
        for i in range(trade_index, real_place_order_info[0]):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 29900:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_big_num_count += 1
                break
        if total_big_num_count == 0:
            # 没有剩下大单
            return True, total_datas[cancel_half_index], f"B撤:撤单索引-{cancel_half_index}"
        return False, None, "还有大单没撤单"
 
    def place_order_success(self, code):
        self.clear(code)
 
    def cancel_success(self, code):
        self.clear(code)
 
 
# ---------------------------------新G撤-------------------------------
class NewGCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __real_place_order_index_dict = {}
    __trade_progress_index_dict = {}
    __watch_indexes_dict = {}
    # 最新处理的卖单
    __latest_process_sell_order_no_dict = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(NewGCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "g_cancel_watch_index_info-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                if val:
                    val = json.loads(val)
                    val = set(val)
                CodeDataCacheUtil.set_cache(cls.__watch_indexes_dict, code, val)
        finally:
            RedisUtils.realse(__redis)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    def __set_watch_index(self, code, indexes):
        CodeDataCacheUtil.set_cache(self.__watch_indexes_dict, code, indexes)
        RedisUtils.setex_async(self.__db, f"g_cancel_watch_index_info-{code}", tool.get_expire(),
                               json.dumps(list(indexes)))
 
    def set_real_place_order_index(self, code, index, buy_single_index, is_default):
        self.__real_place_order_index_dict[code] = (index, is_default)
        start_index = buy_single_index
        if not is_default:
            trade_index, is_default = TradeBuyQueue().get_traded_index(code)
            if trade_index is None:
                start_index = 0
            else:
                start_index = trade_index
        self.__commpute_watch_indexes(code, start_index, (index, is_default), from_real_order_index_changed=True)
 
    def clear(self, code=None):
        if code:
            if code in self.__real_place_order_index_dict:
                self.__real_place_order_index_dict.pop(code)
            if code in self.__watch_indexes_dict:
                self.__watch_indexes_dict.pop(code)
            RedisUtils.delete_async(self.__db, f"g_cancel_watch_index_info-{code}")
            if code in self.__trade_progress_index_dict:
                self.__trade_progress_index_dict.pop(code)
        else:
            self.__real_place_order_index_dict.clear()
            self.__watch_indexes_dict.clear()
            self.__trade_progress_index_dict.clear()
            keys = RedisUtils.keys(self.__get_redis(), f"g_cancel_watch_index_info-*")
            for k in keys:
                RedisUtils.delete(self.__get_redis(), k)
 
    # recompute:是否重新计算
    def __commpute_watch_indexes(self, code, traded_index, real_order_index_info, from_real_order_index_changed=False,
                                 recompute=False):
        if traded_index is None or real_order_index_info is None:
            return
        real_order_index, is_default = real_order_index_info[0], real_order_index_info[1]
        origin_watch_index = self.__watch_indexes_dict.get(code)
        if origin_watch_index is None:
            origin_watch_index = set()
        # 重新计算需要清除之前的数据
        if recompute:
            origin_watch_index.clear()
 
        start_index = traded_index
        if traded_index in origin_watch_index:
            # 正在成交的是已经囊括了的大单
            start_index = traded_index + 1
 
        total_datas = local_today_datas.get(code)
        watch_indexes = set()
        for i in range(start_index, real_order_index):
            # 判断是否有未撤的大单
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 29900:
                continue
            # 是否已撤单
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                watch_indexes.add(i)
        if watch_indexes:
            # 还有300万以上的大单没有撤单
            if from_real_order_index_changed or recompute:
                # 真实下单位改变后才会更新
                final_watch_indexes = origin_watch_index | watch_indexes
                self.__set_watch_index(code, final_watch_indexes)
                l2_log.g_cancel_debug(code, f"大单监听:{final_watch_indexes} 是否重新计算:{recompute}")
 
    def set_trade_progress(self, code, buy_single_index, index):
        # if self.__trade_progress_index_dict.get(code) != index:
        self.__trade_progress_index_dict[code] = index
        # self.__commpute_watch_indexes(code, index, self.__real_place_order_index_dict.get(code))
 
    def need_cancel(self, code, buy_exec_index, start_index, end_index):
        if code not in self.__real_place_order_index_dict:
            return False, None, "没有找到真实下单位"
 
        real_place_order_index, is_default = self.__real_place_order_index_dict.get(code)
        total_datas = local_today_datas.get(code)
 
        # if tool.trade_time_sub(total_datas[end_index]["val"]["time"], total_datas[buy_exec_index]['val']['time']) > 180:
        #     return False, None, "超过180s的生效时间"
 
        watch_indexes = self.__watch_indexes_dict.get(code)
        if watch_indexes is None:
            watch_indexes = set()
        if len(watch_indexes) < 3:
            return False, None, "大于等于3个大单生效"
 
        need_compute = False
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data["val"]
            if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                continue
            if val["num"] * float(val["price"]) < 5000:
                continue
            buy_index = l2_data_source_util.L2DataSourceUtils.get_buy_index_with_cancel_data_v2(data,
                                                                                                local_today_buyno_map.get(
                                                                                                    code))
            if buy_index is not None and buy_index < real_place_order_index and (buy_index in watch_indexes):
                if buy_index in watch_indexes:
                    # 大单撤需要重新计算大单撤单比例
                    need_compute = True
                    break
        if need_compute and watch_indexes:
            canceled_indexes = set()
            for index in watch_indexes:
                cancel_data = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_canceled_data_v2(code, index,
                                                                                                      total_datas,
                                                                                                      local_today_canceled_buyno_map.get(
                                                                                                          code))
                if cancel_data:
                    canceled_indexes.add(cancel_data["index"])
            cancel_rate = round(len(canceled_indexes) / len(watch_indexes), 2)
            threshhold_rate = constant.G_CANCEL_RATE
            situation = trade_manager.MarketSituationManager().get_situation_cache()
            if situation == trade_manager.MarketSituationManager.SITUATION_GOOD:
                threshhold_rate = constant.G_CANCEL_RATE_FOR_GOOD_MARKET
            if gpcode_manager.MustBuyCodesManager().is_in_cache(code):
                threshhold_rate = constant.G_CANCEL_RATE_WITH_MUST_BUY
            if cancel_rate > threshhold_rate:
                canceled_indexes_list = list(canceled_indexes)
                canceled_indexes_list.sort()
                return True, total_datas[canceled_indexes_list[-1]], f"撤单比例:{cancel_rate}"
        return False, None, ""
 
    def place_order_success(self, code):
        self.clear(code)
 
    def cancel_success(self, code):
        self.clear(code)
 
    # B撤单
    # 剩余一个大单撤半截就撤单
    def need_cancel_for_b(self, code, start_index, end_index):
        real_place_order_info = self.__real_place_order_index_dict.get(code)
        if not real_place_order_info or real_place_order_info[1]:
            # 没有真实下单位置
            return False, None, "没有真实下单位置"
        trade_index, is_default = TradeBuyQueue().get_traded_index(code)
        if trade_index is None:
            return False, None, "未获取到成交进度位"
        total_datas = local_today_datas.get(code)
        buyno_map = local_today_buyno_map.get(code)
        cancel_half_index = None
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                continue
            orderNo = val['orderNo']
            buy_data = buyno_map.get(f"{orderNo}")
            if not buy_data:
                continue
            # 判断大单
            if buy_data["val"]["num"] * float(buy_data["val"]["price"]) < 29900:
                continue
            # 判断是否撤半截
            if buy_data["val"]["num"] > val["num"]:
                cancel_half_index = i
                break
        if cancel_half_index is None:
            return False, None, "没有撤半截"
        # 有大单撤半截桩
        # 计算是否还剩下大单
        total_big_num_count = 0
        for i in range(trade_index, real_place_order_info[0]):
            data = total_datas[i]
            val = data['val']
            if not L2DataUtil.is_limit_up_price_buy(val):
                continue
            if val["num"] * float(val["price"]) < 29900:
                continue
            left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                     total_datas,
                                                                                                     local_today_canceled_buyno_map.get(
                                                                                                         code))
            if left_count > 0:
                total_big_num_count += 1
                break
        if total_big_num_count == 0:
            # 没有剩下大单
            return True, total_datas[cancel_half_index], f"B撤:撤单索引-{cancel_half_index}"
        return False, None, "还有大单没撤单"
 
    def test(self):
        self.__set_watch_index("000333", {1, 2, 3, 4, 5, 6, 7})
 
 
# ---------------------------------独苗撤-------------------------------
class UCancelBigNumComputer:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __cancel_real_order_index_cache = {}
    __SCancelBigNumComputer = SCancelBigNumComputer()
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(UCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __load_datas(cls):
        pass
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    # 是否可以撤单
    def need_cancel(self, code, transaction_index, order_begin_pos: OrderBeginPosInfo,
                    current_limit_up_block_codes_dict, volume_rate):
        if not order_begin_pos or not order_begin_pos.buy_exec_index or order_begin_pos.buy_exec_index < 0:
            return False, "尚未下单"
        if not current_limit_up_block_codes_dict:
            return False, "涨停列表无数据"
        # 获取涨停原因
        block = None
        for b in current_limit_up_block_codes_dict:
            if code in current_limit_up_block_codes_dict[b]:
                block = b
                break
        if not block:
            return False, "没有找到代码的涨停原因"
        if len(current_limit_up_block_codes_dict[block]) > 1:
            return False, "有后排无需撤单"
        total_datas = local_today_datas.get(code)
        time_sub = tool.trade_time_sub(tool.get_now_time_str(),
                                       total_datas[order_begin_pos.buy_exec_index]["val"]["time"])
        if 2 < time_sub < 30 * 60:
            real_place_order_index = self.__SCancelBigNumComputer.get_real_place_order_index_cache(code)
            if not real_place_order_index:
                return False, "尚未找到真实下单位置"
            total_left_count = 0
            for i in range(transaction_index, real_place_order_index):
                data = total_datas[i]
                val = data["val"]
                if float(val['price']) * val['num'] < 50 * 100:
                    continue
                left_count = l2_data_source_util.L2DataSourceUtils.get_limit_up_buy_no_canceled_count_v2(code, i,
                                                                                                         total_datas,
                                                                                                         local_today_canceled_buyno_map.get(
                                                                                                             code))
                if left_count > 0:
                    total_left_count += 1
                    if total_left_count > 5:
                        break
            # 成交进度变化
            # if len(current_limit_up_block_codes_dict[block]) == 1 and volume_rate < 0.6 and total_left_count <= 5:
            #     return True, "独苗下单30分钟无后排且成交位离我们很近且量小于60%"
        # if time_sub > 10 * 60:
        #     if len(current_limit_up_block_codes_dict[block]) == 1 and volume_rate < 0.7:
        #         return True, f"独苗下单10分钟无后排且量({volume_rate})小于70%"
        return False, "不需要撤单"
 
 
# --------------------------------封单额变化撤------------------------
# 涨停封单额统计
class L2LimitUpMoneyStatisticUtil:
    _db = 1
    _redisManager = redis_manager.RedisManager(1)
    _thsBuy1VolumnManager = trade_queue_manager.THSBuy1VolumnManager()
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(L2LimitUpMoneyStatisticUtil, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
 
    @classmethod
    def __get_redis(cls):
        return cls._redisManager.getRedis()
 
    # 设置l2的每一秒涨停封单额数据
 
    def __set_l2_second_money_record(self, code, time, num, from_index, to_index):
        old_num, old_from, old_to = self.__get_l2_second_money_record(code, time)
        if old_num is None:
            old_num = num
            old_from = from_index
            old_to = to_index
        else:
            old_num += num
            old_to = to_index
        key = "l2_limit_up_second_money-{}-{}".format(code, time.replace(":", ""))
        RedisUtils.setex(self.__get_redis(), key, tool.get_expire(), json.dumps((old_num, old_from, old_to)))
 
    def __get_l2_second_money_record(self, code, time):
        key = "l2_limit_up_second_money-{}-{}".format(code, time.replace(":", ""))
        val = RedisUtils.get(self.__get_redis(), key)
        return self.__format_second_money_record_val(val)
 
    def __format_second_money_record_val(self, val):
        if val is None:
            return None, None, None
        val = json.loads(val)
        return val[0], val[1], val[2]
 
    def __get_l2_second_money_record_keys(self, code, time_regex):
        key = "l2_limit_up_second_money-{}-{}".format(code, time_regex)
        keys = RedisUtils.keys(self.__get_redis(), key)
        return keys
 
    # 设置l2最新的封单额数据
 
    def __set_l2_latest_money_record(self, code, index, num):
        key = "l2_limit_up_money-{}".format(code)
        RedisUtils.setex(self.__get_redis(), key, tool.get_expire(), json.dumps((num, index)))
 
    # 返回数量,索引
    def __get_l2_latest_money_record(self, code):
        key = "l2_limit_up_money-{}".format(code)
        result = RedisUtils.get(self.__get_redis(), key)
        if result:
            result = json.loads(result)
            return result[0], result[1]
        else:
            return 0, -1
 
    # 矫正数据
    # 矫正方法为取矫正时间两侧的秒分布数据,用于确定计算结束坐标
    def verify_num(self, code, num, time_str):
        # 记录买1矫正日志
        logger_buy_1_volumn.info("涨停封单量矫正:代码-{} 量-{} 时间-{}", code, num, time_str)
        time_ = time_str.replace(":", "")
        key = None
        # 获取矫正时间前1分钟的数据
        keys = []
        if not constant.TEST:
            for i in range(0, 3600):
                temp_time = tool.trade_time_add_second(time_str, 0 - i)
                # 只处理9:30后的数据
                if int(temp_time.replace(":", "")) < int("093000"):
                    break
                keys_ = self.__get_l2_second_money_record_keys(code, temp_time.replace(":", ""))
                if len(keys_) > 0:
                    keys.append(keys_[0])
                if len(keys) >= 1:
                    break
        else:
            keys_ = self.__get_l2_second_money_record_keys(code, "*")
            key_list = []
            for k in keys_:
                time__ = k.split("-")[-1]
                key_list.append((int(time__), k))
            key_list.sort(key=lambda tup: tup[0])
            for t in key_list:
                if t[0] <= int(time_):
                    keys.append(t[1])
                    break
 
        keys.sort(key=lambda tup: int(tup.split("-")[-1]))
        if len(keys) > 0:
            key = keys[0]
            val = RedisUtils.get(self.__get_redis(), key)
            old_num, old_from, old_to = self.__format_second_money_record_val(val)
            end_index = old_to
            # 保存最近的数据
            self.__set_l2_latest_money_record(code, end_index, num)
            logger_buy_1_volumn.info("涨停封单量矫正成功:代码-{} 位置-{} 量-{}", code, end_index, num)
        else:
            logger_buy_1_volumn.info("涨停封单量矫正失败:代码-{} 时间-{} 量-{}", code, time_str, num)
        # 取消此种方法
        #
        # for i in range(4, -2, -2):
        #     # 获取本(分钟/小时/天)内秒分布数据
        #     time_regex = "{}*".format(time_[:i])
        #     keys_ = cls.__get_l2_second_money_record_keys(code, time_regex)
        #     if keys_ and len(keys_) > 1:
        #         # 需要排序
        #         keys = []
        #         for k in keys_:
        #             keys.append(k)
        #         keys.sort(key=lambda tup: int(tup.split("-")[-1]))
        #         # if i == 4:
        #         #    keys=keys[:5]
        #         # 有2个元素
        #         for index in range(0, len(keys) - 1):
        #             time_1 = keys[index].split("-")[-1]
        #             time_2 = keys[index + 1].split("-")[-1]
        #             if int(time_1) <= int(time_) <= int(time_2):
        #                 # 在此时间范围内
        #                 if time_ == time_2:
        #                     key = keys[index + 1]
        #                 else:
        #                     key = keys[index]
        #                 break
        #         if key:
        #             break
        # # 如果没有找到匹配的区间
        # if not key:
        #     # 最后一条数据的时间为相应的区间
        #     total_datas = local_today_datas[code]
        #
        # if key:
        #     val = cls.__get_redis().get(key)
        #     old_num, old_from, old_to = cls.__format_second_money_record_val(val)
        #     end_index = old_to
        #     # 保存最近的数据
        #     cls.__set_l2_latest_money_record(code, end_index, num)
        #     logger_buy_1_volumn.info("涨停封单量矫正结果:代码-{} 位置-{} 量-{}", code, end_index, num)
 
    # 计算量,用于涨停封单量的计算
    def __compute_num(self, code, data, buy_single_data):
        if L2DataUtil.is_limit_up_price_buy_cancel(data["val"]) or L2DataUtil.is_sell(data["val"]):
            # 涨停买撤与卖
            return 0 - int(data["val"]["num"]) * data["re"]
        else:
            # 卖撤
            if L2DataUtil.is_sell_cancel(data["val"]):
                # 卖撤的买数据是否在买入信号之前,如果在之前就不计算,不在之前就计算
                if l2_data_util.is_sell_index_before_target(data, buy_single_data,
                                                            local_today_num_operate_map.get(code)):
                    return 0
 
            return int(data["val"]["num"]) * data["re"]
 
    def clear(self, code):
        key = "l2_limit_up_money-{}".format(code)
        RedisUtils.delete(self.__get_redis(), key)
 
    # 返回取消的标志数据
    # with_cancel 是否需要判断是否撤销
    def process_data(self, code, start_index, end_index, buy_single_begin_index, buy_exec_index,
                     with_cancel=True):
        if buy_single_begin_index is None or buy_exec_index is None:
            return None, None
        start_time = round(time.time() * 1000)
        total_datas = local_today_datas[code]
        time_dict_num = {}
        # 记录计算的坐标
        time_dict_num_index = {}
        # 坐标-量的map
        num_dict = {}
        # 统计时间分布
        time_dict = {}
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data["val"]
            time_ = val["time"]
            if time_ not in time_dict:
                time_dict[time_] = i
 
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data["val"]
            time_ = val["time"]
            if time_ not in time_dict_num:
                time_dict_num[time_] = 0
                time_dict_num_index[time_] = {"s": i, "e": i}
            time_dict_num_index[time_]["e"] = i
            num = self.__compute_num(code, data, total_datas[buy_single_begin_index])
            num_dict[i] = num
            time_dict_num[time_] = time_dict_num[time_] + num
        for t_ in time_dict_num:
            self.__set_l2_second_money_record(code, t_, time_dict_num[t_], time_dict_num_index[t_]["s"],
                                              time_dict_num_index[t_]["e"])
 
        print("保存涨停封单额时间:", round(time.time() * 1000) - start_time)
 
        # 累计最新的金额
        total_num, index = self.__get_l2_latest_money_record(code)
        record_msg = f"同花顺买1信息 {total_num},{index}"
 
        if index == -1:
            # 没有获取到最新的矫正封单额,需要从买入信号开始点计算
            index = buy_single_begin_index - 1
            total_num = 0
 
        cancel_index = None
        cancel_msg = None
        # 待计算量
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        min_volumn = round(10000000 / (limit_up_price * 100))
        min_volumn_big = min_volumn * 5
        # 不同时间的数据开始坐标
        time_start_index_dict = {}
        # 数据时间分布
        time_list = []
        # 到当前时间累积的买1量
        time_total_num_dict = {}
 
        # 大单撤销笔数
        cancel_big_num_count = 0
        buy_exec_time = tool.get_time_as_second(total_datas[buy_exec_index]["val"]["time"])
 
        # 获取最大封单额
        max_buy1_volume = self._thsBuy1VolumnManager.get_max_buy1_volume_cache(code)
 
        # 从同花顺买1矫正过后的位置开始计算,到end_index结束
 
        for i in range(index + 1, end_index + 1):
            data = total_datas[i]
            # 统计撤销数量
            try:
                if big_money_num_manager.is_big_num(data["val"]):
                    if L2DataUtil.is_limit_up_price_buy_cancel(data["val"]):
                        cancel_big_num_count += int(data["re"])
                        # 获取是否在买入执行信号周围2s
                        buy_index = l2_data_source_util.L2DataSourceUtils.get_buy_index_with_cancel_data_v2(data,
                                                                                                            local_today_buyno_map.get(
                                                                                                                code))
                        if buy_index is not None:
                            # 相差1s
                            buy_time = total_datas[buy_index]["val"]["time"]
                            if abs(buy_exec_time - tool.get_time_as_second(buy_time)) < 2:
                                cancel_big_num_count += int(data["re"])
 
                    elif L2DataUtil.is_limit_up_price_buy(data["val"]):
                        cancel_big_num_count -= int(data["re"])
            except Exception as e:
                logging.exception(e)
 
            threshold_rate = 0.5
            if cancel_big_num_count >= 0:
                if cancel_big_num_count < 10:
                    threshold_rate = threshold_rate - cancel_big_num_count * 0.01
                else:
                    threshold_rate = threshold_rate - 10 * 0.01
 
            time_ = data["val"]["time"]
            if time_ not in time_start_index_dict:
                # 记录每一秒的开始位置
                time_start_index_dict[time_] = i
                # 记录时间分布
                time_list.append(time_)
                # 上一段时间的总数
                time_total_num_dict[time_] = total_num
 
            exec_time_offset = tool.trade_time_sub(data["val"]["time"], total_datas[buy_exec_index]["val"]["time"])
 
            val = num_dict.get(i)
            if val is None:
                val = self.__compute_num(code, data, total_datas[buy_single_begin_index])
            total_num += val
            # 在处理数据的范围内,就需要判断是否要撤单了
            if start_index <= i <= end_index:
                # 如果是减小项
                if val < 0:
                    # 累计封单金额小于1000万
                    if total_num < min_volumn:
                        # 与执行位相隔>=5s时规则生效
                        if exec_time_offset >= 5:
                            cancel_index = i
                            cancel_msg = "封单金额小于1000万,为{}".format(total_num)
                            break
                    # 相邻2s内的数据减小50%
                    # 上1s的总数
                    last_second_total_volumn = time_total_num_dict.get(time_list[-1])
                    if last_second_total_volumn > 0 and (
                            last_second_total_volumn - total_num) / last_second_total_volumn >= threshold_rate:
                        # 与执行位相隔>=5s时规则生效
                        if exec_time_offset >= 5:
                            # 相邻2s内的数据减小50%
                            cancel_index = i
                            cancel_msg = "相邻2s({})内的封单量减小50%({}->{})".format(time_, last_second_total_volumn,
                                                                             total_num)
                        break
                    # 记录中有上2个数据
                    if len(time_list) >= 2:
                        # 倒数第2个数据
                        last_2_second_total_volumn = time_total_num_dict.get(time_list[-2])
                        if last_2_second_total_volumn > 0:
                            if last_2_second_total_volumn > last_second_total_volumn > total_num:
                                dif = last_2_second_total_volumn - total_num
                                if dif / last_2_second_total_volumn >= threshold_rate:
                                    # 与执行位相隔>=5s时规则生效
                                    if exec_time_offset >= 5:
                                        cancel_index = i
                                        cancel_msg = "相邻3s({})内的封单量(第3秒 与 第1的 减小比例)减小50%({}->{}->{})".format(time_,
                                                                                                             last_2_second_total_volumn,
                                                                                                             last_second_total_volumn,
                                                                                                             total_num)
                                    break
 
        if not with_cancel:
            cancel_index = None
 
        print("封单额计算时间:", round(time.time() * 1000) - start_time)
        process_end_index = end_index
        if cancel_index:
            process_end_index = cancel_index
        # 保存最新累计金额
        # cls.__set_l2_latest_money_record(code, process_end_index, total_num)
        # l2_data_log.l2_time(code, round(time.time() * 1000) - start_time,
        #                     "l2数据封单额计算时间",
        #                     False)
        if cancel_index:
            l2_log.cancel_debug(code, "数据处理位置:{}-{},{},最终买1为:{}", start_index, end_index, record_msg,
                                total_num)
            return total_datas[cancel_index], cancel_msg
        return None, None
 
 
# ---------------------------------板上卖-----------------------------
# 涨停卖统计
class L2LimitUpSellStatisticUtil:
    __db = 0
    __redisManager = redis_manager.RedisManager(0)
    __limit_up_sell_num_cache = {}
    __limit_up_sell_index_cache = {}
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(L2LimitUpSellStatisticUtil, cls).__new__(cls, *args, **kwargs)
            # 初始化
            cls.load_data()
        return cls.__instance
 
    @classmethod
    def load_data(cls):
        redis_ = cls.__get_redis()
        try:
            keys = RedisUtils.keys(redis_, "limit_up_sell_num-*")
            for k in keys:
                code = k.split["-"][-1]
                cls.__limit_up_sell_num_cache[code] = RedisUtils.get(redis_, k)
            keys = RedisUtils.keys(redis_, "limit_up_sell_index-*")
            for k in keys:
                code = k.split["-"][-1]
                cls.__limit_up_sell_index_cache[code] = RedisUtils.get(redis_, k)
        finally:
            RedisUtils.realse(redis_)
 
    @classmethod
    def __get_redis(cls):
        return cls.__redisManager.getRedis()
 
    # 新增卖数据
    def __incre_sell_data(self, code, num):
        if code not in self.__limit_up_sell_num_cache:
            self.__limit_up_sell_num_cache[code] = 0
        self.__limit_up_sell_num_cache[code] += num
        key = "limit_up_sell_num-{}".format(code)
        RedisUtils.incrby_async(self.__db, key, num)
        RedisUtils.expire_async(self.__db, key, tool.get_expire())
 
    def __get_sell_data(self, code):
        key = "limit_up_sell_num-{}".format(code)
        val = RedisUtils.get(self.__get_redis(), key)
        if val is None:
            return 0
        return int(val)
 
    def __get_sell_data_cache(self, code):
        if code in self.__limit_up_sell_num_cache:
            return int(self.__limit_up_sell_num_cache[code])
        return 0
 
    def __save_process_index(self, code, index):
        tool.CodeDataCacheUtil.set_cache(self.__limit_up_sell_index_cache, code, index)
        key = "limit_up_sell_index-{}".format(code)
        RedisUtils.setex_async(self.__db, key, tool.get_expire(), index)
 
    def __get_process_index(self, code):
        key = "limit_up_sell_index-{}".format(code)
        val = RedisUtils.get(self.__get_redis(), key)
        if val is None:
            return -1
        return int(val)
 
    def __get_process_index_cache(self, code):
        cache_result = tool.CodeDataCacheUtil.get_cache(self.__limit_up_sell_index_cache, code)
        if cache_result[0]:
            return int(cache_result[1])
        return -1
 
    # 清除数据,当取消成功与买入之前需要清除数据
 
    def delete(self, code):
        tool.CodeDataCacheUtil.clear_cache(self.__limit_up_sell_index_cache, code)
        tool.CodeDataCacheUtil.clear_cache(self.__limit_up_sell_num_cache, code)
        key = "limit_up_sell_num-{}".format(code)
        RedisUtils.delete_async(self.__db, key)
        key = "limit_up_sell_index-{}".format(code)
        RedisUtils.delete_async(self.__db, key)
 
    def clear(self):
        keys = RedisUtils.keys(self.__get_redis(), "limit_up_sell_num-*")
        for k in keys:
            code = k.split("-")[-1]
            self.delete(code)
 
    # 处理数据,返回是否需要撤单
    # 处理范围:买入执行位-当前最新位置
 
    def process(self, code, start_index, end_index, buy_exec_index):
        # 获取涨停卖的阈值
        limit_up_price = gpcode_manager.get_limit_up_price(code)
        zyltgb = l2_trade_factor.L2TradeFactorUtil.get_zyltgb(code)
        # 大于自由流通市值的4.8%
        threshold_num = int(zyltgb * 0.048) // (limit_up_price * 100)
        total_num = self.__get_sell_data_cache(code)
        cancel_index = None
        process_index = self.__get_process_index_cache(code)
        total_datas = local_today_datas.get(code)
        for i in range(start_index, end_index + 1):
            if i < buy_exec_index:
                continue
            if i <= process_index:
                continue
            if L2DataUtil.is_limit_up_price_sell(total_datas[i]["val"]) or L2DataUtil.is_sell(total_datas[i]["val"]):
                num = int(total_datas[i]["val"]["num"])
                self.__incre_sell_data(code, num)
                total_num += num
                if total_num > threshold_num:
                    cancel_index = i
                    break
        if cancel_index is not None:
            process_index = cancel_index
        else:
            process_index = end_index
        l2_log.cancel_debug(code, "板上卖信息:计算位置:{}-{} 板上卖数据{}/{}", start_index, end_index, total_num,
                            threshold_num)
 
        self.__save_process_index(code, process_index)
        if cancel_index is not None:
            return total_datas[cancel_index], "板上卖的手数{} 超过{}".format(total_num, threshold_num)
        return None, ""
 
 
class LatestCancelIndexManager:
    __db = 0
    __redis_manager = redis_manager.RedisManager(0)
    __latest_cancel_index_cache = {}
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(LatestCancelIndexManager, cls).__new__(cls, *args, **kwargs)
            cls.__load_datas()
        return cls.__instance
 
    @classmethod
    def __get_redis(cls):
        return cls.__redis_manager.getRedis()
 
    @classmethod
    def __load_datas(cls):
        __redis = cls.__get_redis()
        try:
            keys = RedisUtils.keys(__redis, "latest_cancel_index-*")
            for k in keys:
                code = k.split("-")[-1]
                val = RedisUtils.get(__redis, k)
                val = int(val)
                CodeDataCacheUtil.set_cache(cls.__latest_cancel_index_cache, code, val)
        finally:
            RedisUtils.realse(__redis)
 
    def __save_latest_cancel_index(self, code, index):
        RedisUtils.setex_async(self.__db, f"latest_cancel_index-{code}", tool.get_expire(), index)
 
    def set_latest_cancel_index(self, code, index):
        CodeDataCacheUtil.set_cache(self.__latest_cancel_index_cache, code, index)
        self.__save_latest_cancel_index(code, index)
 
    def get_latest_cancel_index_cache(self, code):
        result = CodeDataCacheUtil.get_cache(self.__latest_cancel_index_cache, code)
        if result[0]:
            return result[1]
        return None
 
    pass
 
 
class JCancelBigNumComputer(BaseCancel):
    """
    J撤:
    1000ms内若有三笔,我们后面的涨停撤买L ,
    此时算一次信号,即开始计算我们后面的未撤的所有涨停总额,
    当此总涨停额下降至50%则撤单。
    更新屏幕,3分钟以后有新的信号,
    则重新计算总额。如果3分钟后没有新的信号,
    则沿用上一次计算的后涨停额。
    守护时间14点50分00秒,
    此撤关于我们后面的不想顶而撤,
    导致封单额陡然降低
    """
 
    __cancel_single_cache = {}
 
    __real_place_order_index_info_dict = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(JCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
 
    def set_real_place_order_index(self, code, index, buy_single_index, is_default):
        self.__real_place_order_index_info_dict[code] = (index, is_default)
 
    def __compute_cancel_single(self, code, start_index, end_index):
        """
        计算撤单信号:1000ms内有3笔撤单
        @param code:
        @param start_index: 开始索引
        @param end_index: 结束索引
        @return:
        """
        # 获取真实下单位置
        real_place_order_index_info = self.__real_place_order_index_info_dict.get(code)
        if not real_place_order_index_info or real_place_order_index_info[1]:
            # 尚未获取到真实下单位置
            return
 
        real_place_order_index = real_place_order_index_info[0]
        # 获取撤单信号[时间,真实下单位置, 信号总手数,目前手数,最新计算的索引]
        cancel_single_info = self.__cancel_single_cache.get(code)
        outoftime = False
        total_datas = local_today_datas.get(code)
        if cancel_single_info:
            outoftime = tool.trade_time_sub(total_datas[-1]['val']['time'], cancel_single_info[0]) > 180
            if not outoftime:
                # 上次计算还未超时
                return
        limit_up_price = round(float(gpcode_manager.get_limit_up_price(code)), 2)
 
        if cancel_single_info and outoftime:
            # 更新需要计算信号
            min_volume = 50 * 10000 // int(limit_up_price * 100)
            # 计算本批数据是否有撤单
            single_info = None  # (index, 时间ms)
            for i in range(end_index, start_index - 1, -1):
                data = total_datas[i]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                    continue
                if val['num'] < min_volume:
                    continue
                single_info = (i, L2DataUtil.get_time_with_ms(val))
                break
            if not single_info:
                # "无涨停撤单"
                return
            indexes = [single_info[0]]  # 包含信号笔数
            for i in range(single_info[0] - 1, real_place_order_index, -1):
                data = total_datas[i]
                val = data['val']
                if not L2DataUtil.is_limit_up_price_buy_cancel(val):
                    continue
                if val['num'] < min_volume:
                    continue
                time_ms = L2DataUtil.get_time_with_ms(val)
                if tool.trade_time_sub_with_ms(single_info[1], time_ms) > 1000:
                    break
                indexes.append(i)
                if len(indexes) >= 3:
                    break
            if len(indexes) < 3:
                # 不满足更新条件
                return
        total_count, total_num = L2DataComputeUtil.compute_left_buy_order(code, real_place_order_index + 1,
                                                                          total_datas[-1]['index'], limit_up_price)
        self.__cancel_single_cache[code] = [total_datas[-1]['val']['time'], real_place_order_index, total_num,
                                            total_num,
                                            total_datas[-1]['index']]
        l2_log.j_cancel_debug(code, f"触发囊括:{self.__cancel_single_cache[code]}")
 
    def need_cancel(self, code, start_index, end_index):
        if 1 > 0:
            return False, None, "J撤不生效"
        # 需要先计算
        self.__compute_cancel_single(code, start_index, end_index)
        # [时间, 真实下单位置, 信号总手数, 目前手数, 最新计算的索引]
        cancel_single_info = self.__cancel_single_cache.get(code)
        if not cancel_single_info:
            return False, None, "没有监听"
 
        # 计算剩余数量
        total_datas = local_today_datas.get(code)
        if int(total_datas[end_index]['val']['time'].replace(":", "")) > 145000:
            return False, None, "超过生效时间"
 
        buyno_map = local_today_buyno_map.get(code)
        limit_up_price = round(float(gpcode_manager.get_limit_up_price(code)), 2)
        min_volume = 50 * 10000 // int(limit_up_price * 100)
        # 计算纯买额
        for i in range(start_index, end_index + 1):
            data = total_datas[i]
            val = data['val']
            if data['index'] <= cancel_single_info[4]:
                continue
            if val['num'] < min_volume:
                continue
            if L2DataUtil.is_limit_up_price_buy_cancel(val):
                orderNo = val['orderNo']
                buy_data = buyno_map.get(f"{orderNo}")
                if buy_data and buy_data['index'] > cancel_single_info[1]:
                    cancel_single_info[3] -= val['num']
            elif L2DataUtil.is_limit_up_price_buy(val):
                cancel_single_info[3] += val['num']
            else:
                continue
        cancel_single_info[4] = end_index
        # self.__cancel_single_cache[code] = cancel_single_info
 
        threshold_rate = constant.J_CANCEL_RATE
        if gpcode_manager.MustBuyCodesManager().is_in_cache(code):
            threshold_rate = constant.J_CANCEL_RATE_WITH_MUST_BUY
        cancel_num = cancel_single_info[2] - cancel_single_info[3]
        rate = round(cancel_num / cancel_single_info[2], 2)
        if rate >= threshold_rate:
            return True, total_datas[
                end_index], f"撤单比例达到:{rate}/{threshold_rate} 剩余手数:{cancel_single_info[3]}/{cancel_single_info[2]}"
        return False, None, f"尚未达到撤单比例{rate} , {cancel_num}/{cancel_single_info[2]}"
 
    def __clear_data(self, code):
        if code in self.__cancel_single_cache:
            self.__cancel_single_cache.pop(code)
        if code in self.__real_place_order_index_info_dict:
            self.__real_place_order_index_info_dict.pop(code)
 
    def cancel_success(self, code):
        self.__clear_data(code)
 
    def place_order_success(self, code):
        self.__clear_data(code)
 
 
class NBCancelBigNumComputer(BaseCancel):
    """
    NB撤:
    大市值5分钟内前面没有大单撤
    """
    __real_place_order_index_info_dict = {}
 
    __instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(NBCancelBigNumComputer, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
 
    def set_real_place_order_index(self, code, index, buy_single_index, is_default):
        self.__real_place_order_index_info_dict[code] = (index, is_default)
 
    def need_cancel(self, code, trade_index):
        # [时间, 真实下单位置, 信号总手数, 目前手数, 最新计算的索引]
        real_place_order_index_info = self.__real_place_order_index_info_dict.get(code)
        if not real_place_order_index_info or real_place_order_index_info[1]:
            return False, "没有找到真实下单位"
        real_place_order_index = real_place_order_index_info[0]
 
        limit_up_price = round(float(gpcode_manager.get_limit_up_price(code)), 2)
        if limit_up_price < 3:
            return False, "股价小于3块"
 
        zyltgb = l2_trade_factor.L2TradeFactorUtil.get_zyltgb(code)
        zyltgb_unit_y = round(zyltgb / 100000000, 1)
        if zyltgb_unit_y < 50:
            return False, '自由流通股本小于50亿'
 
        # 计算剩余数量
        total_datas = local_today_datas.get(code)
        if tool.trade_time_sub(tool.get_now_time_str(), total_datas[real_place_order_index]['val']['time']) > 300:
            return False, "超过生效时间"
        total_left_count, total_left_num = L2DataComputeUtil.compute_left_buy_order(code, trade_index,
                                                                                    real_place_order_index,
                                                                                    limit_up_price, 299 * 10000)
        if total_left_count > 0:
            return False, '有大单'
        return True, f'无大单:{trade_index}-{real_place_order_index}'
 
    def __clear_data(self, code):
        if code in self.__real_place_order_index_info_dict:
            self.__real_place_order_index_info_dict.pop(code)
 
    def cancel_success(self, code):
        self.__clear_data(code)
 
    def place_order_success(self, code):
        self.__clear_data(code)
 
 
if __name__ == "__main__":
    pass