rustrade_execution/exchange/mock/account.rs
1use crate::{
2 UnindexedAccountSnapshot,
3 balance::{AssetBalance, Balance, MarginDetails},
4 exchange::mock::orders::{
5 AlreadyResting, OpenOrder, OpenOrders, Reservation, RestingOrder, as_open,
6 },
7 margin::MarginEffect,
8 order::{
9 Order, UnindexedInactiveOrder,
10 id::ClientOrderId,
11 state::{Cancelled, Expired, Filled, InactiveOrderState, Open, OrderState},
12 },
13 trade::Trade,
14};
15use chrono::{DateTime, Utc};
16use fnv::FnvHashMap;
17use rust_decimal::Decimal;
18use rustrade_instrument::{
19 asset::name::AssetNameExchange, exchange::ExchangeId, instrument::name::InstrumentNameExchange,
20};
21use thiserror::Error;
22
23#[derive(Debug)]
24pub struct AccountState {
25 balances: FnvHashMap<AssetNameExchange, AssetBalance<AssetNameExchange>>,
26 orders_open: OpenOrders,
27 orders_cancelled:
28 FnvHashMap<ClientOrderId, Order<ExchangeId, InstrumentNameExchange, Cancelled>>,
29 /// Orders that filled, kept so a cancel arriving after one can say *why* it failed, and so an
30 /// order-state lookup can report how it ended.
31 ///
32 /// Whole orders, like `orders_cancelled`: the fill's total and average price are not
33 /// recoverable from [`trades`](Self::trades) alone, which records each cross separately. Grows
34 /// with the run, like `trades` and `orders_cancelled` — a simulated venue's ledgers are bounded
35 /// by the dataset, not reaped.
36 orders_filled: FnvHashMap<ClientOrderId, Order<ExchangeId, InstrumentNameExchange, Filled>>,
37 /// Orders retired by their own deadline, kept so they reach a later account snapshot and so a
38 /// cancel arriving after one can say *why* it failed.
39 ///
40 /// Whole orders rather than ids alone, unlike [`orders_filled`](Self::orders_filled): nothing
41 /// else records an expiry, so a snapshot has no other source for it — whereas a fill is already
42 /// in [`trades`](Self::trades). Grows with the run, like `trades` and `orders_cancelled`.
43 orders_expired: FnvHashMap<ClientOrderId, Order<ExchangeId, InstrumentNameExchange, Expired>>,
44 trades: Vec<Trade<AssetNameExchange, InstrumentNameExchange>>,
45 /// Whether this is a margin account, which reports every balance's loan, or a cash account,
46 /// which reports none and borrows nothing. Set by [`enable_margin`](Self::enable_margin).
47 margin: bool,
48 /// Counts each time an asset's principal opened from zero or was repaid to zero. Read through
49 /// [`loans_changed`](Self::loans_changed).
50 loans_changed: u64,
51}
52
53impl AccountState {
54 pub fn new(
55 balances: FnvHashMap<AssetNameExchange, AssetBalance<AssetNameExchange>>,
56 orders_open: OpenOrders,
57 orders_cancelled: FnvHashMap<
58 ClientOrderId,
59 Order<ExchangeId, InstrumentNameExchange, Cancelled>,
60 >,
61 trades: Vec<Trade<AssetNameExchange, InstrumentNameExchange>>,
62 ) -> Self {
63 Self {
64 balances,
65 orders_open,
66 orders_cancelled,
67 orders_filled: FnvHashMap::default(),
68 orders_expired: FnvHashMap::default(),
69 trades,
70 margin: false,
71 loans_changed: 0,
72 }
73 }
74
75 /// Makes this a margin account: every balance reports its loan, and an order whose
76 /// [`MarginEffect`] says so borrows what an arrival lacks or repays loans from what it
77 /// receives — see [`SpotMarginConfig`](crate::margin::SpotMarginConfig).
78 ///
79 /// A balance that already reports a loan, as one seeded from a live margin account does, keeps
80 /// it; every other balance starts owing nothing.
81 pub fn enable_margin(&mut self) {
82 self.margin = true;
83 for balance in self.balances.values_mut() {
84 balance
85 .balance
86 .margin
87 .get_or_insert_with(MarginDetails::default);
88 }
89 }
90
91 /// The free balance of `asset`, zero for an asset the account has never held.
92 pub fn free(&self, asset: &AssetNameExchange) -> Decimal {
93 self.balances
94 .get(asset)
95 .map_or(Decimal::ZERO, |balance| balance.balance.free)
96 }
97
98 /// Each asset this account owes principal in, with the principal owed.
99 pub fn loans(&self) -> impl Iterator<Item = (&AssetNameExchange, Decimal)> + '_ {
100 self.balances.iter().filter_map(|(asset, balance)| {
101 let borrowed = balance.balance.margin?.borrowed;
102 (borrowed > Decimal::ZERO).then_some((asset, borrowed))
103 })
104 }
105
106 /// A count that changes whenever the set of assets in [`loans`](Self::loans) may have: each
107 /// time an asset's principal opens from zero or is repaid to zero.
108 ///
109 /// For a caller that caches something derived from that set, such as when interest next falls
110 /// due, and would otherwise recompute it after every operation.
111 pub fn loans_changed(&self) -> u64 {
112 self.loans_changed
113 }
114
115 /// Adds `interest` to the interest `asset`'s loan owes, leaving `total` and `free` as they
116 /// are: interest is owed to the lender, and repaid before principal.
117 ///
118 /// # Panics
119 /// Panics if `asset` has no balance — see [`reserve`](Self::reserve). A loan opens its
120 /// balance, so an asset with a loan to charge always has one.
121 pub fn charge_interest(
122 &mut self,
123 asset: &AssetNameExchange,
124 interest: Decimal,
125 time_exchange: DateTime<Utc>,
126 ) -> AssetBalance<AssetNameExchange> {
127 let balance = self.balance_expect(asset);
128 balance
129 .balance
130 .margin
131 .get_or_insert_with(MarginDetails::default)
132 .interest += interest;
133 balance.time_exchange = time_exchange;
134
135 balance.clone()
136 }
137
138 /// This account's open orders, indexed for lookup and ordered for matching.
139 pub fn orders(&self) -> &OpenOrders {
140 &self.orders_open
141 }
142
143 /// Takes the order resting under `cid` off the book, with whatever is held against it.
144 ///
145 /// The caller records how it ended, with [`ack_cancelled`](Self::ack_cancelled),
146 /// [`ack_filled`](Self::ack_filled) or [`ack_expired`](Self::ack_expired). Booking is only
147 /// through [`book`](Self::book), which keeps an id in at most one place.
148 pub fn remove_order(&mut self, cid: &ClientOrderId) -> Option<RestingOrder> {
149 self.orders_open.remove(cid)
150 }
151
152 /// Puts `order` on the book holding `reservation`, unless an order is already resting under
153 /// its [`ClientOrderId`].
154 ///
155 /// A client order id names one order at a time, not one for good: once an order has ended its
156 /// id may name a new one. So booking forgets how an earlier order under the same id ended,
157 /// which keeps an id in at most one place, the book or one ledger, and a snapshot from listing
158 /// it twice.
159 ///
160 /// # Errors
161 /// [`AlreadyResting`], with `order` and `reservation` handed back and nothing changed, if an
162 /// order is already resting under its id. See [`OpenOrders::insert`].
163 pub fn book(
164 &mut self,
165 order: OpenOrder,
166 reservation: Option<Reservation>,
167 ) -> Result<(), AlreadyResting> {
168 let cid = order.key.cid.clone();
169 self.orders_open.insert(order, reservation)?;
170 self.forget_ended(&cid);
171 Ok(())
172 }
173
174 /// Holds `order` until its venue releases it, with `reservation` held against it, unless an
175 /// order is already resting under its [`ClientOrderId`]. Forgets how an earlier order under
176 /// the id ended, as [`book`](Self::book) does.
177 ///
178 /// # Errors
179 /// [`AlreadyResting`], as for [`book`](Self::book). See [`OpenOrders::hold`].
180 pub fn hold(
181 &mut self,
182 order: OpenOrder,
183 reservation: Option<Reservation>,
184 ) -> Result<(), AlreadyResting> {
185 let cid = order.key.cid.clone();
186 self.orders_open.hold(order, reservation)?;
187 self.forget_ended(&cid);
188 Ok(())
189 }
190
191 /// The orders held on `instrument`, earliest arrival first, no longer held. See
192 /// [`OpenOrders::take_held`].
193 pub fn take_held(&mut self, instrument: &InstrumentNameExchange) -> Vec<ClientOrderId> {
194 self.orders_open.take_held(instrument)
195 }
196
197 /// Drops what the ledgers remember of how an order under `cid` ended, so that the order about
198 /// to be recorded under it is the only one they hold.
199 fn forget_ended(&mut self, cid: &ClientOrderId) {
200 self.orders_cancelled.remove(cid);
201 self.orders_filled.remove(cid);
202 self.orders_expired.remove(cid);
203 }
204
205 /// Records that `order` was cancelled, so it is reported by a later account snapshot and a
206 /// second cancel for it can be told apart from a cancel for an order that never existed.
207 ///
208 /// Replaces whatever the ledgers held for an earlier order under the same id.
209 pub fn ack_cancelled(&mut self, order: Order<ExchangeId, InstrumentNameExchange, Cancelled>) {
210 self.forget_ended(&order.key.cid);
211 self.orders_cancelled.insert(order.key.cid.clone(), order);
212 }
213
214 /// Whether `cid` names an order this account cancelled.
215 pub fn is_cancelled(&self, cid: &ClientOrderId) -> bool {
216 self.orders_cancelled.contains_key(cid)
217 }
218
219 /// Records that `order` filled, so a cancel that loses the race to it can say so and an
220 /// order-state lookup can report it.
221 ///
222 /// Replaces whatever the ledgers held for an earlier order under the same id.
223 pub fn ack_filled(&mut self, order: Order<ExchangeId, InstrumentNameExchange, Filled>) {
224 self.forget_ended(&order.key.cid);
225 self.orders_filled.insert(order.key.cid.clone(), order);
226 }
227
228 /// Whether `cid` names an order this account filled.
229 pub fn is_filled(&self, cid: &ClientOrderId) -> bool {
230 self.orders_filled.contains_key(cid)
231 }
232
233 /// How the order `cid` ended, or `None` if it is still open or this account never held it.
234 ///
235 /// An order a configured `initial_state` reported as cancelled is found too; one it reported
236 /// in any other inactive state is not, because a snapshot seeds only open and cancelled orders.
237 ///
238 /// An id names at most one order at a time, and an id is in at most one place: the book, or
239 /// one of the ledgers an order can end in, holding the latest order under it (see
240 /// [`book`](Self::book)). So the answer is how the latest order under `cid` ended.
241 pub fn order_ended(&self, cid: &ClientOrderId) -> Option<UnindexedInactiveOrder> {
242 if self.orders_open.contains(cid) {
243 None
244 } else if let Some(filled) = self.orders_filled.get(cid) {
245 Some(filled.clone().map_state(InactiveOrderState::FullyFilled))
246 } else if let Some(cancelled) = self.orders_cancelled.get(cid) {
247 Some(cancelled.clone().map_state(InactiveOrderState::Cancelled))
248 } else {
249 self.orders_expired
250 .get(cid)
251 .map(|expired| expired.clone().map_state(InactiveOrderState::Expired))
252 }
253 }
254
255 /// Records that `order` reached its own deadline, so it is reported by a later account snapshot
256 /// and a cancel arriving after it can be told apart from a cancel for an unknown order.
257 ///
258 /// Replaces whatever the ledgers held for an earlier order under the same id.
259 pub fn ack_expired(&mut self, order: Order<ExchangeId, InstrumentNameExchange, Expired>) {
260 self.forget_ended(&order.key.cid);
261 self.orders_expired.insert(order.key.cid.clone(), order);
262 }
263
264 /// Whether `cid` names an order that reached its deadline while this account held it.
265 pub fn is_expired(&self, cid: &ClientOrderId) -> bool {
266 self.orders_expired.contains_key(cid)
267 }
268
269 /// Restates every balance as of `time_exchange`.
270 ///
271 /// # Open orders keep their own stamps
272 /// [`Open::time_exchange`](crate::order::state::Open::time_exchange) is the instant the venue
273 /// accepted the order, and an order does not become a different order because time passed. This
274 /// used to rewrite it on every advance, which was invisible only because nothing rested: the
275 /// venue filled every order on arrival, so `orders_open` held at most what an `initial_state`
276 /// seeded.
277 ///
278 /// It is not invisible once orders rest. Arrival order is half of price-time priority, so
279 /// rewriting it would make a matching engine's tie-break depend on when the clock last moved
280 /// rather than on when each order arrived — and since every order would be rewritten to the
281 /// same instant, there would be no tie-break left at all. It would also make every open order
282 /// look newer than the engine's copy on each advance, which is exactly what the `rustrade`
283 /// engine's `OrderManager` recency guard reads to decide whether an update is stale.
284 pub fn update_time_exchange(&mut self, time_exchange: DateTime<Utc>) {
285 for balance in self.balances.values_mut() {
286 balance.time_exchange = time_exchange;
287 }
288 }
289
290 pub fn balances(&self) -> impl Iterator<Item = &AssetBalance<AssetNameExchange>> + '_ {
291 self.balances.values()
292 }
293
294 /// Every open order, in no particular order — see [`OpenOrders::resting`] for the order a
295 /// venue matches in.
296 pub fn orders_open(
297 &self,
298 ) -> impl Iterator<Item = &Order<ExchangeId, InstrumentNameExchange, Open>> + '_ {
299 self.orders_open.iter()
300 }
301
302 pub fn orders_cancelled(
303 &self,
304 ) -> impl Iterator<Item = &Order<ExchangeId, InstrumentNameExchange, Cancelled>> + '_ {
305 self.orders_cancelled.values()
306 }
307
308 pub fn orders_expired(
309 &self,
310 ) -> impl Iterator<Item = &Order<ExchangeId, InstrumentNameExchange, Expired>> + '_ {
311 self.orders_expired.values()
312 }
313
314 pub fn trades(
315 &self,
316 time_since: DateTime<Utc>,
317 ) -> impl Iterator<Item = &Trade<AssetNameExchange, InstrumentNameExchange>> + '_ {
318 self.trades
319 .iter()
320 .filter(move |trade| trade.time_exchange >= time_since)
321 }
322
323 pub fn balance_mut(
324 &mut self,
325 asset: &AssetNameExchange,
326 ) -> Option<&mut AssetBalance<AssetNameExchange>> {
327 self.balances.get_mut(asset)
328 }
329
330 pub fn ack_trade(&mut self, trade: Trade<AssetNameExchange, InstrumentNameExchange>) {
331 self.trades.push(trade);
332 }
333
334 /// Holds `amount` of `asset` against an order, moving it out of `free`.
335 ///
336 /// `total` is untouched: the asset is still held, it is merely no longer spendable. The held
337 /// portion is `total - free`, which is what [`Balance::used`](crate::balance::Balance::used)
338 /// reports and what a venue restates to its client.
339 ///
340 /// # Errors
341 /// [`BalanceInsufficient`] if `free` does not cover `amount`. The ledger is left untouched, so
342 /// a caller may reject the order and carry on.
343 ///
344 /// # Panics
345 /// Panics if `asset` has no balance. The balances are the venue's own fixture, so an absent one
346 /// is a mis-specified account rather than a runtime condition — see [`SimulatedVenue`]'s
347 /// caller obligations.
348 ///
349 /// [`SimulatedVenue`]: crate::exchange::mock::SimulatedVenue
350 pub fn reserve(
351 &mut self,
352 asset: &AssetNameExchange,
353 amount: Decimal,
354 time_exchange: DateTime<Utc>,
355 ) -> Result<AssetBalance<AssetNameExchange>, BalanceInsufficient> {
356 let balance = self.balance_expect(asset);
357
358 if balance.balance.free < amount {
359 return Err(BalanceInsufficient {
360 asset: asset.clone(),
361 free: balance.balance.free,
362 required: amount,
363 borrowable: None,
364 });
365 }
366
367 balance.balance.free -= amount;
368 balance.time_exchange = time_exchange;
369
370 Ok(balance.clone())
371 }
372
373 /// Settles `amount` of `asset` already held by [`reserve`](Self::reserve) out of the account.
374 ///
375 /// Only `total` moves: `free` was reduced when the amount was reserved. Reserving and then
376 /// settling the same amount therefore lowers both by it, which is what an order that fills on
377 /// arrival does.
378 ///
379 /// # Panics
380 /// Panics if `asset` has no balance — see [`reserve`](Self::reserve). Settling more than is
381 /// held would take `total` below `free` and break the ledger's invariant, so it panics in debug
382 /// builds; callers settle an amount they reserved.
383 pub fn settle(
384 &mut self,
385 asset: &AssetNameExchange,
386 amount: Decimal,
387 time_exchange: DateTime<Utc>,
388 ) -> AssetBalance<AssetNameExchange> {
389 let balance = self.balance_expect(asset);
390
391 debug_assert!(
392 balance.balance.total - amount >= balance.balance.free,
393 "settling {amount} of {asset} would take total {} below free {}: only a reserved \
394 amount may be settled",
395 balance.balance.total,
396 balance.balance.free
397 );
398
399 balance.balance.total -= amount;
400 balance.time_exchange = time_exchange;
401
402 balance.clone()
403 }
404
405 /// Gives `amount` of `asset` back to `free`, undoing a [`reserve`](Self::reserve) that will
406 /// never be settled.
407 ///
408 /// Only `free` moves: nothing left the account, so `total` is unchanged. This is what a
409 /// cancelled, expired or rejected order does to the balance held against it.
410 ///
411 /// # Panics
412 /// Panics if `asset` has no balance — see [`reserve`](Self::reserve). Releasing more than is
413 /// held would take `free` above `total` and break the ledger's invariant, so it panics in debug
414 /// builds; callers release an amount they reserved.
415 pub fn release(
416 &mut self,
417 asset: &AssetNameExchange,
418 amount: Decimal,
419 time_exchange: DateTime<Utc>,
420 ) -> AssetBalance<AssetNameExchange> {
421 let balance = self.balance_expect(asset);
422
423 debug_assert!(
424 balance.balance.free + amount <= balance.balance.total,
425 "releasing {amount} of {asset} would take free {} above total {}: only a reserved \
426 amount may be released",
427 balance.balance.free,
428 balance.balance.total
429 );
430
431 balance.balance.free += amount;
432 balance.time_exchange = time_exchange;
433
434 balance.clone()
435 }
436
437 /// Moves `amount` of `asset` into the account, or out of it when negative, whatever `free`
438 /// holds.
439 ///
440 /// For a charge the account cannot refuse, such as a holding cost: a venue posts carry whether
441 /// or not the account can cover it. `total` and `free` move together, so what is held stays
442 /// held, and a debit larger than `free` takes `free` below zero rather than being refused. The
443 /// caller reports that, since only it knows what the charge was for.
444 ///
445 /// # Panics
446 /// Panics if `asset` has no balance — see [`reserve`](Self::reserve).
447 pub fn charge(
448 &mut self,
449 asset: &AssetNameExchange,
450 amount: Decimal,
451 time_exchange: DateTime<Utc>,
452 ) -> AssetBalance<AssetNameExchange> {
453 let balance = self.balance_expect(asset);
454
455 balance.balance.total += amount;
456 balance.balance.free += amount;
457 balance.time_exchange = time_exchange;
458
459 balance.clone()
460 }
461
462 /// Moves a [`Delivery`] into the account, or out of it when negative, creating the balance at
463 /// zero if the account has never held its asset.
464 ///
465 /// What a fill delivers: the base a spot buy receives, or the proceeds of a spot sell. A
466 /// venue credits the asset an order receives whether or not the account held it before, so
467 /// unlike every debit, an absent balance here is not a mis-specified fixture. `total` and
468 /// `free` move together, as for [`charge`](Self::charge).
469 ///
470 /// **Unchecked**, like [`charge`](Self::charge): a negative delivery larger than `free` takes
471 /// `free` below zero rather than being refused. [`commit`](Self::commit) is the checked path,
472 /// and a fill that can be refused goes through it.
473 ///
474 /// On a margin account, for an order whose `effect` is [`Repay`](MarginEffect::Repay), what is
475 /// delivered into an asset the account owes repays that loan first, interest then principal,
476 /// and only the rest is added to `free`. Under any other effect, or on a cash account, all of
477 /// it is added to `free`.
478 pub fn deliver(
479 &mut self,
480 delivery: &Delivery,
481 effect: MarginEffect,
482 time_exchange: DateTime<Utc>,
483 ) -> AssetBalance<AssetNameExchange> {
484 let repays = self.margin && effect == MarginEffect::Repay;
485 let balance = self.balance_or_open(&delivery.asset, time_exchange);
486
487 balance.balance.total += delivery.amount;
488 balance.balance.free += delivery.amount;
489 let cleared = repays && repay(&mut balance.balance, delivery.amount);
490 balance.time_exchange = time_exchange;
491
492 let balance = balance.clone();
493 self.loans_changed += u64::from(cleared);
494 balance
495 }
496
497 /// Gives `reservation` back to `free`, as [`release`](Self::release) does, then, with
498 /// `auto_repay_at_cancel`, repays the loan its order took when it was placed out of what came
499 /// back, interest first.
500 ///
501 /// What a cancelled, expired or rejected order does to the balance held against it on a margin
502 /// account, which repays an unused loan when the order it was taken for ends. Without
503 /// `auto_repay_at_cancel` the loan stays owed. A reservation that borrowed nothing is simply
504 /// released.
505 ///
506 /// # Panics
507 /// As [`release`](Self::release).
508 pub fn release_reservation(
509 &mut self,
510 reservation: &Reservation,
511 auto_repay_at_cancel: bool,
512 time_exchange: DateTime<Utc>,
513 ) -> AssetBalance<AssetNameExchange> {
514 let released = self.release(&reservation.asset, reservation.amount, time_exchange);
515 match auto_repay_at_cancel && !reservation.borrowed.is_zero() {
516 false => released,
517 true => self.repay_loan(&reservation.asset, reservation.borrowed, time_exchange),
518 }
519 }
520
521 /// Repays up to `amount` of `asset`'s loan out of its free balance, interest first, and never
522 /// more than `free` holds.
523 ///
524 /// # Panics
525 /// Panics if `asset` has no balance — see [`reserve`](Self::reserve).
526 pub fn repay_loan(
527 &mut self,
528 asset: &AssetNameExchange,
529 amount: Decimal,
530 time_exchange: DateTime<Utc>,
531 ) -> AssetBalance<AssetNameExchange> {
532 let balance = self.balance_expect(asset);
533 let available = amount.min(balance.balance.free);
534 let cleared = repay(&mut balance.balance, available);
535 balance.time_exchange = time_exchange;
536
537 let balance = balance.clone();
538 self.loans_changed += u64::from(cleared);
539 balance
540 }
541
542 /// Lends `amount` of `asset`: `total` and `free` rise by it, and so does the loan. An asset the
543 /// account has never held is opened at zero first, as a delivery opens one.
544 fn borrow(&mut self, asset: &AssetNameExchange, amount: Decimal, time_exchange: DateTime<Utc>) {
545 let balance = &mut self.balance_or_open(asset, time_exchange).balance;
546 balance.total += amount;
547 balance.free += amount;
548 let margin = balance.margin.get_or_insert_with(MarginDetails::default);
549 let opened = margin.borrowed.is_zero();
550 margin.borrowed += amount;
551
552 self.loans_changed += u64::from(opened);
553 }
554
555 /// `asset`'s balance, opened at zero if the account has never held it, reporting a loan from
556 /// the start on a margin account.
557 fn balance_or_open(
558 &mut self,
559 asset: &AssetNameExchange,
560 time_exchange: DateTime<Utc>,
561 ) -> &mut AssetBalance<AssetNameExchange> {
562 let margin = self.margin.then(MarginDetails::default);
563 // `SmolStr` clones without allocating for an asset name, so the entry API costs nothing
564 // on the common path where the balance exists.
565 self.balances
566 .entry(asset.clone())
567 .or_insert_with(|| AssetBalance {
568 asset: asset.clone(),
569 balance: Balance {
570 margin,
571 ..Balance::new(Decimal::ZERO, Decimal::ZERO)
572 },
573 time_exchange,
574 })
575 }
576
577 /// Commits one arriving order's whole ledger effect, or none of it.
578 ///
579 /// One order's arrival can both settle a fill and take a hold: a taker that the book could
580 /// only partly fill settles what traded and reserves against the remainder it leaves resting.
581 /// Those are one event at the venue, so they are one operation here — and because every
582 /// requirement is tested before anything moves, an arrival this account cannot afford leaves
583 /// the ledger exactly as it found it.
584 ///
585 /// # Why this is not two calls
586 /// Settling first and reserving second is the same two moves in the order that can fail
587 /// halfway: the settle commits, the reserve is refused, and nothing puts back what `total`
588 /// has already lost — [`release`](Self::release) moves only `free`, and its own assertion
589 /// fires if it is used as a rollback. The venue would then hold a balance its client never
590 /// hears about, silently and for the rest of the run. Asking for the whole requirement up
591 /// front is what makes that state unreachable rather than merely avoided.
592 ///
593 /// # One restatement per asset moved
594 /// A balance is an absolute restatement rather than a delta, and a fill is atomic at the
595 /// venue, so emitting the state between the settle and the hold would report a balance the
596 /// account never held — for the same reason a conservative reservation that had to be released
597 /// and re-debited would. [`Committed`] therefore carries one balance per asset the arrival
598 /// moved: the one it paid with, and the one it received when that is another asset.
599 ///
600 /// # What the fill pays back
601 /// `credit` is what the fill gives the account, and which [`Credit`] it is decides what it
602 /// does:
603 /// - **[`PaidBack`](Credit::PaidBack)**, into the paying asset — the margin and realised PnL
604 /// of the part of a CFD fill that closes a position. It counts towards what `free` must
605 /// cover, because one fill can carry both: a CFD flip, closing a long and opening a short in
606 /// one order, is paid back for the long and posts margin for the short, so the flip is
607 /// funded by the long it closes.
608 /// - **[`Delivery`](Credit::Delivery)**, into another asset — what a spot fill receives: base
609 /// for a buy, the proceeds for a sell, each net of any fee charged in it. It funds nothing,
610 /// since it is not the asset paid with, and it is [delivered](Self::deliver) whether or not
611 /// the account held that asset before. It is negative only for a fill whose fee exceeds
612 /// what it receives, and then that asset's `free` must cover the excess too.
613 ///
614 /// Nothing is credited until every requirement is known to be covered, so a refusal still
615 /// leaves the ledger exactly as it was. `None` is an arrival with nothing to pay back: an
616 /// order that rests having traded nothing.
617 ///
618 /// # What a margin account lends and repays
619 /// On a margin account, for an order whose `effect` is [`Borrow`](MarginEffect::Borrow), a
620 /// requirement `free` and the credit do not cover borrows the shortfall of the paying asset, if
621 /// it is at most `borrowable`, the most the venue will lend of it now. The loan is taken with
622 /// the rest of the arrival, or not at all. [`Committed::borrowed`] says how much was lent. A
623 /// paying asset the account has never held has nothing free, and is opened when the loan is
624 /// taken. A cash account, and an order with another effect, ignore `borrowable`, and a
625 /// negative one lends nothing.
626 ///
627 /// For an order whose `effect` is [`Repay`](MarginEffect::Repay), what the credit delivers
628 /// repays the loan of the asset it is delivered into, as [`deliver`](Self::deliver) does.
629 ///
630 /// # Errors
631 /// [`BalanceInsufficient`], naming the asset short, if `free` plus a credit into the paying
632 /// asset, plus what may be borrowed, does not cover [`settled`](Debit::settled) +
633 /// [`reserved`](Debit::reserved), or if a negative credit into another asset exceeds that
634 /// asset's `free`. The ledger is left untouched.
635 ///
636 /// # Panics
637 /// Panics if the paying asset has no balance and the arrival borrows none of it — see
638 /// [`reserve`](Self::reserve). Debug-asserts that a [`PaidBack`](Credit::PaidBack) credit is
639 /// not negative.
640 pub fn commit(
641 &mut self,
642 debit: &Debit,
643 credit: Option<&Credit>,
644 effect: MarginEffect,
645 borrowable: Decimal,
646 time_exchange: DateTime<Utc>,
647 ) -> Result<Committed, BalanceInsufficient> {
648 let (funding, delivery) = match credit {
649 Some(Credit::PaidBack(amount)) => {
650 debug_assert!(
651 !amount.is_sign_negative(),
652 "a credit of {amount} {} is negative: a loss beyond the margin is debited",
653 debit.asset
654 );
655 (*amount, None)
656 }
657 Some(Credit::Delivery(delivery)) => (Decimal::ZERO, Some(delivery)),
658 None => (Decimal::ZERO, None),
659 };
660
661 // Asked for as one requirement, so a refusal refuses the arrival rather than half of it.
662 // A margin account lends the shortfall, within what the venue allows.
663 // A margin account borrows even an asset it has never held, which it opens on lending.
664 let required = debit.settled + debit.reserved;
665 let lends = self.margin && effect == MarginEffect::Borrow;
666 let free = match self.margin {
667 true => self.free(&debit.asset),
668 false => self.balance_expect(&debit.asset).balance.free,
669 };
670 let shortfall = required - (free + funding);
671 let borrowed = match shortfall > Decimal::ZERO {
672 false => Decimal::ZERO,
673 true if lends && shortfall <= borrowable => shortfall,
674 true => {
675 return Err(BalanceInsufficient {
676 asset: debit.asset.clone(),
677 free: free + funding,
678 required,
679 borrowable: lends.then_some(borrowable.max(Decimal::ZERO)),
680 });
681 }
682 };
683
684 // A delivery that takes rather than gives -- a fill whose fee exceeds what it receives --
685 // must be covered before anything moves too. An asset never held has nothing free.
686 if let Some(delivery) = delivery.filter(|delivery| delivery.amount.is_sign_negative()) {
687 let free = self
688 .balances
689 .get(&delivery.asset)
690 .map_or(Decimal::ZERO, |balance| balance.balance.free);
691 if free + delivery.amount < Decimal::ZERO {
692 return Err(BalanceInsufficient {
693 asset: delivery.asset.clone(),
694 free,
695 required: -delivery.amount,
696 borrowable: None,
697 });
698 }
699 }
700
701 // Applied only now that every requirement is covered, so a refusal moves nothing.
702 if !borrowed.is_zero() {
703 self.borrow(&debit.asset, borrowed, time_exchange);
704 }
705 if !funding.is_zero() {
706 let balance = self.balance_expect(&debit.asset);
707 balance.balance.total += funding;
708 balance.balance.free += funding;
709 }
710
711 // Infallible: `free` now covers the whole requirement. `total` cannot fall below `free`,
712 // which the reserve takes the whole requirement out of, and whatever was reserved and not
713 // settled stays held.
714 self.reserve(&debit.asset, required, time_exchange)?;
715 let paid = self.settle(&debit.asset, debit.settled, time_exchange);
716 let received = delivery.map(|delivery| self.deliver(delivery, effect, time_exchange));
717
718 Ok(Committed {
719 paid,
720 received,
721 borrowed,
722 })
723 }
724
725 #[allow(clippy::expect_used)] // Documented panic: an absent balance is a mis-specified fixture.
726 fn balance_expect(
727 &mut self,
728 asset: &AssetNameExchange,
729 ) -> &mut AssetBalance<AssetNameExchange> {
730 self.balances
731 .get_mut(asset)
732 .expect("SimulatedVenue has Balance for all configured Instrument assets")
733 }
734}
735
736/// Repays up to `available` of `balance`'s loan, interest first, then principal, out of its
737/// `total` and `free`, and returns whether that repaid the last of its principal. Repays nothing
738/// from a `available` that is not positive, or from a balance that owes nothing.
739fn repay(balance: &mut Balance, available: Decimal) -> bool {
740 let Some(margin) = balance.margin.as_mut() else {
741 return false;
742 };
743 let available = available.max(Decimal::ZERO);
744 let interest = margin.interest.min(available);
745 let principal = margin.borrowed.min(available - interest);
746 margin.interest -= interest;
747 margin.borrowed -= principal;
748
749 let repaid = interest + principal;
750 balance.total -= repaid;
751 balance.free -= repaid;
752 principal > Decimal::ZERO && margin.borrowed.is_zero()
753}
754
755/// What one arriving order does to one asset's balance, as a single commitment.
756///
757/// Both fields are denominated in [`asset`](Self::asset) and inclusive of fees. They are one
758/// asset, not two, because they come from one order: which asset an order pays with is decided by
759/// its instrument and its side, and an order has one of each. That is what makes an arrival a
760/// single ledger operation rather than two that must be kept in step.
761///
762/// The three arrivals a [`SimulatedVenue`] can have are the three shapes of this type:
763///
764/// | arrival | `settled` | `reserved` |
765/// |---|---|---|
766/// | fills in full | the fill | zero |
767/// | rests, having traded nothing | zero | the reservation |
768/// | fills in part and rests the remainder | the fill | the remainder's reservation |
769///
770/// [`SimulatedVenue`]: crate::exchange::mock::SimulatedVenue
771#[derive(Debug, Clone, PartialEq, Eq)]
772pub struct Debit {
773 /// Which asset the order pays with: quote for a buy or a CFD, base for a spot sell.
774 pub asset: AssetNameExchange,
775
776 /// Left the account outright, because it traded. Lowers `free` and `total` alike.
777 pub settled: Decimal,
778
779 /// Held against a remainder that is still working. Lowers `free` and leaves `total`, so it is
780 /// still the account's until whatever it is held against settles or is released.
781 pub reserved: Decimal,
782}
783
784/// What one fill gives the account. See [`AccountState::commit`].
785///
786/// Two kinds, because where a credit goes decides what it does: one paid back into the asset the
787/// order paid with funds that order, and one delivered in another asset does not.
788#[derive(Debug, Clone, PartialEq, Eq)]
789pub enum Credit {
790 /// Paid back into the asset the order paid with: the margin and realised PnL of the part of a
791 /// CFD fill that closes a position. Zero for a fill that closes nothing, and never negative,
792 /// since a loss beyond the margin is part of the debit.
793 PaidBack(Decimal),
794 /// Delivered in another asset: what a spot fill receives.
795 Delivery(Delivery),
796}
797
798/// What a spot fill delivers, in the asset it receives.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub struct Delivery {
801 /// The asset received: base for a buy, quote for a sell.
802 pub asset: AssetNameExchange,
803 /// Denominated in [`asset`](Self::asset), net of any fee charged in it. Negative only for a
804 /// fill whose fee exceeds what it receives.
805 pub amount: Decimal,
806}
807
808/// The balances one [`AccountState::commit`] restated, one per asset it moved.
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub struct Committed {
811 /// The asset the order paid with, or held against it.
812 pub paid: AssetBalance<AssetNameExchange>,
813 /// The asset a spot fill delivered, which is never the one paid with. `None` for an arrival
814 /// that moved one asset: a CFD fill, or an order that rests having traded nothing.
815 pub received: Option<AssetBalance<AssetNameExchange>>,
816 /// How much of the paying asset a margin account lent the arrival. Zero when it lent nothing.
817 pub borrowed: Decimal,
818}
819
820/// A ledger operation asked for more of an asset than `free` covers.
821///
822/// Carries the asset and both sides of the comparison so the caller can report them without
823/// re-reading the ledger it has just been refused by.
824#[derive(Debug, Clone, PartialEq, Eq)]
825pub struct BalanceInsufficient {
826 /// The asset short of what was asked for.
827 pub asset: AssetNameExchange,
828 /// Freely-spendable amount at the moment of refusal.
829 pub free: Decimal,
830 /// Amount the operation asked for.
831 pub required: Decimal,
832 /// How much of the asset a margin account would have lent, or `None` when the account lends
833 /// nothing, as a cash account does.
834 pub borrowable: Option<Decimal>,
835}
836
837/// An account snapshot lists one [`ClientOrderId`] more than once among the orders it seeds.
838///
839/// A snapshot seeds open and cancelled orders, and a client order id names one order at a time,
840/// so it can be listed once among them. Two entries under one id would leave the venue to choose
841/// which order it holds, silently.
842#[derive(Debug, Clone, PartialEq, Eq, Error)]
843#[error("account snapshot lists {0} more than once among its open and cancelled orders")]
844pub struct DuplicateSeededOrder(pub ClientOrderId);
845
846/// Seeds an account from a snapshot, as a [`SimulatedVenue`] does from its `initial_state`.
847///
848/// # Errors
849/// [`DuplicateSeededOrder`] if the snapshot lists one [`ClientOrderId`] more than once among its
850/// open and cancelled orders.
851///
852/// [`SimulatedVenue`]: crate::exchange::mock::SimulatedVenue
853impl TryFrom<UnindexedAccountSnapshot> for AccountState {
854 type Error = DuplicateSeededOrder;
855
856 fn try_from(value: UnindexedAccountSnapshot) -> Result<Self, Self::Error> {
857 let UnindexedAccountSnapshot {
858 exchange: _,
859 balances,
860 instruments,
861 } = value;
862
863 let balances = balances
864 .into_iter()
865 .map(|asset_balance| (asset_balance.asset.clone(), asset_balance))
866 .collect();
867
868 let mut orders_open = OpenOrders::default();
869 let mut orders_cancelled = FnvHashMap::default();
870 for order in instruments.into_iter().flat_map(|snapshot| snapshot.orders) {
871 match &order.state {
872 OrderState::Active(_) => {
873 // `as_open` yields `None` for an active order that is not yet open — an
874 // `OpenInFlight`, which has no venue-side existence to record.
875 let Some(open) = as_open(order) else {
876 continue;
877 };
878 let cid = open.key.cid.clone();
879 if orders_cancelled.contains_key(&cid) {
880 return Err(DuplicateSeededOrder(cid));
881 }
882 // Seeded, not booked here: the venue holds nothing against it.
883 orders_open
884 .insert(open, None)
885 .map_err(|_| DuplicateSeededOrder(cid))?;
886 }
887 OrderState::Inactive(InactiveOrderState::Cancelled(cancelled)) => {
888 let cid = order.key.cid.clone();
889 if orders_open.contains(&cid) || orders_cancelled.contains_key(&cid) {
890 return Err(DuplicateSeededOrder(cid));
891 }
892 let cancelled = cancelled.clone();
893 orders_cancelled.insert(
894 cid,
895 Order {
896 key: order.key,
897 side: order.side,
898 price: order.price,
899 quantity: order.quantity,
900 kind: order.kind,
901 time_in_force: order.time_in_force,
902 state: cancelled,
903 },
904 );
905 }
906 // Not seeded: see `order_ended`.
907 OrderState::Inactive(_) => {}
908 }
909 }
910
911 Ok(Self {
912 balances,
913 orders_open,
914 orders_cancelled,
915 orders_filled: FnvHashMap::default(),
916 orders_expired: FnvHashMap::default(),
917 trades: vec![],
918 margin: false,
919 loans_changed: 0,
920 })
921 }
922}
923
924#[cfg(test)]
925#[allow(clippy::unwrap_used)] // Test code: panics are the correct failure mode
926mod tests {
927 use super::*;
928 use crate::{
929 balance::Balance,
930 exchange::mock::fixtures::{funded, seeded_gtd, spot_config_holding},
931 order::{
932 UnindexedOrder,
933 id::OrderId,
934 state::{Cancelled, Filled},
935 },
936 };
937 use rust_decimal_macros::dec;
938
939 fn usd() -> AssetNameExchange {
940 AssetNameExchange::new("usd")
941 }
942
943 fn account_with_usd(amount: Decimal) -> AccountState {
944 AccountState::new(
945 FnvHashMap::from_iter([(usd(), funded(usd(), amount))]),
946 OpenOrders::default(),
947 FnvHashMap::default(),
948 vec![],
949 )
950 }
951
952 fn usd_balance(account: &AccountState) -> Balance {
953 let Some(balance) = account.balances().find(|balance| balance.asset == usd()) else {
954 panic!("the account holds usd");
955 };
956 balance.balance
957 }
958
959 /// A CFD flip: what closing the old position pays back funds the margin the new one posts,
960 /// so a requirement above `free` alone is met, and the remainder's hold stays held.
961 #[test]
962 fn a_credit_counts_towards_the_requirement_it_arrives_with() {
963 let mut account = account_with_usd(dec!(100));
964 let debit = Debit {
965 asset: usd(),
966 settled: dec!(250),
967 reserved: dec!(40),
968 };
969
970 let credit = Credit::PaidBack(dec!(200));
971
972 let Ok(committed) = account.commit(
973 &debit,
974 Some(&credit),
975 MarginEffect::NoSideEffect,
976 Decimal::ZERO,
977 DateTime::<Utc>::MIN_UTC,
978 ) else {
979 panic!("100 free plus a 200 credit covers 290");
980 };
981
982 // total: 100 + 200 credited - 250 settled; free: that, less the 40 still held.
983 assert_eq!(committed.paid.balance, Balance::new(dec!(50), dec!(10)));
984 assert_eq!(
985 committed.received, None,
986 "a CFD credit restates the asset it paid with"
987 );
988 assert_eq!(usd_balance(&account), Balance::new(dec!(50), dec!(10)));
989 }
990
991 #[test]
992 fn a_refused_commit_applies_none_of_its_credit() {
993 let mut account = account_with_usd(dec!(100));
994 let debit = Debit {
995 asset: usd(),
996 settled: dec!(250),
997 reserved: dec!(60),
998 };
999
1000 let credit = Credit::PaidBack(dec!(200));
1001
1002 let Err(insufficient) = account.commit(
1003 &debit,
1004 Some(&credit),
1005 MarginEffect::NoSideEffect,
1006 Decimal::ZERO,
1007 DateTime::<Utc>::MIN_UTC,
1008 ) else {
1009 panic!("100 free plus a 200 credit does not cover 310");
1010 };
1011
1012 assert_eq!(
1013 insufficient,
1014 BalanceInsufficient {
1015 asset: usd(),
1016 free: dec!(300),
1017 required: dec!(310),
1018 borrowable: None,
1019 }
1020 );
1021 assert_eq!(usd_balance(&account), Balance::new(dec!(100), dec!(100)));
1022 }
1023
1024 fn btc() -> AssetNameExchange {
1025 AssetNameExchange::new("btc")
1026 }
1027
1028 fn balance_of(account: &AccountState, asset: &AssetNameExchange) -> Option<Balance> {
1029 account
1030 .balances()
1031 .find(|balance| &balance.asset == asset)
1032 .map(|balance| balance.balance)
1033 }
1034
1035 /// A spot buy pays quote and receives base: the base funds nothing, is restated as its own
1036 /// balance, and is created at zero when the account never held it.
1037 #[test]
1038 fn a_credit_into_another_asset_is_delivered_and_restated_separately() {
1039 let mut account = account_with_usd(dec!(100));
1040 let debit = Debit {
1041 asset: usd(),
1042 settled: dec!(100),
1043 reserved: dec!(0),
1044 };
1045 let credit = Credit::Delivery(Delivery {
1046 asset: btc(),
1047 amount: dec!(2),
1048 });
1049
1050 let Ok(committed) = account.commit(
1051 &debit,
1052 Some(&credit),
1053 MarginEffect::NoSideEffect,
1054 Decimal::ZERO,
1055 DateTime::<Utc>::MIN_UTC,
1056 ) else {
1057 panic!("100 free covers 100");
1058 };
1059
1060 assert_eq!(committed.paid.balance, Balance::new(dec!(0), dec!(0)));
1061 let Some(received) = committed.received else {
1062 panic!("a credit into another asset restates that asset");
1063 };
1064 assert_eq!(received.asset, btc());
1065 assert_eq!(received.balance, Balance::new(dec!(2), dec!(2)));
1066 assert_eq!(
1067 balance_of(&account, &btc()),
1068 Some(Balance::new(dec!(2), dec!(2)))
1069 );
1070 }
1071
1072 /// A credit into another asset is not the asset paid with, so it cannot fund the debit.
1073 #[test]
1074 fn a_credit_into_another_asset_does_not_fund_the_debit() {
1075 let mut account = account_with_usd(dec!(100));
1076 let debit = Debit {
1077 asset: usd(),
1078 settled: dec!(101),
1079 reserved: dec!(0),
1080 };
1081 let credit = Credit::Delivery(Delivery {
1082 asset: btc(),
1083 amount: dec!(1000),
1084 });
1085
1086 let Err(insufficient) = account.commit(
1087 &debit,
1088 Some(&credit),
1089 MarginEffect::NoSideEffect,
1090 Decimal::ZERO,
1091 DateTime::<Utc>::MIN_UTC,
1092 ) else {
1093 panic!("100 free does not cover 101, whatever another asset is credited");
1094 };
1095
1096 assert_eq!(
1097 insufficient,
1098 BalanceInsufficient {
1099 asset: usd(),
1100 free: dec!(100),
1101 required: dec!(101),
1102 borrowable: None,
1103 }
1104 );
1105 assert_eq!(usd_balance(&account), Balance::new(dec!(100), dec!(100)));
1106 assert_eq!(
1107 balance_of(&account, &btc()),
1108 None,
1109 "a refusal creates nothing"
1110 );
1111 }
1112
1113 /// A fill whose fee exceeds what it receives takes the excess from the asset it receives, and
1114 /// is refused, moving nothing, when that asset cannot cover it.
1115 #[test]
1116 fn a_negative_delivery_must_be_covered_by_its_own_asset() {
1117 let mut account = AccountState::new(
1118 FnvHashMap::from_iter([
1119 (usd(), funded(usd(), dec!(3))),
1120 (btc(), funded(btc(), dec!(1))),
1121 ]),
1122 OpenOrders::default(),
1123 FnvHashMap::default(),
1124 vec![],
1125 );
1126 let debit = Debit {
1127 asset: btc(),
1128 settled: dec!(1),
1129 reserved: dec!(0),
1130 };
1131 let short = Credit::Delivery(Delivery {
1132 asset: usd(),
1133 amount: dec!(-4),
1134 });
1135
1136 let Err(insufficient) = account.commit(
1137 &debit,
1138 Some(&short),
1139 MarginEffect::NoSideEffect,
1140 Decimal::ZERO,
1141 DateTime::<Utc>::MIN_UTC,
1142 ) else {
1143 panic!("3 usd free does not cover a 4 usd excess fee");
1144 };
1145 assert_eq!(
1146 insufficient,
1147 BalanceInsufficient {
1148 asset: usd(),
1149 free: dec!(3),
1150 required: dec!(4),
1151 borrowable: None,
1152 }
1153 );
1154 assert_eq!(
1155 balance_of(&account, &btc()),
1156 Some(Balance::new(dec!(1), dec!(1)))
1157 );
1158 assert_eq!(usd_balance(&account), Balance::new(dec!(3), dec!(3)));
1159
1160 let covered = Credit::Delivery(Delivery {
1161 asset: usd(),
1162 amount: dec!(-2),
1163 });
1164 let Ok(committed) = account.commit(
1165 &debit,
1166 Some(&covered),
1167 MarginEffect::NoSideEffect,
1168 Decimal::ZERO,
1169 DateTime::<Utc>::MIN_UTC,
1170 ) else {
1171 panic!("3 usd free covers a 2 usd excess fee");
1172 };
1173 assert_eq!(committed.paid.balance, Balance::new(dec!(0), dec!(0)));
1174 assert_eq!(
1175 committed.received.map(|balance| balance.balance),
1176 Some(Balance::new(dec!(1), dec!(1)))
1177 );
1178 }
1179
1180 #[test]
1181 fn a_charge_moves_total_and_free_together_and_may_take_free_negative() {
1182 let mut account = account_with_usd(dec!(100));
1183 account
1184 .reserve(&usd(), dec!(60), DateTime::<Utc>::MIN_UTC)
1185 .unwrap();
1186
1187 let charged = account.charge(&usd(), dec!(-50), DateTime::<Utc>::MIN_UTC);
1188 assert_eq!(charged.balance, Balance::new(dec!(50), dec!(-10)));
1189 assert_eq!(usd_balance(&account), Balance::new(dec!(50), dec!(-10)));
1190
1191 let credited = account.charge(&usd(), dec!(15), DateTime::<Utc>::MIN_UTC);
1192 assert_eq!(credited.balance, Balance::new(dec!(65), dec!(5)));
1193 }
1194
1195 /// A snapshot holding `orders`, as a configured `initial_state` would.
1196 fn snapshot_of(orders: impl IntoIterator<Item = UnindexedOrder>) -> UnindexedAccountSnapshot {
1197 let mut orders = orders.into_iter();
1198 let first = orders.next().unwrap();
1199 let mut snapshot = spot_config_holding("1", "1000", first).initial_state;
1200 snapshot.instruments[0].orders.extend(orders);
1201 snapshot
1202 }
1203
1204 fn open(cid: &str) -> UnindexedOrder {
1205 let at = DateTime::<Utc>::MIN_UTC;
1206 seeded_gtd(cid, "100", at, at + chrono::TimeDelta::days(1))
1207 }
1208
1209 fn ended(
1210 cid: &str,
1211 state: OrderState<AssetNameExchange, InstrumentNameExchange>,
1212 ) -> UnindexedOrder {
1213 UnindexedOrder { state, ..open(cid) }
1214 }
1215
1216 fn cancelled(cid: &str) -> UnindexedOrder {
1217 let at = DateTime::<Utc>::MIN_UTC;
1218 ended(
1219 cid,
1220 OrderState::inactive(Cancelled::new(OrderId::new(cid), at, None)),
1221 )
1222 }
1223
1224 /// One id listed twice among the orders a snapshot seeds is refused, rather than one of them
1225 /// silently winning, whichever two of open and cancelled they are.
1226 #[test]
1227 fn a_snapshot_seeding_one_id_twice_is_refused() {
1228 for (orders, case) in [
1229 ([open("x"), open("x")], "open twice"),
1230 ([open("x"), cancelled("x")], "open, then cancelled"),
1231 ([cancelled("x"), open("x")], "cancelled, then open"),
1232 ([cancelled("x"), cancelled("x")], "cancelled twice"),
1233 ] {
1234 assert_eq!(
1235 AccountState::try_from(snapshot_of(orders)).err(),
1236 Some(DuplicateSeededOrder(ClientOrderId::new("x"))),
1237 "{case}"
1238 );
1239 }
1240 }
1241
1242 /// An order the snapshot does not seed holds no id, so it cannot clash with one it does.
1243 #[test]
1244 fn an_order_a_snapshot_does_not_seed_does_not_clash() {
1245 let at = DateTime::<Utc>::MIN_UTC;
1246 let filled = ended(
1247 "x",
1248 OrderState::fully_filled(Filled::new(OrderId::new("x"), at, dec!(1), None)),
1249 );
1250
1251 let Ok(account) = AccountState::try_from(snapshot_of([filled, open("x")])) else {
1252 panic!("a filled order is not seeded");
1253 };
1254 assert!(account.orders().contains(&ClientOrderId::new("x")));
1255 }
1256
1257 /// A margin account owing 30 usd of principal and 1 of interest out of 100 held, as one seeded
1258 /// from a live margin account does: no loan has opened through it, so its count starts at zero.
1259 fn account_owing_usd() -> AccountState {
1260 let owing = AssetBalance::new(
1261 usd(),
1262 Balance::new_margin(dec!(100), dec!(100), dec!(30), dec!(1)),
1263 DateTime::<Utc>::MIN_UTC,
1264 );
1265 let mut account = AccountState::new(
1266 FnvHashMap::from_iter([(usd(), owing)]),
1267 OpenOrders::default(),
1268 FnvHashMap::default(),
1269 vec![],
1270 );
1271 account.enable_margin();
1272 account
1273 }
1274
1275 #[test]
1276 fn the_loan_count_changes_only_when_a_principal_is_repaid_to_zero() {
1277 let mut account = account_owing_usd();
1278 let at = DateTime::<Utc>::MIN_UTC;
1279
1280 account.deliver(
1281 &Delivery {
1282 asset: btc(),
1283 amount: dec!(1),
1284 },
1285 MarginEffect::Repay,
1286 at,
1287 );
1288 assert_eq!(
1289 account.loans_changed(),
1290 0,
1291 "a delivery into an asset owing nothing repays no loan"
1292 );
1293
1294 // The 1 interest, then 10 of the principal.
1295 account.repay_loan(&usd(), dec!(11), at);
1296 assert_eq!(
1297 account.loans_changed(),
1298 0,
1299 "20 of the principal is still owed"
1300 );
1301
1302 account.repay_loan(&usd(), dec!(20), at);
1303 assert_eq!(account.loans_changed(), 1);
1304 assert_eq!(account.loans().count(), 0);
1305 }
1306}