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
|
namespace FundLab.Domain.Tests
module DomainTests =
open System
open Xunit
open FundLab.Domain
let private unwrap result =
match result with
| Ok value -> value
| Error error -> failwithf "%A" error
[<Fact>]
let ``new fund retains initial cash and starts with zero units`` () =
let fund = Fund.create "退休账户" 1000m 1.00000000m
Assert.Equal("退休账户", fund.Name)
Assert.Equal(1000m, fund.NetAssets)
Assert.Equal(0m, fund.OutstandingUnits)
Assert.Equal(FundStatus.Empty, fund.Status)
Assert.Equal(UnitNavStatus.ZeroUnits, Fund.unitNavStatus fund)
[<Fact>]
let ``pending order is not a confirmed holding`` () =
Assert.False(OrderStatus.isConfirmed OrderStatus.PendingNav)
Assert.True(OrderStatus.isConfirmed OrderStatus.Settled)
[<Fact>]
let ``external redemption creates a payable without changing user holdings`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000001")
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000011")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-000000000012")
let at = DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "退休账户" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId redemptionId "redemption-1" 25.00000000m 1.00000000m at true
|> unwrap
let fund = Ledger.getFund fundId state |> unwrap
Assert.Equal(75.00000000m, fund.OutstandingUnits)
Assert.Equal(100.00m, fund.AvailableCash)
Assert.Equal(25.00m, fund.balanceSheet.RedemptionPayable)
Assert.Equal(75.00m, fund.balanceSheet.NetAssets)
[<Fact>]
let ``external redemption payment is idempotent and conflicts are rejected`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000002")
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000021")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-000000000022")
let at = DateTimeOffset(2026, 1, 2, 0, 0, 0, TimeSpan.Zero)
let deposited =
Ledger.empty
|> Ledger.initializeFund fundId "支付测试" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
let redeemed =
deposited
|> Ledger.confirmExternalRedemption fundId redemptionId "redemption-1" 25.00000000m 1.00000000m at true
|> unwrap
let paid =
redeemed
|> Ledger.payExternalRedemption fundId redemptionId "payment-1" at true
|> unwrap
let replayed =
redeemed
|> Ledger.payExternalRedemption fundId redemptionId "payment-1" at true
|> unwrap
let conflict =
paid
|> Ledger.payExternalRedemption fundId redemptionId "payment-1" (at.AddMinutes 1.0) true
let fund = Ledger.getFund fundId paid |> unwrap
Assert.Equal(paid, replayed)
Assert.Equal(Error(IdempotencyConflict "payment-1"), conflict)
Assert.Equal(75.00m, fund.AvailableCash)
Assert.Equal(0.00m, fund.balanceSheet.RedemptionPayable)
Assert.Equal(75.00m, fund.balanceSheet.NetAssets)
[<Fact>]
let ``underlying purchase freezes then confirms cash and holding`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000003")
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000031")
let orderId = Guid.Parse("00000000-0000-0000-0000-000000000032")
let instrumentId = Guid.Parse("00000000-0000-0000-0000-000000000033")
let at = DateTimeOffset(2026, 1, 3, 0, 0, 0, TimeSpan.Zero)
let deposited =
Ledger.empty
|> Ledger.initializeFund fundId "底层申购" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
let frozen =
deposited
|> Ledger.freezeUnderlyingPurchase fundId orderId "purchase-1" instrumentId 60.00m at true
|> unwrap
let frozenFund = Ledger.getFund fundId frozen |> unwrap
Assert.Equal(40.00m, frozenFund.AvailableCash)
Assert.Equal(60.00m, frozenFund.FrozenCash)
Assert.Equal(100.00m, frozenFund.balanceSheet.NetAssets)
let confirmed =
frozen
|> Ledger.confirmUnderlyingPurchase fundId orderId "purchase-confirm-1" 20.00000000m 3.00000000m at true
|> unwrap
let fund = Ledger.getFund fundId confirmed |> unwrap
let holding = fund.Holdings |> Map.find instrumentId
let order = fund.Orders |> Map.find orderId
Assert.Equal(40.00m, fund.AvailableCash)
Assert.Equal(0.00m, fund.FrozenCash)
Assert.Equal(20.00000000m, holding.AvailableUnits)
Assert.Equal(60.00m, holding.SettledValue)
Assert.Equal(OrderStatus.Confirmed, order.Status)
Assert.Equal(100.00m, fund.balanceSheet.NetAssets)
[<Fact>]
let ``cancelled underlying purchase releases its frozen cash`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000004")
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000041")
let orderId = Guid.Parse("00000000-0000-0000-0000-000000000042")
let instrumentId = Guid.Parse("00000000-0000-0000-0000-000000000043")
let at = DateTimeOffset(2026, 1, 4, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "取消申购" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
|> Ledger.freezeUnderlyingPurchase fundId orderId "purchase-1" instrumentId 60.00m at true
|> unwrap
|> Ledger.cancelUnderlyingPurchase fundId orderId "purchase-cancel-1" at true
|> unwrap
let fund = Ledger.getFund fundId state |> unwrap
let order = fund.Orders |> Map.find orderId
Assert.Equal(100.00m, fund.AvailableCash)
Assert.Equal(0.00m, fund.FrozenCash)
Assert.Equal(OrderStatus.Cancelled, order.Status)
Assert.Empty(fund.Holdings)
[<Fact>]
let ``underlying redemption uses a receivable until cash is received`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000005")
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000051")
let purchaseId = Guid.Parse("00000000-0000-0000-0000-000000000052")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-000000000053")
let instrumentId = Guid.Parse("00000000-0000-0000-0000-000000000054")
let at = DateTimeOffset(2026, 1, 5, 0, 0, 0, TimeSpan.Zero)
let purchased =
Ledger.empty
|> Ledger.initializeFund fundId "底层赎回" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
|> Ledger.freezeUnderlyingPurchase fundId purchaseId "purchase-1" instrumentId 60.00m at true
|> unwrap
|> Ledger.confirmUnderlyingPurchase fundId purchaseId "purchase-confirm-1" 20.00000000m 3.00000000m at true
|> unwrap
|> Ledger.freezeUnderlyingRedemption fundId redemptionId "redemption-1" instrumentId 20.00000000m at true
|> unwrap
let confirmed =
purchased
|> Ledger.confirmUnderlyingRedemption fundId redemptionId "redemption-confirm-1" 3.00000000m at true
|> unwrap
let beforeReceipt = Ledger.getFund fundId confirmed |> unwrap
Assert.Equal(40.00m, beforeReceipt.AvailableCash)
Assert.Equal(60.00m, beforeReceipt.balanceSheet.RedemptionReceivable)
Assert.Equal(0.00m, beforeReceipt.balanceSheet.OtherInTransitAssets)
Assert.Equal(100.00m, beforeReceipt.balanceSheet.NetAssets)
Assert.Equal(100.00000000m, beforeReceipt.OutstandingUnits)
let received =
confirmed
|> Ledger.receiveUnderlyingRedemption fundId redemptionId "redemption-receipt-1" at true
|> unwrap
let fund = Ledger.getFund fundId received |> unwrap
let order = fund.Orders |> Map.find redemptionId
Assert.Equal(100.00m, fund.AvailableCash)
Assert.Equal(0.00m, fund.balanceSheet.RedemptionReceivable)
Assert.Equal(0.00m, fund.balanceSheet.OtherInTransitAssets)
Assert.Equal(OrderStatus.Settled, order.Status)
Assert.Equal(100.00m, fund.balanceSheet.NetAssets)
[<Fact>]
let ``operations keep two funds isolated and synthetic provenance explicit`` () =
let fundA = Guid.Parse("00000000-0000-0000-0000-000000000006")
let fundB = Guid.Parse("00000000-0000-0000-0000-000000000007")
let at = DateTimeOffset(2026, 1, 6, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundA "基金A" 0m 1.00000000m true
|> unwrap
|> Ledger.initializeFund fundB "基金B" 25.00m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundA (Guid.NewGuid()) "fund-a-deposit" 100.00m 1.00000000m at true
|> unwrap
let first = Ledger.getFund fundA state |> unwrap
let second = Ledger.getFund fundB state |> unwrap
Assert.Equal(100.00m, first.AvailableCash)
Assert.Equal(25.00m, second.AvailableCash)
Assert.True(first.IsSynthetic)
Assert.True(second.IsSynthetic)
Assert.All(first.Events, fun event -> Assert.True(event.IsSynthetic))
Assert.All(first.CashFlows, fun flow -> Assert.True(flow.IsSynthetic))
[<Fact>]
let ``precision and residual ownership are explicit`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000008")
let at = DateTimeOffset(2026, 1, 7, 0, 0, 0, TimeSpan.Zero)
let depositId = Guid.Parse("00000000-0000-0000-0000-000000000081")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-000000000082")
let initialized =
Ledger.empty
|> Ledger.initializeFund fundId "残差基金" 0m 1.00000000m true
|> unwrap
let badPrecision =
initialized
|> Ledger.confirmExternalDeposit fundId depositId "bad-precision" 1.001m 1.00000000m at true
let afterDeposit =
initialized
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 1.00m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId redemptionId "redemption-1" 1.00000000m 1.00500000m at true
|> unwrap
let fund = Ledger.getFund fundId afterDeposit |> unwrap
let blocked =
afterDeposit
|> Ledger.confirmExternalDeposit fundId (Guid.NewGuid()) "deposit-2" 1.00m 1.00000000m at true
let allocated =
afterDeposit
|> Ledger.allocateResidual fundId (Guid.Parse("00000000-0000-0000-0000-000000000083")) "residual-allocation-1" ResidualOwner.FundReserve at true
|> unwrap
|> Ledger.confirmExternalDeposit fundId (Guid.NewGuid()) "deposit-3" 1.00m 1.00000000m at true
|> unwrap
let allocatedFund = Ledger.getFund fundId allocated |> unwrap
Assert.Equal(Error(InvalidPrecision "external deposit cash"), badPrecision)
Assert.Equal(ResidualState.RequiresAllocation 0.00500000m, fund.ResidualState)
Assert.Equal(Error(ResidualOwnershipRequired 0.00500000m), blocked)
Assert.Equal(ResidualState.Allocated(0.00500000m, ResidualOwner.FundReserve), allocatedFund.ResidualState)
Assert.Equal(1, List.length allocatedFund.ResidualAllocations)
let residualEvent = allocatedFund.Events |> List.find (fun (event: LedgerEvent) -> event.EventType = "residual_allocated")
Assert.Equal(Some ResidualOwner.FundReserve, residualEvent.ResidualOwner)
Assert.Equal(2.00m, allocatedFund.AvailableCash)
[<Fact>]
let ``residual allocation requires zero outstanding units`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-00000000000B")
let depositId = Guid.Parse("00000000-0000-0000-0000-0000000000B1")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-0000000000B2")
let allocationId = Guid.Parse("00000000-0000-0000-0000-0000000000B3")
let at = DateTimeOffset(2026, 1, 9, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "残差未清" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 1.00m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId redemptionId "redemption-1" 0.50000000m 1.00500000m at true
|> unwrap
let result =
state
|> Ledger.allocateResidual fundId allocationId "residual-allocation-1" ResidualOwner.FundReserve at true
Assert.Equal(Error(InvalidState "residual allocation requires zero outstanding units"), result)
[<Fact>]
let ``external redemption payment settles only the referenced redemption`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-00000000000C")
let depositId = Guid.Parse("00000000-0000-0000-0000-0000000000C1")
let firstRedemptionId = Guid.Parse("00000000-0000-0000-0000-0000000000C2")
let secondRedemptionId = Guid.Parse("00000000-0000-0000-0000-0000000000C3")
let at = DateTimeOffset(2026, 1, 10, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "逐笔付款" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId firstRedemptionId "redemption-1" 10.00000000m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId secondRedemptionId "redemption-2" 20.00000000m 1.00000000m at true
|> unwrap
|> Ledger.payExternalRedemption fundId firstRedemptionId "payment-1" at true
|> unwrap
let fund = Ledger.getFund fundId state |> unwrap
let first = fund.ExternalRedemptions |> Map.find firstRedemptionId
let second = fund.ExternalRedemptions |> Map.find secondRedemptionId
let unknownPayment =
state
|> Ledger.payExternalRedemption fundId (Guid.Parse("00000000-0000-0000-0000-0000000000CF")) "payment-unknown" at true
Assert.Equal(20.00m, fund.RedemptionPayable)
Assert.Equal(ExternalRedemptionStatus.Paid, first.Status)
Assert.Equal(ExternalRedemptionStatus.PendingPayment, second.Status)
Assert.Equal(Error(ExternalRedemptionNotFound(Guid.Parse("00000000-0000-0000-0000-0000000000CF"))), unknownPayment)
[<Fact>]
let ``empty idempotency keys and identifiers are rejected`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-00000000000D")
let transactionId = Guid.Parse("00000000-0000-0000-0000-0000000000D1")
let at = DateTimeOffset(2026, 1, 11, 0, 0, 0, TimeSpan.Zero)
let initialized =
Ledger.empty
|> Ledger.initializeFund fundId "输入校验" 0m 1.00000000m true
|> unwrap
let emptyKey =
initialized
|> Ledger.confirmExternalDeposit fundId transactionId " " 1.00m 1.00000000m at true
let emptyTransaction =
initialized
|> Ledger.confirmExternalDeposit fundId Guid.Empty "deposit-1" 1.00m 1.00000000m at true
let emptyOrder =
initialized
|> Ledger.freezeUnderlyingPurchase fundId Guid.Empty "purchase-1" (Guid.NewGuid()) 1.00m at true
Assert.Equal(Error(InvalidState "idempotency key cannot be empty"), emptyKey)
Assert.Equal(Error(InvalidIdentifier "transaction id"), emptyTransaction)
Assert.Equal(Error(InvalidIdentifier "order id"), emptyOrder)
[<Fact>]
let ``duplicate transaction identifiers are rejected`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-00000000000E")
let transactionId = Guid.Parse("00000000-0000-0000-0000-0000000000E1")
let at = DateTimeOffset(2026, 1, 12, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "交易唯一" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId transactionId "deposit-1" 1.00m 1.00000000m at true
|> unwrap
let duplicate =
state
|> Ledger.confirmExternalDeposit fundId transactionId "deposit-2" 1.00m 1.00000000m at true
Assert.Equal(Error(TransactionAlreadyExists transactionId), duplicate)
[<Fact>]
let ``time weighted return excludes external additional capital`` () =
let at day = DateTimeOffset(2026, 1, day, 0, 0, 0, TimeSpan.Zero)
let observations =
[
{ At = at 1; NetAssets = 100.00m; ExternalCashFlow = 0.00m }
{ At = at 2; NetAssets = 200.00m; ExternalCashFlow = 100.00m }
]
let result = Performance.timeWeightedReturn observations |> unwrap
Assert.Equal(0.00m, result)
[<Fact>]
let ``invalid fund and reservation operations return typed errors`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-000000000009")
let missingFund = Ledger.getFund fundId Ledger.empty
let initialized =
Ledger.empty
|> Ledger.initializeFund fundId "错误路径" 0m 1.00000000m true
|> unwrap
let duplicate =
initialized
|> Ledger.initializeFund fundId "重复基金" 0m 1.00000000m true
let insufficientCash =
initialized
|> Ledger.freezeUnderlyingPurchase fundId (Guid.NewGuid()) "purchase-1" (Guid.NewGuid()) 1.00m (DateTimeOffset.UtcNow) true
let insufficientUnits =
initialized
|> Ledger.confirmExternalRedemption fundId (Guid.NewGuid()) "redemption-1" 1.00000000m 1.00000000m (DateTimeOffset.UtcNow) true
Assert.Equal(Error(FundNotFound fundId), missingFund)
Assert.Equal(Error(FundAlreadyExists fundId), duplicate)
Assert.Equal(Error(InsufficientCash 1.00m), insufficientCash)
Assert.Equal(Error(InsufficientUnits 1.00000000m), insufficientUnits)
[<Fact>]
let ``performance observations must be chronological`` () =
let at day = DateTimeOffset(2026, 1, day, 0, 0, 0, TimeSpan.Zero)
let observations =
[
{ At = at 2; NetAssets = 100.00m; ExternalCashFlow = 0.00m }
{ At = at 1; NetAssets = 100.00m; ExternalCashFlow = 0.00m }
]
let result = Performance.timeWeightedReturn observations
Assert.Equal(Error(InvalidObservation "observations must be strictly ordered"), result)
[<Fact>]
let ``external redemption payment cannot spend frozen or invested cash`` () =
let fundId = Guid.Parse("00000000-0000-0000-0000-00000000000A")
let depositId = Guid.Parse("00000000-0000-0000-0000-0000000000A1")
let purchaseId = Guid.Parse("00000000-0000-0000-0000-0000000000A2")
let instrumentId = Guid.Parse("00000000-0000-0000-0000-0000000000A3")
let redemptionId = Guid.Parse("00000000-0000-0000-0000-0000000000A4")
let at = DateTimeOffset(2026, 1, 8, 0, 0, 0, TimeSpan.Zero)
let state =
Ledger.empty
|> Ledger.initializeFund fundId "现金不足" 0m 1.00000000m true
|> unwrap
|> Ledger.confirmExternalDeposit fundId depositId "deposit-1" 100.00m 1.00000000m at true
|> unwrap
|> Ledger.freezeUnderlyingPurchase fundId purchaseId "purchase-1" instrumentId 100.00m at true
|> unwrap
|> Ledger.confirmUnderlyingPurchase fundId purchaseId "purchase-confirm-1" 100.00000000m 1.00000000m at true
|> unwrap
|> Ledger.confirmExternalRedemption fundId redemptionId "redemption-1" 50.00000000m 1.00000000m at true
|> unwrap
let payment = state |> Ledger.payExternalRedemption fundId redemptionId "payment-1" at true
Assert.Equal(Error(InsufficientCash 50.00m), payment)
[<Fact>]
let ``time weighted return distinguishes investment growth from withdrawals`` () =
let at day = DateTimeOffset(2026, 1, day, 0, 0, 0, TimeSpan.Zero)
let growth =
[
{ At = at 1; NetAssets = 100.00m; ExternalCashFlow = 0.00m }
{ At = at 2; NetAssets = 110.00m; ExternalCashFlow = 0.00m }
]
|> Performance.timeWeightedReturn
|> unwrap
let withdrawal =
[
{ At = at 1; NetAssets = 100.00m; ExternalCashFlow = 0.00m }
{ At = at 2; NetAssets = 50.00m; ExternalCashFlow = -50.00m }
]
|> Performance.timeWeightedReturn
|> unwrap
Assert.Equal(0.10m, growth)
Assert.Equal(0.00m, withdrawal)
[<Fact>]
let ``single invalid performance observations are rejected`` () =
let at = DateTimeOffset(2026, 1, 13, 0, 0, 0, TimeSpan.Zero)
let negative =
Performance.timeWeightedReturn [ { At = at; NetAssets = -1.00m; ExternalCashFlow = 0.00m } ]
let zero =
Performance.timeWeightedReturn [ { At = at; NetAssets = 0.00m; ExternalCashFlow = 0.00m } ]
Assert.Equal(Error(InvalidObservation "net assets cannot be negative"), negative)
Assert.Equal(Error(InvalidObservation "first net assets must be positive"), zero)
module RedemptionPolicyTests =
open Xunit
open FundLab.Domain
let private unwrap result =
match result with
| Ok value -> value
| Error error -> failwithf "%A" error
[<Fact>]
let ``redemption request above available units is rejected`` () =
Assert.Equal(Error "requested units exceed available holdings", RedemptionPolicy.validateRequest 10.00000000m 10.00000001m 0.00m)
Assert.Equal(Error "redemption units must be positive", RedemptionPolicy.validateRequest 10.00000000m 0m 0.00m)
Assert.Equal(Error "redemption fee cannot be negative", RedemptionPolicy.validateRequest 10.00000000m 5.00000000m -0.01m)
Assert.Equal(Ok(), RedemptionPolicy.validateRequest 10.00000000m 10.00000000m 1.50m)
[<Fact>]
let ``full redemption releases the entire position cost`` () =
let computed = RedemptionPolicy.compute 40.00000000m 2.5m 1.00m 100.00m 40.00000000m |> unwrap
Assert.Equal(100.00m, computed.GrossCash)
Assert.Equal(1.00m, computed.Fee)
Assert.Equal(99.00m, computed.Proceeds)
Assert.Equal(100.00m, computed.RedeemedCost)
[<Fact>]
let ``partial redemption writes off cost pro rata rounded down`` () =
let computed = RedemptionPolicy.compute 10.00000000m 2.5m 0.00m 100.00m 40.00000000m |> unwrap
Assert.Equal(25.00m, computed.GrossCash)
Assert.Equal(0.00m, computed.Fee)
Assert.Equal(25.00m, computed.Proceeds)
Assert.Equal(25.00m, computed.RedeemedCost)
let uneven = RedemptionPolicy.compute 1.00000000m 3m 0.00m 100.00m 3.00000000m |> unwrap
Assert.Equal(3.00m, uneven.GrossCash)
Assert.Equal(33.33m, uneven.RedeemedCost)
[<Fact>]
let ``redemption computation rejects invalid economics`` () =
Assert.Equal(Error "redemption units exceed position units", RedemptionPolicy.compute 41.00000000m 2.5m 0.00m 100.00m 40.00000000m)
Assert.Equal(Error "unit nav must be positive", RedemptionPolicy.compute 1.00000000m 0m 0.00m 100.00m 40.00000000m)
Assert.Equal(Error "redemption fee exceeds redemption value", RedemptionPolicy.compute 1.00000000m 2.5m 3.00m 100.00m 40.00000000m)
Assert.Equal(Error "redemption proceeds rounds to zero", RedemptionPolicy.compute 0.00000001m 1500000m 0.01m 100.00m 40.00000000m)
Assert.Equal(Error "redemption cash rounds to zero", RedemptionPolicy.compute 0.00000001m 2m 0.00m 100.00m 40.00000000m)
module CapitalPolicyTests =
open Xunit
open FundLab.Domain
[<Fact>]
let ``deposit validation rejects non positive or imprecise amounts`` () =
Assert.Equal(Error "deposit amount must be positive", CapitalPolicy.validateDeposit 0m)
Assert.Equal(Error "deposit amount must be positive", CapitalPolicy.validateDeposit -100.00m)
Assert.Equal(Error "deposit amount exceeds cash precision", CapitalPolicy.validateDeposit 100.005m)
Assert.Equal(Ok(), CapitalPolicy.validateDeposit 500.00m)
[<Fact>]
let ``settlement adds to available cash without touching units or nav`` () =
Assert.Equal(Ok 5398.51m, CapitalPolicy.settle 4898.51m 500.00m)
Assert.Equal(Ok 10000.00m, CapitalPolicy.settle 9000.00m 1000.00m)
let overflow = CapitalPolicy.settle CapitalPolicy.cashMaximum 0.01m
Assert.Equal(Error "available cash exceeds database precision", overflow)
module SipPolicyTests =
open System
open Xunit
open FundLab.Domain
let d (year: int) (month: int) (day: int) = DateOnly(year, month, day)
[<Fact>]
let ``sip amount validation rejects non positive or imprecise values`` () =
Assert.Equal(Error "sip amount must be positive", SipPolicy.validateAmount 0m)
Assert.Equal(Error "sip amount must be positive", SipPolicy.validateAmount -200.00m)
Assert.Equal(Error "sip amount exceeds cash precision", SipPolicy.validateAmount 200.005m)
Assert.Equal(Ok(), SipPolicy.validateAmount 200.00m)
[<Fact>]
let ``frequency parsing roundtrips through the canonical text`` () =
Assert.Equal(Some Weekly, SipPolicy.parseFrequency "weekly")
Assert.Equal(Some BiWeekly, SipPolicy.parseFrequency "biweekly")
Assert.Equal(Some Monthly, SipPolicy.parseFrequency "monthly")
Assert.Equal(None, SipPolicy.parseFrequency "daily")
Assert.Equal(None, SipPolicy.parseFrequency null)
for frequency in [ Weekly; BiWeekly; Monthly ] do
Assert.Equal(Some frequency, SipPolicy.parseFrequency (SipPolicy.frequencyText frequency))
[<Fact>]
let ``weekly and biweekly next trade dates step from the anchor`` () =
let anchor = d 2026 9 21
Assert.Equal(d 2026 9 21, SipPolicy.nextTradeDate Weekly anchor (d 2026 9 21))
Assert.Equal(d 2026 9 28, SipPolicy.nextTradeDate Weekly anchor (d 2026 9 22))
Assert.Equal(d 2026 10 5, SipPolicy.nextTradeDate BiWeekly anchor (d 2026 9 28))
[<Fact>]
let ``next trade dates roll off weekends`` () =
let anchor = d 2026 9 21
Assert.Equal(d 2026 9 28, SipPolicy.nextTradeDate Weekly anchor (d 2026 9 26))
Assert.Equal(d 2026 9 28, SipPolicy.nextTradeDate Weekly anchor (d 2026 9 27))
[<Fact>]
let ``monthly next trade date clamps to month end and rolls off weekends`` () =
let anchor = d 2026 1 31
// 2026-01-31 is a Saturday: first run rolls to Monday 02-02
Assert.Equal(d 2026 2 2, SipPolicy.nextTradeDate Monthly anchor anchor)
// February clamps day 31 to 28 (Saturday) and rolls to Monday 03-02
Assert.Equal(d 2026 3 2, SipPolicy.nextTradeDate Monthly anchor (d 2026 2 1))
Assert.Equal(d 2026 3 2, SipPolicy.nextTradeDate Monthly anchor (d 2026 2 28))
Assert.Equal(d 2026 2 5, SipPolicy.nextTradeDate Monthly (d 2026 1 5) (d 2026 1 20))
[<Fact>]
let ``due flag and net amount define the executor contract without side effects`` () =
Assert.True(SipPolicy.isDue (d 2026 9 21) (d 2026 9 21))
Assert.True(SipPolicy.isDue (d 2026 9 21) (d 2026 9 28))
Assert.False(SipPolicy.isDue (d 2026 9 28) (d 2026 9 21))
Assert.Equal(Ok 200.00m, SipPolicy.executionNetAmount 200.00m)
Assert.Equal(Error "sip amount must be positive", SipPolicy.executionNetAmount 0m)
|