File: tamultiseries.pas

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (2583 lines) | stat: -rw-r--r-- 77,967 bytes parent folder | download
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
{
 *****************************************************************************
  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************

  Authors: Alexander Klenin

}

unit TAMultiSeries;

{$MODE ObjFPC}{$H+}
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined}

interface

uses
  Classes, Graphics,
  TAChartUtils, TATypes, TACustomSource, TACustomSeries, TADrawUtils, TALegend;

const
  DEF_BOX_WIDTH = 50;
  DEF_WHISKERS_WIDTH = 25;
  DEF_OHLC_TICK_WIDTH = 25;
  
  DEF_YINDEX_OPEN = 1;
  DEF_YINDEX_HIGH = 3;
  DEF_YINDEX_LOW = 0;
  DEF_YINDEX_CLOSE = 2;
  
  DEF_YINDEX_WHISKERMIN = 0;
  DEF_YINDEX_BOXMIN = 1;
  DEF_YINDEX_CENTER = 2;
  DEF_YINDEX_BOXMAX = 3;
  DEF_YINDEX_WHISKERMAX = 4;

type

  // TBubbleRadiusTransform = (brtNone, brtX, brtY); not used
  TBubbleOverrideColor = (bocBrush, bocPen);
  TBubbleOverrideColors = set of TBubbleOverrideColor;
  TBubbleRadiusUnits = (
    bruX,                // Circle with radius given in x axis units
    bruY,                // Circle with radius given in y axis units
    bruXY,               // Ellipse
    bruPercentageRadius, // Bubble radius is percentage of the smallest dimension of plot area
    bruPercentageArea    // dto., but bubble area
  );

  { TBubbleSeries }

  TBubbleSeries = class(TBasicPointSeries)
  private
    FBubbleBrush: TBrush;
    FBubblePen: TPen;
    FOverrideColor: TBubbleOverrideColors;
    FBubbleRadiusPercentage: Integer;
    FBubbleRadiusUnits: TBubbleRadiusUnits;
    FBubbleScalingFactor: Double;
    procedure SetBubbleBrush(AValue: TBrush);
    procedure SetBubblePen(AValue: TPen);
    procedure SetBubbleRadiusPercentage(AValue: Integer);
    procedure SetBubbleRadiusUnits(AValue: TBubbleRadiusUnits);
    procedure SetOverrideColor(AValue: TBubbleOverrideColors);
  protected
    function CalcBubbleScalingFactor(const ARect: TRect): Double;
    function GetBubbleRect(AItem: PChartDataItem; AFactor: Double; out ARect: TRect): Boolean;
    function GetLabelDataPoint(AIndex, AYIndex: Integer): TDoublePoint; override;
    procedure GetLegendItems(AItems: TChartLegendItems); override;
    function GetSeriesColor: TColor; override;
    class procedure GetXYCountNeeded(out AXCount, AYCount: Cardinal); override;
    function ToolTargetDistance(const AParams: TNearestPointParams;
      AGraphPt: TDoublePoint; APointIdx, AXIdx, AYIdx: Integer): Integer; override;
    procedure UpdateLabelDirectionReferenceLevel(AIndex, AYIndex: Integer;
      var ALevel: Double); override;
    procedure UpdateMargins(ADrawer: IChartDrawer; var AMargins: TRect); override;
  public
    function AddXY(AX, AY, ARadius: Double; AXLabel: String = '';
      AColor: TColor = clTAColor): Integer; overload;
    procedure Assign(ASource: TPersistent); override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Draw(ADrawer: IChartDrawer); override;
    function Extent: TDoubleRect; override;
    function GetNearestPoint(const AParams: TNearestPointParams;
      out AResults: TNearestPointResults): Boolean; override;
    procedure MovePointEx(var AIndex: Integer; AXIndex, AYIndex: Integer;
      const ANewPos: TDoublePoint); override;
  published
    property AxisIndexX;
    property AxisIndexY;
    property BubbleBrush: TBrush read FBubbleBrush write SetBubbleBrush;
    property BubblePen: TPen read FBubblePen write SetBubblePen;
    property BubbleRadiusPercentage: Integer read FBubbleRadiusPercentage
      write SetBubbleRadiusPercentage default 20;
    property BubbleRadiusUnits: TBubbleRadiusUnits read FBubbleRadiusUnits
      write SetBubbleRadiusUnits default bruXY;
    property MarkPositions;
    property Marks;
    property OverrideColor: TBubbleOverrideColors
      read FOverrideColor write SetOverrideColor default [];
    property Source;
    property Styles;
    property ToolTargets default [nptPoint, nptYList, nptCustom];
  end;

  TBoxAndWhiskerSeriesLegendDir = (bwlHorizontal, bwlVertical, bwlAuto);
  TBoxAndWhiskerSeriesWidthStyle = (bwsPercent, bwsPercentMin);
  TBoxAndWhiskerYDataLayout = (bwlNormal, bwlLegacy, bwlCustom);

  TBoxAndWhiskerSeries = class(TBasicPointSeries)
  strict private
    FBoxBrush: TBrush;
    FBoxPen: TPen;
    FBoxWidth: Integer;
    FLegendDirection: TBoxAndWhiskerSeriesLegendDir;
    FMedianPen: TPen;
    FWhiskersPen: TPen;
    FWhiskersWidth: Integer;
    FWidthStyle: TBoxAndWhiskerSeriesWidthStyle;
    FYDataLayout: TBoxAndWhiskerYDataLayout;
    FYIndexWhiskerMin: Integer;
    FYIndexBoxMin: Integer;
    FYIndexCenter: Integer;
    FYIndexBoxMax: Integer;
    FYIndexWhiskerMax: Integer;
    procedure SetBoxBrush(AValue: TBrush);
    procedure SetBoxPen(AValue: TPen);
    procedure SetBoxWidth(AValue: Integer);
    procedure SetLegendDirection(AValue: TBoxAndWhiskerSeriesLegendDir);
    procedure SetMedianPen(AValue: TPen);
    procedure SetWhiskersPen(AValue: TPen);
    procedure SetWhiskersWidth(AValue: Integer);
    procedure SetYDataLayout(AValue: TBoxAndWhiskerYDataLayout);
    procedure SetYIndexBoxMax(AValue: Integer);
    procedure SetYIndexBoxMin(AValue: Integer);
    procedure SetYIndexCenter(AValue: Integer);
    procedure SetYIndexWhiskerMax(AValue: Integer);
    procedure SetYIndexWhiskerMin(AValue: Integer);
    procedure UpdateYDataLayout;
  protected
    procedure GetLegendItems(AItems: TChartLegendItems); override;
    function GetSeriesColor: TColor; override;
    class procedure GetXYCountNeeded(out AXCount, AYCount: Cardinal); override;
    function SkipMissingValues(AIndex: Integer): Boolean; override;
    function ToolTargetDistance(const AParams: TNearestPointParams;
      AGraphPt: TDoublePoint; APointIdx, AXIdx, AYIdx: Integer): Integer; override;
    procedure UpdateLabelDirectionReferenceLevel(AIndex, AYIndex: Integer;
      var ALevel: Double); override;
  public
    function AddXY(
      AX, AYLoWhisker, AYLoBox, AY, AYHiBox, AYHiWhisker: Double;
      AXLabel: String = ''; AColor: TColor = clTAColor): Integer; overload;
    procedure Assign(ASource: TPersistent); override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Draw(ADrawer: IChartDrawer); override;
    function Extent: TDoubleRect; override;
    function GetNearestPoint(const AParams: TNearestPointParams;
      out AResults: TNearestPointResults): Boolean; override;
  published
    property BoxBrush: TBrush read FBoxBrush write SetBoxBrush;
    property BoxPen: TPen read FBoxPen write SetBoxPen;
    property BoxWidth: Integer
      read FBoxWidth write SetBoxWidth default DEF_BOX_WIDTH;
    property LegendDirection: TBoxAndWhiskerSeriesLegendDir
      read FLegendDirection write SetLegendDirection default bwlHorizontal;
    property MedianPen: TPen read FMedianPen write SetMedianPen;
    property ToolTargets default [nptPoint, nptYList, nptCustom];
    property WidthStyle: TBoxAndWhiskerSeriesWidthStyle
      read FWidthStyle write FWidthStyle default bwsPercent;
    property WhiskersPen: TPen read FWhiskersPen write SetWhiskersPen;
    property WhiskersWidth: Integer
      read FWhiskersWidth write SetWhiskersWidth default DEF_WHISKERS_WIDTH;
    property YDataLayout: TBoxAndWhiskerYDataLayout
      read FYDataLayout write SetYDataLayout default bwlLegacy;
    property YIndexBoxMax: Integer
      read FYIndexBoxMax write SetYIndexBoxMax default DEF_YINDEX_BOXMAX;
    property YIndexBoxMin: Integer
      read FYIndexBoxMin write SetYIndexBoxMin default DEF_YINDEX_BOXMIN;
    property YIndexCenter: Integer
      read FYIndexCenter write SetYIndexCenter default DEF_YINDEX_CENTER;
    property YIndexWhiskerMax: Integer
      read FYIndexWhiskerMax write SetYIndexWhiskerMax default DEF_YINDEX_WHISKERMAX;
    property YIndexWhiskerMin: Integer
      read FYIndexWhiskerMin write SetYIndexWhiskerMin default DEF_YINDEX_WHISKERMIN;
  published
    property AxisIndexX;
    property AxisIndexY;
    property MarkPositions;
    property Marks;
    property Source;
  end;

  TOHLCBrushKind = (obkCandleUp, obkCandleDown);
  TOHLCPenKind = (opkCandleUp, opkCandleDown, opkCandleLine, opkLineUp, opkLineDown);

  TOHLCBrush = class(TBrush)
  private
    const
      DEFAULT_COLORS: array[TOHLCBrushKind] of TColor = (clLime, clRed);
  private
    FBrushKind: TOHLCBrushKind;
    function IsColorStored: Boolean;
    procedure SetBrushKind(AValue: TOHLCBrushKind);
  public
    property BrushKind: TOHLCBrushKind read FBrushKind write SetBrushKind;
  published
    property Color stored IsColorStored;
  end;

  TOHLCPen = class(TPen)
  private
    const
      DEFAULT_COLORS: array[TOHLCPenKind] of TColor = (clGreen, clMaroon, clDefault, clLime, clRed);
  private
    FPenKind: TOHLCPenKind;
    function IsColorStored: Boolean;
    procedure SetPenKind(AValue: TOHLCPenKind);
  public
    property PenKind: TOHLCPenKind read FPenKind write SetPenKind;
  published
    property Color stored IsColorStored;
  end;

  TOHLCMode = (mOHLC, mCandleStick);
  TTickWidthStyle = (twsPercent, twsPercentMin);

  TOpenHighLowCloseSeries = class(TBasicPointSeries)
  private
    FPen: array[TOHLCPenKind] of TOHLCPen;
    FBrush: array[TOHLCBrushKind] of TOHLCBrush;
    FTickWidth: Integer;
    FTickWidthStyle: TTickWidthStyle;
    FYIndexClose: Integer;
    FYIndexHigh: Integer;
    FYIndexLow: Integer;
    FYIndexOpen: Integer;
    FMode: TOHLCMode;
    function GetBrush(AIndex: TOHLCBrushKind): TOHLCBrush;
    function GetPen(AIndex: TOHLCPenKind): TOHLCPen;
    procedure SetBrush(AIndex: TOHLCBrushKind; AValue: TOHLCBrush);
    procedure SetPen(AIndex: TOHLCPenKind; AValue: TOHLCPen);
    procedure SetOHLCMode(AValue: TOHLCMode);
    procedure SetTickWidth(AValue: Integer);
    procedure SetTickWidthStyle(AValue: TTickWidthStyle);
    procedure SetYIndexClose(AValue: Integer);
    procedure SetYIndexHigh(AValue: Integer);
    procedure SetYIndexLow(AValue: Integer);
    procedure SetYIndexOpen(AValue: Integer);
  protected
    function CalcTickWidth(AX: Double; AIndex: Integer): Double;
    procedure GetLegendItems(AItems: TChartLegendItems); override;
    function GetSeriesColor: TColor; override;
    class procedure GetXYCountNeeded(out AXCount, AYCount: Cardinal); override;
    function SkipMissingValues(AIndex: Integer): Boolean; override;
    function ToolTargetDistance(const AParams: TNearestPointParams;
      AGraphPt: TDoublePoint; APointIdx, AXIdx, AYIdx: Integer): Integer; override;
    procedure UpdateLabelDirectionReferenceLevel(AIndex, AYIndex: Integer;
      var ALevel: Double); override;
  public
    procedure Assign(ASource: TPersistent); override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  public
    function AddXOHLC(
      AX, AOpen, AHigh, ALow, AClose: Double;
      ALabel: String = ''; AColor: TColor = clTAColor): Integer; inline;
    procedure Draw(ADrawer: IChartDrawer); override;
    function Extent: TDoubleRect; override;
    function GetNearestPoint(const AParams: TNearestPointParams;
      out AResults: TNearestPointResults): Boolean; override;
  published
    property CandlestickDownBrush: TOHLCBrush index obkCandleDown read GetBrush write SetBrush;
    property CandlestickDownPen: TOHLCPen index opkCandleDown read GetPen write SetPen;
    property CandlestickLinePen: TOHLCPen index opkCandleLine read GetPen write SetPen;
    property CandlestickUpBrush: TOHLCBrush index obkCandleUp read GetBrush write SetBrush;
    property CandlestickUpPen: TOHLCPen index opkCandleUp read GetPen write Setpen;
    property DownLinePen: TOHLCPen index opkLineDown read GetPen write SetPen;
    property LinePen: TOHLCPen index opkLineUp read GetPen write SetPen;
    property Mode: TOHLCMode read FMode write SetOHLCMode default mOHLC;
    property TickWidth: integer
      read FTickWidth write SetTickWidth default DEF_OHLC_TICK_WIDTH;
    property TickWidthStyle: TTickWidthStyle
      read FTickWidthStyle write SetTickWidthStyle default twsPercent;
    property ToolTargets default [nptPoint, nptYList, nptCustom];
    property YIndexClose: integer
      read FYIndexClose write SetYIndexClose default DEF_YINDEX_CLOSE;
    property YIndexHigh: Integer
      read FYIndexHigh write SetYIndexHigh default DEF_YINDEX_HIGH;
    property YIndexLow: Integer
      read FYIndexLow write SetYIndexLow default DEF_YINDEX_LOW;
    property YIndexOpen: Integer
      read FYIndexOpen write SetYIndexOpen default DEF_YINDEX_OPEN;
  published
    property AxisIndexX;
    property AxisIndexY;
    property MarkPositions;
    property Marks;
    property Source;
  end;

  TVectorCoordKind = (vckCenterDir, vckStartEnd);

  TFieldSeries = class(TBasicPointSeries)
  private
    FArrow: TChartArrow;
    FPen: TPen;
    FCoordKind: TVectorCoordKind;
    procedure SetArrow(AValue: TChartArrow);
    procedure SetCoordKind(AValue: TVectorCoordKind);
    procedure SetPen(AValue: TPen);
  protected
    procedure AfterAdd; override;
    procedure DrawVector(ADrawer: IChartDrawer; AStartPt, AEndPt: TDoublePoint;
      APen: TPen);
    function GetColor(AIndex: Integer): TColor; inline;
    function GetVectorPoints(AIndex: Integer;
      out AStartPt, AEndPt: TDoublePoint): Boolean; inline;
    class procedure GetXYCountNeeded(out AXCount, AYCount: Cardinal); override;
  public
    procedure Assign(ASource: TPersistent); override;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    function AddVector(AX, AY, AVectorX, AVectorY: Double; AXLabel: String = '';
      AColor: TColor = clTAColor): Integer; //inline;
    function GetVector(AIndex: Integer): TDoublePoint; inline;
    procedure SetVector(AIndex: Integer; const AValue: TDoublePoint); inline;

    procedure Draw(ADrawer: IChartDrawer); override;
    function Extent: TDoubleRect; override;
    procedure GetLegendItems(AItems: TChartLegendItems); override;
    function GetNearestPoint(const AParams: TNearestPointParams;
      out AResults: TNearestPointResults): Boolean; override;
    procedure MovePointEx(var AIndex: Integer; AXIndex, AYIndex: Integer;
      const ANewPos: TDoublePoint); override;
    procedure NormalizeVectors(ALength: Double);

  published
    property Arrow: TChartArrow read FArrow write SetArrow;
    property AxisIndexX;
    property AxisIndexY;
    property MarkPositions;
    property Marks;
    property Pen: TPen read FPen write SetPen;
    property Source;
    property ToolTargets default [nptPoint, nptXList, nptYList, nptCustom];
    property VectorCoordKind: TVectorCoordKind read FCoordKind write SetCoordKind default vckCenterDir;
  end;

implementation

uses
  FPCanvas, Math, SysUtils, Types,
  TAChartStrConsts, TAGeometry, TAGraph, TAMath;

type

  TLegendItemOHLCLine = class(TLegendItemLine)
  strict private
    FMode: TOHLCMode;
    FCandleStickUpColor: TColor;
    FCandleStickDownColor: TColor;
  public
    constructor Create(ASeries: TOpenHighLowCloseSeries; const AText: String);
    procedure Draw(ADrawer: IChartDrawer; const ARect: TRect); override;
  end;

  TLegendItemBoxAndWhiskers = class(TLegendItem)
  strict private
    FBoxBrush: TBrush;
    FBoxPen: TPen;
    FBoxWidth: Integer;
    FIsVertical: Boolean;
    FMedianPen: TPen;
    FWhiskersPen: TPen;
    FWhiskersWidth: Integer;
  public
    constructor Create(ASeries: TBoxAndWhiskerSeries; const AText: String);
    procedure Draw(ADrawer: IChartDrawer; const ARect: TRect); override;
  end;

  TLegendItemField = class(TLegendItemLine)
  strict private
    FArrow: TChartArrow;
  public
    constructor Create(APen: TPen; AArrow: TChartArrow; const AText: String);
    procedure Draw(ADrawer: IChartDrawer; const ARect: TRect); override;
  end;

{ TLegendItemOHLCLine }

constructor TLegendItemOHLCLine.Create(ASeries: TOpenHighLowCloseSeries; const AText: String);
var
  pen: TFPCustomPen;
begin
  case ASeries.Mode of
    mOHLC        : pen := ASeries.LinePen;
    mCandleStick : pen := ASeries.CandleStickLinePen;
  end;
  inherited Create(pen, AText);
  FMode := ASeries.Mode;
  FCandlestickUpColor := ASeries.CandlestickUpBrush.Color;
  FCandlestickDownColor := ASeries.CandlestickDownBrush.Color;
end;

procedure TLegendItemOHLCLine.Draw(ADrawer: IChartDrawer; const ARect: TRect);
const
  TICK_LENGTH = 3;
var
  dx, dy, x, y: Integer;
  pts: array[0..3] of TPoint;
begin
  inherited Draw(ADrawer, ARect);
  y := (ARect.Top + ARect.Bottom) div 2;
  dx := (ARect.Right - ARect.Left) div 3;
  x := ARect.Left + dx;
  case FMode of
    mOHLC:
      begin
        dy := ADrawer.Scale(TICK_LENGTH);
        ADrawer.Line(x, y, x, y + dy);
        x += dx;
        ADrawer.Line(x, y, x, y - dy);
      end;
    mCandlestick:
      begin
        dy := (ARect.Bottom - ARect.Top) div 4;
        pts[0] := Point(x, y-dy);
        pts[1] := Point(x, y+dy);
        pts[2] := Point(x+dx, y+dy);
        pts[3] := pts[0];
        ADrawer.SetBrushParams(bsSolid, FCandlestickUpColor);
        ADrawer.Polygon(pts, 0, 4);
        pts[0] := Point(x+dx, y+dy);
        pts[1] := Point(x+dx, y-dy);
        pts[2] := Point(x, y-dy);
        pts[3] := pts[0];
        ADrawer.SetBrushParams(bsSolid, FCandlestickDownColor);
        ADrawer.Polygon(pts, 0, 4);
      end;
  end;
end;

{ TLegendItemBoxAndWhiskers }

constructor TLegendItemBoxAndWhiskers.Create(
  ASeries: TBoxAndWhiskerSeries; const AText: String);
begin
  inherited Create(AText);
  with ASeries do begin
    FBoxBrush := BoxBrush;
    FBoxPen := BoxPen;
    FBoxWidth := BoxWidth;
    FIsVertical :=
      (LegendDirection = bwlVertical) or
      (LegendDirection = bwlAuto) and IsRotated;
    FMedianPen := MedianPen;
    FWhiskersPen := WhiskersPen;
    FWhiskersWidth := WhiskersWidth;
  end;
end;

procedure TLegendItemBoxAndWhiskers.Draw(
  ADrawer: IChartDrawer; const ARect: TRect);

  function FlipRect(const AR: TRect): TRect;
  begin
    Result := Rect(AR.Top, AR.Left, AR.Bottom, AR.Right);
  end;

var
  symbol: array [1..5] of TRect;
var
  center: TPoint;
  i, m, ww, bw: Integer;
  r: TRect;
begin
  inherited Draw(ADrawer, ARect);
  r := ARect;
  r.BottomRight -= Point(1, 1);
  if FIsVertical then
    r := FlipRect(r);

  center := (r.TopLeft + r.BottomRight) div 2;
  m := MaxValue([FWhiskersWidth, FBoxWidth, 1]) * 2;
  ww := (r.Bottom - r.Top) * FWhiskersWidth div m;
  symbol[1] := Rect(r.Left, center.y, r.Right, center.y);
  symbol[2] := Rect(r.Left, center.y - ww, r.Left, center.y + ww + 1);
  symbol[3] := Rect(r.Right, center.y - ww, r.Right, center.y + ww + 1);
  bw := (r.Bottom - r.Top) * FBoxWidth div m;
  symbol[4] := Rect(
    (r.Left * 2 + r.Right) div 3, center.y - bw,
    (r.Left + r.Right * 2) div 3, center.y + bw);
  bw -= Math.IfThen(FBoxPen.Style = psClear, 0, (FBoxPen.Width + 1) div 2);
  symbol[5] := Rect(center.x, center.y - bw, center.x, center.y + bw);

  if FIsVertical then
    for i := 1 to High(symbol) do
      symbol[i] := FlipRect(symbol[i]);

  // Whisker
  ADrawer.Pen := FWhiskersPen;
  ADrawer.SetPenColor(FWhiskersPen.Color);
  ADrawer.SetBrushParams(bsClear, clTAColor);
  for i := 1 to 3 do
    ADrawer.Line(symbol[i].TopLeft, symbol[i].BottomRight);

  // Box
  ADrawer.Pen := FBoxPen;
  ADrawer.SetPenColor(FBoxPen.Color);
  ADrawer.Brush:= FBoxBrush;
  ADrawer.SetBrushColor(FBoxBrush.Color);
  ADrawer.Rectangle(symbol[4]);

  // Median line
  ADrawer.Pen := FMedianPen;
  ADrawer.SetPenColor(FMedianPen.Color);
  ADrawer.Line(symbol[5].TopLeft, symbol[5].BottomRight);
end;

{ TLegendItemField }

constructor TLegendItemField.Create(APen: TPen; AArrow: TChartArrow;
  const AText: String);
begin
  inherited Create(APen, AText);
  FArrow := AArrow;
end;

procedure TLegendItemField.Draw(ADrawer: IChartDrawer; const ARect: TRect);
var
  y: Integer;
  len: Double;
  arr: TChartArrow;
begin
  inherited Draw(ADrawer, ARect);
  if (FPen = nil) or (FArrow = nil) or not FArrow.Visible then
    exit;
  len := (ARect.Right - ARect.Left) * 0.01;
  arr := TChartArrow.Create(nil);
  try
    arr.Assign(FArrow);
    arr.SetOwner(nil);
    arr.BaseLength := round(FArrow.BaseLength * len);
    arr.Length := round(FArrow.Length * len);
    arr.Width := round(FArrow.Width * len);
    y := (ARect.Top + ARect.Bottom) div 2;
    arr.Draw(ADrawer, Point(ARect.Right, y), 0, FPen);
  finally
    arr.Free;
  end;
end;


{ TBubbleSeries }

function TBubbleSeries.AddXY(AX, AY, ARadius: Double; AXLabel: String;
  AColor: TColor): Integer;
begin
  Result := AddXY(AX, AY, [ARadius], AXLabel, AColor);
end;

procedure TBubbleSeries.Assign(ASource: TPersistent);
begin
  if ASource is TBubbleSeries then
    with TBubbleSeries(ASource) do begin
      Self.BubbleBrush := FBubbleBrush;
      Self.BubblePen := FBubblePen;
      Self.BubbleRadiusUnits := FBubbleRadiusUnits;
      Self.BubbleRadiusPercentage := FBubbleRadiusPercentage;
      Self.OverrideColor := FOverrideColor;
    end;
  inherited Assign(ASource);
end;

{ Adjusts a scaling factor such that the largest bubble radius is the
  given percentage (FBubbleRadiusPercentage) of the smallest edge of
  the chart area (ARect). }
function TBubbleSeries.CalcBubbleScalingFactor(const ARect: TRect): Double;
var
  rMin: Double = 0.0;
  rMax: Double = 0.0;
begin
  if FBubbleRadiusUnits in [bruPercentageRadius, bruPercentageArea] then
  begin
    Source.YRange(1, rMin, rMax);
    if FBubbleRadiusUnits = bruPercentageArea then
      rMax := sqrt(abs(rMax));
    Result := Min(ARect.Width, ARect.Height) * FBubbleRadiusPercentage * PERCENT / abs(rMax);
  end else
    Result := 1.0;
end;

constructor TBubbleSeries.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  ToolTargets := [nptPoint, nptYList, nptCustom];
  FBubblePen := TPen.Create;
  FBubblePen.OnChange := @StyleChanged;
  FBubbleBrush := TBrush.Create;
  FBubbleBrush.OnChange := @StyleChanged;
  FBubbleRadiusPercentage := 20;
  FBubbleRadiusUnits := bruXY;
  FBubbleScalingFactor := 1.0;
end;

destructor TBubbleSeries.Destroy;
begin
  FreeAndNil(FBubbleBrush);
  FreeAndNil(FBubblePen);
  inherited Destroy;
end;

procedure TBubbleSeries.Draw(ADrawer: IChartDrawer);
var
  i: Integer;
  item: PChartDataItem;
  clipR: TRect;
  irect: TRect;
  dummyR: TRect = (Left:0; Top:0; Right:0; Bottom:0);
  ext: TDoubleRect;
  nx, ny: Cardinal;
begin
  if IsEmpty or (not Active) then exit;
  if not RequestValidChartScaling then exit;

  ADrawer.Pen := BubblePen;
  if BubblePen.Color = clDefault then
    ADrawer.SetPenColor(FChart.GetDefaultColor(dctFont))
  else
    ADrawer.SetPenColor(BubblePen.Color);
  ADrawer.Brush := BubbleBrush;
  if BubbleBrush.Color = clDefault then
    ADrawer.SetBrushColor(FChart.GetDefaultColor(dctBrush))
  else
    ADrawer.SetBrushColor(BubbleBrush.Color);

  ext := ParentChart.CurrentExtent;
  clipR.TopLeft := ParentChart.GraphToImage(ext.a);
  clipR.BottomRight := ParentChart.GraphToImage(ext.b);
  NormalizeRect(clipR);
  ADrawer.ClippingStart(clipR);

  FBubbleScalingFactor := CalcBubbleScalingFactor(clipR);

  for i := 0 to Count - 1 do begin
    item := Source[i];
    if not GetBubbleRect(item, FBubbleScalingFactor, irect) then
      continue;
    if not IntersectRect(dummyR, clipR, irect) then
      continue;
    if bocPen in OverrideColor then
      ADrawer.SetPenParams(BubblePen.Style, ColorDef(item^.Color, BubblePen.Color));
    if bocBrush in OverrideColor then
      ADrawer.SetBrushColor(ColorDef(item^.Color, BubbleBrush.Color));

    if Styles <> nil then
      Styles.Apply(ADrawer, i);

    ADrawer.Ellipse(irect.Left, irect.Top, irect.Right, irect.Bottom);
  end;

  GetXYCountNeeded(nx, ny);
  if Source.YCount >= ny then
    for i := 0 to ny - 1 do DrawLabels(ADrawer, i)
  else
    DrawLabels(ADrawer);

  ADrawer.ClippingStop;
end;

{ Calculates the extent of the series such that bubbles are not clipped.
  But note that this method is correct only for BubbleRadiusUnits bruXY, it
  would crash for bruX and bruY. Adjust Chart.Margins or Chart.ExpandPercentage
  in these cases. }
function TBubbleSeries.Extent: TDoubleRect;
var
  i: Integer;
  r: Double;
  sp, gp, gq, rp: TDoublePoint;
  item: PChartDataItem;
begin
  Result := EmptyExtent;
  if IsEmpty then exit;
  if not RequestValidChartScaling then exit;

  if FBubbleRadiusUnits = bruXY then
  begin
    for i := 0 to Count - 1 do begin
      item := Source[i];
      sp := item^.Point;
      if TAChartUtils.IsNaN(sp) then
        continue;
      r := item^.YList[0];
      if Math.IsNaN(r) then
        continue;
      rp := DoublePoint(r, r);
      gp := AxisToGraph(sp);
      gq := AxisToGraph(sp + rp);
      rp := gq - gp;

      Result.a.X := Min(Result.a.X, sp.x - rp.x);
      Result.b.X := Max(Result.b.X, sp.x + rp.x);
      Result.a.Y := Min(Result.a.Y, sp.y - rp.y);
      Result.b.Y := Max(Result.b.Y, sp.y + rp.y);
    end;
  end else
    Result := Source.BasicExtent;
end;

function TBubbleSeries.GetBubbleRect(AItem: PChartDataItem;
  AFactor: Double; out ARect: TRect): Boolean;
var
  sp: TDoublePoint;    // source point in axis units
  p: TPoint;           // bubble center in image units
  q: TPoint;           // bubble center offset by 1 radius, in image units
  r: Double;           // radius in axis units
  ri: Integer;         // radius in image units
begin
  Result := false;
  sp := AItem^.Point;
  if TAChartUtils.IsNaN(sp) then
    exit;
  r := AItem^.YList[0];
  if Math.IsNaN(r) then
    exit;

  case FBubbleRadiusUnits of
    bruX:
      begin
        p := ParentChart.GraphToImage(AxisToGraph(sp));
        q := ParentChart.GraphToImage(AxisToGraph(sp + DoublePoint(r, 0)));  // offset along x
        if IsRotated then ri := q.y - p.y else ri := q.x - p.x;
        ARect := Rect(p.x - ri, p.y - ri, p.x + ri, p.y + ri);
      end;
    bruY:
      begin
        p := ParentChart.GraphToImage(AxisToGraph(sp));
        q := ParentChart.GraphToImage(AxisToGraph(sp + DoublePoint(0, r)));  // offset along y
        if IsRotated then ri := q.x - p.x else ri := q.y - p.y;
        ARect := Rect(p.x - ri, p.y - ri, p.x + ri, p.y + ri);
      end;
    bruXY:
      begin
        ARect.TopLeft := ParentChart.GraphToImage(AxisToGraph(DoublePoint(sp.x - r, sp.y - r)));
        ARect.BottomRight := ParentChart.GraphToImage(AxisToGraph(DoublePoint(sp.x + r, sp.y + r)));
      end;
    bruPercentageRadius:
      begin
        p := ParentChart.GraphToImage(AxisToGraph(sp));
        ri := round(r * AFactor);
        ARect := Rect(p.x - ri, p.y - ri, p.x + ri, p.y + ri);
      end;
    bruPercentageArea:
      begin
        p := ParentChart.GraphToImage(AxisToGraph(sp));
        ri := round(sqrt(abs(r)) * AFactor);
        ARect := Rect(p.x - ri, p.y - ri, p.x + ri, p.y + ri);
      end;
  end;
  NormalizeRect(ARect);
  Result := true;
end;

function TBubbleSeries.GetLabelDataPoint(AIndex, AYIndex: Integer): TDoublePoint;
const
  DIRECTION: array [Boolean, Boolean] of TLabelDirection =
    ((ldTop, ldBottom), (ldRight, ldLeft));
  IS_NEGATIVE: array[TLinearMarkPositions] of boolean =
    (true,        false,       true,        false);
    //lmpOutside, lmpPositive, lmpNegative, lmpInside
var
  R: TRect;
  RArray: array[0..3] of Integer absolute R;
  isneg: Boolean;
  dir: TLabelDirection;
begin
  if (AYIndex = 1) and GetBubbleRect(Source.Item[AIndex + FLoBound], FBubbleScalingFactor, R) then begin
    isNeg := IS_NEGATIVE[MarkPositions];
    if Assigned(GetAxisY) then
      if (IsRotated and ParentChart.IsRightToLeft) xor GetAxisY.Inverted then
        isNeg := not isNeg;
    dir := DIRECTION[IsRotated, isNeg];
    if IsRotated then
      Result := ParentChart.ImageToGraph(Point(RArray[ord(dir)], (R.Top + R.Bottom) div 2))
    else
      Result := ParentChart.ImageToGraph(Point((R.Left + R.Right) div 2, RArray[ord(dir)]));
  end else
    Result := GetGraphPoint(AIndex, 0, 0);
end;

procedure TBubbleSeries.GetLegendItems(AItems: TChartLegendItems);
begin
  GetLegendItemsRect(AItems, BubbleBrush, BubblePen);
end;

function TBubbleSeries.GetNearestPoint(const AParams: TNearestPointParams;
  out AResults: TNearestPointResults): Boolean;
var
  i: Integer;
  item: PChartDataItem;
  iRect: TRect;
  p: TPoint;
  dperim: Integer;      // Distance of perimeter point from center of bubble
  d, dist: Integer;
  phi: Double;
  rx, ry: Integer;
  cosphi, sinphi: Math.float;
begin
  Result := inherited;
  if IsEmpty or not RequestValidChartScaling then exit;
  if Result and (nptPoint in AParams.FTargets) and (nptPoint in ToolTargets) then
    if (AResults.FYIndex = 0) then
      exit;

  if Result and (nptYList in AParams.FTargets) and (nptYList in ToolTargets) then
    if (AResults.FYIndex = 1) then begin
      item := Source[AResults.FIndex];
      GetBubbleRect(item, FBubbleScalingFactor, iRect);
      rx := (iRect.Right - iRect.Left) div 2;
      ry := (iRect.Bottom - iRect.Top) div 2;
      p := ParentChart.GraphToImage(AxisToGraph(item^.Point));
      phi := arctan2(AParams.FPoint.Y - p.y, AParams.FPoint.X - p.x);
      SinCos(phi, sinphi, cosphi);
      AResults.FImg := p + Point(round(rx * cosPhi), round(ry * sinPhi));
      exit;
    end;

  if (nptCustom in AParams.FTargets) and (nptCustom in ToolTargets) then begin
    dist := MaxInt;
    for i := 0 to Count - 1 do begin
      item := Source[i];
      if not GetBubbleRect(item, FBubbleScalingFactor, irect) then
        continue;
      rx := (iRect.Right - iRect.Left) div 2;
      ry := (iRect.Bottom - iRect.Top) div 2;
      p := ParentChart.GraphToImage(AxisToGraph(item^.Point));
      phi := -arctan2(AParams.FPoint.Y - p.y, AParams.FPoint.X - p.x);
      SinCos(phi, sinphi, cosphi);
      dperim := round(sqrt(sqr(rx * cosPhi) + sqr(ry * sinPhi)));
      d := round(sqrt(PointDistSq(p, AParams.FPoint)));
      if (d < dist) and (d < dperim + AParams.FRadius) then begin  // not quite exact...
        dist := d;
        AResults.FDist := d;
        AResults.FIndex := i;
        AResults.FYIndex := -1;
        AResults.FValue := item^.Point;
        AResults.FImg := AParams.FPoint;
        if d = 0 then break;
      end;
    end;
    if AResults.FIndex <> -1 then begin
      AResults.FDist := sqr(AResults.FDist);  // we need sqr for comparison with other series
      Result := true;
    end;
  end;
end;

function TBubbleSeries.GetSeriesColor: TColor;
begin
  Result := FBubbleBrush.Color;
end;

class procedure TBubbleSeries.GetXYCountNeeded(out AXCount, AYCount: Cardinal);
begin
  AXCount := 1;
  AYCount := 2;
end;

procedure TBubbleSeries.MovePointEx(var AIndex: Integer;
  AXIndex, AYIndex: Integer; const ANewPos: TDoublePoint);
var
  np: TDoublePoint;   // ANewPos, in axis units
  sp: TDoublePoint;   // Orig data point (source point), in axis units
  gp: TDoublePoint;   // Orig data point, in graph units
  ip: TPoint;         // original data point, in image units
  r: Double;          // radius, in axis units
  inp: TPoint;        // NewPos in image units
  rvec: TDoublePoint; // Rotated radius vector
begin
  Unused(AXIndex);

  ParentChart.DisableRedrawing;
  ListSource.BeginUpdate;
  try
    case AYIndex of
      -1,
       0: begin
            np := GraphToAxis(ANewPos);
            ListSource.SetXValue(AIndex, np.X);
            ListSource.SetYValue(AIndex, np.Y);
          end;
      1:  begin
            sp := ListSource.Item[AIndex]^.Point;
            gp := AxisToGraph(sp);
            case FBubbleRadiusUnits of
              bruX:
                begin
                  inp := ParentChart.GraphToImage(ANewPos);
                  ip := ParentChart.GraphToImage(gp);
                  // Distance data pt to ANewPos, in image units
                  r := sqrt(sqr(ip.X - inp.X) + sqr(ip.Y - inp.Y));
                  // Vector from bubble center to right bubble perimeter, in axis units
                  rvec := GraphToAxis(ParentChart.ImageToGraph(Point(ip.x + round(r), ip.y))) - sp;
                  // Radius of the circle
                  r := abs(rvec.x);
                end;
              bruY:
                begin
                  // like bruX, but with y instead of x
                  inp := ParentChart.GraphToImage(ANewPos);
                  ip := ParentChart.GraphToImage(gp);
                  r := sqrt(sqr(ip.X - inp.X) + sqr(ip.Y - inp.Y));
                  rvec := GraphToAxis(ParentChart.ImageToGraph(Point(ip.x, ip.y + round(r)))) - sp;
                  r := abs(rvec.y);
                end;
              bruXY:
                begin
                  // Blubble radius is the distance between data pt and mouse pt, in axis units
                  np := GraphToAxis(ANewPos);
                  rvec := np - sp;
                  r := sqrt(sqr(rvec.x) + sqr(rvec.y));
                end;
            end;
            ListSource.SetYList(AIndex, [r]);
          end;
    end;
  finally
    ListSource.EndUpdate;
    ParentChart.EnableRedrawing;
    UpdateParentChart;
  end;
end;

procedure TBubbleSeries.SetBubbleBrush(AValue: TBrush);
begin
  if FBubbleBrush = AValue then exit;
  FBubbleBrush.Assign(AValue);
  UpdateParentChart;
end;

procedure TBubbleSeries.SetBubblePen(AValue: TPen);
begin
  if FBubblePen = AValue then exit;
  FBubblePen.Assign(AValue);
  UpdateParentChart;
end;

procedure TBubbleSeries.SetBubbleRadiusPercentage(AValue: Integer);
begin
  if FBubbleRadiusPercentage = AValue then exit;
  FBubbleRadiusPercentage := AValue;
  UpdateParentChart;
end;

procedure TBubbleSeries.SetBubbleRadiusUnits(AValue: TBubbleRadiusUnits);
begin
  if FBubbleRadiusUnits = AValue then exit;
  FBubbleRadiusUnits := AValue;
  UpdateParentChart;
end;

procedure TBubbleSeries.SetOverrideColor(AValue: TBubbleOverrideColors);
begin
  if FOverrideColor = AValue then exit;
  FOverrideColor := AValue;
  UpdateParentChart;
end;

function TBubbleSeries.ToolTargetDistance(const AParams: TNearestPointParams;
  AGraphPt: TDoublePoint; APointIdx, AXIdx, AYIdx: Integer): Integer;
var
  item: PChartDataItem;
  iRect: TRect;
  rx, ry: Integer;
  d, dPerim: Integer;
  p: TPoint;
  phi, sinPhi, cosPhi: Math.float;
begin
  if AYIdx = 0 then begin
    Result := inherited;
    exit;
  end;

  item := Source[APointIdx];
  GetBubbleRect(item, FBubbleScalingFactor, iRect);
  rx := (iRect.Right - iRect.Left) div 2;
  ry := (iRect.Bottom - iRect.Top) div 2;
  p := ParentChart.GraphToImage(AxisToGraph(item^.Point));
  d := round(sqrt(PointDistSq(p, AParams.FPoint)));  // dist between data pt and clicked pt
  phi := -arctan2(AParams.FPoint.Y - p.y, AParams.FPoint.X - p.x);
  SinCos(phi, sinphi, cosphi);
  dperim := round(sqrt((sqr(rx * cosPhi) + sqr(ry * sinPhi))));

  if AYIdx = 1 then
    Result := sqr(abs(d - dperim))
  else begin
    Result := PointDistSq(p, AParams.FPoint);
    if sqrt(Result) > dperim then
      Result := MaxInt;
  end;
end;

procedure TBubbleSeries.UpdateLabelDirectionReferenceLevel(AIndex, AYIndex: Integer;
  var ALevel: Double);
begin
  Unused(AIndex);
  case AYIndex of
    0: ALevel := -Infinity;
    1: ALevel := +Infinity;
  end;
end;

procedure TBubbleSeries.UpdateMargins(ADrawer: IChartDrawer;
  var AMargins: TRect);
var
  i, dist, j: Integer;
  labelText: String;
  dir: TLabelDirection;
  m: array [TLabelDirection] of Integer absolute AMargins;
  gp: TDoublePoint;
  scMarksDistance: Integer;
  center: Double;
begin
  if not Marks.IsMarkLabelsVisible or not Marks.AutoMargins then exit;
  if IsEmpty then exit;
  if not RequestValidChartScaling then exit;

  FindExtentInterval(ParentChart.CurrentExtent, Source.IsSortedByXAsc);
  with Extent do
    center := AxisToGraphY((a.y + b.y) * 0.5);
  UpdateLabelDirectionReferenceLevel(0, 0, center);
  scMarksDistance := ADrawer.Scale(Marks.Distance);

  for i := FLoBound to FUpBound do begin
    for j := 0 to Min(1, Source.YCount-1) do begin
      gp := GetLabelDataPoint(i, j);
      if not ParentChart.IsPointInViewPort(gp) then break;
      labelText := FormattedMark(i, '', j);
      if labelText = '' then break;
      UpdateLabelDirectionReferenceLevel(i, j, center);
      dir := GetLabelDirection(TDoublePointBoolArr(gp)[not IsRotated], center);
      with Marks.MeasureLabel(ADrawer, labelText) do
        dist := Math.IfThen(dir in [ldLeft, ldRight], cx, cy);
      if Marks.DistanceToCenter then
        dist := dist div 2;
      m[dir] := Max(m[dir], dist + scMarksDistance);
    end;
  end;
end;



{ TBoxAndWhiskerSeries }

function TBoxAndWhiskerSeries.AddXY(
  AX, AYLoWhisker, AYLoBox, AY, AYHiBox, AYHiWhisker: Double; AXLabel: String;
  AColor: TColor): Integer;
var
  y: Double;
begin
  if FYIndexWhiskerMin = 0 then
    y := AYLoWhisker
  else if FYIndexBoxMin = 0 then
    y := AYLoBox
  else if FYIndexCenter = 0 then
    y := AY
  else if FYIndexBoxMax = 0 then
    y := AYHiBox
  else if FYIndexWhiskerMax = 0 then
    y := AYHiWhisker
  else
    raise Exception.Create('[TBoxAndWhiskerSeries.AddXY] Ordinary y value missing');

  Result := ListSource.Add(AX, y, AXLabel, AColor);
  with ListSource.Item[Result]^ do begin
    SetY(FYIndexWhiskerMin, AYLoWhisker);
    SetY(FYIndexBoxMin, AYLoBox);
    SetY(FYIndexCenter, AY);
    SetY(FYIndexBoxMax, AYHiBox);
    SetY(FYIndexWhiskerMax, AYHiWhisker);
  end;
end;

procedure TBoxAndWhiskerSeries.Assign(ASource: TPersistent);
begin
  if ASource is TBoxAndWhiskerSeries then
    with TBoxAndWhiskerSeries(ASource) do begin
      Self.BoxBrush.Assign(FBoxBrush);
      Self.BoxPen.Assign(FBoxPen);
      Self.FBoxWidth := FBoxWidth;
      Self.MedianPen.Assign(FMedianPen);
      Self.WhiskersPen.Assign(FWhiskersPen);
      Self.FWhiskersWidth := FWhiskersWidth;
      Self.FYDataLayout := FYDataLayout;
      Self.FYIndexWhiskerMin := FYIndexWhiskerMin;
      Self.FYIndexBoxMin := FYIndexBoxMin;
      Self.FYIndexCenter := FYIndexCenter;
      Self.FYIndexBoxMax := FYIndexBoxMax;
      Self.FYIndexWhiskerMax := FYIndexWhiskerMax;
    end;
  inherited Assign(ASource);
end;

constructor TBoxAndWhiskerSeries.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  ToolTargets := [nptPoint, nptYList, nptCustom];
  FOptimizeX := false;
  FBoxBrush := TBrush.Create;
  FBoxBrush.OnChange := @StyleChanged;
  FBoxPen := TPen.Create;
  FBoxPen.OnChange := @StyleChanged;
  FBoxWidth := DEF_BOX_WIDTH;
  FMedianPen := TPen.Create;
  FMedianPen.OnChange := @StyleChanged;
  FWhiskersPen := TPen.Create;
  FWhiskersPen.OnChange := @StyleChanged;
  FWhiskersWidth := DEF_WHISKERS_WIDTH;
  FYDataLayout := bwlLegacy;
  FYIndexWhiskerMin := DEF_YINDEX_WHISKERMIN;
  FYIndexBoxMin := DEF_YINDEX_BOXMIN;
  FYIndexCenter := DEF_YINDEX_CENTER;
  FYIndexBoxMax := DEF_YINDEX_BOXMAX;
  FYIndexWhiskerMax := DEF_YINDEX_WHISKERMAX;
end;

destructor TBoxAndWhiskerSeries.Destroy;
begin
  FreeAndNil(FBoxBrush);
  FreeAndNil(FBoxPen);
  FreeAndNil(FMedianPen);
  FreeAndNil(FWhiskersPen);
  inherited Destroy;
end;

procedure TBoxAndWhiskerSeries.Draw(ADrawer: IChartDrawer);

  procedure GraphToImage_Whisker(X, XW, Y1, Y2: Double; 
    out iX1, iX, iX2, iY1, iY2: Integer);
  begin
    if IsRotated then
    begin
      iX1 := ParentChart.YGraphToImage(X - XW);
      iX2 := ParentChart.YGraphToImage(X + XW);
      if iX1 <> iX2 then
        iX := ParentChart.YGraphToImage(X)
      else
        iX := iX1;
      iY1 := ParentChart.XGraphToImage(Y1);
      iY2 := ParentChart.XGraphToImage(Y2);      
    end else
    begin
      iX1 := ParentChart.XGraphToImage(X - XW);
      iX2 := ParentChart.XGraphToImage(X + XW);
      if iX1 <> iX2 then
        iX := ParentChart.XGraphToImage(X)
      else
        iX := iX1;
      iY1 := ParentChart.YGraphToImage(Y1);
      iY2 := ParentChart.YGraphToImage(Y2);
    end;
  end;
  
  procedure GraphToImage_Bar(X1, X2, Y1, Y2: Double; 
    out iX1, iX2, iY1, iY2: Integer);
  begin
    if IsRotated then
    begin
      iX1 := ParentChart.YGraphToImage(X1);
      iX2 := ParentChart.YGraphToImage(X2);
      iY1 := ParentChart.XGraphToImage(Y1);
      iY2 := ParentChart.XGraphToImage(Y2);
    end else
    begin
      iX1 := ParentChart.XGraphToImage(X1);
      iX2 := ParentChart.XGraphToImage(X2);
      iY1 := ParentChart.YGraphToImage(Y1);
      iY2 := ParentChart.YGraphToImage(Y2);
    end;
  end;
  
  procedure GraphToImage_Median(Y: Double; out iY: Integer);
  begin
    if IsRotated then
      iY := ParentChart.XGraphToImage(Y)
    else
      iY := ParentChart.YGraphToImage(Y);
  end;

  procedure PrepareLine(i: Integer; APen: TPen);
  begin
    ADrawer.Pen := APen;
    if (Source[i]^.Color <> clTAColor) and (APen.Color = clTAColor) then
      ADrawer.SetPenColor(Source[i]^.Color);
    ADrawer.SetBrushParams(bsClear, clTAColor);
  end;
    
  procedure PrepareBox(i: Integer);
  begin
    ADrawer.Pen := BoxPen;
    if Source[i]^.Color <> clTAColor then
    begin
      if BoxPen.Color = clTAColor then
        ADrawer.SetPenColor(Source[i]^.Color);
      ADrawer.SetBrushParams(bsSolid, Source[i]^.Color);
    end
    else
      ADrawer.Brush := BoxBrush;
  end;
  
  {    X1   X   X2
       |----+----|       Y
            |
      +-----+-----+      YBox
      |           |
      |           |
  }
  procedure DrawWhisker(X1, X, X2, Y, YBox: Integer);
  begin
    if IsRotated then
    begin
      if X1 <> X2 then
        ADrawer.Line(Y, X1, Y, X2);
      ADrawer.Line(Y, X, YBox, X);
    end else
    begin
      if X1 <> X2 then
        ADrawer.Line(X1, Y, X2, Y);
      ADrawer.Line(X, Y, X, YBox);
    end;
  end;
  
  procedure DrawBox(XBox1, XBox2, YBox1, YBox2: Integer);
  begin
    if (XBox1 = XBox2) or (YBox1 = YBox2) then
    begin
      if IsRotated then
        ADrawer.Line(YBox1, XBox1, YBox2, XBox2)
      else
        ADrawer.Line(XBox1, YBox1, XBox2, YBox2);
    end else
    begin
      if IsRotated then
        ADrawer.Rectangle(YBox1, XBox1, YBox2, XBox2)
      else
        ADrawer.Rectangle(XBox1, YBox1, XBox2, YBox2);
    end;
  end;
  
  procedure DrawMedian(X1, X2, Y: Integer);
  begin
    if IsRotated then
      ADrawer.Line(Y, X1, Y, X2)
    else
      ADrawer.Line(X1, Y, X2, Y);
  end;

  function GetY(AItem: PChartDataItem; AYIndex: Integer; out AY: Double): Boolean;
  var
    y: Double;
  begin
    Result := false;
    if AYIndex = 0 then
      y := AItem^.Y
    else
      y := AItem^.YList[AYIndex-1];
    if IsNaN(y) then
      exit;

    AY := AxisToGraphY(y);
    Result := true;
  end;
    
var
  ext2: TDoubleRect;
  x, ymin, yqmin, ymed, yqmax, ymax, wb, ww, w: Double;
  i: Integer;
  ix, ixb1, ixb2, ixw1, ixw2: Integer;
  iymin, iyqmin, iymed, iyqmax, iymax: Integer;
  nx, ny: Cardinal;
  item: PChartDataItem;
begin
  if IsEmpty or (not Active) then exit;

  if FWidthStyle = bwsPercentMin then
    UpdateMinXRange;

  ext2 := ParentChart.CurrentExtent;
  ExpandRange(ext2.a.X, ext2.b.X, 1.0);
  ExpandRange(ext2.a.Y, ext2.b.Y, 1.0);

  PrepareGraphPoints(ext2, true);

  for i := FLoBound to FUpBound do begin
    // Get values from source and convert to graph units.
    item := Source[i];
    x := GetGraphPointX(i);
    if IsNaN(x) then continue;
    if not GetY(item, FYIndexWhiskerMin, ymin) then continue;
    if not GetY(item, FYIndexBoxMin, yqmin) then continue;
    if not GetY(item, FYIndexCenter, ymed) then continue;
    if not GetY(item, FYIndexBoxMax, yqmax) then continue;
    if not GetY(item, FYIndexWhiskerMax, ymax) then continue;
    
    case FWidthStyle of
      bwsPercent: w := GetXRange(x, i) * PERCENT / 2;
      bwsPercentMin: w := FMinXRange * PERCENT / 2;
    end;
    wb := w * BoxWidth;
    ww := w * WhiskersWidth;
    
    // Calculate image coordiantes
    GraphToImage_Whisker(x, ww, ymin, ymax, ixw1, ix, ixw2, iymin, iymax);
    GraphToImage_Bar(x-wb, x+wb, yqmin, yqmax, ixb1, ixb2, iyqmin, iyqmax);
    GraphToImage_Median(ymed, iymed);
     
    // Draw whisker
    PrepareLine(i, WhiskersPen);
    DrawWhisker(ixw1, ix, ixw2, iymin, iyqmin);
    DrawWhisker(ixw1, ix, ixw2, iymax, iyqmax);
    
    // Draw box
    PrepareBox(i);
    DrawBox(ixb1, ixb2, iyqmin, iyqmax);
    ADrawer.Pen := WhiskersPen;
    ADrawer.SetPenColor(WhiskersPen.Color);
    
    // Draw median line
    PrepareLine(i, MedianPen);
    DrawMedian(ixb1, ixb2, iymed);
  end;

  GetXYCountNeeded(nx, ny);
  if Source.YCount > ny then
    for i := 0 to ny-1 do DrawLabels(ADrawer, i)
  else
    DrawLabels(ADrawer);
end;

function TBoxAndWhiskerSeries.Extent: TDoubleRect;
var
  x: Double;
  j: Integer;

  function ExtraWidth(AIndex: Integer): Double;
  begin
    Result := GetXRange(x, AIndex) * Max(BoxWidth, WhiskersWidth) * PERCENT / 2;
  end;

begin
  Result := Source.ExtentList;
  if Source.Count = 0 then
    exit;
  
  // Show first and last boxes fully.
  j := -1;
  x := NaN;
  while IsNaN(x) and (j < Source.Count-1) do begin
    inc(j);
    x := GetGraphPointX(j);
  end;
  Result.a.X := Min(Result.a.X, GraphToAxisX(x - ExtraWidth(j)));
  j := Count;
  x := NaN;
  while IsNaN(x) and (j > 0) do begin
    dec(j);
    x := GetGraphPointX(j);
  end;
  Result.b.X := Max(Result.b.X, GraphToAxisX(x + ExtraWidth(j)));
end;

procedure TBoxAndWhiskerSeries.GetLegendItems(AItems: TChartLegendItems);
begin
  AItems.Add(TLegendItemBoxAndWhiskers.Create(Self, LegendTextSingle));
end;

function TBoxAndWhiskerSeries.GetNearestPoint(const AParams: TNearestPointParams;
  out AResults: TNearestPointResults): Boolean;
var
  i, j: Integer;
  graphClickPt, pt: TDoublePoint;
  x, w, wb: Double;
  y: Array[0..4] of Double;
  pImg: TPoint;
  R: TDoubleRect;
  xImg, dist: Integer;
begin
  Result := inherited;

  if Result then begin
    if (nptPoint in AParams.FTargets) and (nptPoint in ToolTargets) then
      exit;
    if (nptYList in AParams.FTargets) and (nptYList in ToolTargets) then
      exit;
  end;

  if not ((nptCustom in AParams.FTargets) and (nptCustom in ToolTargets))
  then
    exit;

  pImg := AParams.FPoint;
  graphClickPt := ParentChart.ImageToGraph(AParams.FPoint);
  if IsRotated then begin
    Exchange(graphclickpt.X, graphclickpt.Y);
    pImg := ParentChart.GraphToImage(graphclickPt);
  end;

  // Iterate through all points of the series
  for i := 0 to Count - 1 do begin
    x := GetGraphPointX(i);
    for j := 0 to High(y) do
      y[j] := GetGraphPointY(i, j);
    case FWidthStyle of
      bwsPercent    : w := GetXRange(x, i) * PERCENT / 2;
      bwsPercentMin : w := FMinXRange * PERCENT / 2;
    end;
    wb := w * BoxWidth;

    dist := MaxInt;

    // click inside box
    R.a := DoublePoint(x - wb, y[FYIndexBoxMin]);  
    R.b := DoublePoint(x + wb, y[FYIndexBoxMax]);  
    if InRange(graphClickPt.X, R.a.x, R.b.x) and InRange(graphClickPt.Y, R.a.Y, R.b.Y) then
    begin
      dist := 0;
      AResults.FYIndex := -1;
   end;

    // click on whisker line
    xImg := ParentChart.XGraphToImage(x);
    if InRange(graphClickPt.Y, y[FYIndexWhiskerMin], y[FYIndexBoxMin]) or 
       InRange(graphClickPt.Y, y[FYIndexWhiskerMax], y[FYIndexBoxMax])
    then begin
      dist := sqr(pImg.X - xImg);
      AResults.FYIndex := -1;
    end;

    // Sufficiently close?
    if dist < AResults.FDist then begin
      AResults.FDist := dist;
      AResults.FIndex := i;
      pt := DoublePoint(x, y[2]);   // Median
      AResults.FValue := pt;
      if IsRotated then Exchange(pt.X, pt.Y);
      AResults.FImg := ParentChart.GraphToImage(pt);
      if dist = 0 then break;
    end;
  end;
  Result := AResults.FIndex > -1;
end;

function TBoxAndWhiskerSeries.GetSeriesColor: TColor;
begin
  Result := BoxBrush.Color;
end;

class procedure TBoxAndWhiskerSeries.GetXYCountNeeded(out AXCount, AYCount: Cardinal);
begin
  AXCount := 0;
  AYCount := 5;
end;

procedure TBoxAndWhiskerSeries.SetBoxBrush(AValue: TBrush);
begin
  if FBoxBrush = AValue then exit;
  FBoxBrush.Assign(AValue);
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetBoxPen(AValue: TPen);
begin
  if FBoxPen = AValue then exit;
  FBoxPen.Assign(AValue);
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetBoxWidth(AValue: Integer);
begin
  if FBoxWidth = AValue then exit;
  FBoxWidth := AValue;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetLegendDirection(
  AValue: TBoxAndWhiskerSeriesLegendDir);
begin
  if FLegendDirection = AValue then exit;
  FLegendDirection := AValue;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetMedianPen(AValue: TPen);
begin
  if FMedianPen = AValue then exit;
  FMedianPen.Assign(AValue);
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetWhiskersPen(AValue: TPen);
begin
  if FWhiskersPen = AValue then exit;
  FWhiskersPen.Assign(AValue);
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetWhiskersWidth(AValue: Integer);
begin
  if FWhiskersWidth = AValue then exit;
  FWhiskersWidth := AValue;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYIndexBoxMax(AValue: Integer);
begin
  if FYIndexBoxMax = AValue then exit;
  FYIndexBoxMax := AValue;
  UpdateYDataLayout;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYIndexBoxMin(AValue: Integer);
begin
  if FYIndexBoxMin = AValue then exit;
  FYIndexBoxMin := AValue;
  UpdateYDataLayout;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYIndexCenter(AValue: Integer);
begin
  if FYIndexCenter = AValue then exit;
  FYIndexCenter := AValue;
  UpdateYDataLayout;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYIndexWhiskerMax(AValue: Integer);
begin
  if FYIndexWhiskerMax = AValue then exit;
  FYIndexWhiskerMax := AValue;
  UpdateYDataLayout;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYIndexWhiskerMin(AValue: Integer);
begin
  if FYIndexWhiskerMin = AValue then exit;
  FYIndexWhiskerMin := AValue;
  UpdateYDataLayout;
  UpdateParentChart;
end;

procedure TBoxAndWhiskerSeries.SetYDataLayout(AValue: TBoxAndWhiskerYDataLayout);

  procedure SetYIndices(AWhiskerMin, ABoxMin, ACenter, ABoxMax, AWhiskerMax: Integer);
  begin
    FYIndexWhiskerMin := AWhiskerMin;
    FYIndexBoxMin := ABoxMin;
    FYIndexCenter := ACenter;
    FYIndexBoxMax := ABoxMax;
    FYIndexWhiskerMax := AWhiskerMax;
  end;

begin
  if FYDataLayout = AValue then exit;
  FYDataLayout := AValue;
  case FYDataLayout of
    bwlNormal: SetYIndices(1, 2, 0, 3, 4);   
    bwlLegacy: SetYIndices(0, 1, 2, 3, 4);
    bwlCustom: ;
  end;
  UpdateParentChart;
end;

function TBoxAndWhiskerSeries.SkipMissingValues(AIndex: Integer): Boolean;
begin
  Result := IsNaN(Source[AIndex]^.Point);
  if not Result then
    Result := HasMissingYValue(AIndex, 5);
end;

function TBoxAndWhiskerSeries.ToolTargetDistance(
  const AParams: TNearestPointParams; AGraphPt: TDoublePoint;
  APointIdx, AXIdx, AYIdx: Integer): Integer;

  // All in image coordinates transformed to have a horizontal x axis
  function DistanceToLine(Pt: TPoint; x1, x2, y: Integer): Integer;
  begin
    if InRange(Pt.X, x1, x2) then
      Result := sqr(Pt.Y - y)   // FDistFunc does not calc sqrt
    else
      Result := Min(
        AParams.FDistFunc(Pt, Point(x1, y)),
        AParams.FDistFunc(Pt, Point(x2, y))
      );
  end;

var
  xw1, xw2, xb1, xb2, y: Integer;
  w, wb, ww: Double;
  clickPt: TPoint;
  gp: TDoublePoint;
begin
  Unused(AXIdx);

  if IsRotated then begin
    gp := ParentChart.ImageToGraph(AParams.FPoint);
    Exchange(gp.X, gp.Y);
    clickPt := ParentChart.GraphToImage(gp);
    Exchange(AGraphPt.X, AGraphPt.Y);
  end else
    clickPt := AParams.FPoint;

  case FWidthStyle of
    bwsPercent    : w := GetXRange(AGraphPt.X, APointIdx) * PERCENT / 2;
    bwsPercentMin : w := FMinXRange * PERCENT / 2;
  end;
  wb := w * BoxWidth;
  ww := w * WhiskersWidth;

  xw1 := ParentChart.XGraphToImage(AGraphPt.X - ww);
  xw2 := ParentChart.XGraphToImage(AGraphPt.X + ww);
  xb1 := ParentChart.XGraphToImage(AGraphPt.X - wb);
  xb2 := ParentChart.XGraphToImage(AGraphPt.X + wb);
  y := ParentChart.YGraphToImage(AGraphPt.Y);

  if AYIdx in [FYIndexWhiskerMax, FYIndexWhiskerMin] then   
    Result := DistanceToLine(clickPt, xw1, xw2, y)
  else if AYIdx in [FYIndexBoxMax, FYIndexCenter, FYIndexBoxMin] then
    Result := DistanceToLine(clickPt, xb1, xb2, y)
  else
    raise Exception.Create('[TBoxAndWhiskerSeries.ToolTargetDistance] Unknown y index.');
end;

procedure TBoxAndWhiskerSeries.UpdateLabelDirectionReferenceLevel(
  AIndex, AYIndex: Integer; var ALevel: Double);
var
  item: PChartDataItem;
  y0, y3: Double;
begin
  { ToDo: The version before introducing FYIndex* variables had used the values 
    0 and 3 here. 3 means: FYIndexBoxMax. Interpreted this as a typo, but there
    is some chance that it would be correct --> needs to be checked. }
  if (AYIndex = FYIndexWhiskerMin) then
    ALevel := +Infinity
  else if (AYIndex = FYIndexWhiskerMax) then
    ALevel := -Infinity
  else
  begin
    item := Source.Item[AIndex];
    y0 := AxisToGraphY(item^.GetY(FYIndexWhiskerMin));
    y3 := AxisToGraphY(item^.GetY(FYIndexWhiskerMax));
    ALevel := (y0 + y3) * 0.5;
  end;
end;

procedure TBoxAndWhiskerSeries.UpdateYDataLayout;
begin
  if (FYIndexWhiskerMin = 0) and (FYIndexBoxMin = 1) and (FYIndexCenter = 2) and
     (FYIndexBoxMax = 3) and (FYIndexWhiskerMax = 4) 
  then 
    FYDataLayout := bwlLegacy
  else
  if (FYIndexCenter = 0) and (FYIndexWhiskerMin = 1) and (FYIndexBoxMin = 2) and
     (FYIndexBoxMax = 3) and (FYIndexWhiskerMax = 4) 
  then 
    FYDataLayout := bwlNormal
  else
    FYDataLayout := bwlCustom;
end;

{ TOHLCBrush }

function TOHLCBrush.IsColorStored: Boolean;
begin
  Result := (Color = DEFAULT_COLORS[FBrushKind]);
end;

procedure TOHLCBrush.SetBrushKind(AValue: TOHLCBrushKind);
begin
  FBrushKind := AValue;
  Color := DEFAULT_COLORS[FBrushKind];
end;

{ TOHLCPen }

function TOHLCPen.IsColorStored: Boolean;
begin
  Result := (Color = DEFAULT_COLORS[FPenKind]);
end;

procedure TOHLCPen.SetPenKind(AValue: TOHLCPenKind);
begin
  FPenKind := AValue;
  Color := DEFAULT_COLORS[FPenKind];
end;

{ TOpenHighLowCloseSeries }

function TOpenHighLowCloseSeries.AddXOHLC(
  AX, AOpen, AHigh, ALow, AClose: Double;
  ALabel: String; AColor: TColor): Integer;
var
  y: Double;
begin
  if YIndexOpen = 0 then
    y := AOpen
  else if YIndexHigh = 0 then
    y := AHigh
  else if YIndexLow = 0 then
    y := ALow
  else if YIndexClose = 0 then
    y := AClose
  else
    raise Exception.Create('TOpenHighLowCloseSeries: Ordinary y value missing');

  Result := ListSource.Add(AX, y, ALabel, AColor);
  with ListSource.Item[Result]^ do begin
    SetY(YIndexOpen, AOpen);
    SetY(YIndexHigh, AHigh);
    SetY(YIndexLow, ALow);
    SetY(YIndexClose, AClose);
  end;
end;

procedure TOpenHighLowCloseSeries.Assign(ASource: TPersistent);
var
  bk: TOHLCBrushKind;
  pk: TOHLCPenKind;
begin
  if ASource is TOpenHighLowCloseSeries then
    with TOpenHighLowCloseSeries(ASource) do begin
      for bk in TOHLCBrushKind do
        Self.FBrush[bk] := FBrush[bk];
      for pk in TOHLCPenKind do
        Self.FPen[pk] := FPen[pk];
      Self.FMode := FMode;
      Self.FTickWidth := FTickWidth;
      Self.FYIndexClose := FYIndexClose;
      Self.FYIndexHigh := FYIndexHigh;
      Self.FYIndexLow := FYIndexLow;
      Self.FYIndexOpen := FYIndexOpen;
    end;
  inherited Assign(ASource);
end;

constructor TOpenHighLowCloseSeries.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  ToolTargets := [nptPoint, nptYList, nptCustom];
  FOptimizeX := false;
  FStacked := false;
  FTickWidth := DEF_OHLC_TICK_WIDTH;
  FYIndexClose := DEF_YINDEX_CLOSE;
  FYIndexHigh := DEF_YINDEX_HIGH;
  FYIndexLow := DEF_YINDEX_LOW;
  FYIndexOpen := DEF_YINDEX_OPEN;

  // Candlestick up brush
  FBrush[obkCandleUp] := TOHLCBrush.Create;
  FBrush[obkCandleUp].BrushKind := obkCandleUp;
  FBrush[obkCandleUp].OnChange := @StyleChanged;
  // Candlestick down brush
  FBrush[obkCandleDown] := TOHLCBrush.Create;
  FBrush[obkCandleDown].BrushKind := obkCandleDown;
  FBrush[obkCandleDown].OnChange := @StyleChanged;
  // Candlestick up border pen
  FPen[opkCandleUp] := TOHLCPen.Create;
  FPen[opkCandleUp].PenKind := opkCandleUp;
  FPen[opkCandleUp].OnChange := @StyleChanged;
  // Candlestick down border pen
  FPen[opkCandleDown] := TOHLCPen.Create;
  FPen[opkCandleDown].PenKind := opkCandleDown;
  FPen[opkCandleDown].OnChange := @StyleChanged;
  // Candlestick range pen
  FPen[opkCandleLine] := TOHLCPen.Create;
  FPen[opkCandleLine].PenKind := opkCandleLine;
  FPen[opkCandleLine].OnChange := @StyleChanged;
  // OHLC up pen
  FPen[opkLineUp] := TOHLCPen.Create;
  FPen[opkLineUp].PenKind := opkLineUp;
  FPen[opkLineUp].OnChange := @StyleChanged;
  // OHLC down pen
  FPen[opkLineDown] := TOHLCPen.Create;
  FPen[opkLineDown].PenKind := opkLineDown;
  FPen[opkLineDown].OnChange := @StyleChanged;
end;

destructor TOpenHighLowCloseSeries.Destroy;
var
  bk: TOHLCBrushKind;
  pk: TOHLCPenKind;
begin
  for bk in TOHLCBrushKind do
    FreeAndNil(FBrush[bk]);
  for pk in TOHLCPenKind do
    FreeAndNil(FPen[pk]);
  inherited;
end;

function TOpenHighLowCloseSeries.CalcTickWidth(AX: Double; AIndex: Integer): Double;
begin
  case FTickWidthStyle of
    twsPercent:
      Result := GetXRange(AX, AIndex) * PERCENT * TickWidth;
    twsPercentMin:
      begin
        if FMinXRange = 0 then
          UpdateMinXRange;
        Result := FMinXRange * PERCENT * TickWidth;
      end;
  end;
end;

procedure TOpenHighLowCloseSeries.Draw(ADrawer: IChartDrawer);

  function MaybeRotate(AX, AY: Double): TPoint;
  begin
    if IsRotated then
      Exchange(AX, AY);
    Result := ParentChart.GraphToImage(DoublePoint(AX, AY));
  end;

  procedure DoLine(AX1, AY1, AX2, AY2: Double);
  begin
    ADrawer.Line(MaybeRotate(AX1, AY1), MaybeRotate(AX2, AY2));
  end;

  procedure NoZeroRect(var R: TRect);
  begin
    if IsRotated then
    begin
      if R.Left = R.Right then inc(R.Right);
    end else
    begin
      if R.Top = R.Bottom then inc(R.Bottom);
    end;
  end;

  procedure DoRect(AX1, AY1, AX2, AY2: Double);
  var
    r: TRect;
  begin
    r.TopLeft := MaybeRotate(AX1, AY1);
    r.BottomRight := MaybeRotate(AX2, AY2);
    NoZeroRect(r);
    ADrawer.FillRect(r.Left, r.Top, r.Right, r.Bottom);
    ADrawer.Rectangle(r);
  end;

  procedure DrawOHLC(x, yopen, yhigh, ylow, yclose, tw: Double);
  begin
    DoLine(x, yhigh, x, ylow);
    DoLine(x, yclose, x + tw, yclose);
    if not IsNaN(yopen) then
      DoLine(x - tw, yopen, x, yopen);
  end;

  procedure DrawCandleStick(x, yopen, yhigh, ylow, yclose, tw: Double; APenIdx: Integer);
  begin
    if CandleStickLinePen.Color = clDefault then
      // use linepen and linedown pen for range line
      ADrawer.Pen := FPen[TOHLCPenKind(APenIdx + 3)]
    else
      ADrawer.Pen := CandleStickLinePen;
    DoLine(x, yhigh, x, ylow);
    ADrawer.Pen := FPen[TOHLCPenKind(APenIdx)];
    DoRect(x - tw, yopen, x + tw, yclose);
  end;

const
  UP_INDEX = 0;
  DOWN_INDEX = 1;
var
  my: Cardinal;
  ext2: TDoubleRect;
  i: Integer;
  x, tw, yopen, yhigh, ylow, yclose, prevclose: Double;
  idx: Integer;
  nx, ny: Cardinal;
begin
  if IsEmpty or (not Active) then exit;
  my := MaxIntValue([YIndexOpen, YIndexHigh, YIndexLow, YIndexClose]);
  if my >= Source.YCount then exit;

  ext2 := ParentChart.CurrentExtent;
  ExpandRange(ext2.a.X, ext2.b.X, 1.0);
  ExpandRange(ext2.a.Y, ext2.b.Y, 1.0);

  PrepareGraphPoints(ext2, true);

  prevclose := -Infinity;
  for i := FLoBound to FUpBound do begin
    x := GetGraphPointX(i);
    if IsNaN(x) then Continue;
    yopen := GetGraphPointY(i, YIndexOpen);
    if IsNaN(yopen) and (FMode = mCandleStick) then Continue;
    yhigh := GetGraphPointY(i, YIndexHigh);
    if IsNaN(yhigh) then Continue;
    ylow := GetGraphPointY(i, YIndexLow);
    if IsNaN(ylow) then Continue;
    yclose := GetGraphPointY(i, YIndexClose);
    if IsNaN(yclose) then Continue;
    tw := CalcTickWidth(x, i);

    if IsNaN(yopen) then
    begin
      // HLC chart: compare with close value of previous data point
      if prevclose < yclose then
        idx := UP_INDEX
      else
        idx := DOWN_INDEX;
    end else
    if (yopen <= yclose) then
      idx := UP_INDEX
    else
      idx := DOWN_INDEX;
    ADrawer.Brush := FBrush[TOHLCBrushKind(idx)];
    case FMode of
      mOHLC: ADrawer.Pen := FPen[TOHLCPenKind(idx + 3)];
      mCandlestick: ADrawer.Pen := FPen[TOHLCPenKind(idx)];
    end;
    if Source[i]^.Color <> clTAColor then
    begin
      ADrawer.SetPenParams(FPen[TOHLCPenKind(idx)].Style, Source[i]^.Color, FPen[TOHLCPenKind(idx)].Width);
      ADrawer.SetBrushParams(FBrush[TOHLCBrushKind(idx)].Style, Source[i]^.Color);
    end;

    case FMode of
      mOHLC: DrawOHLC(x, yopen, yhigh, ylow, yclose, tw);
      mCandleStick: DrawCandleStick(x, yopen, yhigh, ylow, yclose, tw, idx);
    end;

    prevclose := yclose;
  end;

  GetXYCountNeeded(nx, ny);
  if Source.YCount > ny then
    for i := 0 to ny-1 do DrawLabels(ADrawer, i)
  else
    DrawLabels(ADrawer);
end;

function TOpenHighLowCloseSeries.Extent: TDoubleRect;
var
  x: Double;
  tw: Double;
  j: Integer;
begin
  Result := Source.ExtentList;                            // axis units

  // Enforce recalculation of tick/candlebox width
  FMinXRange := 0;

  // Show first and last open/close ticks and candle boxes fully.
  j := -1;
  x := NaN;
  while IsNaN(x) and (j < Source.Count-1) do begin
    inc(j);
    x := GetGraphPointX(j);                                 // graph units
  end;
  tw := CalcTickWidth(x, j);
  Result.a.X := Min(Result.a.X, GraphToAxisX(x - tw));    // axis units
//  Result.a.X := Min(Result.a.X, x - tw);
  j := Count;
  x := NaN;
  While IsNaN(x) and (j > 0) do begin
    dec(j);
    x := GetGraphPointX(j);
  end;
  tw := CalcTickWidth(x, j);
  Result.b.X := Max(Result.b.X, AxisToGraphX(x + tw));
//  Result.b.X := Max(Result.b.X, x + tw);
end;

function TOpenHighLowCloseSeries.GetBrush(AIndex: TOHLCBrushKind): TOHLCBrush;
begin
  Result := FBrush[AIndex];
end;

procedure TOpenHighLowCloseSeries.GetLegendItems(AItems: TChartLegendItems);
begin
  AItems.Add(TLegendItemOHLCLine.Create(Self, LegendTextSingle));
end;

function TOpenHighLowCloseSeries.GetNearestPoint(const AParams: TNearestPointParams;
  out AResults: TNearestPointResults): Boolean;
var
  i: Integer;
  graphClickPt, p: TDoublePoint;
  pImg: TPoint;
  x, yopen, yhigh, ylow, yclose, tw: Double;
  xImg, dist: Integer;
  R: TDoubleRect;
begin
  Result := inherited;

  if Result then begin
    if (nptPoint in AParams.FTargets) and (nptPoint in ToolTargets) then
      exit;
    if (nptYList in AParams.FTargets) and (nptYList in ToolTargets) then
      exit;
  end;
  if not ((nptCustom in AParams.FTargets) and (nptCustom in ToolTargets))
  then
    exit;

  graphClickPt := ParentChart.ImageToGraph(AParams.FPoint);
  pImg := AParams.FPoint;
  if IsRotated then begin
//    Exchange(pImg.X, pImg.Y);
    Exchange(graphclickpt.X, graphclickpt.Y);
    pImg := ParentChart.GraphToImage(graphClickPt);
  end;

  // Iterate through all points of the series
  for i := 0 to Count - 1 do begin
    x := GetGraphPointX(i);
    yopen := GetGraphPointY(i, YIndexOpen);
    yhigh := GetGraphPointY(i, YIndexHigh);
    ylow := GetGraphPointY(i, YIndexLow);
    yclose := GetGraphPointY(i, YIndexClose);
    tw := CalcTickWidth(x, i);

    dist := MaxInt;

    // click on vertical line
    if InRange(graphClickPt.Y, ylow, yhigh) then begin
      xImg := ParentChart.XGraphToImage(x);
      dist := sqr(pImg.X - xImg);
      AResults.FYIndex := -1;
    end;

    // click on candle box
    if FMode = mCandlestick then begin
      R.a := DoublePoint(x - tw, Min(yopen, yclose));
      R.b := DoublePoint(x + tw, Max(yopen, yclose));
      if InRange(graphClickPt.X, R.a.x, R.b.x) and InRange(graphClickPt.Y, R.a.Y, R.b.Y) then
      begin
        dist := 0;
        AResults.FYIndex := -1;
      end;
    end;

    // Sufficiently close?
    if dist < AResults.FDist then begin
      AResults.FDist := dist;
      AResults.FIndex := i;
      p := DoublePoint(x, yclose);   // "Close" value
      AResults.FValue := p;
      if IsRotated then Exchange(p.X, p.Y);
      AResults.FImg := ParentChart.GraphToImage(p);
      if dist = 0 then break;
    end;
  end;
  Result := AResults.FIndex > -1;
end;

function TOpenHighLowCloseSeries.GetPen(AIndex: TOHLCPenKind): TOHLCPen;
begin
  Result := FPen[AIndex];
end;

function TOpenHighLowCloseSeries.GetSeriesColor: TColor;
begin
  Result := LinePen.Color;
end;

class procedure TOpenHighLowCloseSeries.GetXYCountNeeded(out AXCount, AYCount: Cardinal);
begin
  AXCount := 0;
  AYCount := 4;
end;

procedure TOpenHighLowCloseSeries.SetBrush(AIndex: TOHLCBrushKind; AValue: TOHLCBrush);
begin
  if GetBrush(AIndex) = AValue then exit;
  FBrush[AIndex].Assign(AValue);
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetPen(AIndex: TOHLCPenKind; AValue: TOHLCPen);
begin
  if GetPen(AIndex) = AValue then exit;
  FPen[AIndex].Assign(AValue);
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetOHLCMode(AValue: TOHLCMode);
begin
  if FMode = AValue then exit;
  FMode := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetTickWidth(AValue: Integer);
begin
  if FTickWidth = AValue then exit;
  FTickWidth := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetTickWidthStyle(AValue: TTickWidthStyle);
begin
  if FTickWidthStyle = AValue then exit;
  FTickWidthStyle := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetYIndexClose(AValue: Integer);
begin
  if FYIndexClose = AValue then exit;
  FYIndexClose := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetYIndexHigh(AValue: Integer);
begin
  if FYIndexHigh = AValue then exit;
  FYIndexHigh := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetYIndexLow(AValue: Integer);
begin
  if FYIndexLow = AValue then exit;
  FYIndexLow := AValue;
  UpdateParentChart;
end;

procedure TOpenHighLowCloseSeries.SetYIndexOpen(AValue: Integer);
begin
  if FYIndexOpen = AValue then exit;
  FYIndexOpen := AValue;
  UpdateParentChart;
end;

function TOpenHighLowCloseSeries.SkipMissingValues(AIndex: Integer): Boolean;
begin
  Result := IsNaN(Source[AIndex]^.Point);
  if not Result then
    Result := HasMissingYValue(AIndex, 4);
end;

function TOpenHighLowCloseSeries.ToolTargetDistance(
  const AParams: TNearestPointParams; AGraphPt: TDoublePoint;
  APointIdx, AXIdx, AYIdx: Integer): Integer;

  // All in image coordinates transformed to have a horizontal x axis
  function DistanceToLine(Pt: TPoint; x1, x2, y: Integer): Integer;
  begin
    if InRange(Pt.X, x1, x2) then     // FDistFunc does not calculate sqrt
      Result := sqr(Pt.Y - y)
    else
      Result := Min(
        AParams.FDistFunc(Pt, Point(x1, y)),
        AParams.FDistFunc(Pt, Point(x2, y))
      );
  end;

var
  x1, x2: Integer;
  w: Double;
  p, clickPt: TPoint;
  gp: TDoublePoint;
begin
  Unused(AXIdx);

  // Convert the "clicked" and "test" point to non-rotated axes
  if IsRotated then begin
    gp := ParentChart.ImageToGraph(AParams.FPoint);
    Exchange(gp.X, gp.Y);
    clickPt := ParentChart.GraphToImage(gp);
    Exchange(AGraphPt.X, AGraphPt.Y);
  end else
    clickPt := AParams.FPoint;

  w := CalcTickWidth(AGraphPt.X, APointIdx);
  x1 := ParentChart.XGraphToImage(AGraphPt.X - w);
  x2 := ParentChart.XGraphToImage(AGraphPt.X + w);
  p := ParentChart.GraphToImage(AGraphPt);

  case FMode of
    mOHLC:
      with ParentChart do
        if (AYIdx = YIndexOpen) then
          Result := DistanceToLine(clickPt, x1, p.x, p.y)
        else if (AYIdx = YIndexClose) then
          Result := DistanceToLine(clickPt, p.x, x2, p.y)
        else if (AYIdx = YIndexHigh) or (AYIdx = YIndexLow) then
          Result := AParams.FDistFunc(clickPt, p)
        else
          raise Exception.Create('TOpenHighLowCloseSeries.ToolTargetDistance: Illegal YIndex.');
    mCandleStick:
      with ParentChart do
        if (AYIdx = YIndexOpen) or (AYIdx = YIndexClose) then
          Result := DistanceToLine(clickPt, x1, x2, p.y)
        else if (AYIdx = YIndexHigh) or (AYIdx = YIndexLow) then
          Result := AParams.FDistFunc(clickPt, p)
        else
          raise Exception.Create('TOpenHighLowCloseSeries.ToolTargetDistance: Illegal YIndex.');
  end;
end;

procedure TOpenHighLowCloseSeries.UpdateLabelDirectionReferenceLevel(
  AIndex, AYIndex: Integer; var ALevel: Double);
var
  item: PChartDataItem;
begin
  if AYIndex = FYIndexLow then
    ALevel := +Infinity
  else if AYIndex = FYIndexHigh then
    ALevel := -Infinity
  else begin
    item := Source.Item[AIndex];
    ALevel := (AxisToGraphY(item^.GetY(FYIndexLow)) + AxisToGraphY(item^.GetY(FYIndexHigh)))*0.5;
  end;
end;


{ TFieldSeries }

constructor TFieldSeries.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  ToolTargets := [nptPoint, nptXList, nptYList, nptCustom];
  FArrow := TChartArrow.Create(ParentChart);
  FArrow.Length := 20;
  FArrow.Width := 10;
  FArrow.Visible := true;
  FPen := TPen.Create;
  FPen.OnChange := @StyleChanged;
end;

destructor TFieldSeries.Destroy;
begin
  FreeAndNil(FArrow);
  FreeAndNil(FPen);
  inherited;
end;

function TFieldSeries.AddVector(AX, AY, AVectorX, AVectorY: Double;
  AXLabel: String = ''; AColor: TColor = clTAColor): Integer;
begin
  Result := AddXY(AX, AY, AXLabel, AColor);
  SetVector(Result, DoublePoint(AVectorX, AVectorY));
end;

procedure TFieldSeries.AfterAdd;
begin
  inherited;
  FArrow.SetOwner(ParentChart);
end;

procedure TFieldSeries.Assign(ASource: TPersistent);
begin
  if ASource is TFieldSeries then
    with TFieldSeries(ASource) do begin
      Self.FArrow.Assign(FArrow);
      Self.FPen := FPen;
    end;
  inherited Assign(ASource);
end;

procedure TFieldSeries.Draw(ADrawer: IChartDrawer);
var
  ext: TDoubleRect;
  i: Integer;
  p1, p2: TDoublePoint;
  lPen: TPen;
begin
  if IsEmpty or (not Active) then exit;
  with Extent do begin
    ext.a := AxisToGraph(a);
    ext.b := AxisToGraph(b);
  end;
  NormalizeRect(ext);
  // Do not draw anything if the series extent does not intersect CurrentExtent.
  if not RectIntersectsRect(ext, ParentChart.CurrentExtent) then exit;

  lPen := TPen.Create;
  try
    lPen.Assign(FPen);
    if (AxisIndexX < 0) and (AxisIndexY < 0) then begin
      // Optimization: bypass transformations in the default case
      for i := 0 to Count - 1 do
        if GetVectorPoints(i, p1, p2) then begin
          lPen.Color := GetColor(i);
          DrawVector(ADrawer, p1, p2, lPen);
        end;
    end else begin
      for i := 0 to Count - 1 do
        if GetVectorPoints(i, p1, p2) then begin
          p1 := AxisToGraph(p1);
          p2 := AxisToGraph(p2);
          lPen.Color := GetColor(i);
          DrawVector(ADrawer, p1, p2, lPen);
        end;
    end;
    DrawLabels(ADrawer, 0);
  finally
    lPen.Free;
  end;
end;

procedure TFieldSeries.DrawVector(ADrawer: IChartDrawer;
  AStartPt, AEndPt: TDoublePoint; APen: TPen);
var
  p1, p2: TPoint;
  arr: TChartArrow;
  len: Double;
begin
  p1 := ParentChart.GraphToImage(AStartPt);
  p2 := ParentChart.GraphToImage(AEndPt);
  ADrawer.Pen := APen;
  if APen.Color = clDefault then
    ADrawer.SetPenColor(FChart.GetDefaultColor(dctFont))
  else
    ADrawer.SetPenColor(APen.Color);
  ADrawer.Line(p1.x, p1.y, p2.x, p2.y);
  if FArrow.Visible then begin
    len := sqrt(sqr(p2.x - p1.x) + sqr(p2.y - p1.y)) * 0.01 / ADrawer.Scale(1);
    // Be aware that the drawer scales pixels. But the arrow length here is
    // already at the correct size!
    arr := TChartArrow.Create(nil);
    arr.Assign(FArrow);
    arr.SetOwner(nil);  // avoid repainting due to next commands
    arr.BaseLength := round(FArrow.BaseLength * len);
    arr.Length := round(FArrow.Length * len);
    arr.Width := round(FArrow.Width * len);
    arr.Draw(ADrawer, p2, arctan2(p2.y-p1.y, p2.x-p1.x), APen);
    arr.Free;
  end;
end;

function TFieldSeries.Extent: TDoubleRect;
var
  p1, p2: TDoublePoint;
  i: Integer;
begin
  Result := Source.Extent;
  for i := 0 to Source.Count - 1 do
    if GetVectorPoints(i, p1, p2) then begin
      UpdateMinMax(p1.X, Result.a.X, Result.b.X);
      UpdateMinMax(p2.X, Result.a.X, Result.b.X);
      UpdateMinMax(p1.Y, Result.a.Y, Result.b.Y);
      UpdateMinMax(p2.Y, Result.a.Y, Result.b.Y);
    end;
end;

function TFieldSeries.GetColor(AIndex: Integer): TColor;
begin
  with Source.Item[AIndex]^ do
    Result := TColor(Math.IfThen(Color = clTAColor, FPen.Color, Color));
end;

procedure TFieldSeries.GetLegendItems(AItems: TChartLegendItems);
begin
  AItems.Add(TLegendItemField.Create(FPen, FArrow, LegendTextSingle));
end;

function TFieldSeries.GetNearestPoint(const AParams: TNearestPointParams;
  out AResults: TNearestPointResults): Boolean;
var
  dist, d, i, xidx, yidx: Integer;
  pt1, pt2: TPoint;
  sp1, sp2: TDoublePoint;
  R: TRect;
  img: TPoint;
begin
  AResults.FDist := Sqr(AParams.FRadius) + 1;
  AResults.FIndex := -1;
  AResults.FXIndex := 0;
  AResults.FYIndex := 0;
  if IsEmpty then exit(false);

  for i := 0 to Count - 1 do begin
    if not GetVectorPoints(i, sp1, sp2) then
      Continue;
    // End points of the vector arrow
    pt1 := ParentChart.GraphToImage(AxisToGraph(sp1));
    pt2 := ParentChart.GraphToImage(AxisToGraph(sp2));
    // At first we check if the point is in the rect spanned by the vector.
    R := Rect(pt1.x, pt1.y, pt2.x, pt2.y);
    NormalizeRect(R);
    R.TopLeft := R.TopLeft - Point(AParams.FRadius, AParams.FRadius);
    R.BottomRight := R.BottomRight + Point(AParams.FRadius, AParams.FRadius);
    if not IsPointInRect(AParams.FPoint, R) then continue;

    dist := MaxInt;
    xidx := -1;
    yidx := -1;
    if (nptPoint in AParams.FTargets) and (nptPoint in ToolTargets) then begin
      dist := AParams.FDistFunc(AParams.FPoint, pt1);
      xidx := 0;
      yidx := 0;
      img := pt1;
    end;

    if (AParams.FTargets * [nptXList, nptYList] <> []) and
       (ToolTargets * [nptXList, nptYList] <> [])
    then begin
      d := AParams.FDistFunc(AParams.FPoint, pt2);
      if d < dist then begin
        dist := d;
        xidx := 1;
        yidx := 1;
        img := pt2;
      end;
    end;
    // give priority to end points
    if (dist > AResults.FDist) and
       (nptCustom in AParams.FTargets) and
       (nptCustom in ToolTargets)
    then begin
      d := PointLineDistSq(AParams.FPoint, pt1, pt2);  // distance of point from line
      if d < dist then begin
        dist := d;
        xidx := -1;
        yidx := -1;
        img := ProjToLine(AParams.FPoint, pt1, pt2);
      end;
    end;
    if dist >= AResults.FDist then continue;

    AResults.FDist := dist;
    AResults.FIndex := i;
    AResults.FXIndex := xidx;
    AResults.FYIndex := yidx;
    AResults.FImg := img;
    AResults.FValue := Source[i]^.Point;
    break;
  end;
  Result := AResults.FIndex >= 0;
end;

function TFieldSeries.GetVector(AIndex: Integer): TDoublePoint;
begin
  with Source.Item[AIndex]^ do
    case FCoordKind of
      vckCenterDir: Result := DoublePoint(XList[0], YList[0]);
      vckStartEnd: Result := DoublePoint(XList[0]-X, YList[0]-Y);
    end;
end;

function TFieldSeries.GetVectorPoints(AIndex: Integer;
  out AStartPt, AEndPt: TDoublePoint): Boolean;
var
  dx, dy: Double;
begin
  with Source.Item[AIndex]^ do begin
    if isNaN(X) or IsNaN(Y) or IsNaN(XList[0]) or IsNaN(YList[0]) then
      exit(false)
    else begin
      case FCoordKind of
        vckCenterDir:
          begin
            dx := XList[0] * 0.5;
            dy := YList[0] * 0.5;
            AStartPt := DoublePoint(X - dx, Y - dy);
            AEndPt := DoublePoint(X + dx, Y + dy);
          end;
        vckStartEnd:
          begin
            AStartPt := DoublePoint(X, Y);
            AEndPt := DoublePoint(XList[0], YList[0]);
          end;
      end;
      Result := true;
    end;
  end;
end;

class procedure TFieldSeries.GetXYCountNeeded(out AXCount, AYCount: Cardinal);
begin
  AXCount := 2;
  AYCount := 2;
end;

procedure TFieldSeries.MovePointEx(var AIndex: Integer;
  AXIndex, AYIndex: Integer; const ANewPos: TDoublePoint);
var
  np, p: TDoublePoint;
begin
  Unused(AXIndex);

  if not InRange(AIndex, 0, Count - 1) then
    exit;

  p := DoublePoint(XValue[AIndex], YValue[AIndex]);
  np := GraphToAxis(ANewPos);

  ParentChart.DisableRedrawing;
  try
    case AYIndex of
     -1: begin
           ListSource.SetXValue(AIndex, np.X);
           ListSource.SetYValue(AIndex, np.Y);
         end;
      0: SetVector(AIndex, (p - np) * 2);
      1: SetVector(AIndex, (np - p) * 2);
    end;
  finally
    ParentChart.EnableRedrawing;
    UpdateParentChart;
  end;
end;

procedure TFieldSeries.NormalizeVectors(ALength: Double);
var
  factor, maxlen, len: Double;
  i: Integer;
  v: TDoublePoint;
begin
  maxLen := 0;
  for i := 0 to Count - 1 do begin
    v := GetVector(i);
    len := v.x * v.x + v.y * v.y;
    len := sqrt(v.x*v.x + v.y*v.y);
//    len := sqrt(sqr(v.x) + sqr(v.y));
    maxLen := Max(len, maxlen);
  end;
  if maxLen = 0 then
    exit;
  factor := ALength / maxLen;
  for i := 0 to Count - 1 do begin
    v := GetVector(i);
    SetVector(i, v*factor);
  end;
end;

procedure TFieldSeries.SetArrow(AValue: TChartArrow);
begin
  FArrow.Assign(AValue);
  UpdateParentChart;
end;

procedure TFieldSeries.SetCoordKind(AValue: TVectorCoordkind);
begin
  if AValue <> FCoordKind then
  begin
    FCoordKind := AValue;
    UpdateParentChart;
  end;
end;

procedure TFieldSeries.SetPen(AValue: TPen);
begin
  FPen.Assign(AValue);
end;

procedure TFieldSeries.SetVector(AIndex: Integer; const AValue: TDoublePoint);
begin
  with ListSource.Item[AIndex]^ do begin
    case FCoordKind of
      vckCenterDir:
        begin
          XList[0] := AValue.X;
          YList[0] := AValue.Y;
        end;
      vckStartEnd:
        begin
          XList[0] := X + AValue.X;
          YList[0] := Y + AValue.Y;
        end;
    end;
  end;
end;


initialization
  RegisterSeriesClass(TBubbleSeries, @rsBubbleSeries);
  RegisterSeriesClass(TBoxAndWhiskerSeries, @rsBoxAndWhiskerSeries);
  RegisterSeriesClass(TOpenHighLowCloseSeries, @rsOpenHighLowCloseSeries);
  RegisterSeriesClass(TFieldSeries, @rsFieldSeries);

end.