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
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
|
namespace FundLab.Api
open System
open System.Data
open System.Data.Common
open System.Globalization
open System.Security.Cryptography
open System.Text
open FundLab.Domain
open Npgsql
open NpgsqlTypes
open System.Text.Json
module ConfirmationPolicy =
let cutoffTimeOfDay = TimeSpan(15, 0, 0)
let unitsMaximum = 99999999999999999999.99999999m
let amountMaximum = 999999999999999999.99m
let private shanghaiZone =
lazy (
try
TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai")
with _ ->
TimeZoneInfo.CreateCustomTimeZone(
"Asia/Shanghai (UTC+8)",
TimeSpan(8, 0, 0),
"Asia/Shanghai (UTC+8)",
"Asia/Shanghai (UTC+8)"
)
)
let shanghaiDate (moment: DateTimeOffset) : DateOnly =
DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, shanghaiZone.Value).Date)
let private isWeekend (date: DateOnly) =
date.DayOfWeek = DayOfWeek.Saturday || date.DayOfWeek = DayOfWeek.Sunday
let rec private rollToWeekday (date: DateOnly) =
if isWeekend date then rollToWeekday (date.AddDays 1) else date
let isModeledTradingDay (date: DateOnly) : bool = not (isWeekend date)
/// Test-only clock anchor: modules may pin the trading-date clock by exporting
/// FUND_LAB_TEST_TRADE_DATE so suites stay independent of the wall clock. Unset in
/// production, the real Shanghai rule applies unchanged.
let tradeDateFor (submittedAt: DateTimeOffset) : DateOnly =
match Environment.GetEnvironmentVariable("FUND_LAB_TEST_TRADE_DATE") with
| value when not (String.IsNullOrWhiteSpace value) ->
match DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
| true, anchored -> anchored
| _ ->
let local = TimeZoneInfo.ConvertTime(submittedAt, shanghaiZone.Value)
let date = DateOnly.FromDateTime(local.Date)
let candidate = if local.TimeOfDay >= cutoffTimeOfDay then date.AddDays 1 else date
rollToWeekday candidate
| _ ->
let local = TimeZoneInfo.ConvertTime(submittedAt, shanghaiZone.Value)
let date = DateOnly.FromDateTime(local.Date)
let candidate = if local.TimeOfDay >= cutoffTimeOfDay then date.AddDays 1 else date
rollToWeekday candidate
/// Calendar date used to bucket events (cash flows, holdings) on the returns
/// timeline. Shares the FUND_LAB_TEST_TRADE_DATE anchor with tradeDateFor so a
/// pinned suite does not drift when the host crosses midnight; production (no
/// pin) is exactly the Shanghai calendar date of the moment.
let eventDateFor (moment: DateTimeOffset) : DateOnly =
match Environment.GetEnvironmentVariable("FUND_LAB_TEST_TRADE_DATE") with
| value when not (String.IsNullOrWhiteSpace value) ->
match DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
| true, anchored -> anchored
| _ -> shanghaiDate moment
| _ -> shanghaiDate moment
type NavQuote =
{ NavDate: DateOnly
Nav: decimal
CollectedAt: DateTimeOffset
PublishedAt: DateTimeOffset option }
type ConfirmationComputation =
{
Units: decimal
InvestedCash: decimal
ResidualCash: decimal
}
let navDeferralReason
(quote: NavQuote)
(tradeDate: DateOnly)
(today: DateOnly)
(now: DateTimeOffset)
: string option =
let tradeDateText = tradeDate.ToString("yyyy-MM-dd")
if quote.Nav <= 0m then
Some(sprintf "nav for trade date %s is not positive" tradeDateText)
elif quote.NavDate > today then
Some(sprintf "nav for trade date %s is dated in the future" tradeDateText)
elif quote.CollectedAt > now then
Some(sprintf "nav for trade date %s is not yet collected" tradeDateText)
elif quote.PublishedAt |> Option.exists (fun publishedAt -> publishedAt > now) then
Some(sprintf "nav for trade date %s is not yet published" tradeDateText)
elif quote.NavDate <> tradeDate then
Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
else
None
let compute (amount: decimal) (nav: decimal) : Result<ConfirmationComputation, string> =
if amount <= 0m then
Error "amount must be positive"
elif amount > amountMaximum then
Error "amount exceeds supported precision"
elif nav <= 0m then
Error "unit nav must be positive"
elif nav < 0.00000001m then
Error "unit nav is below database precision"
else
let rawUnits = amount / nav
if rawUnits > unitsMaximum then
Error "unit amount exceeds database precision"
else
let units = Decimal.Truncate(rawUnits * 100000000m) / 100000000m
if units <= 0m then
Error "amount converts to zero units at this unit nav"
else
let invested = Decimal.Truncate(units * nav * 100m) / 100m
Ok
{
Units = units
InvestedCash = invested
ResidualCash = amount - invested
}
[<CLIMutable>]
type FundCreateCommand =
{
Name: string
InitialCash: decimal
InitialUnitNav: decimal
IsSynthetic: bool
}
type FundRecord =
{
Id: Guid
Name: string
Currency: string
InitialCash: decimal
InitialUnitNav: decimal
IsSynthetic: bool
AvailableCash: decimal
ReservedCash: decimal
Status: string
CreatedAt: DateTimeOffset
}
type FundWriteResult =
| Created of FundRecord
| Replayed of FundRecord
| IdempotencyConflict
| Invalid of string
[<CLIMutable>]
type SubscriptionOrderCommand =
{
FundCode: string
Amount: decimal
FeeAmount: decimal
}
type ConfirmedQuoteEvidence =
{
Nav: decimal
NavDate: DateOnly
Source: string
Revision: string
CollectedAt: DateTimeOffset
PublishedAt: DateTimeOffset option
PayloadHash: string
FirstSeenAt: DateTimeOffset
}
type SubscriptionOrderRecord =
{
Id: Guid
FundId: Guid
FundCode: string
Amount: decimal
FeeAmount: decimal
ReservedTotal: decimal
Status: string
SubmittedAt: DateTimeOffset
IsSynthetic: bool
TradeDate: DateOnly
ConfirmIdempotencyKey: string option
PendingReason: string option
ConfirmedAt: DateTimeOffset option
ConfirmedQuote: ConfirmedQuoteEvidence option
ConfirmedUnits: decimal option
ConfirmedInvestedCash: decimal option
ConfirmedResidualCash: decimal option
}
type SubscriptionOrderWriteResult =
| OrderCreated of SubscriptionOrderRecord
| OrderReplayed of SubscriptionOrderRecord
| OrderIdempotencyConflict
| OrderInvalid of string
| OrderFundNotFound
| OrderInstrumentNotFound
| OrderInsufficientFunds
type SubscriptionConfirmResult =
| OrderConfirmed of SubscriptionOrderRecord
| ConfirmReplayed of SubscriptionOrderRecord
| ConfirmPendingNav of SubscriptionOrderRecord
| ConfirmIdempotencyConflict
| ConfirmAlreadyConfirmed
| ConfirmOrderNotFound
| ConfirmInvalidStatus
| ConfirmInvalid of string
type FundPositionRecord =
{
FundId: Guid
InstrumentCode: string
Units: decimal
ReservedUnits: decimal
CostCash: decimal
LastConfirmedAt: DateTimeOffset
ValuationNav: decimal option
ValuationNavDate: DateOnly option
ValuationCollectedAt: DateTimeOffset option
}
type RedemptionCommand =
{
InstrumentCode: string
Units: decimal
FeeAmount: decimal
}
type RedemptionOrderRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
Units: decimal
FeeAmount: decimal
Status: string
IsSynthetic: bool
SubmittedAt: DateTimeOffset
TradeDate: DateOnly
ConfirmIdempotencyKey: string option
PendingReason: string option
ConfirmedAt: DateTimeOffset option
ConfirmedNav: decimal option
ConfirmedNavDate: DateOnly option
ConfirmedProceeds: decimal option
ConfirmedCostReleased: decimal option
}
type RedemptionWriteResult =
| RedemptionCreated of RedemptionOrderRecord
| RedemptionReplayed of RedemptionOrderRecord
| RedemptionIdempotencyConflict
| RedemptionInvalid of string
| RedemptionFundNotFound
| RedemptionInstrumentNotFound
| RedemptionInsufficientUnits
type RedemptionConfirmResult =
| RedemptionConfirmed of RedemptionOrderRecord
| RedemptionConfirmReplayed of RedemptionOrderRecord
| RedemptionPendingNav of RedemptionOrderRecord
| RedemptionConfirmIdempotencyConflict
| RedemptionAlreadyConfirmed
| RedemptionOrderNotFound
| RedemptionInvalidStatus
| RedemptionInvalid of string
type SipPlanCommand =
{
InstrumentCode: string
Amount: decimal
Frequency: SipFrequency
}
/// Minimal live-quote view used to drive a stock SIP period. The resolver is
/// supplied by the API layer (which owns the market-data probe); the repository
/// only interprets the snapshot.
type StockSipQuote =
{
Price: decimal option
Name: string option
Suspended: bool option
}
type StockTradeCommand =
{
InstrumentCode: string
StockName: string option
Quantity: decimal
Price: decimal
}
type StockTradeRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
StockName: string option
Quantity: decimal
Price: decimal
CostCash: decimal
IsSynthetic: bool
ExecutedAt: DateTimeOffset
}
type StockPositionRecord =
{
FundId: Guid
InstrumentCode: string
StockName: string option
Quantity: decimal
CostCash: decimal
LastTradedAt: DateTimeOffset
}
type StockTradeWriteResult =
| StockTradeCreated of StockTradeRecord
| StockTradeReplayed of StockTradeRecord
| StockTradeIdempotencyConflict
| StockTradeInvalid of string
| StockTradeInsufficientFunds of string
| StockTradeFundNotFound
type StockSellCommand =
{
InstrumentCode: string
StockName: string option
Quantity: decimal
Price: decimal
FeeAmount: decimal
}
type StockSellRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
StockName: string option
Quantity: decimal
Price: decimal
FeeAmount: decimal
Proceeds: decimal
IsSynthetic: bool
ExecutedAt: DateTimeOffset
}
type StockSellWriteResult =
| StockSellCreated of StockSellRecord
| StockSellReplayed of StockSellRecord
| StockSellIdempotencyConflict
| StockSellInvalid of string
| StockSellInsufficientHoldings of string
| StockSellFundNotFound
type StockCashflowCommand =
{
InstrumentCode: string
StockName: string option
/// "buy" (cash out), "sell" (cash in) or "dividend" (cash in).
EventType: string
EventDate: DateOnly
Quantity: decimal
/// Absolute cash magnitude; the sign is implied by the event type.
Amount: decimal
Note: string option
}
type StockCashflowRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
StockName: string option
EventType: string
EventDate: DateOnly
Quantity: decimal
Amount: decimal
Note: string option
IsSynthetic: bool
CreatedAt: DateTimeOffset
}
type StockCashflowWriteResult =
| StockCashflowCreated of StockCashflowRecord
| StockCashflowReplayed of StockCashflowRecord
| StockCashflowIdempotencyConflict
| StockCashflowInvalid of string
| StockCashflowFundNotFound
type BondTradeCommand =
{
InstrumentCode: string
BondName: string option
Quantity: decimal
/// All-in (dirty/全价) execution price per 100 of face value.
Price: decimal
CleanPrice: decimal
AccruedInterest: decimal
ParValue: decimal
SettlementDate: DateOnly
CouponRate: decimal option
ValueDate: DateOnly option
MaturityDate: DateOnly option
/// Explicit trade/valuation date supplied by the caller (wins over the
/// quote's own date so tests and backfills stay deterministic).
TradeDate: DateOnly option
}
type BondTradeRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
BondName: string option
Quantity: decimal
Price: decimal
CleanPrice: decimal
AccruedInterest: decimal
ParValue: decimal
SettlementDate: DateOnly
CouponRate: decimal option
ValueDate: DateOnly option
MaturityDate: DateOnly option
TradeDate: DateOnly
CostCash: decimal
IsSynthetic: bool
ExecutedAt: DateTimeOffset
}
type BondCashflowCommand =
{
InstrumentCode: string
BondName: string option
/// "coupon" (付息) or "maturity" (到期).
EventType: string
EventDate: DateOnly
Quantity: decimal
/// Cash credited to the fund's available cash.
Amount: decimal
Note: string option
}
type BondCashflowRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
BondName: string option
EventType: string
EventDate: DateOnly
Quantity: decimal
Amount: decimal
Note: string option
IsSynthetic: bool
CreatedAt: DateTimeOffset
}
type BondCashflowWriteResult =
| BondCashflowCreated of BondCashflowRecord
| BondCashflowReplayed of BondCashflowRecord
| BondCashflowIdempotencyConflict
| BondCashflowInvalid of string
| BondCashflowFundNotFound
| BondCashflowPositionNotFound
type BondPositionRecord =
{
FundId: Guid
InstrumentCode: string
BondName: string option
Quantity: decimal
CostCash: decimal
LastTradedAt: DateTimeOffset
}
type BondSellCommand =
{
InstrumentCode: string
BondName: string option
Quantity: decimal
/// All-in (dirty/全价) sell price per 100 of face value.
Price: decimal
CleanPrice: decimal
AccruedInterest: decimal
ParValue: decimal
SettlementDate: DateOnly
TradeDate: DateOnly option
FeeAmount: decimal
}
type BondSellRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
BondName: string option
Quantity: decimal
Price: decimal
CleanPrice: decimal
AccruedInterest: decimal
ParValue: decimal
SettlementDate: DateOnly
TradeDate: DateOnly
FeeAmount: decimal
/// Cash credited to the fund after fees (dirty amount minus fee).
Proceeds: decimal
/// Average-cost basis removed from the position.
CostReleased: decimal
RealizedPnl: decimal
IsSynthetic: bool
ExecutedAt: DateTimeOffset
}
type BondSellWriteResult =
| BondSellCreated of BondSellRecord
| BondSellReplayed of BondSellRecord
| BondSellIdempotencyConflict
| BondSellInvalid of string
| BondSellInsufficientHoldings of string
| BondSellFundNotFound
type InstrumentSnapshotRecord =
{
InstrumentCode: string
AssetClass: string
SnapshotDate: DateOnly
Price: decimal
Source: string
SourceRevision: string
SourceCollectedAt: DateTimeOffset
SourcePayloadHash: string
}
type BondTradeWriteResult =
| BondTradeCreated of BondTradeRecord
| BondTradeReplayed of BondTradeRecord
| BondTradeIdempotencyConflict
| BondTradeInvalid of string
| BondTradeFundNotFound
type SipPlanRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
AssetClass: string
Amount: decimal
Frequency: SipFrequency
Status: string
IsSynthetic: bool
AnchorDate: DateOnly
NextTradeDate: DateOnly
CreatedAt: DateTimeOffset
LastExecutionStatus: string option
LastExecutionDate: DateOnly option
}
type SipPlanWriteResult =
| SipPlanCreated of SipPlanRecord
| SipPlanReplayed of SipPlanRecord
| SipPlanIdempotencyConflict
| SipPlanInvalid of string
| SipPlanFundNotFound
| SipPlanInstrumentNotFound
type SipPlanStatusResult =
| SipPlanStatusChanged of SipPlanRecord
| SipPlanStatusNotFound
type SipExecutionOutcome =
{
TradeDate: DateOnly
Status: string
OrderId: Guid option
PendingReason: string option
}
type SipPlanAdvanceResult =
{
PlanId: Guid
InstrumentCode: string
AssetClass: string
Amount: decimal
Frequency: SipFrequency
Executions: SipExecutionOutcome list
NextTradeDate: DateOnly
}
type SipAdvanceResult =
{
FundId: Guid
Plans: SipPlanAdvanceResult list
}
type InvestmentPlanCommand =
{
InstrumentCode: string
Amount: decimal
Frequency: InvestmentFrequency
}
type InvestmentPlanRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
Amount: decimal
Frequency: InvestmentFrequency
Status: string
IsSynthetic: bool
AnchorDate: DateOnly
NextRunDate: DateOnly
CreatedAt: DateTimeOffset
LastRunStatus: string option
LastRunDate: DateOnly option
}
type InvestmentPlanWriteResult =
| InvestmentPlanCreated of InvestmentPlanRecord
| InvestmentPlanReplayed of InvestmentPlanRecord
| InvestmentPlanIdempotencyConflict
| InvestmentPlanInvalid of string
| InvestmentPlanFundNotFound
| InvestmentPlanInstrumentNotFound
type InvestmentPlanRunOutcome =
{
RunDate: DateOnly
Status: string
OrderId: Guid option
PendingReason: string option
}
type InvestmentPlanRunPlanResult =
{
PlanId: Guid
InstrumentCode: string
Amount: decimal
Frequency: InvestmentFrequency
Runs: InvestmentPlanRunOutcome list
NextRunDate: DateOnly
}
type InvestmentPlanRunResult =
{
FundId: Guid
ProcessingDate: DateOnly
Plans: InvestmentPlanRunPlanResult list
}
type RebalanceTarget = RebalancePolicy.TargetAllocation
type RebalancePlanCommand =
{
Targets: RebalanceTarget list
}
type RebalancePlanRecord =
{
Id: Guid
FundId: Guid
Targets: RebalanceTarget list
Status: string
IsSynthetic: bool
CreatedAt: DateTimeOffset
}
type RebalanceWriteResult =
| RebalancePlanCreated of RebalancePlanRecord
| RebalancePlanReplayed of RebalancePlanRecord
| RebalanceIdempotencyConflict
| RebalanceInvalid of string
| RebalanceFundNotFound
| RebalanceInstrumentNotFound
type RebalanceArchiveResult =
| RebalancePlanArchived of RebalancePlanRecord
| RebalanceArchiveNotFound
type RebalanceOrderOutcome =
{
InstrumentCode: string
Action: string
Amount: string
Status: string
OrderId: Guid option
PendingReason: string option
}
type RebalanceExecutionResult =
{
PlanId: Guid
RunDate: DateOnly
Outcomes: RebalanceOrderOutcome list
}
type RebalanceExecutionRecord =
{
PlanId: Guid
RunDate: DateOnly
InstrumentCode: string
Action: string
Amount: decimal
Status: string
OrderId: Guid option
PendingReason: string option
ExecutedAt: DateTimeOffset
}
type RebalancePreview =
{
PlanId: Guid
RunDate: DateOnly
AvailableCash: decimal
Equity: decimal
Rows: RebalancePolicy.RebalanceWeightRow list
}
type DividendMode = DividendPolicy.DividendMode
type DividendCommand =
{
InstrumentCode: string
NavDate: DateOnly
Dps: decimal
Mode: DividendMode
}
type DividendRecord =
{
Id: Guid
FundId: Guid
InstrumentCode: string
NavDate: DateOnly
Dps: decimal
Mode: DividendMode
Status: string
IsSynthetic: bool
GrossCash: decimal option
CreditedUnits: decimal option
CreditedInvested: decimal option
OrderId: Guid option
PendingReason: string option
CreatedAt: DateTimeOffset
}
type DividendWriteResult =
| DividendCredited of DividendRecord
| DividendReplayed of DividendRecord
| DividendPendingReinvest of DividendRecord
| DividendIdempotencyConflict
| DividendInvalid of string
| DividendFundNotFound
| DividendInstrumentNotFound
| DividendNoHoldings
type DividendStageDecision =
| StageReplay of Guid
| StageFail of DividendWriteResult
| StageBooked of DividendRecord
type CapitalDepositCommand =
{
Amount: decimal
Note: string option
}
type CapitalDepositRecord =
{
Id: Guid
FundId: Guid
Amount: decimal
Note: string option
IsSynthetic: bool
CreatedAt: DateTimeOffset
}
type CapitalDepositWriteResult =
| CapitalDepositCreated of CapitalDepositRecord
| CapitalDepositReplayed of CapitalDepositRecord
| CapitalDepositIdempotencyConflict
| CapitalDepositInvalid of string
| CapitalDepositFundNotFound
/// One reconstructed end-of-day fund valuation. `TotalAssets`/`UnitNav`/
/// `HoldingsValue`/`CumulativeReturn` are `None` when a held instrument has no
/// NAV observation dated on or before `Date`: the value is unknown, never zero.
type FundReturnsPoint =
{
Date: DateOnly
Pending: bool
TotalAssets: decimal option
UnitNav: decimal option
Cash: decimal
ReservedCash: decimal
HoldingsValue: decimal option
CumulativeReturn: decimal option
NetExternalFlow: decimal
}
type FundReturns =
{
FundId: Guid
Pending: bool
DataUpdatedAt: DateTimeOffset option
Points: FundReturnsPoint list
}
type FundRepository(connectionString: string) =
let cashMaximum = 999999999999999999.99m
let unitNavMaximum = 99999999999999999999.99999999m
let schema =
"""
CREATE TABLE IF NOT EXISTS funds (
id uuid PRIMARY KEY,
name text NOT NULL,
currency text NOT NULL,
initial_cash numeric(20, 2) NOT NULL,
initial_unit_nav numeric(28, 8) NOT NULL,
is_synthetic boolean NOT NULL,
available_cash numeric(20, 2) NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS fund_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS instruments (
code text PRIMARY KEY CHECK (code ~ '^[0-9]{6}$'),
name text NOT NULL,
fund_type text NULL,
source text NOT NULL,
source_revision text NOT NULL,
source_collected_at timestamptz NOT NULL,
source_payload_hash text NOT NULL,
first_seen_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS fund_nav_observations (
instrument_code text NOT NULL REFERENCES instruments(code),
nav_date date NOT NULL,
published_at timestamptz NULL,
nav numeric(28, 8) NOT NULL,
accumulated_nav numeric(28, 8) NULL,
daily_return numeric(20, 8) NULL,
source text NOT NULL,
source_revision text NOT NULL,
source_collected_at timestamptz NOT NULL,
source_payload_hash text NOT NULL,
first_seen_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (instrument_code, nav_date)
);
CREATE INDEX IF NOT EXISTS fund_nav_observations_date_idx
ON fund_nav_observations (instrument_code, nav_date);
CREATE TABLE IF NOT EXISTS fund_nav_observation_evidence (
instrument_code text NOT NULL REFERENCES instruments(code),
nav_date date NOT NULL,
source_payload_hash text NOT NULL,
source_revision text NOT NULL,
source text NOT NULL,
source_collected_at timestamptz NOT NULL,
published_at timestamptz NULL,
nav numeric(28, 8) NOT NULL,
first_seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (instrument_code, nav_date, source_payload_hash)
);
ALTER TABLE funds ADD COLUMN IF NOT EXISTS reserved_cash numeric(20, 2) NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS subscription_orders (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
fund_code text NOT NULL,
amount numeric(20, 2) NOT NULL CHECK (amount > 0),
fee_amount numeric(20, 2) NOT NULL CHECK (fee_amount >= 0),
reserved_total numeric(20, 2) NOT NULL CHECK (reserved_total > 0),
status text NOT NULL,
is_synthetic boolean NOT NULL,
submitted_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE subscription_orders DROP CONSTRAINT IF EXISTS subscription_orders_fee_amount_check;
ALTER TABLE subscription_orders ADD CONSTRAINT subscription_orders_fee_amount_check CHECK (fee_amount >= 0);
CREATE TABLE IF NOT EXISTS subscription_order_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
order_id uuid NOT NULL REFERENCES subscription_orders(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirm_idempotency_key text NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS pending_reason text NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_at timestamptz NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav numeric(28, 8) NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_date date NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_source text NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_revision text NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_collected_at timestamptz NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_published_at timestamptz NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_units numeric(28, 8) NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_invested_cash numeric(20, 2) NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_residual_cash numeric(20, 2) NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_payload_hash text NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_first_seen_at timestamptz NULL;
ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS trade_date date NULL;
UPDATE subscription_orders SET trade_date = (submitted_at AT TIME ZONE 'Asia/Shanghai')::date WHERE trade_date IS NULL;
CREATE TABLE IF NOT EXISTS fund_positions (
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL REFERENCES instruments(code),
units numeric(28, 8) NOT NULL CHECK (units > 0),
cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
first_confirmed_at timestamptz NOT NULL,
last_confirmed_at timestamptz NOT NULL,
PRIMARY KEY (fund_id, instrument_code)
);
CREATE TABLE IF NOT EXISTS subscription_order_events (
id bigserial PRIMARY KEY,
order_id uuid NOT NULL REFERENCES subscription_orders(id),
event_type text NOT NULL,
detail jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS subscription_confirm_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
order_id uuid NOT NULL REFERENCES subscription_orders(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS redemption_orders (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL REFERENCES instruments(code),
units numeric(28, 8) NOT NULL CHECK (units > 0),
fee_amount numeric(20, 2) NOT NULL CHECK (fee_amount >= 0),
status text NOT NULL,
is_synthetic boolean NOT NULL,
submitted_at timestamptz NOT NULL DEFAULT now(),
trade_date date NOT NULL,
confirm_idempotency_key text NULL,
pending_reason text NULL,
confirmed_at timestamptz NULL,
confirmed_nav numeric(28, 8) NULL,
confirmed_nav_date date NULL,
confirmed_proceeds numeric(20, 2) NULL,
confirmed_cost_released numeric(20, 2) NULL
);
CREATE TABLE IF NOT EXISTS redemption_order_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
order_id uuid NOT NULL REFERENCES redemption_orders(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS redemption_confirm_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
order_id uuid NOT NULL REFERENCES redemption_orders(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE fund_positions ADD COLUMN IF NOT EXISTS reserved_units numeric(28, 8) NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS fund_capital_deposits (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
amount numeric(20, 2) NOT NULL CHECK (amount > 0),
note text NULL,
is_synthetic boolean NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS fund_capital_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
deposit_id uuid NOT NULL REFERENCES fund_capital_deposits(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS sip_plans (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL REFERENCES instruments(code),
amount numeric(20, 2) NOT NULL CHECK (amount > 0),
frequency text NOT NULL,
status text NOT NULL,
is_synthetic boolean NOT NULL,
anchor_date date NOT NULL,
next_trade_date date NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE sip_plans ADD COLUMN IF NOT EXISTS asset_class text NOT NULL DEFAULT 'fund';
ALTER TABLE sip_plans DROP CONSTRAINT IF EXISTS sip_plans_instrument_code_fkey;
CREATE TABLE IF NOT EXISTS sip_plan_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
plan_id uuid NOT NULL REFERENCES sip_plans(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS sip_executions (
plan_id uuid NOT NULL REFERENCES sip_plans(id),
trade_date date NOT NULL,
amount numeric(20, 2) NOT NULL,
fee_amount numeric(20, 2) NOT NULL,
status text NOT NULL,
order_id uuid NULL,
pending_reason text NULL,
executed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (plan_id, trade_date)
);
CREATE TABLE IF NOT EXISTS rebalance_plans (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
status text NOT NULL,
is_synthetic boolean NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS rebalance_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
plan_id uuid NOT NULL REFERENCES rebalance_plans(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS rebalance_targets (
plan_id uuid NOT NULL REFERENCES rebalance_plans(id),
instrument_code text NOT NULL REFERENCES instruments(code),
target_percent numeric(9, 2) NOT NULL CHECK (target_percent > 0 AND target_percent <= 100),
PRIMARY KEY (plan_id, instrument_code)
);
CREATE TABLE IF NOT EXISTS rebalance_executions (
plan_id uuid NOT NULL REFERENCES rebalance_plans(id),
run_date date NOT NULL,
instrument_code text NOT NULL,
action text NOT NULL,
amount numeric(20, 2) NOT NULL,
status text NOT NULL,
order_id uuid NULL,
pending_reason text NULL,
executed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (plan_id, run_date, instrument_code)
);
CREATE TABLE IF NOT EXISTS dividend_records (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL REFERENCES instruments(code),
nav_date date NOT NULL,
dps numeric(28, 8) NOT NULL CHECK (dps > 0),
mode text NOT NULL,
status text NOT NULL,
is_synthetic boolean NOT NULL,
gross_cash numeric(20, 2) NULL,
credited_units numeric(28, 8) NULL,
credited_invested numeric(20, 2) NULL,
order_id uuid NULL,
pending_reason text NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS stock_trades (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
stock_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
price numeric(20, 4) NOT NULL CHECK (price > 0),
cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
is_synthetic boolean NOT NULL,
executed_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS stock_trade_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
trade_id uuid NOT NULL REFERENCES stock_trades(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS stock_positions (
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
stock_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
last_traded_at timestamptz NOT NULL,
PRIMARY KEY (fund_id, instrument_code)
);
CREATE TABLE IF NOT EXISTS stock_sells (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
stock_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
price numeric(20, 4) NOT NULL CHECK (price > 0),
fee_amount numeric(20, 2) NOT NULL CHECK (fee_amount >= 0),
proceeds numeric(20, 2) NOT NULL CHECK (proceeds >= 0),
is_synthetic boolean NOT NULL,
executed_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS stock_cashflow_events (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
stock_name text NULL,
event_type text NOT NULL CHECK (event_type IN ('buy', 'sell', 'dividend')),
event_date date NOT NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity >= 0),
amount numeric(20, 2) NOT NULL CHECK (amount >= 0),
note text NULL,
is_synthetic boolean NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS stock_cashflow_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
event_id uuid NOT NULL REFERENCES stock_cashflow_events(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS stock_sell_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
sell_id uuid NOT NULL REFERENCES stock_sells(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS bond_trades (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
bond_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
price numeric(20, 4) NOT NULL CHECK (price > 0),
cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
is_synthetic boolean NOT NULL,
executed_at timestamptz NOT NULL
);
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS clean_price numeric(20, 4) NOT NULL DEFAULT 0;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS accrued_interest numeric(20, 4) NOT NULL DEFAULT 0;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS par_value numeric(20, 4) NOT NULL DEFAULT 100;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS settlement_date date NOT NULL DEFAULT CURRENT_DATE;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS coupon_rate numeric(12, 6) NULL;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS value_date date NULL;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS maturity_date date NULL;
ALTER TABLE bond_trades ADD COLUMN IF NOT EXISTS trade_date date NOT NULL DEFAULT CURRENT_DATE;
CREATE TABLE IF NOT EXISTS bond_trade_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
trade_id uuid NOT NULL REFERENCES bond_trades(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS bond_cashflow_events (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
bond_name text NULL,
event_type text NOT NULL CHECK (event_type IN ('coupon', 'maturity', 'redemption')),
event_date date NOT NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
amount numeric(20, 2) NOT NULL CHECK (amount >= 0),
note text NULL,
is_synthetic boolean NOT NULL,
created_at timestamptz NOT NULL
);
ALTER TABLE bond_cashflow_events DROP CONSTRAINT IF EXISTS bond_cashflow_events_event_type_check;
ALTER TABLE bond_cashflow_events ADD CONSTRAINT bond_cashflow_events_event_type_check CHECK (event_type IN ('coupon', 'maturity', 'redemption'));
CREATE TABLE IF NOT EXISTS bond_cashflow_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
event_id uuid NOT NULL REFERENCES bond_cashflow_events(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS bond_sells (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
bond_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
price numeric(20, 4) NOT NULL CHECK (price > 0),
clean_price numeric(20, 4) NOT NULL DEFAULT 0,
accrued_interest numeric(20, 4) NOT NULL DEFAULT 0,
par_value numeric(20, 4) NOT NULL DEFAULT 100,
settlement_date date NOT NULL DEFAULT CURRENT_DATE,
trade_date date NOT NULL DEFAULT CURRENT_DATE,
fee_amount numeric(20, 2) NOT NULL DEFAULT 0 CHECK (fee_amount >= 0),
proceeds numeric(20, 2) NOT NULL DEFAULT 0,
cost_released numeric(20, 2) NOT NULL DEFAULT 0,
realized_pnl numeric(20, 2) NOT NULL DEFAULT 0,
is_synthetic boolean NOT NULL,
executed_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS bond_sell_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
sell_id uuid NOT NULL REFERENCES bond_sells(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS bond_positions (
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL,
bond_name text NULL,
quantity numeric(28, 8) NOT NULL CHECK (quantity > 0),
cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
last_traded_at timestamptz NOT NULL,
PRIMARY KEY (fund_id, instrument_code)
);
CREATE TABLE IF NOT EXISTS instrument_snapshots (
instrument_code text NOT NULL,
asset_class text NOT NULL CHECK (asset_class IN ('stock', 'bond')),
snapshot_date date NOT NULL,
price numeric(28, 8) NOT NULL CHECK (price > 0),
source text NOT NULL,
source_revision text NOT NULL,
source_collected_at timestamptz NOT NULL,
source_payload_hash text NOT NULL,
first_seen_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (instrument_code, asset_class, snapshot_date)
);
CREATE INDEX IF NOT EXISTS instrument_snapshots_date_idx
ON instrument_snapshots (instrument_code, asset_class, snapshot_date DESC);
CREATE TABLE IF NOT EXISTS dividend_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
record_id uuid NOT NULL REFERENCES dividend_records(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS investment_plans (
id uuid PRIMARY KEY,
fund_id uuid NOT NULL REFERENCES funds(id),
instrument_code text NOT NULL REFERENCES instruments(code),
amount numeric(20, 2) NOT NULL CHECK (amount > 0),
frequency text NOT NULL,
status text NOT NULL,
is_synthetic boolean NOT NULL,
anchor_date date NOT NULL,
next_run_date date NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS investment_plan_idempotencies (
idempotency_key text PRIMARY KEY,
request_hash text NOT NULL,
plan_id uuid NOT NULL REFERENCES investment_plans(id),
fund_id uuid NOT NULL REFERENCES funds(id),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS investment_plan_runs (
plan_id uuid NOT NULL REFERENCES investment_plans(id),
run_date date NOT NULL,
amount numeric(20, 2) NOT NULL,
fee_amount numeric(20, 2) NOT NULL,
status text NOT NULL,
order_id uuid NULL,
pending_reason text NULL,
executed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (plan_id, run_date)
);
"""
let statusText status =
match status with
| FundStatus.Empty -> "empty"
| FundStatus.Active -> "active"
| FundStatus.ZeroUnits -> "zero_units"
let cashText (value: decimal) = value.ToString("0.00", CultureInfo.InvariantCulture)
let decimalText (value: decimal) = value.ToString("0.00000000", CultureInfo.InvariantCulture)
let recordFromLedger (fund: LedgerFund) =
{
Id = fund.Id
Name = fund.Name
Currency = fund.Currency
InitialCash = fund.InitialCash
InitialUnitNav = fund.InitialUnitNav
IsSynthetic = fund.IsSynthetic
AvailableCash = fund.AvailableCash
ReservedCash = fund.FrozenCash
Status = statusText fund.Status
CreatedAt = DateTimeOffset.UtcNow
}
let recordFromReader (reader: DbDataReader) =
{
Id = reader.GetGuid(0)
Name = reader.GetString(1)
Currency = reader.GetString(2)
InitialCash = reader.GetDecimal(3)
InitialUnitNav = reader.GetDecimal(4)
IsSynthetic = reader.GetBoolean(5)
AvailableCash = reader.GetDecimal(6)
ReservedCash = reader.GetDecimal(7)
Status = reader.GetString(8)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(9)
}
let dateTimeOffsetFromReader (reader: DbDataReader) index =
reader.GetFieldValue<DateTimeOffset>(index)
let optionalDateTimeOffsetFromReader (reader: DbDataReader) index =
if reader.IsDBNull(index) then None else Some(dateTimeOffsetFromReader reader index)
let optionalDecimalFromReader (reader: DbDataReader) index =
if reader.IsDBNull(index) then None else Some(reader.GetDecimal(index))
let instrumentRecordFromReader (reader: DbDataReader) : MarketDataInstrumentRecord =
{
Code = reader.GetString(0)
Name = reader.GetString(1)
FundType = if reader.IsDBNull(2) then None else Some(reader.GetString(2))
Source = reader.GetString(3)
SourceRevision = reader.GetString(4)
SourceCollectedAt = dateTimeOffsetFromReader reader 5
SourcePayloadHash = reader.GetString(6)
FirstSeenAt = dateTimeOffsetFromReader reader 7
LastSeenAt = dateTimeOffsetFromReader reader 8
}
let navRecordFromReader (reader: DbDataReader) : MarketDataNavRecord =
{
Code = reader.GetString(0)
NavDate = reader.GetFieldValue<DateOnly>(1)
PublishedAt = optionalDateTimeOffsetFromReader reader 2
Nav = reader.GetDecimal(3)
AccumulatedNav = optionalDecimalFromReader reader 4
DailyReturn = optionalDecimalFromReader reader 5
Source = reader.GetString(6)
SourceRevision = reader.GetString(7)
SourceCollectedAt = dateTimeOffsetFromReader reader 8
SourcePayloadHash = reader.GetString(9)
FirstSeenAt = dateTimeOffsetFromReader reader 10
LastSeenAt = dateTimeOffsetFromReader reader 11
}
let commandWithTransaction (connection: NpgsqlConnection) (transaction: NpgsqlTransaction option) sql =
let command = connection.CreateCommand()
command.CommandText <- sql
match transaction with
| Some value -> command.Transaction <- value
| None -> ()
command
let addParameter (command: NpgsqlCommand) name dbType (value: obj) =
let parameter = command.Parameters.Add(name, dbType)
parameter.Value <- value
parameter
let optionalParameterValue value =
match value with
| Some actual -> box actual
| None -> box DBNull.Value
let findFund connection transaction fundId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT id, name, currency, initial_cash, initial_unit_nav,
is_synthetic, available_cash, reserved_cash, status, created_at
FROM funds
WHERE id = @fund_id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(recordFromReader reader) else None
let findIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id FROM fund_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(reader.GetString(0), reader.GetGuid(1)) else None
let insertFund connection transaction (fund: LedgerFund) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO funds
(id, name, currency, initial_cash, initial_unit_nav,
is_synthetic, available_cash, reserved_cash, status)
VALUES
(@id, @name, @currency, @initial_cash, @initial_unit_nav,
@is_synthetic, @available_cash, @reserved_cash, @status)
"""
addParameter command "id" NpgsqlDbType.Uuid (box fund.Id) |> ignore
addParameter command "name" NpgsqlDbType.Text (box fund.Name) |> ignore
addParameter command "currency" NpgsqlDbType.Text (box fund.Currency) |> ignore
addParameter command "initial_cash" NpgsqlDbType.Numeric (box fund.InitialCash) |> ignore
addParameter command "initial_unit_nav" NpgsqlDbType.Numeric (box fund.InitialUnitNav) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box fund.IsSynthetic) |> ignore
addParameter command "available_cash" NpgsqlDbType.Numeric (box fund.AvailableCash) |> ignore
addParameter command "reserved_cash" NpgsqlDbType.Numeric (box fund.FrozenCash) |> ignore
addParameter command "status" NpgsqlDbType.Text (box (statusText fund.Status)) |> ignore
command.ExecuteNonQuery() |> ignore
let insertIdempotency connection transaction key requestHash fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO fund_idempotencies (idempotency_key, request_hash, fund_id)
VALUES (@idempotency_key, @request_hash, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let orderStatusText = "submitted"
let readStringOption (reader: DbDataReader) ordinal =
if reader.IsDBNull ordinal then None else Some(reader.GetString ordinal)
let readDecimalOption (reader: DbDataReader) ordinal =
if reader.IsDBNull ordinal then None else Some(reader.GetDecimal ordinal)
let orderRecordFromReader (reader: DbDataReader) : SubscriptionOrderRecord =
let confirmedQuote =
if reader.IsDBNull(13) then
None
else
Some
{
Nav = reader.GetDecimal(13)
NavDate = reader.GetFieldValue<DateOnly>(14)
Source = reader.GetString(15)
Revision = reader.GetString(16)
CollectedAt = reader.GetFieldValue<DateTimeOffset>(17)
PublishedAt =
if reader.IsDBNull(18) then
None
else
Some(reader.GetFieldValue<DateTimeOffset>(18))
PayloadHash =
if reader.IsDBNull(19) then
""
else
reader.GetString(19)
FirstSeenAt =
if reader.IsDBNull(20) then
DateTimeOffset.UnixEpoch
else
reader.GetFieldValue<DateTimeOffset>(20)
}
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
FundCode = reader.GetString(2)
Amount = reader.GetDecimal(3)
FeeAmount = reader.GetDecimal(4)
ReservedTotal = reader.GetDecimal(5)
Status = reader.GetString(6)
IsSynthetic = reader.GetBoolean(7)
SubmittedAt = reader.GetFieldValue<DateTimeOffset>(8)
TradeDate = reader.GetFieldValue<DateOnly>(9)
ConfirmIdempotencyKey = readStringOption reader 10
PendingReason = readStringOption reader 11
ConfirmedAt =
if reader.IsDBNull(12) then
None
else
Some(reader.GetFieldValue<DateTimeOffset>(12))
ConfirmedUnits = readDecimalOption reader 21
ConfirmedQuote = confirmedQuote
ConfirmedInvestedCash = readDecimalOption reader 22
ConfirmedResidualCash = readDecimalOption reader 23
}
let findOrder connection transaction orderId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT id, fund_id, fund_code, amount, fee_amount,
reserved_total, status, is_synthetic, submitted_at,
trade_date,
confirm_idempotency_key, pending_reason, confirmed_at,
confirmed_nav, confirmed_nav_date, confirmed_nav_source,
confirmed_nav_revision, confirmed_nav_collected_at, confirmed_nav_published_at,
confirmed_nav_payload_hash, confirmed_nav_first_seen_at,
confirmed_units, confirmed_invested_cash, confirmed_residual_cash
FROM subscription_orders
WHERE id = @order_id
"""
addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(orderRecordFromReader reader) else None
let findConfirmIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, order_id FROM subscription_confirm_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findOrderIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, order_id FROM subscription_order_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let instrumentExists connection transaction code =
use command =
commandWithTransaction
connection
transaction
"SELECT 1 FROM instruments WHERE code = @code"
addParameter command "code" NpgsqlDbType.Text (box code) |> ignore
use reader = command.ExecuteReader()
reader.Read()
let lockFundForOrder connection transaction fundId =
use command =
commandWithTransaction
connection
transaction
"SELECT is_synthetic FROM funds WHERE id = @fund_id FOR UPDATE"
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(reader.GetBoolean(0)) else None
let insertSubscriptionOrder connection transaction (order: SubscriptionOrderRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO subscription_orders
(id, fund_id, fund_code, amount, fee_amount,
reserved_total, status, is_synthetic, trade_date)
VALUES
(@id, @fund_id, @fund_code, @amount, @fee_amount,
@reserved_total, @status, @is_synthetic, @trade_date)
RETURNING submitted_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box order.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box order.FundId) |> ignore
addParameter command "fund_code" NpgsqlDbType.Text (box order.FundCode) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box order.Amount) |> ignore
addParameter command "fee_amount" NpgsqlDbType.Numeric (box order.FeeAmount) |> ignore
addParameter command "reserved_total" NpgsqlDbType.Numeric (box order.ReservedTotal) |> ignore
addParameter command "status" NpgsqlDbType.Text (box order.Status) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box order.IsSynthetic) |> ignore
addParameter command "trade_date" NpgsqlDbType.Date (box order.TradeDate) |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertOrderIdempotency connection transaction key requestHash orderId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO subscription_order_idempotencies (idempotency_key, request_hash, order_id, fund_id)
VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let upsertInstrument connection transaction (payload: MarketDataSearchPayload) payloadHash (instrument: MarketDataInstrument) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO instruments
(code, name, fund_type, source, source_revision,
source_collected_at, source_payload_hash)
VALUES
(@code, @name, @fund_type, @source, @source_revision,
@source_collected_at, @source_payload_hash)
ON CONFLICT (code) DO UPDATE SET
name = EXCLUDED.name,
fund_type = EXCLUDED.fund_type,
source = EXCLUDED.source,
source_revision = EXCLUDED.source_revision,
source_collected_at = EXCLUDED.source_collected_at,
source_payload_hash = EXCLUDED.source_payload_hash,
last_seen_at = now()
"""
addParameter command "code" NpgsqlDbType.Text (box instrument.Code) |> ignore
addParameter command "name" NpgsqlDbType.Text (box instrument.Name) |> ignore
addParameter
command
"fund_type"
NpgsqlDbType.Text
(optionalParameterValue instrument.FundType)
|> ignore
addParameter command "source" NpgsqlDbType.Text (box payload.Source) |> ignore
addParameter command "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
addParameter command "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore
addParameter command "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
command.ExecuteNonQuery() |> ignore
let upsertNavObservation connection transaction (payload: MarketDataNavPayload) payloadHash (observation: MarketDataObservation) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO fund_nav_observations
(instrument_code, nav_date, published_at, nav, accumulated_nav,
daily_return, source, source_revision, source_collected_at,
source_payload_hash)
VALUES
(@instrument_code, @nav_date, @published_at, @nav, @accumulated_nav,
@daily_return, @source, @source_revision, @source_collected_at,
@source_payload_hash)
ON CONFLICT (instrument_code, nav_date) DO UPDATE SET
published_at = EXCLUDED.published_at,
nav = EXCLUDED.nav,
accumulated_nav = EXCLUDED.accumulated_nav,
daily_return = EXCLUDED.daily_return,
source = EXCLUDED.source,
source_revision = EXCLUDED.source_revision,
source_collected_at = EXCLUDED.source_collected_at,
source_payload_hash = EXCLUDED.source_payload_hash,
last_seen_at = now(),
first_seen_at =
CASE
WHEN fund_nav_observations.source_payload_hash = EXCLUDED.source_payload_hash
THEN fund_nav_observations.first_seen_at
ELSE now()
END
"""
addParameter command "instrument_code" NpgsqlDbType.Text (box payload.Code) |> ignore
addParameter command "nav_date" NpgsqlDbType.Date (box observation.NavDate) |> ignore
addParameter
command
"published_at"
NpgsqlDbType.TimestampTz
(optionalParameterValue observation.PublishedAt)
|> ignore
addParameter command "nav" NpgsqlDbType.Numeric (box observation.Nav) |> ignore
addParameter
command
"accumulated_nav"
NpgsqlDbType.Numeric
(optionalParameterValue observation.AccumulatedNav)
|> ignore
addParameter
command
"daily_return"
NpgsqlDbType.Numeric
(optionalParameterValue observation.DailyReturn)
|> ignore
addParameter command "source" NpgsqlDbType.Text (box payload.Source) |> ignore
addParameter command "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
addParameter command "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore
addParameter command "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
command.ExecuteNonQuery() |> ignore
use evidenceCommand =
commandWithTransaction
connection
transaction
"""
INSERT INTO fund_nav_observation_evidence
(instrument_code, nav_date, source_payload_hash, source_revision, source,
source_collected_at, published_at, nav)
VALUES
(@instrument_code, @nav_date, @source_payload_hash, @source_revision, @source,
@source_collected_at, @published_at, @nav)
ON CONFLICT (instrument_code, nav_date, source_payload_hash) DO NOTHING
"""
addParameter evidenceCommand "instrument_code" NpgsqlDbType.Text (box payload.Code) |> ignore
addParameter evidenceCommand "nav_date" NpgsqlDbType.Date (box observation.NavDate) |> ignore
addParameter evidenceCommand "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
addParameter evidenceCommand "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
addParameter evidenceCommand "source" NpgsqlDbType.Text (box payload.Source) |> ignore
addParameter evidenceCommand "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore
addParameter
evidenceCommand
"published_at"
NpgsqlDbType.TimestampTz
(optionalParameterValue observation.PublishedAt)
|> ignore
addParameter evidenceCommand "nav" NpgsqlDbType.Numeric (box observation.Nav) |> ignore
evidenceCommand.ExecuteNonQuery() |> ignore
let requestHash (command: FundCreateCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = if isNull command.Name then "" else command.Name
let payload =
String.concat
"|"
[
"fund-create"
encoded name
(encoded (command.InitialCash.ToString("G29", invariant)))
(encoded (command.InitialUnitNav.ToString("G29", invariant)))
(encoded (command.IsSynthetic.ToString()))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let validateStorageRange (command: FundCreateCommand) =
if command.InitialCash > cashMaximum then
Error "initial cash exceeds database precision"
elif command.InitialUnitNav > unitNavMaximum then
Error "initial unit NAV exceeds database precision"
else
Ok()
let orderRequestHash (fundId: Guid) (command: SubscriptionOrderCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let fundCode = if isNull command.FundCode then "" else command.FundCode
let payload =
String.concat
"|"
[
"subscription-order"
encoded (fundId.ToString("D"))
encoded fundCode
(encoded (command.Amount.ToString("G29", invariant)))
(encoded (command.FeeAmount.ToString("G29", invariant)))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let validateOrderCommand (command: SubscriptionOrderCommand) =
if String.IsNullOrWhiteSpace command.FundCode then
Error "fund code cannot be empty"
elif command.Amount <= 0m then
Error "amount must be positive"
elif command.FeeAmount < 0m then
Error "fee amount cannot be negative"
elif Decimal.Round(command.Amount, 2) <> command.Amount then
Error "amount exceeds cash precision"
elif Decimal.Round(command.FeeAmount, 2) <> command.FeeAmount then
Error "fee amount exceeds cash precision"
elif command.Amount > cashMaximum then
Error "amount exceeds database precision"
elif command.FeeAmount > cashMaximum then
Error "fee amount exceeds database precision"
elif command.Amount + command.FeeAmount > cashMaximum then
Error "reserved total exceeds database precision"
else
Ok()
let ledgerErrorMessage error =
match error with
| InvalidIdentifier label -> sprintf "%s is invalid" label
| InvalidAmount label -> sprintf "%s is invalid" label
| InvalidPrecision label -> sprintf "%s has invalid precision" label
| InvalidState message -> message
| FundAlreadyExists fundId -> sprintf "fund %O already exists" fundId
| other -> sprintf "%A" other
let redemptionRecordFromReader (reader: DbDataReader) : RedemptionOrderRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
Units = reader.GetDecimal(3)
FeeAmount = reader.GetDecimal(4)
Status = reader.GetString(5)
IsSynthetic = reader.GetBoolean(6)
SubmittedAt = reader.GetFieldValue<DateTimeOffset>(7)
TradeDate = reader.GetFieldValue<DateOnly>(8)
ConfirmIdempotencyKey = readStringOption reader 9
PendingReason = readStringOption reader 10
ConfirmedAt = optionalDateTimeOffsetFromReader reader 11
ConfirmedNav = readDecimalOption reader 12
ConfirmedNavDate =
if reader.IsDBNull(13) then
None
else
Some(reader.GetFieldValue<DateOnly>(13))
ConfirmedProceeds = readDecimalOption reader 14
ConfirmedCostReleased = readDecimalOption reader 15
}
let redemptionOrderColumns =
"""
SELECT id, fund_id, instrument_code, units, fee_amount,
status, is_synthetic, submitted_at, trade_date,
confirm_idempotency_key, pending_reason, confirmed_at,
confirmed_nav, confirmed_nav_date, confirmed_proceeds, confirmed_cost_released
FROM redemption_orders
"""
let findRedemptionOrder connection transaction orderId =
use command =
commandWithTransaction connection transaction (redemptionOrderColumns + " WHERE id = @order_id")
addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(redemptionRecordFromReader reader) else None
let findRedemptionOrderIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, order_id FROM redemption_order_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findRedemptionConfirmIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, order_id FROM redemption_confirm_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertRedemptionOrder connection transaction (order: RedemptionOrderRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO redemption_orders
(id, fund_id, instrument_code, units, fee_amount,
status, is_synthetic, trade_date)
VALUES
(@id, @fund_id, @instrument_code, @units, @fee_amount,
@status, @is_synthetic, @trade_date)
RETURNING submitted_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box order.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box order.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
addParameter command "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
addParameter command "fee_amount" NpgsqlDbType.Numeric (box order.FeeAmount) |> ignore
addParameter command "status" NpgsqlDbType.Text (box order.Status) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box order.IsSynthetic) |> ignore
addParameter command "trade_date" NpgsqlDbType.Date (box order.TradeDate) |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertRedemptionOrderIdempotency connection transaction key requestHash orderId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO redemption_order_idempotencies (idempotency_key, request_hash, order_id, fund_id)
VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let insertRedemptionConfirmIdempotency connection transaction key requestHash orderId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO redemption_confirm_idempotencies (idempotency_key, request_hash, order_id, fund_id)
VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let redemptionRequestHash (fundId: Guid) (command: RedemptionCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode
let payload =
String.concat
"|"
[
"redemption-order"
encoded (fundId.ToString("D"))
encoded code
(encoded (command.Units.ToString("G29", invariant)))
(encoded (command.FeeAmount.ToString("G29", invariant)))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let validateRedemptionCommand (command: RedemptionCommand) =
if String.IsNullOrWhiteSpace command.InstrumentCode then
Error "instrument code cannot be empty"
elif command.Units <= 0m then
Error "units must be positive"
elif command.FeeAmount < 0m then
Error "fee amount cannot be negative"
elif Decimal.Round(command.Units, 8) <> command.Units then
Error "units exceed supported precision"
elif Decimal.Round(command.FeeAmount, 2) <> command.FeeAmount then
Error "fee amount exceeds cash precision"
elif command.Units > RedemptionPolicy.unitsMaximum then
Error "units exceed database precision"
elif command.FeeAmount > cashMaximum then
Error "fee amount exceeds database precision"
else
Ok()
let capitalDepositRecordFromReader (reader: DbDataReader) : CapitalDepositRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
Amount = reader.GetDecimal(2)
Note = readStringOption reader 3
IsSynthetic = reader.GetBoolean(4)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(5)
}
let findCapitalDeposit connection transaction depositId =
use command =
commandWithTransaction
connection
transaction
"SELECT id, fund_id, amount, note, is_synthetic, created_at FROM fund_capital_deposits WHERE id = @deposit_id"
addParameter command "deposit_id" NpgsqlDbType.Uuid (box depositId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(capitalDepositRecordFromReader reader) else None
let findCapitalDepositIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, deposit_id FROM fund_capital_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertCapitalDeposit connection transaction (deposit: CapitalDepositRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO fund_capital_deposits (id, fund_id, amount, note, is_synthetic)
VALUES (@id, @fund_id, @amount, @note, @is_synthetic)
RETURNING created_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box deposit.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box deposit.FundId) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box deposit.Amount) |> ignore
let noteParameter =
match deposit.Note with
| Some note -> box note
| None -> box DBNull.Value
addParameter command "note" NpgsqlDbType.Text noteParameter |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box deposit.IsSynthetic) |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertCapitalDepositIdempotency connection transaction key requestHash depositId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO fund_capital_idempotencies (idempotency_key, request_hash, deposit_id, fund_id)
VALUES (@idempotency_key, @request_hash, @deposit_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "deposit_id" NpgsqlDbType.Uuid (box depositId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let capitalDepositRequestHash (fundId: Guid) (command: CapitalDepositCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let note = if command.Note.IsNone then "" else command.Note.Value
let payload =
String.concat
"|"
[
"capital-deposit"
encoded (fundId.ToString("D"))
(encoded (command.Amount.ToString("G29", invariant)))
(encoded note)
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let stockTradeRecordFromReader (reader: DbDataReader) : StockTradeRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
StockName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
Quantity = reader.GetDecimal(4)
Price = reader.GetDecimal(5)
CostCash = reader.GetDecimal(6)
IsSynthetic = reader.GetBoolean(7)
ExecutedAt = reader.GetFieldValue<DateTimeOffset>(8)
}
let insertStockTrade connection transaction (trade: StockTradeRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_trades
(id, fund_id, instrument_code, stock_name, quantity, price, cost_cash, is_synthetic, executed_at)
VALUES
(@id, @fund_id, @instrument_code, @stock_name, @quantity, @price, @cost_cash, @is_synthetic, @executed_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box trade.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box trade.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box trade.InstrumentCode) |> ignore
let nameParameter =
match trade.StockName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "stock_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box trade.Quantity) |> ignore
addParameter command "price" NpgsqlDbType.Numeric (box trade.Price) |> ignore
addParameter command "cost_cash" NpgsqlDbType.Numeric (box trade.CostCash) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box trade.IsSynthetic) |> ignore
addParameter command "executed_at" NpgsqlDbType.TimestampTz (box trade.ExecutedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertStockTradeIdempotency connection transaction key requestHash tradeId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_trade_idempotencies (idempotency_key, request_hash, trade_id, fund_id)
VALUES (@idempotency_key, @request_hash, @trade_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "trade_id" NpgsqlDbType.Uuid (box tradeId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findStockTradeIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, trade_id
FROM stock_trade_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findStockTrade connection transaction tradeId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT id, fund_id, instrument_code, stock_name, quantity, price, cost_cash, is_synthetic, executed_at
FROM stock_trades
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box tradeId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(stockTradeRecordFromReader reader)
else
None
let stockTradeRequestHash (fundId: Guid) (command: StockTradeCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.StockName |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"stock-trade"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Price.ToString("G29", invariant))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let stockSellRecordFromReader (reader: DbDataReader) : StockSellRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
StockName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
Quantity = reader.GetDecimal(4)
Price = reader.GetDecimal(5)
FeeAmount = reader.GetDecimal(6)
Proceeds = reader.GetDecimal(7)
IsSynthetic = reader.GetBoolean(8)
ExecutedAt = reader.GetFieldValue<DateTimeOffset>(9)
}
let insertStockSell connection transaction (sell: StockSellRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_sells
(id, fund_id, instrument_code, stock_name, quantity, price, fee_amount, proceeds, is_synthetic, executed_at)
VALUES
(@id, @fund_id, @instrument_code, @stock_name, @quantity, @price, @fee_amount, @proceeds, @is_synthetic, @executed_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box sell.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box sell.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box sell.InstrumentCode) |> ignore
let nameParameter =
match sell.StockName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "stock_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box sell.Quantity) |> ignore
addParameter command "price" NpgsqlDbType.Numeric (box sell.Price) |> ignore
addParameter command "fee_amount" NpgsqlDbType.Numeric (box sell.FeeAmount) |> ignore
addParameter command "proceeds" NpgsqlDbType.Numeric (box sell.Proceeds) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box sell.IsSynthetic) |> ignore
addParameter command "executed_at" NpgsqlDbType.TimestampTz (box sell.ExecutedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertStockSellIdempotency connection transaction key requestHash sellId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_sell_idempotencies (idempotency_key, request_hash, sell_id, fund_id)
VALUES (@idempotency_key, @request_hash, @sell_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "sell_id" NpgsqlDbType.Uuid (box sellId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findStockSellIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, sell_id
FROM stock_sell_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findStockSell connection transaction sellId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT id, fund_id, instrument_code, stock_name, quantity, price, fee_amount, proceeds, is_synthetic, executed_at
FROM stock_sells
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box sellId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(stockSellRecordFromReader reader)
else
None
let stockSellRequestHash (fundId: Guid) (command: StockSellCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.StockName |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"stock-sell"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Price.ToString("G29", invariant))
encoded (command.FeeAmount.ToString("G29", invariant))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let stockCashflowRecordFromReader (reader: DbDataReader) : StockCashflowRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
StockName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
EventType = reader.GetString(4)
EventDate = reader.GetFieldValue<DateOnly>(5)
Quantity = reader.GetDecimal(6)
Amount = reader.GetDecimal(7)
Note = readStringOption reader 8
IsSynthetic = reader.GetBoolean(9)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(10)
}
let stockCashflowColumns =
"id, fund_id, instrument_code, stock_name, event_type, event_date, quantity, amount, note, is_synthetic, created_at"
let insertStockCashflow connection transaction (record: StockCashflowRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_cashflow_events
(id, fund_id, instrument_code, stock_name, event_type, event_date, quantity, amount, note, is_synthetic, created_at)
VALUES
(@id, @fund_id, @instrument_code, @stock_name, @event_type, @event_date, @quantity, @amount, @note, @is_synthetic, @created_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box record.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box record.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
let nameParameter =
match record.StockName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "stock_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "event_type" NpgsqlDbType.Text (box record.EventType) |> ignore
addParameter command "event_date" NpgsqlDbType.Date (box record.EventDate) |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box record.Quantity) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box record.Amount) |> ignore
let noteParameter =
match record.Note with
| Some note -> box note
| None -> box DBNull.Value
addParameter command "note" NpgsqlDbType.Text noteParameter |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box record.IsSynthetic) |> ignore
addParameter command "created_at" NpgsqlDbType.TimestampTz (box record.CreatedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertStockCashflowIdempotency connection transaction key requestHash eventId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO stock_cashflow_idempotencies (idempotency_key, request_hash, event_id, fund_id)
VALUES (@idempotency_key, @request_hash, @event_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "event_id" NpgsqlDbType.Uuid (box eventId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findStockCashflowIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, event_id
FROM stock_cashflow_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findStockCashflow connection transaction eventId =
use command =
commandWithTransaction
connection
transaction
$"""
SELECT {stockCashflowColumns}
FROM stock_cashflow_events
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box eventId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(stockCashflowRecordFromReader reader)
else
None
let stockCashflowRequestHash (fundId: Guid) (command: StockCashflowCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.StockName |> Option.defaultValue ""
let note = command.Note |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"stock-cashflow"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded command.EventType
encoded (command.EventDate.ToString("yyyy-MM-dd", invariant))
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Amount.ToString("G29", invariant))
encoded note
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let stockCashflowEvent
(fundId: Guid)
(instrumentCode: string)
(stockName: string option)
(eventType: string)
(eventDate: DateOnly)
(quantity: decimal)
(amount: decimal)
(note: string option)
(isSynthetic: bool)
: StockCashflowRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = instrumentCode
StockName = stockName
EventType = eventType
EventDate = eventDate
Quantity = quantity
Amount = amount
Note = note
IsSynthetic = isSynthetic
CreatedAt = DateTimeOffset.UtcNow
}
let bondTradeRecordFromReader (reader: DbDataReader) : BondTradeRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
BondName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
Quantity = reader.GetDecimal(4)
Price = reader.GetDecimal(5)
CleanPrice = reader.GetDecimal(6)
AccruedInterest = reader.GetDecimal(7)
ParValue = reader.GetDecimal(8)
SettlementDate = reader.GetFieldValue<DateOnly>(9)
CouponRate = readDecimalOption reader 10
ValueDate = if reader.IsDBNull(11) then None else Some(reader.GetFieldValue<DateOnly>(11))
MaturityDate = if reader.IsDBNull(12) then None else Some(reader.GetFieldValue<DateOnly>(12))
TradeDate = reader.GetFieldValue<DateOnly>(13)
CostCash = reader.GetDecimal(14)
IsSynthetic = reader.GetBoolean(15)
ExecutedAt = reader.GetFieldValue<DateTimeOffset>(16)
}
let bondTradeColumns =
"id, fund_id, instrument_code, bond_name, quantity, price, clean_price, accrued_interest, par_value, settlement_date, coupon_rate, value_date, maturity_date, trade_date, cost_cash, is_synthetic, executed_at"
let insertBondTrade connection transaction (trade: BondTradeRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_trades
(id, fund_id, instrument_code, bond_name, quantity, price, clean_price, accrued_interest,
par_value, settlement_date, coupon_rate, value_date, maturity_date, trade_date, cost_cash,
is_synthetic, executed_at)
VALUES
(@id, @fund_id, @instrument_code, @bond_name, @quantity, @price, @clean_price, @accrued_interest,
@par_value, @settlement_date, @coupon_rate, @value_date, @maturity_date, @trade_date, @cost_cash,
@is_synthetic, @executed_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box trade.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box trade.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box trade.InstrumentCode) |> ignore
let nameParameter =
match trade.BondName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "bond_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box trade.Quantity) |> ignore
addParameter command "price" NpgsqlDbType.Numeric (box trade.Price) |> ignore
addParameter command "clean_price" NpgsqlDbType.Numeric (box trade.CleanPrice) |> ignore
addParameter command "accrued_interest" NpgsqlDbType.Numeric (box trade.AccruedInterest) |> ignore
addParameter command "par_value" NpgsqlDbType.Numeric (box trade.ParValue) |> ignore
addParameter command "settlement_date" NpgsqlDbType.Date (box trade.SettlementDate) |> ignore
let couponParameter =
match trade.CouponRate with
| Some value -> box value
| None -> box DBNull.Value
addParameter command "coupon_rate" NpgsqlDbType.Numeric couponParameter |> ignore
let valueDateParameter =
match trade.ValueDate with
| Some value -> box value
| None -> box DBNull.Value
addParameter command "value_date" NpgsqlDbType.Date valueDateParameter |> ignore
let maturityParameter =
match trade.MaturityDate with
| Some value -> box value
| None -> box DBNull.Value
addParameter command "maturity_date" NpgsqlDbType.Date maturityParameter |> ignore
addParameter command "trade_date" NpgsqlDbType.Date (box trade.TradeDate) |> ignore
addParameter command "cost_cash" NpgsqlDbType.Numeric (box trade.CostCash) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box trade.IsSynthetic) |> ignore
addParameter command "executed_at" NpgsqlDbType.TimestampTz (box trade.ExecutedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertBondTradeIdempotency connection transaction key requestHash tradeId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_trade_idempotencies (idempotency_key, request_hash, trade_id, fund_id)
VALUES (@idempotency_key, @request_hash, @trade_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "trade_id" NpgsqlDbType.Uuid (box tradeId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findBondTradeIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, trade_id
FROM bond_trade_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findBondTrade connection transaction tradeId =
use command =
commandWithTransaction
connection
transaction
$"""
SELECT {bondTradeColumns}
FROM bond_trades
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box tradeId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(bondTradeRecordFromReader reader)
else
None
let bondTradeRequestHash (fundId: Guid) (command: BondTradeCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.BondName |> Option.defaultValue ""
let dateText (value: DateOnly) = value.ToString("yyyy-MM-dd", invariant)
let optionDate = command.ValueDate |> Option.map dateText |> Option.defaultValue ""
let optionMaturity = command.MaturityDate |> Option.map dateText |> Option.defaultValue ""
let optionCoupon = command.CouponRate |> Option.map (fun v -> v.ToString("G29", invariant)) |> Option.defaultValue ""
let optionTradeDate = command.TradeDate |> Option.map dateText |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"bond-trade"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Price.ToString("G29", invariant))
encoded (command.CleanPrice.ToString("G29", invariant))
encoded (command.AccruedInterest.ToString("G29", invariant))
encoded (command.ParValue.ToString("G29", invariant))
encoded (dateText command.SettlementDate)
encoded optionTradeDate
encoded optionCoupon
encoded optionDate
encoded optionMaturity
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let bondCashflowRecordFromReader (reader: DbDataReader) : BondCashflowRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
BondName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
EventType = reader.GetString(4)
EventDate = reader.GetFieldValue<DateOnly>(5)
Quantity = reader.GetDecimal(6)
Amount = reader.GetDecimal(7)
Note = readStringOption reader 8
IsSynthetic = reader.GetBoolean(9)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(10)
}
let bondCashflowColumns =
"id, fund_id, instrument_code, bond_name, event_type, event_date, quantity, amount, note, is_synthetic, created_at"
let insertBondCashflow connection transaction (record: BondCashflowRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_cashflow_events
(id, fund_id, instrument_code, bond_name, event_type, event_date, quantity, amount, note, is_synthetic, created_at)
VALUES
(@id, @fund_id, @instrument_code, @bond_name, @event_type, @event_date, @quantity, @amount, @note, @is_synthetic, @created_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box record.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box record.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
let nameParameter =
match record.BondName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "bond_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "event_type" NpgsqlDbType.Text (box record.EventType) |> ignore
addParameter command "event_date" NpgsqlDbType.Date (box record.EventDate) |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box record.Quantity) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box record.Amount) |> ignore
let noteParameter =
match record.Note with
| Some note -> box note
| None -> box DBNull.Value
addParameter command "note" NpgsqlDbType.Text noteParameter |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box record.IsSynthetic) |> ignore
addParameter command "created_at" NpgsqlDbType.TimestampTz (box record.CreatedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertBondCashflowIdempotency connection transaction key requestHash eventId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_cashflow_idempotencies (idempotency_key, request_hash, event_id, fund_id)
VALUES (@idempotency_key, @request_hash, @event_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "event_id" NpgsqlDbType.Uuid (box eventId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findBondCashflowIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, event_id
FROM bond_cashflow_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findBondCashflow connection transaction eventId =
use command =
commandWithTransaction
connection
transaction
$"""
SELECT {bondCashflowColumns}
FROM bond_cashflow_events
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box eventId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(bondCashflowRecordFromReader reader)
else
None
let bondCashflowRequestHash (fundId: Guid) (command: BondCashflowCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.BondName |> Option.defaultValue ""
let note = command.Note |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"bond-cashflow"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded command.EventType
encoded (command.EventDate.ToString("yyyy-MM-dd", invariant))
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Amount.ToString("G29", invariant))
encoded note
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let bondSellRecordFromReader (reader: DbDataReader) : BondSellRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
BondName = if reader.IsDBNull(3) then None else Some(reader.GetString(3))
Quantity = reader.GetDecimal(4)
Price = reader.GetDecimal(5)
CleanPrice = reader.GetDecimal(6)
AccruedInterest = reader.GetDecimal(7)
ParValue = reader.GetDecimal(8)
SettlementDate = reader.GetFieldValue<DateOnly>(9)
TradeDate = reader.GetFieldValue<DateOnly>(10)
FeeAmount = reader.GetDecimal(11)
Proceeds = reader.GetDecimal(12)
CostReleased = reader.GetDecimal(13)
RealizedPnl = reader.GetDecimal(14)
IsSynthetic = reader.GetBoolean(15)
ExecutedAt = reader.GetFieldValue<DateTimeOffset>(16)
}
let bondSellColumns =
"id, fund_id, instrument_code, bond_name, quantity, price, clean_price, accrued_interest, par_value, settlement_date, trade_date, fee_amount, proceeds, cost_released, realized_pnl, is_synthetic, executed_at"
let insertBondSell connection transaction (record: BondSellRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_sells
(id, fund_id, instrument_code, bond_name, quantity, price, clean_price, accrued_interest,
par_value, settlement_date, trade_date, fee_amount, proceeds, cost_released, realized_pnl,
is_synthetic, executed_at)
VALUES
(@id, @fund_id, @instrument_code, @bond_name, @quantity, @price, @clean_price, @accrued_interest,
@par_value, @settlement_date, @trade_date, @fee_amount, @proceeds, @cost_released, @realized_pnl,
@is_synthetic, @executed_at)
"""
addParameter command "id" NpgsqlDbType.Uuid (box record.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box record.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
let nameParameter =
match record.BondName with
| Some name -> box name
| None -> box DBNull.Value
addParameter command "bond_name" NpgsqlDbType.Text nameParameter |> ignore
addParameter command "quantity" NpgsqlDbType.Numeric (box record.Quantity) |> ignore
addParameter command "price" NpgsqlDbType.Numeric (box record.Price) |> ignore
addParameter command "clean_price" NpgsqlDbType.Numeric (box record.CleanPrice) |> ignore
addParameter command "accrued_interest" NpgsqlDbType.Numeric (box record.AccruedInterest) |> ignore
addParameter command "par_value" NpgsqlDbType.Numeric (box record.ParValue) |> ignore
addParameter command "settlement_date" NpgsqlDbType.Date (box record.SettlementDate) |> ignore
addParameter command "trade_date" NpgsqlDbType.Date (box record.TradeDate) |> ignore
addParameter command "fee_amount" NpgsqlDbType.Numeric (box record.FeeAmount) |> ignore
addParameter command "proceeds" NpgsqlDbType.Numeric (box record.Proceeds) |> ignore
addParameter command "cost_released" NpgsqlDbType.Numeric (box record.CostReleased) |> ignore
addParameter command "realized_pnl" NpgsqlDbType.Numeric (box record.RealizedPnl) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box record.IsSynthetic) |> ignore
addParameter command "executed_at" NpgsqlDbType.TimestampTz (box record.ExecutedAt) |> ignore
command.ExecuteNonQuery() |> ignore
let insertBondSellIdempotency connection transaction key requestHash sellId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO bond_sell_idempotencies (idempotency_key, request_hash, sell_id, fund_id)
VALUES (@idempotency_key, @request_hash, @sell_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "sell_id" NpgsqlDbType.Uuid (box sellId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let findBondSellIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"""
SELECT request_hash, fund_id, sell_id
FROM bond_sell_idempotencies
WHERE idempotency_key = @idempotency_key
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let findBondSell connection transaction sellId =
use command =
commandWithTransaction
connection
transaction
$"""
SELECT {bondSellColumns}
FROM bond_sells
WHERE id = @id
"""
addParameter command "id" NpgsqlDbType.Uuid (box sellId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(bondSellRecordFromReader reader)
else
None
let bondSellRequestHash (fundId: Guid) (command: BondSellCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let name = command.BondName |> Option.defaultValue ""
let dateText (value: DateOnly) = value.ToString("yyyy-MM-dd", invariant)
let optionTradeDate = command.TradeDate |> Option.map dateText |> Option.defaultValue ""
let payload =
String.concat
"|"
[
"bond-sell"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded name
encoded (command.Quantity.ToString("G29", invariant))
encoded (command.Price.ToString("G29", invariant))
encoded (command.CleanPrice.ToString("G29", invariant))
encoded (command.AccruedInterest.ToString("G29", invariant))
encoded (command.ParValue.ToString("G29", invariant))
encoded (dateText command.SettlementDate)
encoded optionTradeDate
encoded (command.FeeAmount.ToString("G29", invariant))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let sipPlanRecordFromReader (reader: DbDataReader) : SipPlanRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
AssetClass = reader.GetString(3)
Amount = reader.GetDecimal(4)
Frequency =
match SipPolicy.parseFrequency (reader.GetString(5)) with
| Some frequency -> frequency
| None -> failwith "sip plan frequency is invalid"
Status = reader.GetString(6)
IsSynthetic = reader.GetBoolean(7)
AnchorDate = reader.GetFieldValue<DateOnly>(8)
NextTradeDate = reader.GetFieldValue<DateOnly>(9)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(10)
LastExecutionStatus = readStringOption reader 11
LastExecutionDate =
if reader.IsDBNull(12) then None else Some(reader.GetFieldValue<DateOnly>(12))
}
let findSipPlan connection transaction planId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT p.id, p.fund_id, p.instrument_code, p.asset_class, p.amount, p.frequency, p.status, p.is_synthetic,
p.anchor_date, p.next_trade_date, p.created_at,
e.status, e.trade_date
FROM sip_plans p
LEFT JOIN LATERAL (
SELECT status, trade_date FROM sip_executions
WHERE plan_id = p.id ORDER BY executed_at DESC, trade_date DESC LIMIT 1
) e ON true
WHERE p.id = @plan_id
"""
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(sipPlanRecordFromReader reader) else None
let findSipPlanIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, plan_id FROM sip_plan_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertSipPlan connection transaction (plan: SipPlanRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO sip_plans (id, fund_id, instrument_code, asset_class, amount, frequency, status, is_synthetic, anchor_date, next_trade_date)
VALUES (@id, @fund_id, @instrument_code, @asset_class, @amount, @frequency, @status, @is_synthetic, @anchor_date, @next_trade_date)
RETURNING created_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box plan.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box plan.InstrumentCode) |> ignore
addParameter command "asset_class" NpgsqlDbType.Text (box plan.AssetClass) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box plan.Amount) |> ignore
addParameter command "frequency" NpgsqlDbType.Text (box (SipPolicy.frequencyText plan.Frequency)) |> ignore
addParameter command "status" NpgsqlDbType.Text (box plan.Status) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box plan.IsSynthetic) |> ignore
addParameter command "anchor_date" NpgsqlDbType.Date (box plan.AnchorDate) |> ignore
addParameter command "next_trade_date" NpgsqlDbType.Date (box plan.NextTradeDate) |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertSipPlanIdempotency connection transaction key requestHash planId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO sip_plan_idempotencies (idempotency_key, request_hash, plan_id, fund_id)
VALUES (@idempotency_key, @request_hash, @plan_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let sipPlanRequestHash (fundId: Guid) (assetClass: string) (command: SipPlanCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode
let payload =
String.concat
"|"
[
"sip-plan"
encoded (fundId.ToString("D"))
encoded assetClass
encoded code
(encoded (command.Amount.ToString("G29", invariant)))
(encoded (SipPolicy.frequencyText command.Frequency))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let investmentPlanRecordFromReader (reader: DbDataReader) : InvestmentPlanRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
Amount = reader.GetDecimal(3)
Frequency =
match InvestmentPlanPolicy.parseFrequency (reader.GetString(4)) with
| Some frequency -> frequency
| None -> failwith "investment plan frequency is invalid"
Status = reader.GetString(5)
IsSynthetic = reader.GetBoolean(6)
AnchorDate = reader.GetFieldValue<DateOnly>(7)
NextRunDate = reader.GetFieldValue<DateOnly>(8)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(9)
LastRunStatus = readStringOption reader 10
LastRunDate = if reader.IsDBNull(11) then None else Some(reader.GetFieldValue<DateOnly>(11))
}
let findInvestmentPlan connection transaction planId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT p.id, p.fund_id, p.instrument_code, p.amount, p.frequency, p.status, p.is_synthetic,
p.anchor_date, p.next_run_date, p.created_at,
r.status, r.run_date
FROM investment_plans p
LEFT JOIN LATERAL (
SELECT status, run_date FROM investment_plan_runs
WHERE plan_id = p.id ORDER BY executed_at DESC, run_date DESC LIMIT 1
) r ON true
WHERE p.id = @plan_id
"""
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(investmentPlanRecordFromReader reader) else None
let findInvestmentPlanIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, plan_id FROM investment_plan_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertInvestmentPlan connection transaction (plan: InvestmentPlanRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO investment_plans (id, fund_id, instrument_code, amount, frequency, status, is_synthetic, anchor_date, next_run_date)
VALUES (@id, @fund_id, @instrument_code, @amount, @frequency, @status, @is_synthetic, @anchor_date, @next_run_date)
RETURNING created_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box plan.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box plan.InstrumentCode) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box plan.Amount) |> ignore
addParameter command "frequency" NpgsqlDbType.Text (box (InvestmentPlanPolicy.frequencyText plan.Frequency)) |> ignore
addParameter command "status" NpgsqlDbType.Text (box plan.Status) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box plan.IsSynthetic) |> ignore
addParameter command "anchor_date" NpgsqlDbType.Date (box plan.AnchorDate) |> ignore
addParameter command "next_run_date" NpgsqlDbType.Date (box plan.NextRunDate) |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertInvestmentPlanIdempotency connection transaction key requestHash planId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO investment_plan_idempotencies (idempotency_key, request_hash, plan_id, fund_id)
VALUES (@idempotency_key, @request_hash, @plan_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let investmentPlanRequestHash (fundId: Guid) (command: InvestmentPlanCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode
let payload =
String.concat
"|"
[
"investment-plan"
encoded (fundId.ToString("D"))
encoded code
(encoded (command.Amount.ToString("G29", invariant)))
(encoded (InvestmentPlanPolicy.frequencyText command.Frequency))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let rebalancePlanRecordFromReader (reader: DbDataReader) : RebalancePlanRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
Targets = []
Status = reader.GetString(2)
IsSynthetic = reader.GetBoolean(3)
CreatedAt = reader.GetFieldValue<DateTimeOffset>(4)
}
let rebalanceTargetsFromReader (reader: DbDataReader) : RebalanceTarget list =
let targets = ResizeArray<RebalanceTarget>()
while reader.Read() do
targets.Add(
{
InstrumentCode = reader.GetString(0)
TargetPercent = reader.GetDecimal(1)
}
)
targets |> Seq.toList
let rebalancePlanWithTargets connection transaction (plan: RebalancePlanRecord) =
use targetsCommand =
commandWithTransaction
connection
transaction
"SELECT instrument_code, target_percent FROM rebalance_targets WHERE plan_id = @plan_id ORDER BY instrument_code"
addParameter targetsCommand "plan_id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
use reader = targetsCommand.ExecuteReader()
let targets = rebalanceTargetsFromReader reader
{ plan with Targets = targets }
let findRebalancePlan connection transaction planId =
use command =
commandWithTransaction
connection
transaction
"SELECT id, fund_id, status, is_synthetic, created_at FROM rebalance_plans WHERE id = @plan_id"
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
let plan = rebalancePlanRecordFromReader reader
reader.Close()
Some(rebalancePlanWithTargets connection transaction plan)
else
None
let findRebalanceIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, plan_id FROM rebalance_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertRebalancePlan connection transaction (plan: RebalancePlanRecord) =
use planCommand =
commandWithTransaction
connection
transaction
"""
INSERT INTO rebalance_plans (id, fund_id, status, is_synthetic)
VALUES (@id, @fund_id, @status, @is_synthetic)
RETURNING created_at
"""
addParameter planCommand "id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
addParameter planCommand "fund_id" NpgsqlDbType.Uuid (box plan.FundId) |> ignore
addParameter planCommand "status" NpgsqlDbType.Text (box plan.Status) |> ignore
addParameter planCommand "is_synthetic" NpgsqlDbType.Boolean (box plan.IsSynthetic) |> ignore
use reader = planCommand.ExecuteReader()
reader.Read() |> ignore
let createdAt = reader.GetFieldValue<DateTimeOffset>(0)
reader.Close()
for target in plan.Targets do
use targetCommand =
commandWithTransaction
connection
transaction
"""
INSERT INTO rebalance_targets (plan_id, instrument_code, target_percent)
VALUES (@plan_id, @instrument_code, @target_percent)
"""
addParameter targetCommand "plan_id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
addParameter targetCommand "instrument_code" NpgsqlDbType.Text (box target.InstrumentCode) |> ignore
addParameter targetCommand "target_percent" NpgsqlDbType.Numeric (box target.TargetPercent) |> ignore
targetCommand.ExecuteNonQuery() |> ignore
createdAt
let insertRebalanceIdempotency connection transaction key requestHash planId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO rebalance_idempotencies (idempotency_key, request_hash, plan_id, fund_id)
VALUES (@idempotency_key, @request_hash, @plan_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let rebalanceRequestHash (fundId: Guid) (command: RebalancePlanCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let payload =
String.concat
"|"
([ "rebalance-plan"; encoded (fundId.ToString("D")) ]
@ (command.Targets
|> List.sortBy (fun target -> target.InstrumentCode)
|> List.collect (fun target ->
[
encoded target.InstrumentCode
encoded (target.TargetPercent.ToString("G29", invariant))
])))
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let validateRebalanceCommand (command: RebalancePlanCommand) =
match RebalancePolicy.validateTargets command.Targets with
| Error message -> Error message
| Ok() -> Ok()
let rebalanceExecutionRecordFromReader (reader: DbDataReader) : RebalanceExecutionRecord =
{
PlanId = reader.GetGuid(0)
RunDate = reader.GetFieldValue<DateOnly>(1)
InstrumentCode = reader.GetString(2)
Action = reader.GetString(3)
Amount = reader.GetDecimal(4)
Status = reader.GetString(5)
OrderId = if reader.IsDBNull(6) then None else Some(reader.GetGuid(6))
PendingReason = readStringOption reader 7
ExecutedAt = reader.GetFieldValue<DateTimeOffset>(8)
}
let upsertRebalanceExecution
connection
transaction
(planId: Guid)
(runDate: DateOnly)
(outcome: RebalanceOrderOutcome)
=
let amount =
match Decimal.TryParse(outcome.Amount, NumberStyles.Float, CultureInfo.InvariantCulture) with
| true, value -> value
| false, _ -> 0m
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO rebalance_executions (plan_id, run_date, instrument_code, action, amount, status, order_id, pending_reason)
VALUES (@plan_id, @run_date, @instrument_code, @action, @amount, @status, @order_id, @pending_reason)
ON CONFLICT (plan_id, run_date, instrument_code) DO UPDATE
SET action = EXCLUDED.action,
amount = EXCLUDED.amount,
status = EXCLUDED.status,
order_id = EXCLUDED.order_id,
pending_reason = EXCLUDED.pending_reason,
executed_at = now()
"""
addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter command "run_date" NpgsqlDbType.Date (box runDate) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box outcome.InstrumentCode) |> ignore
addParameter command "action" NpgsqlDbType.Text (box outcome.Action) |> ignore
addParameter command "amount" NpgsqlDbType.Numeric (box amount) |> ignore
addParameter command "status" NpgsqlDbType.Text (box outcome.Status) |> ignore
let orderParameter =
match outcome.OrderId with
| Some value -> box value
| None -> box DBNull.Value
addParameter command "order_id" NpgsqlDbType.Uuid orderParameter |> ignore
let reasonParameter =
match outcome.PendingReason with
| Some value -> box value
| None -> box DBNull.Value
addParameter command "pending_reason" NpgsqlDbType.Text reasonParameter |> ignore
command.ExecuteNonQuery() |> ignore
let dividendRecordFromReader (reader: DbDataReader) : DividendRecord =
{
Id = reader.GetGuid(0)
FundId = reader.GetGuid(1)
InstrumentCode = reader.GetString(2)
NavDate = reader.GetFieldValue<DateOnly>(3)
Dps = reader.GetDecimal(4)
Mode =
match DividendPolicy.parseMode (reader.GetString(5)) with
| Some mode -> mode
| None -> failwith "dividend mode is invalid"
Status = reader.GetString(6)
IsSynthetic = reader.GetBoolean(7)
GrossCash = readDecimalOption reader 8
CreditedUnits = readDecimalOption reader 9
CreditedInvested = readDecimalOption reader 10
OrderId = if reader.IsDBNull(11) then None else Some(reader.GetGuid(11))
PendingReason = readStringOption reader 12
CreatedAt = reader.GetFieldValue<DateTimeOffset>(13)
}
let findDividendRecord connection transaction recordId =
use command =
commandWithTransaction
connection
transaction
"""
SELECT id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic,
gross_cash, credited_units, credited_invested, order_id, pending_reason, created_at
FROM dividend_records WHERE id = @record_id
"""
addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(dividendRecordFromReader reader) else None
let findDividendIdempotency connection transaction key =
use command =
commandWithTransaction
connection
transaction
"SELECT request_hash, fund_id, record_id FROM dividend_idempotencies WHERE idempotency_key = @idempotency_key"
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then
Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
else
None
let insertDividendRecord connection transaction (record: DividendRecord) =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO dividend_records
(id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic, gross_cash)
VALUES (@id, @fund_id, @instrument_code, @nav_date, @dps, @mode, @status, @is_synthetic, @gross_cash)
RETURNING created_at
"""
addParameter command "id" NpgsqlDbType.Uuid (box record.Id) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box record.FundId) |> ignore
addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
addParameter command "nav_date" NpgsqlDbType.Date (box record.NavDate) |> ignore
addParameter command "dps" NpgsqlDbType.Numeric (box record.Dps) |> ignore
addParameter command "mode" NpgsqlDbType.Text (box (DividendPolicy.modeText record.Mode)) |> ignore
addParameter command "status" NpgsqlDbType.Text (box record.Status) |> ignore
addParameter command "is_synthetic" NpgsqlDbType.Boolean (box record.IsSynthetic) |> ignore
let grossParameter =
match record.GrossCash with
| Some gross -> box gross
| None -> box DBNull.Value
addParameter command "gross_cash" NpgsqlDbType.Numeric grossParameter |> ignore
use reader = command.ExecuteReader()
reader.Read() |> ignore
reader.GetFieldValue<DateTimeOffset>(0)
let insertDividendIdempotency connection transaction key requestHash recordId fundId =
use command =
commandWithTransaction
connection
transaction
"""
INSERT INTO dividend_idempotencies (idempotency_key, request_hash, record_id, fund_id)
VALUES (@idempotency_key, @request_hash, @record_id, @fund_id)
"""
addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
command.ExecuteNonQuery() |> ignore
let finishDividendRecord connection transaction (recordId: Guid) (status: string) (pendingReason: string option) =
use command =
commandWithTransaction
connection
transaction
"UPDATE dividend_records SET status = @status, pending_reason = @reason WHERE id = @record_id"
addParameter command "status" NpgsqlDbType.Text (box status) |> ignore
let reasonParameter =
match pendingReason with
| Some reason -> box reason
| None -> box DBNull.Value
addParameter command "reason" NpgsqlDbType.Text reasonParameter |> ignore
addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore
command.ExecuteNonQuery() |> ignore
let dividendRequestHash (fundId: Guid) (command: DividendCommand) =
let invariant = CultureInfo.InvariantCulture
let encoded (value: string) = sprintf "%d:%s" value.Length value
let payload =
String.concat
"|"
[
"dividend"
encoded (fundId.ToString("D"))
encoded command.InstrumentCode
encoded (command.NavDate.ToString("yyyy-MM-dd"))
(encoded (command.Dps.ToString("G29", invariant)))
(encoded (DividendPolicy.modeText command.Mode))
]
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))
let dividendSchemeKey (fundId: Guid) (command: DividendCommand) =
DividendPolicy.schemeKey fundId command.InstrumentCode command.NavDate command.Mode
let validateDividendCommand (today: DateOnly) (command: DividendCommand) =
if String.IsNullOrWhiteSpace command.InstrumentCode then
Error "instrument code cannot be empty"
elif command.Dps <= 0m then
Error "dividend per unit must be positive"
else
match DividendPolicy.validateDps command.Dps, DividendPolicy.validateNavDate command.NavDate today with
| Ok(), Ok() -> Ok()
| Error message, _
| _, Error message -> Error message
member _.EnsureSchema() =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command = connection.CreateCommand()
command.CommandText <- schema
command.ExecuteNonQuery() |> ignore
member _.GetFund(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
findFund connection None fundId
member _.UpsertInstruments(payload: MarketDataSearchPayload, payloadHash: string) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
for instrument in payload.Instruments do
upsertInstrument connection (Some transaction) payload payloadHash instrument
transaction.Commit()
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetInstrument(code: string) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT code, name, fund_type, source, source_revision,
source_collected_at, source_payload_hash,
first_seen_at, last_seen_at
FROM instruments
WHERE code = @code
"""
addParameter command "code" NpgsqlDbType.Text (box code) |> ignore
use reader = command.ExecuteReader()
if reader.Read() then Some(instrumentRecordFromReader reader) else None
member _.UpsertNavObservations(payload: MarketDataNavPayload, payloadHash: string) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
for observation in payload.Observations do
upsertNavObservation connection (Some transaction) payload payloadHash observation
transaction.Commit()
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetNav(code: string, fromDate: DateOnly option, toDate: DateOnly option) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
let conditions = ResizeArray<string>()
conditions.Add("instrument_code = @instrument_code")
if fromDate.IsSome then
conditions.Add("nav_date >= @from_date")
if toDate.IsSome then
conditions.Add("nav_date <= @to_date")
use command =
commandWithTransaction
connection
None
(sprintf
"""
SELECT instrument_code, nav_date, published_at, nav, accumulated_nav,
daily_return, source, source_revision, source_collected_at,
source_payload_hash, first_seen_at, last_seen_at
FROM fund_nav_observations
WHERE %s
ORDER BY nav_date ASC
"""
(String.concat " AND " conditions))
addParameter command "instrument_code" NpgsqlDbType.Text (box code) |> ignore
match fromDate with
| Some value -> addParameter command "from_date" NpgsqlDbType.Date (box value) |> ignore
| None -> ()
match toDate with
| Some value -> addParameter command "to_date" NpgsqlDbType.Date (box value) |> ignore
| None -> ()
use reader = command.ExecuteReader()
let records = ResizeArray<MarketDataNavRecord>()
while reader.Read() do
records.Add(navRecordFromReader reader)
records |> Seq.toList
member _.UpsertInstrumentSnapshots(records: InstrumentSnapshotRecord list) =
if records.IsEmpty then
()
else
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
for record in records do
use command =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO instrument_snapshots
(instrument_code, asset_class, snapshot_date, price, source,
source_revision, source_collected_at, source_payload_hash)
VALUES
(@instrument_code, @asset_class, @snapshot_date, @price, @source,
@source_revision, @source_collected_at, @source_payload_hash)
ON CONFLICT (instrument_code, asset_class, snapshot_date) DO UPDATE SET
price = EXCLUDED.price,
source = EXCLUDED.source,
source_revision = EXCLUDED.source_revision,
source_collected_at = EXCLUDED.source_collected_at,
source_payload_hash = EXCLUDED.source_payload_hash,
last_seen_at = now(),
first_seen_at = CASE
WHEN instrument_snapshots.source_payload_hash = EXCLUDED.source_payload_hash
THEN instrument_snapshots.first_seen_at
ELSE now()
END
"""
addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
addParameter command "asset_class" NpgsqlDbType.Text (box record.AssetClass) |> ignore
addParameter command "snapshot_date" NpgsqlDbType.Date (box record.SnapshotDate) |> ignore
addParameter command "price" NpgsqlDbType.Numeric (box record.Price) |> ignore
addParameter command "source" NpgsqlDbType.Text (box record.Source) |> ignore
addParameter command "source_revision" NpgsqlDbType.Text (box record.SourceRevision) |> ignore
addParameter command "source_collected_at" NpgsqlDbType.TimestampTz (box record.SourceCollectedAt) |> ignore
addParameter command "source_payload_hash" NpgsqlDbType.Text (box record.SourcePayloadHash) |> ignore
command.ExecuteNonQuery() |> ignore
transaction.Commit()
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
/// Latest snapshot price on or before `asOfDate` for every instrument of the
/// given asset class held by the fund. Instruments without any snapshot are
/// omitted so a caller can tell "no snapshot yet" from a stored price.
member _.GetLatestSnapshots(fundId: Guid, assetClass: string, asOfDate: DateOnly) : Map<string, InstrumentSnapshotRecord> =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT s.instrument_code, s.asset_class, s.snapshot_date, s.price, s.source,
s.source_revision, s.source_collected_at, s.source_payload_hash
FROM instrument_snapshots s
JOIN (
SELECT instrument_code, MAX(snapshot_date) AS snapshot_date
FROM instrument_snapshots
WHERE asset_class = @asset_class AND snapshot_date <= @as_of_date
GROUP BY instrument_code
) latest
ON latest.instrument_code = s.instrument_code
AND latest.snapshot_date = s.snapshot_date
WHERE s.asset_class = @asset_class
"""
addParameter command "asset_class" NpgsqlDbType.Text (box assetClass) |> ignore
addParameter command "as_of_date" NpgsqlDbType.Date (box asOfDate) |> ignore
use reader = command.ExecuteReader()
let records = System.Collections.Generic.Dictionary<string, InstrumentSnapshotRecord>()
while reader.Read() do
let record : InstrumentSnapshotRecord =
{ InstrumentCode = reader.GetString(0)
AssetClass = reader.GetString(1)
SnapshotDate = reader.GetFieldValue<DateOnly>(2)
Price = reader.GetDecimal(3)
Source = reader.GetString(4)
SourceRevision = reader.GetString(5)
SourceCollectedAt = reader.GetFieldValue<DateTimeOffset>(6)
SourcePayloadHash = reader.GetString(7) }
records.[record.InstrumentCode] <- record
records
|> Seq.map (fun pair -> pair.Key, pair.Value)
|> Map.ofSeq
member _.CreateFund(idempotencyKey: string, command: FundCreateCommand) =
if String.IsNullOrWhiteSpace idempotencyKey then
FundWriteResult.Invalid "idempotency key cannot be empty"
else
match validateStorageRange command with
| Error message -> FundWriteResult.Invalid message
| Ok() ->
let fingerprint = requestHash command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, fundId) when existingHash = fingerprint ->
match findFund connection (Some transaction) fundId with
| Some fund ->
transaction.Commit()
FundWriteResult.Replayed fund
| None ->
transaction.Rollback()
FundWriteResult.Invalid "idempotency record references a missing fund"
| Some _ ->
transaction.Rollback()
FundWriteResult.IdempotencyConflict
| None ->
let fundId = Guid.NewGuid()
match Ledger.initializeFund fundId command.Name command.InitialCash command.InitialUnitNav command.IsSynthetic Ledger.empty with
| Error error ->
transaction.Rollback()
FundWriteResult.Invalid(ledgerErrorMessage error)
| Ok state ->
match Ledger.getFund fundId state with
| Error error ->
transaction.Rollback()
FundWriteResult.Invalid(ledgerErrorMessage error)
| Ok fund ->
insertFund connection (Some transaction) fund
insertIdempotency connection (Some transaction) idempotencyKey fingerprint fundId
transaction.Commit()
FundWriteResult.Created(recordFromLedger fund)
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.CreateSubscriptionOrder(idempotencyKey: string, fundId: Guid, command: SubscriptionOrderCommand, ?tradeDateOverride: DateOnly) : SubscriptionOrderWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
OrderInvalid "idempotency key cannot be empty"
else
match validateOrderCommand command with
| Error message -> OrderInvalid message
| Ok() ->
let fingerprint = orderRequestHash fundId command
let reservedTotal = command.Amount + command.FeeAmount
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findOrderIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, orderId)
when existingHash = fingerprint && existingFundId = fundId ->
match findOrder connection (Some transaction) orderId with
| Some order ->
transaction.Commit()
OrderReplayed order
| None ->
transaction.Rollback()
OrderInvalid "idempotency record references a missing order"
| Some _ ->
transaction.Rollback()
OrderIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
OrderFundNotFound
| Some isSynthetic ->
if instrumentExists connection (Some transaction) command.FundCode then
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE funds
SET available_cash = available_cash - @reserved_total,
reserved_cash = reserved_cash + @reserved_total
WHERE id = @fund_id AND available_cash >= @reserved_total
"""
addParameter cashCommand "reserved_total" NpgsqlDbType.Numeric (box reservedTotal) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
if cashCommand.ExecuteNonQuery() = 0 then
transaction.Rollback()
OrderInsufficientFunds
else
let submittedAt = DateTimeOffset.UtcNow
let tradeDate =
tradeDateOverride
|> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor submittedAt)
let order: SubscriptionOrderRecord =
{
Id = Guid.NewGuid()
FundId = fundId
FundCode = command.FundCode
Amount = command.Amount
FeeAmount = command.FeeAmount
ReservedTotal = reservedTotal
Status = orderStatusText
SubmittedAt = submittedAt
IsSynthetic = isSynthetic
TradeDate = tradeDate
ConfirmIdempotencyKey = None
PendingReason = None
ConfirmedAt = None
ConfirmedQuote = None
ConfirmedUnits = None
ConfirmedInvestedCash = None
ConfirmedResidualCash = None
}
let submittedAt = insertSubscriptionOrder connection (Some transaction) order
insertOrderIdempotency connection (Some transaction) idempotencyKey fingerprint order.Id fundId
transaction.Commit()
OrderCreated { order with SubmittedAt = submittedAt }
else
transaction.Rollback()
OrderInstrumentNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetSubscriptionOrders(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT id, fund_id, fund_code, amount, fee_amount,
reserved_total, status, is_synthetic, submitted_at,
trade_date,
confirm_idempotency_key, pending_reason, confirmed_at,
confirmed_nav, confirmed_nav_date, confirmed_nav_source,
confirmed_nav_revision, confirmed_nav_collected_at, confirmed_nav_published_at,
confirmed_nav_payload_hash, confirmed_nav_first_seen_at,
confirmed_units, confirmed_invested_cash, confirmed_residual_cash
FROM subscription_orders
WHERE fund_id = @fund_id
ORDER BY submitted_at DESC, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<SubscriptionOrderRecord>()
while reader.Read() do
records.Add(orderRecordFromReader reader)
records |> Seq.toList
member _.CreateSipPlan(idempotencyKey: string, fundId: Guid, command: SipPlanCommand, ?anchorOverride: DateOnly, ?assetClass: string) : SipPlanWriteResult =
let resolvedAssetClass =
match assetClass with
| Some value when not (String.IsNullOrWhiteSpace value) -> value.Trim().ToLowerInvariant()
| _ -> "fund"
if resolvedAssetClass <> "fund" && resolvedAssetClass <> "stock" then
SipPlanWriteResult.SipPlanInvalid "assetClass must be fund or stock"
elif String.IsNullOrWhiteSpace idempotencyKey then
SipPlanWriteResult.SipPlanInvalid "idempotency key cannot be empty"
else
match SipPolicy.validateAmount command.Amount with
| Error message -> SipPlanWriteResult.SipPlanInvalid message
| Ok() ->
let fingerprint = sipPlanRequestHash fundId resolvedAssetClass command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findSipPlanIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, planId)
when existingHash = fingerprint && existingFundId = fundId ->
match findSipPlan connection (Some transaction) planId with
| Some plan ->
transaction.Commit()
SipPlanWriteResult.SipPlanReplayed plan
| None ->
transaction.Rollback()
SipPlanWriteResult.SipPlanInvalid "idempotency record references a missing plan"
| Some _ ->
transaction.Rollback()
SipPlanWriteResult.SipPlanIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
SipPlanWriteResult.SipPlanFundNotFound
| Some isSynthetic ->
if resolvedAssetClass = "stock" || instrumentExists connection (Some transaction) command.InstrumentCode then
let anchorDate =
anchorOverride
|> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow)
let plan: SipPlanRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = command.InstrumentCode
AssetClass = resolvedAssetClass
Amount = command.Amount
Frequency = command.Frequency
Status = "active"
IsSynthetic = isSynthetic
AnchorDate = anchorDate
NextTradeDate = SipPolicy.nextTradeDate command.Frequency anchorDate (anchorDate.AddDays 1)
CreatedAt = DateTimeOffset.UtcNow
LastExecutionStatus = None
LastExecutionDate = None
}
let createdAt = insertSipPlan connection (Some transaction) plan
insertSipPlanIdempotency connection (Some transaction) idempotencyKey fingerprint plan.Id fundId
transaction.Commit()
SipPlanWriteResult.SipPlanCreated { plan with CreatedAt = createdAt }
else
transaction.Rollback()
SipPlanWriteResult.SipPlanInstrumentNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member this.AdvanceSipPlans(fundId: Guid, endDate: DateOnly, limit: int, ?stockQuote: string -> Result<StockSipQuote, string>) : SipAdvanceResult =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "sip-advance:%O" fundId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
// 0. retry phase: confirmations that were pending_nav get re-run once their NAV landed
use retryCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT e.plan_id, e.trade_date, e.order_id
FROM sip_executions e
JOIN sip_plans p ON p.id = e.plan_id
WHERE p.fund_id = @fund_id AND e.status = 'pending_nav'
ORDER BY e.trade_date
"""
addParameter retryCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use retryReader = retryCommand.ExecuteReader()
let pendingRetries = ResizeArray<Guid * DateOnly * Guid>()
while retryReader.Read() do
pendingRetries.Add(
retryReader.GetGuid(0),
retryReader.GetFieldValue<DateOnly>(1),
retryReader.GetGuid(2)
)
retryReader.Close()
for (retryPlanId, retryDate, retryOrderId) in pendingRetries do
let confirmKey = sprintf "sip-confirm:%O:%s" retryPlanId (retryDate.ToString("yyyy-MM-dd"))
match this.ConfirmSubscriptionOrder(confirmKey, fundId, retryOrderId) with
| SubscriptionConfirmResult.OrderConfirmed _
| SubscriptionConfirmResult.ConfirmReplayed _ ->
use doneCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE sip_executions SET status = 'succeeded', pending_reason = NULL, executed_at = now() WHERE plan_id = @plan_id AND trade_date = @trade_date"
addParameter doneCommand "plan_id" NpgsqlDbType.Uuid (box retryPlanId) |> ignore
addParameter doneCommand "trade_date" NpgsqlDbType.Date (box retryDate) |> ignore
doneCommand.ExecuteNonQuery() |> ignore
| _ ->
// still pending: keep the execution as pending_nav for the next drive
()
use plansCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT id, instrument_code, asset_class, amount, frequency, anchor_date, next_trade_date FROM sip_plans WHERE fund_id = @fund_id AND status = 'active' ORDER BY created_at"
addParameter plansCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use plansReader = plansCommand.ExecuteReader()
let plans = ResizeArray<Guid * string * string * decimal * SipFrequency * DateOnly * DateOnly>()
while plansReader.Read() do
plans.Add(
plansReader.GetGuid(0),
plansReader.GetString(1),
plansReader.GetString(2),
plansReader.GetDecimal(3),
(match SipPolicy.parseFrequency (plansReader.GetString(4)) with
| Some frequency -> frequency
| None -> failwith "sip plan frequency is invalid"),
plansReader.GetFieldValue<DateOnly>(5),
plansReader.GetFieldValue<DateOnly>(6)
)
plansReader.Close()
let readExecutionsUpTo (planId: Guid) (upTo: DateOnly) =
use replayCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT trade_date, status, order_id, pending_reason
FROM sip_executions
WHERE plan_id = @plan_id AND trade_date <= @up_to
ORDER BY trade_date
"""
addParameter replayCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter replayCommand "up_to" NpgsqlDbType.Date (box upTo) |> ignore
use reader = replayCommand.ExecuteReader()
let rows = ResizeArray<SipExecutionOutcome>()
while reader.Read() do
rows.Add(
{
TradeDate = reader.GetFieldValue<DateOnly>(0)
Status = reader.GetString(1)
OrderId = (if reader.IsDBNull(2) then None else Some(reader.GetGuid(2)))
PendingReason = readStringOption reader 3
}
)
rows |> Seq.toList
let rollPlanPointer (planId: Guid) (nextDate: DateOnly) (frequency: SipFrequency) (anchor: DateOnly) (dueDates: DateOnly list) =
let rolled =
match dueDates with
| [] -> nextDate
| _ -> SipPolicy.nextTradeDate frequency anchor ((List.last dueDates).AddDays 1)
if not (List.isEmpty dueDates) then
use rollCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE sip_plans SET next_trade_date = @next_date WHERE id = @plan_id"
addParameter rollCommand "next_date" NpgsqlDbType.Date (box rolled) |> ignore
addParameter rollCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
rollCommand.ExecuteNonQuery() |> ignore
rolled
// Stock SIP: schedule, lot sizing and idempotency mirror the fund path, but each
// due period buys the target stock through the shared stock-trade pipeline using a
// live quote (suspension and missing prices stop the period).
let advanceStockPlanRow (planId: Guid, code: string, assetClass: string, amount: decimal, frequency: SipFrequency, anchor: DateOnly, nextDate: DateOnly) =
let dueDates =
SipPolicy.advancePlan frequency anchor nextDate endDate
|> List.truncate (max 1 limit)
let outcomes = ResizeArray<SipExecutionOutcome>()
let upsertExecution (tradeDate: DateOnly) =
use insertCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO sip_executions (plan_id, trade_date, amount, fee_amount, status)
VALUES (@plan_id, @trade_date, @amount, @fee_amount, 'processing')
ON CONFLICT (plan_id, trade_date) DO NOTHING
RETURNING trade_date
"""
addParameter insertCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter insertCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
addParameter insertCommand "amount" NpgsqlDbType.Numeric (box amount) |> ignore
addParameter insertCommand "fee_amount" NpgsqlDbType.Numeric (box 0m) |> ignore
use reader = insertCommand.ExecuteReader()
let inserted = reader.Read()
reader.Close()
inserted
let setExecution (tradeDate: DateOnly) (status: string) (orderId: Guid option) (reason: string option) =
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE sip_executions
SET status = @status,
order_id = @order_id,
pending_reason = @reason,
executed_at = now()
WHERE plan_id = @plan_id AND trade_date = @trade_date
"""
addParameter updateCommand "status" NpgsqlDbType.Text (box status) |> ignore
let orderParameter =
match orderId with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "order_id" NpgsqlDbType.Uuid orderParameter |> ignore
let reasonParameter =
match reason with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "reason" NpgsqlDbType.Text reasonParameter |> ignore
addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter updateCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
let findExistingExecution (tradeDate: DateOnly) =
use selectCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT status, order_id, pending_reason FROM sip_executions WHERE plan_id = @plan_id AND trade_date = @trade_date"
addParameter selectCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter selectCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
use reader = selectCommand.ExecuteReader()
if reader.Read() then
Some
(reader.GetString(0),
(if reader.IsDBNull(1) then None else Some(reader.GetGuid(1))),
readStringOption reader 2)
else
None
let settle (tradeDate: DateOnly) (status: string) (orderId: Guid option) (reason: string option) =
setExecution tradeDate status orderId reason
outcomes.Add(
{
TradeDate = tradeDate
Status = status
OrderId = orderId
PendingReason = reason
}
)
for tradeDate in dueDates do
if upsertExecution tradeDate then
let quoteResult =
match stockQuote with
| Some resolve -> resolve code
| None -> Error "stock quote probe is not configured"
match quoteResult with
| Error reason -> settle tradeDate "market_data_unavailable" None (Some reason)
| Ok quote ->
match quote.Suspended with
| Some true -> settle tradeDate "suspended" None (Some "stock is suspended and cannot be traded")
| _ ->
match quote.Price with
| Some price when price > 0m ->
let lot = StockTerms.aShareDefault.MinUnit
let lots = Decimal.Floor(amount / (price * lot))
let quantity = lots * lot
if quantity <= 0m then
settle tradeDate "insufficient_cash" None (Some "scheduled amount is below one board lot at the current price")
else
let tradeKey = sprintf "sip:%O:%s" planId (tradeDate.ToString("yyyy-MM-dd"))
let executedAt = DateTimeOffset(tradeDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero)
let command: StockTradeCommand =
{
InstrumentCode = code
StockName = quote.Name
Quantity = quantity
Price = price
}
match this.CreateStockTrade(tradeKey, fundId, command, executedAt, true) with
| StockTradeWriteResult.StockTradeCreated trade
| StockTradeWriteResult.StockTradeReplayed trade ->
settle tradeDate "succeeded" (Some trade.Id) None
| StockTradeWriteResult.StockTradeInsufficientFunds reason ->
settle tradeDate "insufficient_cash" None (Some reason)
| StockTradeWriteResult.StockTradeInvalid reason -> settle tradeDate "failed" None (Some reason)
| StockTradeWriteResult.StockTradeIdempotencyConflict ->
settle tradeDate "failed" None (Some "idempotency key was used with a different request")
| StockTradeWriteResult.StockTradeFundNotFound ->
settle tradeDate "failed" None (Some "fund was not found")
| _ -> settle tradeDate "market_data_unavailable" None (Some "stock quote did not include a price")
else
match findExistingExecution tradeDate with
| Some(status, orderId, reason) ->
outcomes.Add(
{
TradeDate = tradeDate
Status = status
OrderId = orderId
PendingReason = reason
}
)
| None ->
outcomes.Add(
{
TradeDate = tradeDate
Status = "unknown"
OrderId = None
PendingReason = None
}
)
let rolled = rollPlanPointer planId nextDate frequency anchor dueDates
let replayedOutcomes =
if List.isEmpty dueDates then readExecutionsUpTo planId endDate else outcomes |> Seq.toList
{
PlanId = planId
InstrumentCode = code
AssetClass = assetClass
Amount = amount
Frequency = frequency
Executions = replayedOutcomes
NextTradeDate = rolled
}
let advanceFundPlanRow (planId: Guid, code: string, assetClass: string, amount: decimal, frequency: SipFrequency, anchor: DateOnly, nextDate: DateOnly) =
let dueDates =
SipPolicy.advancePlan frequency anchor nextDate endDate
|> List.truncate (max 1 limit)
let outcomes = ResizeArray<SipExecutionOutcome>()
let upsertExecution (tradeDate: DateOnly) =
use insertCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO sip_executions (plan_id, trade_date, amount, fee_amount, status)
VALUES (@plan_id, @trade_date, @amount, @fee_amount, 'processing')
ON CONFLICT (plan_id, trade_date) DO NOTHING
RETURNING trade_date
"""
addParameter insertCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter insertCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
addParameter insertCommand "amount" NpgsqlDbType.Numeric (box amount) |> ignore
addParameter insertCommand "fee_amount" NpgsqlDbType.Numeric (box 0m) |> ignore
use reader = insertCommand.ExecuteReader()
let inserted = reader.Read()
reader.Close()
inserted
let setExecution (tradeDate: DateOnly) (status: string) (orderId: Guid option) (reason: string option) =
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE sip_executions
SET status = @status,
order_id = @order_id,
pending_reason = @reason,
executed_at = now()
WHERE plan_id = @plan_id AND trade_date = @trade_date
"""
addParameter updateCommand "status" NpgsqlDbType.Text (box status) |> ignore
let orderParameter =
match orderId with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "order_id" NpgsqlDbType.Uuid orderParameter |> ignore
let reasonParameter =
match reason with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "reason" NpgsqlDbType.Text reasonParameter |> ignore
addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter updateCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
let findExistingExecution (tradeDate: DateOnly) =
use selectCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT status, order_id, pending_reason FROM sip_executions WHERE plan_id = @plan_id AND trade_date = @trade_date"
addParameter selectCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter selectCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
use reader = selectCommand.ExecuteReader()
if reader.Read() then
Some
(reader.GetString(0),
(if reader.IsDBNull(1) then None else Some(reader.GetGuid(1))),
readStringOption reader 2)
else
None
let orderIdFor (tradeDate: DateOnly) =
let orderKey = sprintf "sip:%O:%s" planId (tradeDate.ToString("yyyy-MM-dd"))
match this.CreateSubscriptionOrder(orderKey, fundId, { FundCode = code; Amount = amount; FeeAmount = 0m }, tradeDate) with
| SubscriptionOrderWriteResult.OrderCreated order -> Some order.Id
| SubscriptionOrderWriteResult.OrderReplayed order -> Some order.Id
| SubscriptionOrderWriteResult.OrderInsufficientFunds -> None
| other -> failwithf "unexpected sip order result: %A" other
for tradeDate in dueDates do
// 1. claim the slot atomically: same plan + same trade date runs once
if upsertExecution tradeDate then
// 2. place the order through the shared pipeline with a deterministic key
match orderIdFor tradeDate with
| None ->
setExecution tradeDate "insufficient_cash" None (Some "available cash is not enough for the scheduled amount")
outcomes.Add({ TradeDate = tradeDate; Status = "insufficient_cash"; OrderId = None; PendingReason = Some "available cash is not enough for the scheduled amount" })
| Some orderId ->
// 3. confirm through the shared confirmation pipeline
let confirmKey = sprintf "sip-confirm:%O:%s" planId (tradeDate.ToString("yyyy-MM-dd"))
match this.ConfirmSubscriptionOrder(confirmKey, fundId, orderId) with
| SubscriptionConfirmResult.OrderConfirmed _
| SubscriptionConfirmResult.ConfirmReplayed _ ->
setExecution tradeDate "succeeded" (Some orderId) None
outcomes.Add({ TradeDate = tradeDate; Status = "succeeded"; OrderId = Some orderId; PendingReason = None })
| SubscriptionConfirmResult.ConfirmPendingNav record ->
setExecution tradeDate "pending_nav" (Some orderId) record.PendingReason
outcomes.Add({ TradeDate = tradeDate; Status = "pending_nav"; OrderId = Some orderId; PendingReason = record.PendingReason })
| other ->
setExecution tradeDate "failed" (Some orderId) (Some (sprintf "%A" other))
outcomes.Add({ TradeDate = tradeDate; Status = "failed"; OrderId = Some orderId; PendingReason = Some (sprintf "%A" other) })
else
match findExistingExecution tradeDate with
| Some("succeeded", orderId, reason) ->
outcomes.Add({ TradeDate = tradeDate; Status = "succeeded"; OrderId = orderId; PendingReason = reason })
| Some(status, orderId, reason) ->
outcomes.Add({ TradeDate = tradeDate; Status = status; OrderId = orderId; PendingReason = reason })
| None ->
outcomes.Add({ TradeDate = tradeDate; Status = "unknown"; OrderId = None; PendingReason = None })
// 4. roll the plan pointer forward past the processed window
let rolled =
match dueDates with
| [] -> nextDate
| lastDueDates ->
SipPolicy.nextTradeDate frequency anchor ((List.last lastDueDates).AddDays 1)
if not (List.isEmpty dueDates) then
use rollCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE sip_plans SET next_trade_date = @next_date WHERE id = @plan_id"
addParameter rollCommand "next_date" NpgsqlDbType.Date (box rolled) |> ignore
addParameter rollCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
rollCommand.ExecuteNonQuery() |> ignore
let replayedOutcomes =
if List.isEmpty dueDates then
// repeat drive with the same endDate: replay what was already processed
readExecutionsUpTo planId endDate
else
outcomes |> Seq.toList
{
PlanId = planId
InstrumentCode = code
AssetClass = assetClass
Amount = amount
Frequency = frequency
Executions = replayedOutcomes
NextTradeDate = rolled
}
let advancePlanRow (planId: Guid, code: string, assetClass: string, amount: decimal, frequency: SipFrequency, anchor: DateOnly, nextDate: DateOnly) =
if assetClass = "stock" then
advanceStockPlanRow (planId, code, assetClass, amount, frequency, anchor, nextDate)
else
advanceFundPlanRow (planId, code, assetClass, amount, frequency, anchor, nextDate)
let planResults = plans |> Seq.map advancePlanRow |> Seq.toList
transaction.Commit()
{ FundId = fundId; Plans = planResults }
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetSipPlans(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT p.id, p.fund_id, p.instrument_code, p.asset_class, p.amount, p.frequency, p.status, p.is_synthetic,
p.anchor_date, p.next_trade_date, p.created_at,
e.status, e.trade_date
FROM sip_plans p
LEFT JOIN LATERAL (
SELECT status, trade_date FROM sip_executions
WHERE plan_id = p.id ORDER BY executed_at DESC, trade_date DESC LIMIT 1
) e ON true
WHERE p.fund_id = @fund_id
ORDER BY p.created_at DESC, p.id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<SipPlanRecord>()
while reader.Read() do
records.Add(sipPlanRecordFromReader reader)
records |> Seq.toList
member _.SetSipPlanStatus(fundId: Guid, planId: Guid, status: string) : SipPlanStatusResult =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "sip-plan-status:%O" planId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findSipPlan connection (Some transaction) planId with
| Some plan when plan.FundId = fundId ->
if plan.Status = status then
transaction.Commit()
SipPlanStatusResult.SipPlanStatusChanged plan
else
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE sip_plans SET status = @status WHERE id = @plan_id"
addParameter updateCommand "status" NpgsqlDbType.Text (box status) |> ignore
addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
let updated = findSipPlan connection (Some transaction) planId
transaction.Commit()
match updated with
| Some updatedPlan -> SipPlanStatusResult.SipPlanStatusChanged updatedPlan
| None -> SipPlanStatusResult.SipPlanStatusNotFound
| _ ->
transaction.Rollback()
SipPlanStatusResult.SipPlanStatusNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.CreateInvestmentPlan(idempotencyKey: string, fundId: Guid, command: InvestmentPlanCommand, ?anchorOverride: DateOnly) : InvestmentPlanWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
InvestmentPlanWriteResult.InvestmentPlanInvalid "idempotency key cannot be empty"
else
match InvestmentPlanPolicy.validateAmount command.Amount with
| Error message -> InvestmentPlanWriteResult.InvestmentPlanInvalid message
| Ok() ->
let fingerprint = investmentPlanRequestHash fundId command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findInvestmentPlanIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, planId)
when existingHash = fingerprint && existingFundId = fundId ->
match findInvestmentPlan connection (Some transaction) planId with
| Some plan ->
transaction.Commit()
InvestmentPlanWriteResult.InvestmentPlanReplayed plan
| None ->
transaction.Rollback()
InvestmentPlanWriteResult.InvestmentPlanInvalid "idempotency record references a missing plan"
| Some _ ->
transaction.Rollback()
InvestmentPlanWriteResult.InvestmentPlanIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
InvestmentPlanWriteResult.InvestmentPlanFundNotFound
| Some isSynthetic ->
if instrumentExists connection (Some transaction) command.InstrumentCode then
let anchorDate =
anchorOverride
|> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow)
let plan: InvestmentPlanRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = command.InstrumentCode
Amount = command.Amount
Frequency = command.Frequency
Status = "active"
IsSynthetic = isSynthetic
AnchorDate = anchorDate
NextRunDate = InvestmentPlanPolicy.nextRunDate command.Frequency anchorDate anchorDate
CreatedAt = DateTimeOffset.UtcNow
LastRunStatus = None
LastRunDate = None
}
let createdAt = insertInvestmentPlan connection (Some transaction) plan
insertInvestmentPlanIdempotency connection (Some transaction) idempotencyKey fingerprint plan.Id fundId
transaction.Commit()
InvestmentPlanWriteResult.InvestmentPlanCreated { plan with CreatedAt = createdAt }
else
transaction.Rollback()
InvestmentPlanWriteResult.InvestmentPlanInstrumentNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetInvestmentPlans(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT p.id, p.fund_id, p.instrument_code, p.amount, p.frequency, p.status, p.is_synthetic,
p.anchor_date, p.next_run_date, p.created_at,
r.status, r.run_date
FROM investment_plans p
LEFT JOIN LATERAL (
SELECT status, run_date FROM investment_plan_runs
WHERE plan_id = p.id ORDER BY executed_at DESC, run_date DESC LIMIT 1
) r ON true
WHERE p.fund_id = @fund_id
ORDER BY p.created_at DESC, p.id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<InvestmentPlanRecord>()
while reader.Read() do
records.Add(investmentPlanRecordFromReader reader)
records |> Seq.toList
member this.RunInvestmentPlans(fundId: Guid, processingDate: DateOnly) : InvestmentPlanRunResult =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "investment-plan-run:%O" fundId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
// 0. retry phase: runs that were pending_nav get re-confirmed once their NAV landed
use retryCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT r.plan_id, r.run_date, r.order_id
FROM investment_plan_runs r
JOIN investment_plans p ON p.id = r.plan_id
WHERE p.fund_id = @fund_id AND r.status = 'pending_nav'
ORDER BY r.run_date
"""
addParameter retryCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use retryReader = retryCommand.ExecuteReader()
let pendingRetries = ResizeArray<Guid * DateOnly * Guid>()
while retryReader.Read() do
pendingRetries.Add(
retryReader.GetGuid(0),
retryReader.GetFieldValue<DateOnly>(1),
retryReader.GetGuid(2)
)
retryReader.Close()
for (retryPlanId, retryDate, retryOrderId) in pendingRetries do
let confirmKey = sprintf "investment-plan-confirm:%O:%s" retryPlanId (retryDate.ToString("yyyy-MM-dd"))
match this.ConfirmSubscriptionOrder(confirmKey, fundId, retryOrderId) with
| SubscriptionConfirmResult.OrderConfirmed _
| SubscriptionConfirmResult.ConfirmReplayed _ ->
use doneCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE investment_plan_runs SET status = 'succeeded', pending_reason = NULL, executed_at = now() WHERE plan_id = @plan_id AND run_date = @run_date"
addParameter doneCommand "plan_id" NpgsqlDbType.Uuid (box retryPlanId) |> ignore
addParameter doneCommand "run_date" NpgsqlDbType.Date (box retryDate) |> ignore
doneCommand.ExecuteNonQuery() |> ignore
| _ ->
// still pending: keep the run as pending_nav for the next drive
()
use plansCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT id, instrument_code, amount, frequency, anchor_date, next_run_date FROM investment_plans WHERE fund_id = @fund_id AND status = 'active' ORDER BY created_at"
addParameter plansCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use plansReader = plansCommand.ExecuteReader()
let plans = ResizeArray<Guid * string * decimal * InvestmentFrequency * DateOnly * DateOnly>()
while plansReader.Read() do
plans.Add(
plansReader.GetGuid(0),
plansReader.GetString(1),
plansReader.GetDecimal(2),
(match InvestmentPlanPolicy.parseFrequency (plansReader.GetString(3)) with
| Some frequency -> frequency
| None -> failwith "investment plan frequency is invalid"),
plansReader.GetFieldValue<DateOnly>(4),
plansReader.GetFieldValue<DateOnly>(5)
)
plansReader.Close()
let readRunsUpTo (planId: Guid) (upTo: DateOnly) =
use replayCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT run_date, status, order_id, pending_reason
FROM investment_plan_runs
WHERE plan_id = @plan_id AND run_date <= @up_to
ORDER BY run_date
"""
addParameter replayCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter replayCommand "up_to" NpgsqlDbType.Date (box upTo) |> ignore
use reader = replayCommand.ExecuteReader()
let rows = ResizeArray<InvestmentPlanRunOutcome>()
while reader.Read() do
rows.Add(
{
RunDate = reader.GetFieldValue<DateOnly>(0)
Status = reader.GetString(1)
OrderId = (if reader.IsDBNull(2) then None else Some(reader.GetGuid(2)))
PendingReason = readStringOption reader 3
}
)
rows |> Seq.toList
let runPlanRow (planId: Guid, code: string, amount: decimal, frequency: InvestmentFrequency, anchor: DateOnly, nextDate: DateOnly) =
let dueDates = InvestmentPlanPolicy.dueDates frequency anchor nextDate processingDate
let outcomes = ResizeArray<InvestmentPlanRunOutcome>()
let claimRun (runDate: DateOnly) =
use insertCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO investment_plan_runs (plan_id, run_date, amount, fee_amount, status)
VALUES (@plan_id, @run_date, @amount, @fee_amount, 'processing')
ON CONFLICT (plan_id, run_date) DO NOTHING
RETURNING run_date
"""
addParameter insertCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter insertCommand "run_date" NpgsqlDbType.Date (box runDate) |> ignore
addParameter insertCommand "amount" NpgsqlDbType.Numeric (box amount) |> ignore
addParameter insertCommand "fee_amount" NpgsqlDbType.Numeric (box 0m) |> ignore
use reader = insertCommand.ExecuteReader()
let inserted = reader.Read()
reader.Close()
inserted
let setRun (runDate: DateOnly) (status: string) (orderId: Guid option) (reason: string option) =
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE investment_plan_runs
SET status = @status,
order_id = @order_id,
pending_reason = @reason,
executed_at = now()
WHERE plan_id = @plan_id AND run_date = @run_date
"""
addParameter updateCommand "status" NpgsqlDbType.Text (box status) |> ignore
let orderParameter =
match orderId with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "order_id" NpgsqlDbType.Uuid orderParameter |> ignore
let reasonParameter =
match reason with
| Some value -> box value
| None -> box DBNull.Value
addParameter updateCommand "reason" NpgsqlDbType.Text reasonParameter |> ignore
addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter updateCommand "run_date" NpgsqlDbType.Date (box runDate) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
let findExistingRun (runDate: DateOnly) =
use selectCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT status, order_id, pending_reason FROM investment_plan_runs WHERE plan_id = @plan_id AND run_date = @run_date"
addParameter selectCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
addParameter selectCommand "run_date" NpgsqlDbType.Date (box runDate) |> ignore
use reader = selectCommand.ExecuteReader()
if reader.Read() then
Some
(reader.GetString(0),
(if reader.IsDBNull(1) then None else Some(reader.GetGuid(1))),
readStringOption reader 2)
else
None
let orderIdFor (runDate: DateOnly) =
let orderKey = sprintf "investment-plan:%O:%s" planId (runDate.ToString("yyyy-MM-dd"))
match this.CreateSubscriptionOrder(orderKey, fundId, { FundCode = code; Amount = amount; FeeAmount = 0m }, runDate) with
| SubscriptionOrderWriteResult.OrderCreated order -> Some order.Id
| SubscriptionOrderWriteResult.OrderReplayed order -> Some order.Id
| SubscriptionOrderWriteResult.OrderInsufficientFunds -> None
| other -> failwithf "unexpected investment plan order result: %A" other
for runDate in dueDates do
// 1. claim the slot atomically: same plan + same run date executes once
if claimRun runDate then
// 2. place the order through the shared pipeline with a deterministic key
match orderIdFor runDate with
| None ->
setRun runDate "insufficient_cash" None (Some "available cash is not enough for the scheduled amount")
outcomes.Add(
{
RunDate = runDate
Status = "insufficient_cash"
OrderId = None
PendingReason = Some "available cash is not enough for the scheduled amount"
}
)
| Some orderId ->
// 3. confirm through the shared confirmation pipeline
let confirmKey = sprintf "investment-plan-confirm:%O:%s" planId (runDate.ToString("yyyy-MM-dd"))
match this.ConfirmSubscriptionOrder(confirmKey, fundId, orderId) with
| SubscriptionConfirmResult.OrderConfirmed _
| SubscriptionConfirmResult.ConfirmReplayed _ ->
setRun runDate "succeeded" (Some orderId) None
outcomes.Add({ RunDate = runDate; Status = "succeeded"; OrderId = Some orderId; PendingReason = None })
| SubscriptionConfirmResult.ConfirmPendingNav record ->
setRun runDate "pending_nav" (Some orderId) record.PendingReason
outcomes.Add({ RunDate = runDate; Status = "pending_nav"; OrderId = Some orderId; PendingReason = record.PendingReason })
| other ->
setRun runDate "failed" (Some orderId) (Some(sprintf "%A" other))
outcomes.Add({ RunDate = runDate; Status = "failed"; OrderId = Some orderId; PendingReason = Some(sprintf "%A" other) })
else
match findExistingRun runDate with
| Some("succeeded", orderId, reason) ->
outcomes.Add({ RunDate = runDate; Status = "succeeded"; OrderId = orderId; PendingReason = reason })
| Some(status, orderId, reason) ->
outcomes.Add({ RunDate = runDate; Status = status; OrderId = orderId; PendingReason = reason })
| None ->
outcomes.Add({ RunDate = runDate; Status = "unknown"; OrderId = None; PendingReason = None })
// 4. roll the plan pointer forward past the processed window
let rolled =
match dueDates with
| [] -> nextDate
| lastDueDates -> InvestmentPlanPolicy.nextRunDate frequency anchor ((List.last lastDueDates).AddDays 1)
if not (List.isEmpty dueDates) then
use rollCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE investment_plans SET next_run_date = @next_date WHERE id = @plan_id"
addParameter rollCommand "next_date" NpgsqlDbType.Date (box rolled) |> ignore
addParameter rollCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
rollCommand.ExecuteNonQuery() |> ignore
let replayedOutcomes =
if List.isEmpty dueDates then
// repeat drive with the same processing date: replay what was already executed
readRunsUpTo planId processingDate
else
outcomes |> Seq.toList
{
PlanId = planId
InstrumentCode = code
Amount = amount
Frequency = frequency
Runs = replayedOutcomes
NextRunDate = rolled
}
let planResults = plans |> Seq.map runPlanRow |> Seq.toList
transaction.Commit()
{ FundId = fundId; ProcessingDate = processingDate; Plans = planResults }
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.CreateRebalancePlan(idempotencyKey: string, fundId: Guid, command: RebalancePlanCommand) : RebalanceWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
RebalanceWriteResult.RebalanceInvalid "idempotency key cannot be empty"
else
match validateRebalanceCommand command with
| Error message -> RebalanceWriteResult.RebalanceInvalid message
| Ok() ->
let fingerprint = rebalanceRequestHash fundId command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findRebalanceIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, planId)
when existingHash = fingerprint && existingFundId = fundId ->
match findRebalancePlan connection (Some transaction) planId with
| Some plan ->
transaction.Commit()
RebalanceWriteResult.RebalancePlanReplayed plan
| None ->
transaction.Rollback()
RebalanceWriteResult.RebalanceInvalid "idempotency record references a missing plan"
| Some _ ->
transaction.Rollback()
RebalanceWriteResult.RebalanceIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
RebalanceWriteResult.RebalanceFundNotFound
| Some isSynthetic ->
let missingTarget =
command.Targets
|> List.tryFind (fun target -> not (instrumentExists connection (Some transaction) target.InstrumentCode))
match missingTarget with
| Some target ->
transaction.Rollback()
RebalanceWriteResult.RebalanceInstrumentNotFound
| None ->
let plan: RebalancePlanRecord =
{
Id = Guid.NewGuid()
FundId = fundId
Targets = command.Targets
Status = "active"
IsSynthetic = isSynthetic
CreatedAt = DateTimeOffset.UtcNow
}
let createdAt = insertRebalancePlan connection (Some transaction) plan
insertRebalanceIdempotency connection (Some transaction) idempotencyKey fingerprint plan.Id fundId
transaction.Commit()
RebalanceWriteResult.RebalancePlanCreated { plan with CreatedAt = createdAt }
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetRebalancePlans(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"SELECT id, fund_id, status, is_synthetic, created_at FROM rebalance_plans WHERE fund_id = @fund_id ORDER BY created_at DESC, id"
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let plans = ResizeArray<RebalancePlanRecord>()
while reader.Read() do
plans.Add(rebalancePlanRecordFromReader reader)
reader.Close()
plans |> Seq.toList |> List.map (rebalancePlanWithTargets connection None)
member _.ArchiveRebalancePlan(fundId: Guid, planId: Guid) : RebalanceArchiveResult =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "rebalance-archive:%O" planId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findRebalancePlan connection (Some transaction) planId with
| Some plan when plan.FundId = fundId ->
if plan.Status = "archived" then
transaction.Commit()
RebalanceArchiveResult.RebalancePlanArchived plan
else
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE rebalance_plans SET status = 'archived' WHERE id = @plan_id"
addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
let updated = findRebalancePlan connection (Some transaction) planId
transaction.Commit()
match updated with
| Some updatedPlan -> RebalanceArchiveResult.RebalancePlanArchived updatedPlan
| None -> RebalanceArchiveResult.RebalanceArchiveNotFound
| _ ->
transaction.Rollback()
RebalanceArchiveResult.RebalanceArchiveNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member this.ExecuteRebalancePlan(planId: Guid) : Result<RebalanceExecutionResult, string> =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
let plan =
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "rebalance-execute:%O" planId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
let plan = findRebalancePlan connection (Some transaction) planId
transaction.Commit()
plan
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
match plan with
| None -> Error "rebalance plan was not found"
| Some plan when plan.Status = "archived" -> Error "rebalance plan is archived"
| Some plan ->
let fundId = plan.FundId
let runDate = ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow
// snapshot: fund cash plus each holding valued at its latest valuation NAV
let fund = this.GetFund fundId
match fund with
| None -> Error "fund was not found"
| Some fund ->
let positions = this.GetFundPositions fundId
let buildSnapshot (position: FundPositionRecord) : RebalancePolicy.RebalancePositionSnapshot =
let marketValue =
match position.ValuationNav with
| Some nav -> Decimal.Round(position.Units * nav, 2)
| None -> 0m
{
RebalancePolicy.RebalancePositionSnapshot.InstrumentCode = position.InstrumentCode
RebalancePolicy.RebalancePositionSnapshot.MarketValue = marketValue
RebalancePolicy.RebalancePositionSnapshot.Units = position.Units
RebalancePolicy.RebalancePositionSnapshot.AvailableUnits = position.Units - position.ReservedUnits
RebalancePolicy.RebalancePositionSnapshot.ValuationNav = position.ValuationNav
}
let snapshots = positions |> List.map buildSnapshot
let diffs =
RebalancePolicy.computeOrders plan.Targets snapshots fund.AvailableCash
match diffs with
| Error message -> Error message
| Ok diffs ->
let outcomes = ResizeArray<RebalanceOrderOutcome>()
// sells first so freed cash can fund the buys
let ordered =
diffs
|> List.sortBy (fun diff ->
match diff.Action with
| RebalancePolicy.Sell -> 0
| RebalancePolicy.Buy -> 1
| RebalancePolicy.Hold -> 2)
for diff: RebalancePolicy.RebalanceDiff in ordered do
match diff.Action with
| RebalancePolicy.Hold -> ()
| RebalancePolicy.Buy ->
let orderKey = RebalancePolicy.orderKey plan.Id runDate diff.InstrumentCode
match
this.CreateSubscriptionOrder(
orderKey,
fundId,
{ FundCode = diff.InstrumentCode; Amount = diff.Amount; FeeAmount = 0m }
)
with
| SubscriptionOrderWriteResult.OrderCreated order
| SubscriptionOrderWriteResult.OrderReplayed order ->
let confirmKey = RebalancePolicy.confirmKey plan.Id runDate diff.InstrumentCode
match this.ConfirmSubscriptionOrder(confirmKey, fundId, order.Id) with
| SubscriptionConfirmResult.OrderConfirmed _
| SubscriptionConfirmResult.ConfirmReplayed _ ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "succeeded"; OrderId = Some order.Id; PendingReason = None })
| SubscriptionConfirmResult.ConfirmPendingNav record ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "pending_nav"; OrderId = Some order.Id; PendingReason = record.PendingReason })
| SubscriptionConfirmResult.ConfirmIdempotencyConflict ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "idempotency_conflict"; OrderId = Some order.Id; PendingReason = None })
| other ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "failed"; OrderId = Some order.Id; PendingReason = Some (sprintf "%A" other) })
| SubscriptionOrderWriteResult.OrderInsufficientFunds ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "insufficient_cash"; OrderId = None; PendingReason = Some "available cash is not enough for the rebalance buy" })
| other ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "failed"; OrderId = None; PendingReason = Some (sprintf "%A" other) })
| RebalancePolicy.Sell ->
match diff.Units with
| None ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "skipped_no_valuation"; OrderId = None; PendingReason = Some "holding has no valuation NAV to price the sell" })
| Some units when units <= 0m ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "skipped_no_available_units"; OrderId = None; PendingReason = Some "no available units to redeem" })
| Some units ->
let redeemKey = RebalancePolicy.redemptionKey plan.Id runDate diff.InstrumentCode
match
this.CreateRedemptionOrder(
redeemKey,
fundId,
{ InstrumentCode = diff.InstrumentCode; Units = units; FeeAmount = 0m }
)
with
| RedemptionWriteResult.RedemptionCreated order
| RedemptionWriteResult.RedemptionReplayed order ->
let confirmKey = RebalancePolicy.redemptionConfirmKey plan.Id runDate diff.InstrumentCode
match this.ConfirmRedemptionOrder(confirmKey, fundId, order.Id) with
| RedemptionConfirmResult.RedemptionConfirmed _
| RedemptionConfirmResult.RedemptionConfirmReplayed _ ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "succeeded"; OrderId = Some order.Id; PendingReason = None })
| RedemptionConfirmResult.RedemptionPendingNav record ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "pending_nav"; OrderId = Some order.Id; PendingReason = record.PendingReason })
| other ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "failed"; OrderId = Some order.Id; PendingReason = Some (sprintf "%A" other) })
| RedemptionWriteResult.RedemptionInsufficientUnits ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "insufficient_units"; OrderId = None; PendingReason = Some "available units are not enough for the rebalance sell" })
| other ->
outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "failed"; OrderId = None; PendingReason = Some (sprintf "%A" other) })
let outcomeList = outcomes |> Seq.toList
use persistTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
for outcome in outcomeList do
upsertRebalanceExecution connection (Some persistTransaction) plan.Id runDate outcome
persistTransaction.Commit()
with error ->
try
persistTransaction.Rollback()
with _ ->
()
raise error
Ok
{
PlanId = plan.Id
RunDate = runDate
Outcomes = outcomeList
}
member _.GetRebalanceExecutions(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT e.plan_id, e.run_date, e.instrument_code, e.action, e.amount, e.status, e.order_id, e.pending_reason, e.executed_at
FROM rebalance_executions e
JOIN rebalance_plans p ON p.id = e.plan_id
WHERE p.fund_id = @fund_id
ORDER BY e.executed_at DESC, e.run_date DESC, e.instrument_code
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<RebalanceExecutionRecord>()
while reader.Read() do
records.Add(rebalanceExecutionRecordFromReader reader)
records |> Seq.toList
member this.PreviewRebalancePlan(planId: Guid) : Result<RebalancePreview, string> =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
match findRebalancePlan connection None planId with
| None -> Error "rebalance plan was not found"
| Some plan when plan.Status = "archived" -> Error "rebalance plan is archived"
| Some plan ->
match this.GetFund plan.FundId with
| None -> Error "fund was not found"
| Some fund ->
let positions = this.GetFundPositions plan.FundId
let buildSnapshot (position: FundPositionRecord) : RebalancePolicy.RebalancePositionSnapshot =
let marketValue =
match position.ValuationNav with
| Some nav -> Decimal.Round(position.Units * nav, 2)
| None -> 0m
{
RebalancePolicy.RebalancePositionSnapshot.InstrumentCode = position.InstrumentCode
RebalancePolicy.RebalancePositionSnapshot.MarketValue = marketValue
RebalancePolicy.RebalancePositionSnapshot.Units = position.Units
RebalancePolicy.RebalancePositionSnapshot.AvailableUnits = position.Units - position.ReservedUnits
RebalancePolicy.RebalancePositionSnapshot.ValuationNav = position.ValuationNav
}
let snapshots = positions |> List.map buildSnapshot
match RebalancePolicy.weightRows plan.Targets snapshots fund.AvailableCash with
| Error message -> Error message
| Ok rows ->
let equity =
fund.AvailableCash + (snapshots |> List.sumBy (fun snapshot -> snapshot.MarketValue))
Ok
{
PlanId = plan.Id
RunDate = ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow
AvailableCash = fund.AvailableCash
Equity = equity
Rows = rows
}
member this.RegisterDividend(idempotencyKey: string, fundId: Guid, command: DividendCommand) : DividendWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
DividendWriteResult.DividendInvalid "idempotency key cannot be empty"
else
let today = ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow
match validateDividendCommand today command with
| Error message -> DividendWriteResult.DividendInvalid message
| Ok() ->
let schemeKey = dividendSchemeKey fundId command
let fingerprint = dividendRequestHash fundId command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
// Phase 1: claim the scheme atomically, validate, and book the payout
let claimedStage =
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box schemeKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findDividendIdempotency connection (Some transaction) schemeKey with
| Some(existingHash, existingFundId, recordId) when existingFundId = fundId ->
if existingHash = fingerprint then
transaction.Commit()
StageReplay recordId
else
transaction.Rollback()
StageFail DividendWriteResult.DividendIdempotencyConflict
| Some _ ->
transaction.Rollback()
StageFail DividendWriteResult.DividendIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
StageFail DividendWriteResult.DividendFundNotFound
| Some isSynthetic ->
if not (instrumentExists connection (Some transaction) command.InstrumentCode) then
transaction.Rollback()
StageFail DividendWriteResult.DividendInstrumentNotFound
else
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT units FROM fund_positions WHERE fund_id = @fund_id AND instrument_code = @code FOR UPDATE"
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box command.InstrumentCode) |> ignore
use positionReader = positionCommand.ExecuteReader()
let positionFound = positionReader.Read()
let heldUnits = if positionFound then positionReader.GetDecimal(0) else 0m
positionReader.Close()
if not positionFound || heldUnits <= 0m then
transaction.Rollback()
StageFail DividendWriteResult.DividendNoHoldings
else
match DividendPolicy.computeCashPayout heldUnits command.Dps with
| Error message ->
transaction.Rollback()
StageFail (DividendWriteResult.DividendInvalid message)
| Ok payout ->
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash + @gross WHERE id = @fund_id"
addParameter cashCommand "gross" NpgsqlDbType.Numeric (box payout.GrossCash) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
if cashCommand.ExecuteNonQuery() = 0 then
transaction.Rollback()
StageFail DividendWriteResult.DividendFundNotFound
else
let recordId = Guid.NewGuid()
let record: DividendRecord =
{
Id = recordId
FundId = fundId
InstrumentCode = command.InstrumentCode
NavDate = command.NavDate
Dps = command.Dps
Mode = command.Mode
Status = (if command.Mode = DividendPolicy.Cash then "cash_credited" else "pending_nav")
IsSynthetic = isSynthetic
GrossCash = Some payout.GrossCash
CreditedUnits = None
CreditedInvested = None
OrderId = None
PendingReason = None
CreatedAt = DateTimeOffset.UtcNow
}
let createdAt = insertDividendRecord connection (Some transaction) record
insertDividendIdempotency connection (Some transaction) schemeKey fingerprint recordId fundId
transaction.Commit()
StageBooked { record with CreatedAt = createdAt }
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
// Confirmation of the reinvestment order settles the dividend record: the
// credited units/invested cash are persisted and the row is marked succeeded.
let finalizeDividend (record: DividendRecord) (confirmed: SubscriptionOrderRecord) =
let units = confirmed.ConfirmedUnits |> Option.defaultValue 0m
let invested = confirmed.ConfirmedInvestedCash |> Option.defaultValue 0m
do
use finalizeConnection = new NpgsqlConnection(connectionString)
finalizeConnection.Open()
use finalizeTransaction = finalizeConnection.BeginTransaction(IsolationLevel.ReadCommitted)
use finalizeCommand =
commandWithTransaction
finalizeConnection
(Some finalizeTransaction)
"""
UPDATE dividend_records
SET status = 'succeeded',
credited_units = @units,
credited_invested = @invested,
pending_reason = NULL
WHERE id = @record_id
"""
addParameter finalizeCommand "units" NpgsqlDbType.Numeric (box units) |> ignore
addParameter finalizeCommand "invested" NpgsqlDbType.Numeric (box invested) |> ignore
addParameter finalizeCommand "record_id" NpgsqlDbType.Uuid (box record.Id) |> ignore
finalizeCommand.ExecuteNonQuery() |> ignore
finalizeTransaction.Commit()
{ record with Status = "succeeded"; CreditedUnits = Some units; CreditedInvested = Some invested }
// Phase 2: replays never re-book; pending reinvestments retry their confirmation
match claimedStage with
| StageReplay recordId ->
let record =
match findDividendRecord connection None recordId with
| Some record -> record
| None -> failwith "idempotency scheme references a missing dividend"
match record.Status, record.OrderId with
| "pending_nav", Some orderId ->
let confirmKey = sprintf "dividend-confirm:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))
match this.ConfirmSubscriptionOrder(confirmKey, fundId, orderId) with
| SubscriptionConfirmResult.OrderConfirmed confirmed
| SubscriptionConfirmResult.ConfirmReplayed confirmed ->
DividendCredited(finalizeDividend record confirmed)
| SubscriptionConfirmResult.ConfirmPendingNav _ ->
DividendReplayed record
| other ->
failwithf "unexpected dividend confirm replay result: %A" other
| _ ->
DividendReplayed record
| StageFail failure -> failure
| StageBooked record ->
if record.Mode = DividendPolicy.Cash then
DividendCredited record
else
let orderKey = sprintf "dividend:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))
let confirmKey = sprintf "dividend-confirm:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))
match
this.CreateSubscriptionOrder(
orderKey,
fundId,
{ FundCode = command.InstrumentCode; Amount = record.GrossCash |> Option.defaultValue 0m; FeeAmount = 0m },
command.NavDate
)
with
| SubscriptionOrderWriteResult.OrderCreated order
| SubscriptionOrderWriteResult.OrderReplayed order ->
do
use bindConnection = new NpgsqlConnection(connectionString)
bindConnection.Open()
use bindTransaction = bindConnection.BeginTransaction(IsolationLevel.ReadCommitted)
use bindCommand =
commandWithTransaction
bindConnection
(Some bindTransaction)
"UPDATE dividend_records SET order_id = @order_id WHERE id = @record_id"
addParameter bindCommand "order_id" NpgsqlDbType.Uuid (box order.Id) |> ignore
addParameter bindCommand "record_id" NpgsqlDbType.Uuid (box record.Id) |> ignore
bindCommand.ExecuteNonQuery() |> ignore
bindTransaction.Commit()
let recordWithOrder = { record with OrderId = Some order.Id }
match this.ConfirmSubscriptionOrder(confirmKey, fundId, order.Id) with
| SubscriptionConfirmResult.OrderConfirmed confirmed
| SubscriptionConfirmResult.ConfirmReplayed confirmed ->
DividendCredited(finalizeDividend recordWithOrder confirmed)
| SubscriptionConfirmResult.ConfirmPendingNav pending ->
DividendPendingReinvest { recordWithOrder with PendingReason = pending.PendingReason }
| other ->
failwithf "unexpected dividend confirm result: %A" other
| other ->
failwithf "unexpected dividend order result: %A" other
member _.GetDividendRecords(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic,
gross_cash, credited_units, credited_invested, order_id, pending_reason, created_at
FROM dividend_records WHERE fund_id = @fund_id ORDER BY created_at DESC, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<DividendRecord>()
while reader.Read() do
records.Add(dividendRecordFromReader reader)
records |> Seq.toList
member _.CreateCapitalDeposit(idempotencyKey: string, fundId: Guid, command: CapitalDepositCommand) : CapitalDepositWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
CapitalDepositWriteResult.CapitalDepositInvalid "idempotency key cannot be empty"
else
match CapitalPolicy.validateDeposit command.Amount with
| Error message -> CapitalDepositWriteResult.CapitalDepositInvalid message
| Ok() ->
let fingerprint = capitalDepositRequestHash fundId command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findCapitalDepositIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, depositId)
when existingHash = fingerprint && existingFundId = fundId ->
match findCapitalDeposit connection (Some transaction) depositId with
| Some deposit ->
transaction.Commit()
CapitalDepositWriteResult.CapitalDepositReplayed deposit
| None ->
transaction.Rollback()
CapitalDepositWriteResult.CapitalDepositInvalid "idempotency record references a missing deposit"
| Some _ ->
transaction.Rollback()
CapitalDepositWriteResult.CapitalDepositIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
CapitalDepositWriteResult.CapitalDepositFundNotFound
| Some isSynthetic ->
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash + @amount WHERE id = @fund_id"
addParameter cashCommand "amount" NpgsqlDbType.Numeric (box command.Amount) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
if cashCommand.ExecuteNonQuery() = 0 then
transaction.Rollback()
CapitalDepositWriteResult.CapitalDepositFundNotFound
else
let deposit: CapitalDepositRecord =
{
Id = Guid.NewGuid()
FundId = fundId
Amount = command.Amount
Note = command.Note
IsSynthetic = isSynthetic
CreatedAt = DateTimeOffset.UtcNow
}
let createdAt = insertCapitalDeposit connection (Some transaction) deposit
insertCapitalDepositIdempotency connection (Some transaction) idempotencyKey fingerprint deposit.Id fundId
transaction.Commit()
CapitalDepositWriteResult.CapitalDepositCreated { deposit with CreatedAt = createdAt }
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.CreateStockTrade(idempotencyKey: string, fundId: Guid, command: StockTradeCommand, ?executedAtOverride: DateTimeOffset, ?debitAvailableCash: bool) : StockTradeWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
StockTradeWriteResult.StockTradeInvalid "idempotency key cannot be empty"
else
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
if code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
StockTradeWriteResult.StockTradeInvalid "stock code must contain exactly six digits"
elif command.Quantity <= 0m then
StockTradeWriteResult.StockTradeInvalid "quantity must be positive"
elif command.Price <= 0m then
StockTradeWriteResult.StockTradeInvalid "price must be positive"
else
let normalized = { command with InstrumentCode = code }
let fingerprint = stockTradeRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findStockTradeIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, tradeId)
when existingHash = fingerprint && existingFundId = fundId ->
match findStockTrade connection (Some transaction) tradeId with
| Some trade ->
transaction.Commit()
StockTradeWriteResult.StockTradeReplayed trade
| None ->
transaction.Rollback()
StockTradeWriteResult.StockTradeInvalid "idempotency record references a missing trade"
| Some _ ->
transaction.Rollback()
StockTradeWriteResult.StockTradeIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
StockTradeWriteResult.StockTradeFundNotFound
| Some isSynthetic ->
let executedAt = defaultArg executedAtOverride DateTimeOffset.UtcNow
let costCash = Decimal.Round(normalized.Quantity * normalized.Price, 2, MidpointRounding.AwayFromZero)
let debited =
if defaultArg debitAvailableCash false then
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash - @cost WHERE id = @fund_id AND available_cash >= @cost"
addParameter cashCommand "cost" NpgsqlDbType.Numeric (box costCash) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
cashCommand.ExecuteNonQuery() = 1
else
true
if not debited then
transaction.Rollback()
StockTradeWriteResult.StockTradeInsufficientFunds(
sprintf
"available cash is not enough for a stock purchase of %s"
(costCash.ToString("0.00", CultureInfo.InvariantCulture))
)
else
let trade: StockTradeRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = normalized.InstrumentCode
StockName = normalized.StockName
Quantity = normalized.Quantity
Price = normalized.Price
CostCash = costCash
IsSynthetic = isSynthetic
ExecutedAt = executedAt
}
insertStockTrade connection (Some transaction) trade
insertStockTradeIdempotency connection (Some transaction) idempotencyKey fingerprint trade.Id fundId
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO stock_positions
(fund_id, instrument_code, stock_name, quantity, cost_cash, last_traded_at)
VALUES (@fund_id, @code, @name, @quantity, @cost_cash, @last_traded_at)
ON CONFLICT (fund_id, instrument_code) DO UPDATE
SET quantity = stock_positions.quantity + EXCLUDED.quantity,
cost_cash = stock_positions.cost_cash + EXCLUDED.cost_cash,
stock_name = COALESCE(EXCLUDED.stock_name, stock_positions.stock_name),
last_traded_at = EXCLUDED.last_traded_at
"""
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
let nameParameter =
match normalized.StockName with
| Some name -> box name
| None -> box DBNull.Value
addParameter positionCommand "name" NpgsqlDbType.Text nameParameter |> ignore
addParameter positionCommand "quantity" NpgsqlDbType.Numeric (box normalized.Quantity) |> ignore
addParameter positionCommand "cost_cash" NpgsqlDbType.Numeric (box costCash) |> ignore
addParameter positionCommand "last_traded_at" NpgsqlDbType.TimestampTz (box executedAt) |> ignore
positionCommand.ExecuteNonQuery() |> ignore
let buyEvent =
stockCashflowEvent
fundId
normalized.InstrumentCode
normalized.StockName
"buy"
(DateOnly.FromDateTime executedAt.UtcDateTime)
normalized.Quantity
costCash
None
isSynthetic
insertStockCashflow connection (Some transaction) buyEvent
let persisted = { trade with ExecutedAt = executedAt }
transaction.Commit()
StockTradeWriteResult.StockTradeCreated persisted
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetStockTrades(fundId: Guid) : StockTradeRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT id, fund_id, instrument_code, stock_name, quantity, price, cost_cash, is_synthetic, executed_at
FROM stock_trades
WHERE fund_id = @fund_id
ORDER BY executed_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<StockTradeRecord>()
while reader.Read() do
records.Add(stockTradeRecordFromReader reader)
records |> Seq.toList
member _.GetStockPositions(fundId: Guid) : StockPositionRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT instrument_code, stock_name, quantity, cost_cash, last_traded_at
FROM stock_positions
WHERE fund_id = @fund_id
ORDER BY instrument_code
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<StockPositionRecord>()
while reader.Read() do
records.Add(
{
FundId = fundId
InstrumentCode = reader.GetString(0)
StockName = if reader.IsDBNull(1) then None else Some(reader.GetString(1))
Quantity = reader.GetDecimal(2)
CostCash = reader.GetDecimal(3)
LastTradedAt = reader.GetFieldValue<DateTimeOffset>(4)
}
)
records |> Seq.toList
member _.GetStockSells(fundId: Guid) : StockSellRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT id, fund_id, instrument_code, stock_name, quantity, price, fee_amount, proceeds, is_synthetic, executed_at
FROM stock_sells
WHERE fund_id = @fund_id
ORDER BY executed_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<StockSellRecord>()
while reader.Read() do
records.Add(stockSellRecordFromReader reader)
records |> Seq.toList
member _.RecordStockCashflow(idempotencyKey: string, fundId: Guid, command: StockCashflowCommand) : StockCashflowWriteResult =
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
let eventType = if isNull command.EventType then "" else command.EventType.Trim().ToLowerInvariant()
if String.IsNullOrWhiteSpace idempotencyKey then
StockCashflowWriteResult.StockCashflowInvalid "idempotency key cannot be empty"
elif code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
StockCashflowWriteResult.StockCashflowInvalid "stock code must contain exactly six digits"
elif eventType <> "buy" && eventType <> "sell" && eventType <> "dividend" then
StockCashflowWriteResult.StockCashflowInvalid "event type must be buy, sell or dividend"
elif command.Quantity < 0m then
StockCashflowWriteResult.StockCashflowInvalid "quantity cannot be negative"
elif command.Amount < 0m then
StockCashflowWriteResult.StockCashflowInvalid "amount cannot be negative"
else
let normalized = { command with InstrumentCode = code; EventType = eventType }
let fingerprint = stockCashflowRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findStockCashflowIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, eventId)
when existingHash = fingerprint && existingFundId = fundId ->
match findStockCashflow connection (Some transaction) eventId with
| Some record ->
transaction.Commit()
StockCashflowWriteResult.StockCashflowReplayed record
| None ->
transaction.Rollback()
StockCashflowWriteResult.StockCashflowInvalid "idempotency record references a missing event"
| Some _ ->
transaction.Rollback()
StockCashflowWriteResult.StockCashflowIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
StockCashflowWriteResult.StockCashflowFundNotFound
| Some isSynthetic ->
let record =
stockCashflowEvent
fundId
normalized.InstrumentCode
normalized.StockName
normalized.EventType
normalized.EventDate
normalized.Quantity
normalized.Amount
normalized.Note
isSynthetic
insertStockCashflow connection (Some transaction) record
insertStockCashflowIdempotency connection (Some transaction) idempotencyKey fingerprint record.Id fundId
transaction.Commit()
StockCashflowWriteResult.StockCashflowCreated record
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetStockCashflows(fundId: Guid) : StockCashflowRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
$"""
SELECT {stockCashflowColumns}
FROM stock_cashflow_events
WHERE fund_id = @fund_id
ORDER BY event_date, created_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<StockCashflowRecord>()
while reader.Read() do
records.Add(stockCashflowRecordFromReader reader)
records |> Seq.toList
member _.CreateStockSell(idempotencyKey: string, fundId: Guid, command: StockSellCommand, ?executedAtOverride: DateTimeOffset) : StockSellWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
StockSellWriteResult.StockSellInvalid "idempotency key cannot be empty"
else
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
if code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
StockSellWriteResult.StockSellInvalid "stock code must contain exactly six digits"
elif command.Quantity <= 0m then
StockSellWriteResult.StockSellInvalid "quantity must be positive"
elif command.Price <= 0m then
StockSellWriteResult.StockSellInvalid "price must be positive"
elif command.FeeAmount < 0m then
StockSellWriteResult.StockSellInvalid "fee amount cannot be negative"
elif Decimal.Round(command.FeeAmount, 2) <> command.FeeAmount then
StockSellWriteResult.StockSellInvalid "fee amount exceeds cash precision"
else
let normalized = { command with InstrumentCode = code }
let gross = Decimal.Round(normalized.Quantity * normalized.Price, 2, MidpointRounding.AwayFromZero)
if normalized.FeeAmount > gross then
StockSellWriteResult.StockSellInvalid "fee amount cannot exceed the sale proceeds"
else
let fingerprint = stockSellRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findStockSellIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, sellId)
when existingHash = fingerprint && existingFundId = fundId ->
match findStockSell connection (Some transaction) sellId with
| Some sell ->
transaction.Commit()
StockSellWriteResult.StockSellReplayed sell
| None ->
transaction.Rollback()
StockSellWriteResult.StockSellInvalid "idempotency record references a missing sale"
| Some _ ->
transaction.Rollback()
StockSellWriteResult.StockSellIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
StockSellWriteResult.StockSellFundNotFound
| Some isSynthetic ->
let position =
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT quantity, cost_cash
FROM stock_positions
WHERE fund_id = @fund_id AND instrument_code = @instrument_code
FOR UPDATE
"""
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "instrument_code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
use reader = positionCommand.ExecuteReader()
if reader.Read() then
Some(reader.GetDecimal(0), reader.GetDecimal(1))
else
None
match position with
| None ->
transaction.Rollback()
StockSellWriteResult.StockSellInsufficientHoldings(sprintf "no stock position in %s to sell" normalized.InstrumentCode)
| Some(heldQuantity, _) when heldQuantity < normalized.Quantity ->
transaction.Rollback()
StockSellWriteResult.StockSellInsufficientHoldings(
sprintf
"available holdings %s are not enough for the requested sale quantity %s"
(heldQuantity.ToString("G29", CultureInfo.InvariantCulture))
(normalized.Quantity.ToString("G29", CultureInfo.InvariantCulture))
)
| Some(heldQuantity, heldCost) ->
let executedAt = defaultArg executedAtOverride DateTimeOffset.UtcNow
let proceeds = gross - normalized.FeeAmount
let remainingQuantity = heldQuantity - normalized.Quantity
let releasedCost =
if remainingQuantity <= 0m then
heldCost
else
Decimal.Round(heldCost * (normalized.Quantity / heldQuantity), 2, MidpointRounding.AwayFromZero)
if remainingQuantity <= 0m then
use deleteCommand =
commandWithTransaction
connection
(Some transaction)
"DELETE FROM stock_positions WHERE fund_id = @fund_id AND instrument_code = @instrument_code"
addParameter deleteCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter deleteCommand "instrument_code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
deleteCommand.ExecuteNonQuery() |> ignore
else
use updateCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE stock_positions
SET quantity = @quantity,
cost_cash = @cost_cash,
last_traded_at = @last_traded_at
WHERE fund_id = @fund_id AND instrument_code = @instrument_code
"""
addParameter updateCommand "quantity" NpgsqlDbType.Numeric (box remainingQuantity) |> ignore
addParameter updateCommand "cost_cash" NpgsqlDbType.Numeric (box (max 0m (heldCost - releasedCost))) |> ignore
addParameter updateCommand "last_traded_at" NpgsqlDbType.TimestampTz (box executedAt) |> ignore
addParameter updateCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter updateCommand "instrument_code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
updateCommand.ExecuteNonQuery() |> ignore
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash + @proceeds WHERE id = @fund_id"
addParameter cashCommand "proceeds" NpgsqlDbType.Numeric (box proceeds) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
cashCommand.ExecuteNonQuery() |> ignore
let sell: StockSellRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = normalized.InstrumentCode
StockName = normalized.StockName
Quantity = normalized.Quantity
Price = normalized.Price
FeeAmount = normalized.FeeAmount
Proceeds = proceeds
IsSynthetic = isSynthetic
ExecutedAt = executedAt
}
insertStockSell connection (Some transaction) sell
insertStockSellIdempotency connection (Some transaction) idempotencyKey fingerprint sell.Id fundId
let sellEvent =
stockCashflowEvent
fundId
normalized.InstrumentCode
normalized.StockName
"sell"
(DateOnly.FromDateTime executedAt.UtcDateTime)
normalized.Quantity
proceeds
None
isSynthetic
insertStockCashflow connection (Some transaction) sellEvent
transaction.Commit()
StockSellWriteResult.StockSellCreated sell
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.CreateBondTrade(idempotencyKey: string, fundId: Guid, command: BondTradeCommand, ?executedAtOverride: DateTimeOffset) : BondTradeWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
BondTradeWriteResult.BondTradeInvalid "idempotency key cannot be empty"
else
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
if code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
BondTradeWriteResult.BondTradeInvalid "bond code must contain exactly six digits"
elif command.Quantity <= 0m then
BondTradeWriteResult.BondTradeInvalid "quantity must be positive"
elif command.Price <= 0m then
BondTradeWriteResult.BondTradeInvalid "price must be positive"
elif command.CleanPrice <= 0m then
BondTradeWriteResult.BondTradeInvalid "clean price must be positive"
elif command.ParValue <= 0m then
BondTradeWriteResult.BondTradeInvalid "par value must be positive"
elif command.AccruedInterest < 0m then
BondTradeWriteResult.BondTradeInvalid "accrued interest cannot be negative"
else
let normalized = { command with InstrumentCode = code }
let fingerprint = bondTradeRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findBondTradeIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, tradeId)
when existingHash = fingerprint && existingFundId = fundId ->
match findBondTrade connection (Some transaction) tradeId with
| Some trade ->
transaction.Commit()
BondTradeWriteResult.BondTradeReplayed trade
| None ->
transaction.Rollback()
BondTradeWriteResult.BondTradeInvalid "idempotency record references a missing trade"
| Some _ ->
transaction.Rollback()
BondTradeWriteResult.BondTradeIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
BondTradeWriteResult.BondTradeFundNotFound
| Some isSynthetic ->
let executedAt = defaultArg executedAtOverride DateTimeOffset.UtcNow
let costCash =
Decimal.Round(
normalized.Quantity * normalized.Price * normalized.ParValue / 100m,
2,
MidpointRounding.AwayFromZero
)
let trade: BondTradeRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = normalized.InstrumentCode
BondName = normalized.BondName
Quantity = normalized.Quantity
Price = normalized.Price
CleanPrice = normalized.CleanPrice
AccruedInterest = normalized.AccruedInterest
ParValue = normalized.ParValue
SettlementDate = normalized.SettlementDate
CouponRate = normalized.CouponRate
ValueDate = normalized.ValueDate
MaturityDate = normalized.MaturityDate
TradeDate = normalized.TradeDate |> Option.defaultValue normalized.SettlementDate
CostCash = costCash
IsSynthetic = isSynthetic
ExecutedAt = executedAt
}
insertBondTrade connection (Some transaction) trade
insertBondTradeIdempotency connection (Some transaction) idempotencyKey fingerprint trade.Id fundId
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO bond_positions
(fund_id, instrument_code, bond_name, quantity, cost_cash, last_traded_at)
VALUES (@fund_id, @code, @name, @quantity, @cost_cash, @last_traded_at)
ON CONFLICT (fund_id, instrument_code) DO UPDATE
SET quantity = bond_positions.quantity + EXCLUDED.quantity,
cost_cash = bond_positions.cost_cash + EXCLUDED.cost_cash,
bond_name = COALESCE(EXCLUDED.bond_name, bond_positions.bond_name),
last_traded_at = EXCLUDED.last_traded_at
"""
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
let nameParameter =
match normalized.BondName with
| Some name -> box name
| None -> box DBNull.Value
addParameter positionCommand "name" NpgsqlDbType.Text nameParameter |> ignore
addParameter positionCommand "quantity" NpgsqlDbType.Numeric (box normalized.Quantity) |> ignore
addParameter positionCommand "cost_cash" NpgsqlDbType.Numeric (box costCash) |> ignore
addParameter positionCommand "last_traded_at" NpgsqlDbType.TimestampTz (box executedAt) |> ignore
positionCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
BondTradeWriteResult.BondTradeCreated trade
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetBondTrades(fundId: Guid) : BondTradeRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
$"""
SELECT {bondTradeColumns}
FROM bond_trades
WHERE fund_id = @fund_id
ORDER BY executed_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<BondTradeRecord>()
while reader.Read() do
records.Add(bondTradeRecordFromReader reader)
records |> Seq.toList
member _.RecordBondCashflow(idempotencyKey: string, fundId: Guid, command: BondCashflowCommand) : BondCashflowWriteResult =
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
let eventType = if isNull command.EventType then "" else command.EventType.Trim().ToLowerInvariant()
if String.IsNullOrWhiteSpace idempotencyKey then
BondCashflowWriteResult.BondCashflowInvalid "idempotency key cannot be empty"
elif code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
BondCashflowWriteResult.BondCashflowInvalid "bond code must contain exactly six digits"
elif eventType <> "coupon" && eventType <> "maturity" && eventType <> "redemption" then
BondCashflowWriteResult.BondCashflowInvalid "event type must be coupon, maturity or redemption"
elif command.Quantity <= 0m then
BondCashflowWriteResult.BondCashflowInvalid "quantity must be positive"
elif command.Amount < 0m then
BondCashflowWriteResult.BondCashflowInvalid "amount cannot be negative"
else
let normalized = { command with InstrumentCode = code; EventType = eventType }
let fingerprint = bondCashflowRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findBondCashflowIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, eventId)
when existingHash = fingerprint && existingFundId = fundId ->
match findBondCashflow connection (Some transaction) eventId with
| Some record ->
transaction.Commit()
BondCashflowWriteResult.BondCashflowReplayed record
| None ->
transaction.Rollback()
BondCashflowWriteResult.BondCashflowInvalid "idempotency record references a missing event"
| Some _ ->
transaction.Rollback()
BondCashflowWriteResult.BondCashflowIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
BondCashflowWriteResult.BondCashflowFundNotFound
| Some isSynthetic ->
let hasPosition =
use positionQuery =
commandWithTransaction
connection
(Some transaction)
"SELECT 1 FROM bond_positions WHERE fund_id = @fund_id AND instrument_code = @code"
addParameter positionQuery "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionQuery "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
use reader = positionQuery.ExecuteReader()
reader.Read()
if not hasPosition then
transaction.Rollback()
BondCashflowWriteResult.BondCashflowPositionNotFound
else
let record: BondCashflowRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = normalized.InstrumentCode
BondName = normalized.BondName
EventType = normalized.EventType
EventDate = normalized.EventDate
Quantity = normalized.Quantity
Amount = normalized.Amount
Note = normalized.Note
IsSynthetic = isSynthetic
CreatedAt = DateTimeOffset.UtcNow
}
insertBondCashflow connection (Some transaction) record
insertBondCashflowIdempotency connection (Some transaction) idempotencyKey fingerprint record.Id fundId
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash + @amount WHERE id = @fund_id"
addParameter cashCommand "amount" NpgsqlDbType.Numeric (box normalized.Amount) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
cashCommand.ExecuteNonQuery() |> ignore
if normalized.EventType = "maturity" || normalized.EventType = "redemption" then
use removeCommand =
commandWithTransaction
connection
(Some transaction)
"DELETE FROM bond_positions WHERE fund_id = @fund_id AND instrument_code = @code"
addParameter removeCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter removeCommand "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
removeCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
BondCashflowWriteResult.BondCashflowCreated record
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetBondCashflows(fundId: Guid) : BondCashflowRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
$"""
SELECT {bondCashflowColumns}
FROM bond_cashflow_events
WHERE fund_id = @fund_id
ORDER BY event_date, created_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<BondCashflowRecord>()
while reader.Read() do
records.Add(bondCashflowRecordFromReader reader)
records |> Seq.toList
member _.CreateBondSell(idempotencyKey: string, fundId: Guid, command: BondSellCommand, ?executedAtOverride: DateTimeOffset) : BondSellWriteResult =
let code = if isNull command.InstrumentCode then "" else command.InstrumentCode.Trim()
if String.IsNullOrWhiteSpace idempotencyKey then
BondSellWriteResult.BondSellInvalid "idempotency key cannot be empty"
elif code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
BondSellWriteResult.BondSellInvalid "bond code must contain exactly six digits"
elif command.Quantity <= 0m then
BondSellWriteResult.BondSellInvalid "quantity must be positive"
elif command.Price <= 0m then
BondSellWriteResult.BondSellInvalid "price must be positive"
elif command.CleanPrice <= 0m then
BondSellWriteResult.BondSellInvalid "clean price must be positive"
elif command.ParValue <= 0m then
BondSellWriteResult.BondSellInvalid "par value must be positive"
elif command.AccruedInterest < 0m then
BondSellWriteResult.BondSellInvalid "accrued interest cannot be negative"
elif command.FeeAmount < 0m then
BondSellWriteResult.BondSellInvalid "fee cannot be negative"
else
let normalized = { command with InstrumentCode = code }
let fingerprint = bondSellRequestHash fundId normalized
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findBondSellIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, sellId)
when existingHash = fingerprint && existingFundId = fundId ->
match findBondSell connection (Some transaction) sellId with
| Some record ->
transaction.Commit()
BondSellWriteResult.BondSellReplayed record
| None ->
transaction.Rollback()
BondSellWriteResult.BondSellInvalid "idempotency record references a missing sell"
| Some _ ->
transaction.Rollback()
BondSellWriteResult.BondSellIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
BondSellWriteResult.BondSellFundNotFound
| Some isSynthetic ->
let position =
use positionQuery =
commandWithTransaction
connection
(Some transaction)
"SELECT quantity, cost_cash FROM bond_positions WHERE fund_id = @fund_id AND instrument_code = @code FOR UPDATE"
addParameter positionQuery "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionQuery "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
use reader = positionQuery.ExecuteReader()
if reader.Read() then Some(reader.GetDecimal(0), reader.GetDecimal(1)) else None
match position with
| None ->
transaction.Rollback()
BondSellWriteResult.BondSellInsufficientHoldings "fund does not hold this bond"
| Some(positionQuantity, positionCost) ->
if normalized.Quantity > positionQuantity then
transaction.Rollback()
BondSellWriteResult.BondSellInsufficientHoldings(
sprintf "cannot sell %O 张: only %O held" normalized.Quantity positionQuantity
)
else
let executedAt = defaultArg executedAtOverride DateTimeOffset.UtcNow
let gross =
Decimal.Round(
normalized.Quantity * normalized.Price * normalized.ParValue / 100m,
2,
MidpointRounding.AwayFromZero
)
let proceeds = Decimal.Round(gross - normalized.FeeAmount, 2, MidpointRounding.AwayFromZero)
if proceeds < 0m then
transaction.Rollback()
BondSellWriteResult.BondSellInvalid "fee exceeds gross proceeds"
else
let costReleased =
if normalized.Quantity = positionQuantity then
positionCost
else
Decimal.Round(
positionCost * normalized.Quantity / positionQuantity,
2,
MidpointRounding.AwayFromZero
)
let realizedPnl = Decimal.Round(proceeds - costReleased, 2, MidpointRounding.AwayFromZero)
let record: BondSellRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = normalized.InstrumentCode
BondName = normalized.BondName
Quantity = normalized.Quantity
Price = normalized.Price
CleanPrice = normalized.CleanPrice
AccruedInterest = normalized.AccruedInterest
ParValue = normalized.ParValue
SettlementDate = normalized.SettlementDate
TradeDate = normalized.TradeDate |> Option.defaultValue normalized.SettlementDate
FeeAmount = normalized.FeeAmount
Proceeds = proceeds
CostReleased = costReleased
RealizedPnl = realizedPnl
IsSynthetic = isSynthetic
ExecutedAt = executedAt
}
insertBondSell connection (Some transaction) record
insertBondSellIdempotency connection (Some transaction) idempotencyKey fingerprint record.Id fundId
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"UPDATE funds SET available_cash = available_cash + @proceeds WHERE id = @fund_id"
addParameter cashCommand "proceeds" NpgsqlDbType.Numeric (box proceeds) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
cashCommand.ExecuteNonQuery() |> ignore
if normalized.Quantity = positionQuantity then
use removeCommand =
commandWithTransaction
connection
(Some transaction)
"DELETE FROM bond_positions WHERE fund_id = @fund_id AND instrument_code = @code"
addParameter removeCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter removeCommand "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
removeCommand.ExecuteNonQuery() |> ignore
else
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE bond_positions
SET quantity = quantity - @quantity,
cost_cash = cost_cash - @cost_released,
last_traded_at = @last_traded_at
WHERE fund_id = @fund_id AND instrument_code = @code
"""
addParameter positionCommand "quantity" NpgsqlDbType.Numeric (box normalized.Quantity) |> ignore
addParameter positionCommand "cost_released" NpgsqlDbType.Numeric (box costReleased) |> ignore
addParameter positionCommand "last_traded_at" NpgsqlDbType.TimestampTz (box executedAt) |> ignore
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box normalized.InstrumentCode) |> ignore
positionCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
BondSellWriteResult.BondSellCreated record
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetBondSells(fundId: Guid) : BondSellRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
$"""
SELECT {bondSellColumns}
FROM bond_sells
WHERE fund_id = @fund_id
ORDER BY executed_at, id
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<BondSellRecord>()
while reader.Read() do
records.Add(bondSellRecordFromReader reader)
records |> Seq.toList
member _.GetBondPositions(fundId: Guid) : BondPositionRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT instrument_code, bond_name, quantity, cost_cash, last_traded_at
FROM bond_positions
WHERE fund_id = @fund_id
ORDER BY instrument_code
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<BondPositionRecord>()
while reader.Read() do
records.Add(
{
FundId = fundId
InstrumentCode = reader.GetString(0)
BondName = if reader.IsDBNull(1) then None else Some(reader.GetString(1))
Quantity = reader.GetDecimal(2)
CostCash = reader.GetDecimal(3)
LastTradedAt = reader.GetFieldValue<DateTimeOffset>(4)
}
)
records |> Seq.toList
member _.GetCapitalDeposits(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"SELECT id, fund_id, amount, note, is_synthetic, created_at FROM fund_capital_deposits WHERE fund_id = @fund_id ORDER BY created_at DESC, id"
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<CapitalDepositRecord>()
while reader.Read() do
records.Add(capitalDepositRecordFromReader reader)
records |> Seq.toList
member _.CreateRedemptionOrder(idempotencyKey: string, fundId: Guid, command: RedemptionCommand) : RedemptionWriteResult =
if String.IsNullOrWhiteSpace idempotencyKey then
RedemptionWriteResult.RedemptionInvalid "idempotency key cannot be empty"
else
match validateRedemptionCommand command with
| Error message -> RedemptionWriteResult.RedemptionInvalid message
| Ok() ->
let fingerprint = redemptionRequestHash fundId command
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findRedemptionOrderIdempotency connection (Some transaction) idempotencyKey with
| Some(existingHash, existingFundId, orderId)
when existingHash = fingerprint && existingFundId = fundId ->
match findRedemptionOrder connection (Some transaction) orderId with
| Some order ->
transaction.Commit()
RedemptionReplayed order
| None ->
transaction.Rollback()
RedemptionWriteResult.RedemptionInvalid "idempotency record references a missing order"
| Some _ ->
transaction.Rollback()
RedemptionIdempotencyConflict
| None ->
match lockFundForOrder connection (Some transaction) fundId with
| None ->
transaction.Rollback()
RedemptionFundNotFound
| Some isSynthetic ->
if instrumentExists connection (Some transaction) command.InstrumentCode then
use freezeCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE fund_positions
SET reserved_units = reserved_units + @units
WHERE fund_id = @fund_id
AND instrument_code = @code
AND units - reserved_units >= @units
"""
addParameter freezeCommand "units" NpgsqlDbType.Numeric (box command.Units) |> ignore
addParameter freezeCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter freezeCommand "code" NpgsqlDbType.Text (box command.InstrumentCode) |> ignore
if freezeCommand.ExecuteNonQuery() = 0 then
transaction.Rollback()
RedemptionInsufficientUnits
else
let submittedAt = DateTimeOffset.UtcNow
let order: RedemptionOrderRecord =
{
Id = Guid.NewGuid()
FundId = fundId
InstrumentCode = command.InstrumentCode
Units = command.Units
FeeAmount = command.FeeAmount
Status = "submitted"
IsSynthetic = isSynthetic
SubmittedAt = submittedAt
TradeDate = ConfirmationPolicy.tradeDateFor submittedAt
ConfirmIdempotencyKey = None
PendingReason = None
ConfirmedAt = None
ConfirmedNav = None
ConfirmedNavDate = None
ConfirmedProceeds = None
ConfirmedCostReleased = None
}
let submittedAt = insertRedemptionOrder connection (Some transaction) order
insertRedemptionOrderIdempotency connection (Some transaction) idempotencyKey fingerprint order.Id fundId
transaction.Commit()
RedemptionCreated { order with SubmittedAt = submittedAt }
else
transaction.Rollback()
RedemptionInstrumentNotFound
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetRedemptionOrders(fundId: Guid) =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction connection None (redemptionOrderColumns + " WHERE fund_id = @fund_id ORDER BY submitted_at DESC, id")
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<RedemptionOrderRecord>()
while reader.Read() do
records.Add(redemptionRecordFromReader reader)
records |> Seq.toList
member _.ConfirmRedemptionOrder(idempotencyKey: string, fundId: Guid, orderId: Guid) : RedemptionConfirmResult =
if String.IsNullOrWhiteSpace idempotencyKey then
RedemptionConfirmResult.RedemptionInvalid "idempotency key cannot be empty"
else
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
let confirmedAt = DateTimeOffset.UtcNow
let today = ConfirmationPolicy.shanghaiDate confirmedAt
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "confirm-redemption:%O" orderId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findRedemptionOrder connection (Some transaction) orderId with
| None ->
transaction.Rollback()
RedemptionOrderNotFound
| Some order when order.FundId <> fundId ->
transaction.Rollback()
RedemptionOrderNotFound
| Some order ->
if order.Status = "confirmed" then
match order.ConfirmIdempotencyKey with
| Some storedKey when storedKey = idempotencyKey ->
transaction.Commit()
RedemptionConfirmReplayed order
| _ ->
match findRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey with
| Some(_, _, storedOrderId) when storedOrderId = orderId ->
transaction.Commit()
RedemptionConfirmReplayed order
| Some _ ->
transaction.Rollback()
RedemptionConfirmIdempotencyConflict
| None ->
transaction.Rollback()
RedemptionAlreadyConfirmed
elif order.Status <> "submitted" && order.Status <> "pending_nav" then
transaction.Rollback()
RedemptionInvalidStatus
else
match findRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey with
| Some _ ->
transaction.Rollback()
RedemptionConfirmIdempotencyConflict
| None ->
let tradeDate = order.TradeDate
let tradeDateText = tradeDate.ToString("yyyy-MM-dd")
use quoteCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT o.nav, o.nav_date, o.source, o.source_revision, o.source_collected_at, o.published_at,
o.source_payload_hash, o.first_seen_at, e.first_seen_at
FROM fund_nav_observations o
LEFT JOIN fund_nav_observation_evidence e
ON e.instrument_code = o.instrument_code
AND e.nav_date = o.nav_date
AND e.source_payload_hash = o.source_payload_hash
WHERE o.instrument_code = @code AND o.nav_date = @trade_date AND o.nav > 0
ORDER BY o.source_collected_at DESC, o.published_at DESC NULLS LAST, o.source_revision DESC
LIMIT 1
"""
addParameter quoteCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
addParameter quoteCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
use quoteReader = quoteCommand.ExecuteReader()
let quoteFound = quoteReader.Read()
let selectedQuote =
if quoteFound then
let evidenceFirstSeen =
if quoteReader.IsDBNull(8) then
None
else
Some(quoteReader.GetFieldValue<DateTimeOffset>(8))
Some
({
Nav = quoteReader.GetDecimal(0)
NavDate = quoteReader.GetFieldValue<DateOnly>(1)
Source = quoteReader.GetString(2)
Revision = quoteReader.GetString(3)
CollectedAt = quoteReader.GetFieldValue<DateTimeOffset>(4)
PublishedAt =
if quoteReader.IsDBNull(5) then
None
else
Some(quoteReader.GetFieldValue<DateTimeOffset>(5))
PayloadHash = quoteReader.GetString(6)
FirstSeenAt = quoteReader.GetFieldValue<DateTimeOffset>(7)
},
evidenceFirstSeen)
else
None
quoteReader.Close()
let boundQuote =
match selectedQuote with
| Some(quote, Some firstSeen) -> Some { quote with FirstSeenAt = firstSeen }
| _ -> None
let deferralReason =
match selectedQuote with
| None ->
Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
| Some(_, evidenceFirstSeen) when evidenceFirstSeen.IsNone ->
Some(sprintf "nav revision for trade date %s has no observation evidence recorded" tradeDateText)
| Some(quote, _) when quote.FirstSeenAt > confirmedAt ->
Some(sprintf "nav revision for trade date %s was first observed after the confirmation attempt" tradeDateText)
| Some(quote, _) ->
ConfirmationPolicy.navDeferralReason
{
Nav = quote.Nav
NavDate = quote.NavDate
CollectedAt = quote.CollectedAt
PublishedAt = quote.PublishedAt
}
tradeDate
today
confirmedAt
match deferralReason with
| Some reason ->
use pendingCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE redemption_orders
SET status = 'pending_nav',
pending_reason = @reason,
confirm_idempotency_key = NULL,
confirmed_at = NULL,
confirmed_nav = NULL,
confirmed_nav_date = NULL,
confirmed_proceeds = NULL,
confirmed_cost_released = NULL
WHERE id = @order_id
"""
addParameter pendingCommand "reason" NpgsqlDbType.Text (box reason) |> ignore
addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
pendingCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
match findRedemptionOrder connection None orderId with
| Some pendingOrder -> RedemptionPendingNav pendingOrder
| None -> failwith "pending redemption disappeared after confirmation deferral"
| None ->
let nav = boundQuote |> Option.get |> fun quote -> quote.Nav
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT units, reserved_units, cost_cash
FROM fund_positions
WHERE fund_id = @fund_id AND instrument_code = @code
FOR UPDATE
"""
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
use positionReader = positionCommand.ExecuteReader()
let positionFound = positionReader.Read()
let positionUnits = if positionFound then positionReader.GetDecimal(0) else 0m
let positionReserved = if positionFound then positionReader.GetDecimal(1) else 0m
let positionCost = if positionFound then positionReader.GetDecimal(2) else 0m
positionReader.Close()
if not positionFound || positionReserved < order.Units then
failwith "frozen units are missing for redemption confirmation"
match RedemptionPolicy.compute order.Units nav order.FeeAmount positionCost positionUnits with
| Error message ->
use pendingCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE redemption_orders
SET status = 'pending_nav',
pending_reason = @reason
WHERE id = @order_id
"""
addParameter pendingCommand "reason" NpgsqlDbType.Text (box message) |> ignore
addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
pendingCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
match findRedemptionOrder connection None orderId with
| Some pendingOrder -> RedemptionPendingNav pendingOrder
| None -> failwith "pending redemption disappeared after computation failure"
| Ok computation ->
use settlePositionCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE fund_positions
SET units = units - @units,
reserved_units = reserved_units - @units,
cost_cash = cost_cash - @cost_released
WHERE fund_id = @fund_id
AND instrument_code = @code
AND units > @units
AND reserved_units >= @units
AND cost_cash >= @cost_released
"""
addParameter settlePositionCommand "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
addParameter settlePositionCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
addParameter settlePositionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter settlePositionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
if settlePositionCommand.ExecuteNonQuery() = 0 then
use deletePositionCommand =
commandWithTransaction
connection
(Some transaction)
"""
DELETE FROM fund_positions
WHERE fund_id = @fund_id
AND instrument_code = @code
AND units = @units
AND reserved_units >= @units
AND cost_cash >= @cost_released
"""
addParameter deletePositionCommand "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
addParameter deletePositionCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
addParameter deletePositionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter deletePositionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
if deletePositionCommand.ExecuteNonQuery() = 0 then
failwith "position units changed during redemption confirmation"
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE funds
SET available_cash = available_cash + @proceeds
WHERE id = @fund_id
"""
addParameter cashCommand "proceeds" NpgsqlDbType.Numeric (box computation.Proceeds) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
if cashCommand.ExecuteNonQuery() = 0 then
failwith "fund disappeared during redemption confirmation"
use confirmCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE redemption_orders
SET status = 'confirmed',
pending_reason = NULL,
confirm_idempotency_key = @idempotency_key,
confirmed_at = @confirmed_at,
confirmed_nav = @nav,
confirmed_nav_date = @nav_date,
confirmed_proceeds = @proceeds,
confirmed_cost_released = @cost_released
WHERE id = @order_id
"""
addParameter confirmCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
addParameter confirmCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
addParameter confirmCommand "nav" NpgsqlDbType.Numeric (box nav) |> ignore
addParameter confirmCommand "nav_date" NpgsqlDbType.Date (box tradeDate) |> ignore
addParameter confirmCommand "proceeds" NpgsqlDbType.Numeric (box computation.Proceeds) |> ignore
addParameter confirmCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
addParameter confirmCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
confirmCommand.ExecuteNonQuery() |> ignore
insertRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey "" orderId fundId
transaction.Commit()
match findRedemptionOrder connection None orderId with
| Some confirmedOrder -> RedemptionConfirmed confirmedOrder
| None -> failwith "confirmed redemption disappeared after commit"
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.ConfirmSubscriptionOrder(idempotencyKey: string, fundId: Guid, orderId: Guid) =
if String.IsNullOrWhiteSpace idempotencyKey then
ConfirmInvalid "idempotency key cannot be empty"
else
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
try
let confirmedAt = DateTimeOffset.UtcNow
let today = ConfirmationPolicy.shanghaiDate confirmedAt
let requestHash =
Convert
.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sprintf "confirm:%O:%O" fundId orderId)))
.ToLowerInvariant()
use lockCommand =
commandWithTransaction
connection
(Some transaction)
"SELECT pg_advisory_xact_lock(hashtext(@lock_key))"
addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "confirm-order:%O" orderId)) |> ignore
lockCommand.ExecuteNonQuery() |> ignore
match findOrder connection (Some transaction) orderId with
| None ->
transaction.Rollback()
ConfirmOrderNotFound
| Some order when order.FundId <> fundId ->
transaction.Rollback()
ConfirmOrderNotFound
| Some order ->
if order.Status = "confirmed" then
match order.ConfirmIdempotencyKey with
| Some storedKey when storedKey = idempotencyKey ->
transaction.Commit()
ConfirmReplayed order
| _ ->
match findConfirmIdempotency connection (Some transaction) idempotencyKey with
| Some(_, _, storedOrderId) when storedOrderId = orderId ->
transaction.Commit()
ConfirmReplayed order
| Some _ ->
transaction.Rollback()
ConfirmIdempotencyConflict
| None ->
transaction.Rollback()
ConfirmAlreadyConfirmed
elif order.Status <> "submitted" && order.Status <> "pending_nav" then
transaction.Rollback()
ConfirmInvalidStatus
else
match findConfirmIdempotency connection (Some transaction) idempotencyKey with
| Some _ ->
transaction.Rollback()
ConfirmIdempotencyConflict
| None ->
let tradeDate = order.TradeDate
let tradeDateText = tradeDate.ToString("yyyy-MM-dd")
use quoteCommand =
commandWithTransaction
connection
(Some transaction)
"""
SELECT o.nav, o.nav_date, o.source, o.source_revision, o.source_collected_at, o.published_at,
o.source_payload_hash, o.first_seen_at, e.first_seen_at
FROM fund_nav_observations o
LEFT JOIN fund_nav_observation_evidence e
ON e.instrument_code = o.instrument_code
AND e.nav_date = o.nav_date
AND e.source_payload_hash = o.source_payload_hash
WHERE o.instrument_code = @code AND o.nav_date = @trade_date AND o.nav > 0
ORDER BY o.source_collected_at DESC, o.published_at DESC NULLS LAST, o.source_revision DESC
LIMIT 1
"""
addParameter quoteCommand "code" NpgsqlDbType.Text (box order.FundCode) |> ignore
addParameter quoteCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
use quoteReader = quoteCommand.ExecuteReader()
let quoteFound = quoteReader.Read()
let selectedQuote, evidenceFirstSeen =
if quoteFound then
let evidenceFirstSeen =
if quoteReader.IsDBNull(8) then
None
else
Some(quoteReader.GetFieldValue<DateTimeOffset>(8))
Some
{
Nav = quoteReader.GetDecimal(0)
NavDate = quoteReader.GetFieldValue<DateOnly>(1)
Source = quoteReader.GetString(2)
Revision = quoteReader.GetString(3)
CollectedAt = quoteReader.GetFieldValue<DateTimeOffset>(4)
PublishedAt =
if quoteReader.IsDBNull(5) then
None
else
Some(quoteReader.GetFieldValue<DateTimeOffset>(5))
PayloadHash = quoteReader.GetString(6)
FirstSeenAt = quoteReader.GetFieldValue<DateTimeOffset>(7)
},
evidenceFirstSeen
else
None, None
quoteReader.Close()
let boundQuote =
match selectedQuote, evidenceFirstSeen with
| Some quote, Some firstSeen -> Some { quote with FirstSeenAt = firstSeen }
| _ -> None
let deferralReason =
if selectedQuote.IsSome && evidenceFirstSeen.IsNone then
Some(
sprintf
"nav revision for trade date %s has no observation evidence recorded"
tradeDateText
)
else
match boundQuote with
| None -> Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
| Some quote when quote.FirstSeenAt > confirmedAt ->
Some(
sprintf
"nav revision for trade date %s was first observed after the confirmation attempt"
tradeDateText
)
| Some quote ->
ConfirmationPolicy.navDeferralReason
{
Nav = quote.Nav
NavDate = quote.NavDate
CollectedAt = quote.CollectedAt
PublishedAt = quote.PublishedAt
}
tradeDate
today
confirmedAt
let markPending reason =
use pendingCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE subscription_orders
SET status = 'pending_nav',
pending_reason = @reason,
confirm_idempotency_key = NULL,
confirmed_at = NULL,
confirmed_nav = NULL,
confirmed_nav_date = NULL,
confirmed_nav_source = NULL,
confirmed_nav_revision = NULL,
confirmed_nav_collected_at = NULL,
confirmed_nav_published_at = NULL,
confirmed_nav_payload_hash = NULL,
confirmed_nav_first_seen_at = NULL,
confirmed_units = NULL,
confirmed_invested_cash = NULL,
confirmed_residual_cash = NULL
WHERE id = @order_id
"""
addParameter pendingCommand "reason" NpgsqlDbType.Text (box reason) |> ignore
addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
pendingCommand.ExecuteNonQuery() |> ignore
let readPendingAfterCommit () =
match findOrder connection None orderId with
| Some pendingOrder -> ConfirmPendingNav pendingOrder
| None -> failwith "pending order disappeared after confirmation deferral"
match deferralReason with
| Some reason ->
markPending reason
transaction.Commit()
readPendingAfterCommit ()
| None ->
let quote = boundQuote |> Option.get
let source = quote.Source
let revision = quote.Revision
match ConfirmationPolicy.compute order.Amount quote.Nav with
| Error message ->
markPending message
transaction.Commit()
readPendingAfterCommit ()
| Ok computation ->
use cashCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE funds
SET available_cash = available_cash + @residual,
reserved_cash = reserved_cash - @reserved_total
WHERE id = @fund_id AND reserved_cash >= @reserved_total
"""
addParameter cashCommand "residual" NpgsqlDbType.Numeric (box computation.ResidualCash) |> ignore
addParameter cashCommand "reserved_total" NpgsqlDbType.Numeric (box order.ReservedTotal) |> ignore
addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
if cashCommand.ExecuteNonQuery() = 0 then
failwith "insufficient reserved cash for order confirmation"
let publishedParameter =
match quote.PublishedAt with
| Some published -> box published
| None -> box DBNull.Value
use confirmCommand =
commandWithTransaction
connection
(Some transaction)
"""
UPDATE subscription_orders
SET status = 'confirmed',
pending_reason = NULL,
confirm_idempotency_key = @idempotency_key,
confirmed_at = @confirmed_at,
confirmed_nav = @nav,
confirmed_nav_date = @nav_date,
confirmed_nav_source = @source,
confirmed_nav_revision = @revision,
confirmed_nav_collected_at = @collected_at,
confirmed_nav_published_at = @published_at,
confirmed_nav_payload_hash = @payload_hash,
confirmed_nav_first_seen_at = @first_seen_at,
confirmed_units = @units,
confirmed_invested_cash = @invested,
confirmed_residual_cash = @residual
WHERE id = @order_id
"""
addParameter confirmCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
addParameter confirmCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
addParameter confirmCommand "nav" NpgsqlDbType.Numeric (box quote.Nav) |> ignore
addParameter confirmCommand "nav_date" NpgsqlDbType.Date (box quote.NavDate) |> ignore
addParameter confirmCommand "source" NpgsqlDbType.Text (box source) |> ignore
addParameter confirmCommand "revision" NpgsqlDbType.Text (box revision) |> ignore
addParameter confirmCommand "collected_at" NpgsqlDbType.TimestampTz (box quote.CollectedAt) |> ignore
addParameter confirmCommand "published_at" NpgsqlDbType.TimestampTz publishedParameter |> ignore
addParameter confirmCommand "payload_hash" NpgsqlDbType.Text (box quote.PayloadHash) |> ignore
addParameter confirmCommand "first_seen_at" NpgsqlDbType.TimestampTz (box quote.FirstSeenAt) |> ignore
addParameter confirmCommand "units" NpgsqlDbType.Numeric (box computation.Units) |> ignore
addParameter confirmCommand "invested" NpgsqlDbType.Numeric (box computation.InvestedCash) |> ignore
addParameter confirmCommand "residual" NpgsqlDbType.Numeric (box computation.ResidualCash) |> ignore
addParameter confirmCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
confirmCommand.ExecuteNonQuery() |> ignore
use positionCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO fund_positions
(fund_id, instrument_code, units, cost_cash, first_confirmed_at, last_confirmed_at)
VALUES
(@fund_id, @code, @units, @invested, @confirmed_at, @confirmed_at)
ON CONFLICT (fund_id, instrument_code) DO UPDATE
SET units = fund_positions.units + EXCLUDED.units,
cost_cash = fund_positions.cost_cash + EXCLUDED.cost_cash,
last_confirmed_at = EXCLUDED.last_confirmed_at
"""
addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
addParameter positionCommand "code" NpgsqlDbType.Text (box order.FundCode) |> ignore
addParameter positionCommand "units" NpgsqlDbType.Numeric (box computation.Units) |> ignore
addParameter positionCommand "invested" NpgsqlDbType.Numeric (box computation.InvestedCash) |> ignore
addParameter positionCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
positionCommand.ExecuteNonQuery() |> ignore
let publishedJson =
match quote.PublishedAt with
| Some published -> sprintf "\"%O\"" published
| None -> "null"
let detail =
sprintf
"{\"fund_id\":\"%O\",\"order_id\":\"%O\",\"units\":\"%M\",\"invested_cash\":\"%M\",\"residual_cash\":\"%M\",\"quote\":{\"nav_date\":\"%s\",\"nav\":\"%M\",\"source\":%s,\"source_revision\":%s,\"source_collected_at\":\"%O\",\"published_at\":%s,\"source_payload_hash\":%s,\"first_seen_at\":\"%O\"}}"
fundId
orderId
computation.Units
computation.InvestedCash
computation.ResidualCash
(quote.NavDate.ToString("yyyy-MM-dd"))
quote.Nav
(JsonSerializer.Serialize source)
(JsonSerializer.Serialize revision)
quote.CollectedAt
publishedJson
(JsonSerializer.Serialize quote.PayloadHash)
quote.FirstSeenAt
use eventCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO subscription_order_events (order_id, event_type, detail)
VALUES (@order_id, 'confirmed', @detail)
"""
addParameter eventCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
addParameter eventCommand "detail" NpgsqlDbType.Jsonb (box detail) |> ignore
eventCommand.ExecuteNonQuery() |> ignore
use idempotencyCommand =
commandWithTransaction
connection
(Some transaction)
"""
INSERT INTO subscription_confirm_idempotencies
(idempotency_key, request_hash, order_id, fund_id)
VALUES
(@idempotency_key, @request_hash, @order_id, @fund_id)
"""
addParameter idempotencyCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
addParameter idempotencyCommand "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
addParameter idempotencyCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
addParameter idempotencyCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
idempotencyCommand.ExecuteNonQuery() |> ignore
transaction.Commit()
match findOrder connection None orderId with
| Some confirmedOrder -> OrderConfirmed confirmedOrder
| None -> failwith "confirmed order disappeared after commit"
with error ->
try
transaction.Rollback()
with _ ->
()
raise error
member _.GetFundPositions(fundId: Guid) : FundPositionRecord list =
use connection = new NpgsqlConnection(connectionString)
connection.Open()
use command =
commandWithTransaction
connection
None
"""
SELECT p.instrument_code, p.units, p.reserved_units, p.cost_cash, p.last_confirmed_at,
q.nav, q.nav_date, q.source_collected_at
FROM fund_positions p
LEFT JOIN LATERAL (
SELECT nav, nav_date, source_collected_at
FROM fund_nav_observations
WHERE instrument_code = p.instrument_code
AND nav_date <= (now() AT TIME ZONE 'Asia/Shanghai')::date
AND nav > 0
AND source_collected_at <= now()
AND (published_at IS NULL OR published_at <= now())
ORDER BY nav_date DESC, source_collected_at DESC
LIMIT 1
) q ON true
WHERE p.fund_id = @fund_id
ORDER BY p.instrument_code
"""
addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
use reader = command.ExecuteReader()
let records = ResizeArray<FundPositionRecord>()
while reader.Read() do
let valuationNav =
if reader.IsDBNull(5) then None else Some(reader.GetDecimal(5))
let valuationNavDate =
if reader.IsDBNull(6) then None else Some(reader.GetFieldValue<DateOnly>(6))
let valuationCollectedAt =
if reader.IsDBNull(7) then None else Some(reader.GetFieldValue<DateTimeOffset>(7))
records.Add(
{
FundId = fundId
InstrumentCode = reader.GetString(0)
Units = reader.GetDecimal(1)
ReservedUnits = reader.GetDecimal(2)
CostCash = reader.GetDecimal(3)
LastConfirmedAt = reader.GetFieldValue<DateTimeOffset>(4)
ValuationNav = valuationNav
ValuationNavDate = valuationNavDate
ValuationCollectedAt = valuationCollectedAt
}
)
records |> Seq.toList
/// Reconstructs the fund's asset and unit-NAV history from confirmed ledger
/// events plus persisted NAV observations. Unit NAV is rebuilt by issuing fund
/// units for external capital deposits at the previously known unit NAV, so a
/// deposit never moves the unit NAV. Values that cannot be known at a date stay
/// `None`; nothing is filled with zero.
member this.GetFundReturns(fundId: Guid) : FundReturns option =
match this.GetFund fundId with
| None -> None
| Some fund ->
let today = ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow
let deposits = this.GetCapitalDeposits fundId
let orders = this.GetSubscriptionOrders fundId
let redemptions = this.GetRedemptionOrders fundId
let dividends = this.GetDividendRecords fundId
let heldCodes =
[ yield! orders |> List.map (fun order -> order.FundCode)
yield! redemptions |> List.map (fun order -> order.InstrumentCode) ]
|> List.distinct
let navByCode =
heldCodes
|> List.map (fun code -> code, this.GetNav(code, None, Some today))
|> Map.ofList
let firstHoldingDate (code: string) =
orders
|> List.filter (fun order -> order.FundCode = code && order.Status = "confirmed")
|> List.map (fun order -> order.TradeDate)
|> List.sort
|> List.tryHead
let navDates =
heldCodes
|> List.collect (fun code ->
match firstHoldingDate code with
| None -> []
| Some startDate ->
navByCode.[code]
|> List.filter (fun observation ->
observation.NavDate >= startDate && observation.NavDate <= today)
|> List.map (fun observation -> observation.NavDate))
|> Set.ofList
let creationDate = ConfirmationPolicy.eventDateFor fund.CreatedAt
let dividendCredited =
dividends
|> List.filter (fun record -> record.Status = "cash_credited" || record.Status = "succeeded")
let hasActivity =
not (List.isEmpty deposits)
|| not (List.isEmpty orders)
|| not (List.isEmpty redemptions)
|| not (List.isEmpty dividendCredited)
|| not (Set.isEmpty navDates)
if not hasActivity then
Some
{
FundId = fundId
Pending = false
DataUpdatedAt = None
Points = []
}
else
let eventDates =
[ yield creationDate
yield! deposits |> List.map (fun deposit -> ConfirmationPolicy.eventDateFor deposit.CreatedAt)
yield! orders |> List.map (fun order -> order.TradeDate)
yield! redemptions |> List.map (fun order -> order.TradeDate)
yield! dividendCredited |> List.map (fun record -> record.NavDate) ]
|> Set.ofList
let dates =
Set.union eventDates navDates
|> Set.toList
|> List.sort
let dataUpdatedAt =
navByCode
|> Map.toList
|> List.collect snd
|> List.map (fun observation -> observation.LastSeenAt)
|> List.sortDescending
|> List.tryHead
let latestNavOnOrBefore (code: string) (date: DateOnly) =
match Map.tryFind code navByCode with
| None -> None
| Some observations ->
observations
|> List.filter (fun observation -> observation.NavDate <= date && observation.Nav > 0m)
|> List.sortByDescending (fun observation -> observation.NavDate, observation.SourceCollectedAt)
|> List.tryHead
let mutable availableCash = fund.InitialCash
let mutable reservedCash = 0m
let mutable fundUnits = if fund.InitialUnitNav > 0m then fund.InitialCash / fund.InitialUnitNav else 0m
let mutable lastKnownNav = if fund.InitialUnitNav > 0m then Some fund.InitialUnitNav else None
let positions = System.Collections.Generic.Dictionary<string, decimal>()
let mutable cumulativeDeposits = 0m
let points = ResizeArray<FundReturnsPoint>()
for date in dates do
for deposit in deposits do
if ConfirmationPolicy.eventDateFor deposit.CreatedAt = date then
availableCash <- availableCash + deposit.Amount
cumulativeDeposits <- cumulativeDeposits + deposit.Amount
match lastKnownNav with
| Some nav when nav > 0m -> fundUnits <- fundUnits + deposit.Amount / nav
| _ -> ()
for order in orders do
if order.TradeDate = date then
if order.Status = "confirmed" then
let residual = order.ConfirmedResidualCash |> Option.defaultValue 0m
availableCash <- availableCash + residual - order.ReservedTotal
let units = order.ConfirmedUnits |> Option.defaultValue 0m
let current =
match positions.TryGetValue order.FundCode with
| true, value -> value
| _ -> 0m
positions.[order.FundCode] <- current + units
else
availableCash <- availableCash - order.ReservedTotal
reservedCash <- reservedCash + order.ReservedTotal
for order in redemptions do
if order.TradeDate = date && order.Status = "confirmed" then
let current =
match positions.TryGetValue order.InstrumentCode with
| true, value -> value
| _ -> 0m
positions.[order.InstrumentCode] <- current - order.Units
availableCash <- availableCash + (order.ConfirmedProceeds |> Option.defaultValue 0m)
for record in dividendCredited do
if record.NavDate = date then
availableCash <- availableCash + (record.GrossCash |> Option.defaultValue 0m)
let mutable pending = false
let mutable holdingsValue = 0m
for KeyValue(code, units) in positions do
if units > 0m then
match latestNavOnOrBefore code date with
| Some observation -> holdingsValue <- holdingsValue + units * observation.Nav
| None -> pending <- true
let netExternalFlow = fund.InitialCash + cumulativeDeposits
if pending then
points.Add(
{
Date = date
Pending = true
TotalAssets = None
UnitNav = None
Cash = availableCash
ReservedCash = reservedCash
HoldingsValue = None
CumulativeReturn = None
NetExternalFlow = netExternalFlow
}
)
else
let totalAssets = availableCash + reservedCash + holdingsValue
let unitNav = if fundUnits > 0m then Some(totalAssets / fundUnits) else None
match unitNav with
| Some nav -> lastKnownNav <- Some nav
| None -> ()
points.Add(
{
Date = date
Pending = false
TotalAssets = Some totalAssets
UnitNav = unitNav
Cash = availableCash
ReservedCash = reservedCash
HoldingsValue = Some holdingsValue
CumulativeReturn = Some(totalAssets - netExternalFlow)
NetExternalFlow = netExternalFlow
}
)
Some
{
FundId = fundId
Pending = points |> Seq.exists (fun point -> point.Pending)
DataUpdatedAt = dataUpdatedAt
Points = points |> Seq.toList
}
|