Skip to content

Positions: replay and valuation

A position is not stored, it is derived. PositionsFactory rebuilds the whole history of every instrument the user has touched by replaying transactions in time order onto a requested grid of timestamps. Everything the platform shows about holdings, allocation and performance starts from this replay.

Implementation: glacez-lib-factory, com.glacez.lib.factory.position.

What it computes

For each requested timestamp, and for each instrument that has appeared by then: quantity held, average price, realized gains. Optionally, in later stages over the same object: cost basis, market value, ROI, unrealized gains and portfolio weight.

Inputs

Input Type Mandatory
Time grid List<Long> (epoch millis), ascending or not, empty rejected yes
Transactions List<Transaction> yes, except in coherence mode

The grid is the caller's decision, not the factory's: a dashboard request passes a handful of points, a history job passes every day of a range. Timestamps may carry a time of day; the replay sorts them.

Only two transaction shapes are replayed. Each has mandatory fields, and a missing one fails at NullPointerException or produces a silently skipped transaction rather than an error:

Transaction Mandatory fields Effect
ClosedOrder (a settled trade) timestamp, side, pair.source, pair.target, amount (units of the target), total (amount paid in the source currency), price (QuotedValue, price of the target per quote; getCost() is price multiplied by amount) Moves quantity between two positions, updates average price, realizes gain on sells
Transfer (deposit or withdrawal) timestamp, currency, amount, type (DEPOSIT or WITHDRAWAL) Adds or removes quantity on one position, no price involved

Anything else in the list (LimitOrder, MarketOrder) is ignored by the replay. A limit order only enters the ledger once it is converted to a ClosedOrder.

Later stages take their own inputs: prices as TimestampInstrumentQuotedValues, market changes as InstrumentQuotedValues plus a frequency label, and the currencies list for snapshot categories.

Output

LinkedHashMap<Long, HashMap<String, Position>>

One entry per requested timestamp, in ascending order, and inside it one Position per instrument held at that moment. Positions are cumulative snapshots, not deltas: every timestamp carries the full state as of that time.

The replay fills total, avgPrice and rgl. costBasis, marketValue, roi, ugl, weightInPortfolio and changes stay at their defaults until a later stage fills them.

A Position produced here carries the instrument and the numbers only. user and timestamp are attached by the consumer when it needs them (Position.copyAt(user, timestamp, position)), which is also the copy that protects the factory's instances from being mutated by a caller.

How the replay happens

  1. Guards. Null transactions, an empty time grid, or an empty transaction list (outside coherence mode) throw IllegalArgumentException at construction.
  2. Bucketing. Transactions are sorted by timestamp and, within one timestamp, by the transaction's own order: a transfer before an order, then class name, then id. A deposit therefore funds the trades that share its instant, and a bucket replays the same way whatever order the caller supplied the list in. The grid is sorted, and one pass assigns each transaction to the first grid timestamp at or after it. Three consequences: a trade that happened before the first requested point lands on the first bucket, a trade between two buckets lands on the later one, and a trade after the last requested timestamp is never applied.
  3. Carry forward. Each bucket starts empty and inherits the previous bucket's instruments as fresh copies of exactly three fields: total, avgPrice, rgl. Valuation fields are not carried, so a snapshot can never show a stale market value.
  4. Replay each transaction on the bucket, per quote where the field is a QuotedValue.
  5. Buy: source total decreases by the order's total (the money spent), target total increases by the order's amount (the units received).
  6. Sell: source total decreases by the order's amount, target total increases by the order's total (the money received).
  7. Fees. A fee is charged in one instrument and leaves the book in that instrument. Charged in the pair's quote currency, it is added to the cash spent on a buy — so the units received carry it in their cost basis — and subtracted from the cash received on a sell, so the realized gain is net of it. Charged in the base currency, it comes out of the units: a buy receives amount - fee, a sell gives up amount + fee, and the sell's realized gain also loses averagePrice * fee. Charged in a third instrument (a venue token, the chain's gas coin), it is never debited: the pair does not move that balance, there is no price to convert it, and the book's balance for it is not the wallet the venue charged.
  8. A fee charged in the source's own currency is taken only when what is left covers it. The transaction itself stays mandatory — a shortfall on the cash paid or the units sold still raises — but a fee never turns a recorded transaction into an impossible one, because the venue charges it from a balance the book may never have imported.
  9. A negative source total raises NotEnoughException naming the instrument, the shortfall and the transaction timestamp. That exception is the coherence guarantee.
  10. Target average price is a weighted cost: avgPrice = (oldAvgPrice * oldTotal + orderCost) / newTotal. A buy costs price * amount. A sell costs sourceAveragePrice * amount, the units leaving the source at its average cost, and price * amount in any quote where the source has no average price. The choice is made per quote, so one missing quote never switches the whole order to another rule.
  11. Selling realizes gain against the source's average price: rgl += (salePrice - sourceAvgPrice) * amount, accumulated per quote and never reset.
  12. Transfers move quantity: a deposit adds units, a withdrawal subtracts them, and a negative result raises NotEnoughException. A deposit into a position that has no cost basis yet takes the market price of that timestamp as its cost, so a holding that arrived by transfer is worth what it was worth when the book first saw it. Units arriving into a position that already has an average price join that average, because the platform cannot tell an internal wallet move from an acquisition. A withdrawal never changes the average price, and it gives up the fee charged in its own currency when the balance left covers it. A fiat deposit is credited net of the fee charged in its own currency: the venue reports the amount and, beside it, the fee it charged in that currency (a card deposit's 5%, an international transfer's minimum), and what lands is the difference. A deposit in any other instrument keeps its whole amount, because its fee is the sender's gas reported again by the chain, never a charge taken from what arrived. A fee charged in a third instrument is never debited either.
  13. Valuation (processWithPricesCollectingErrors), for positions with a positive total that have a price in at least one quote: costBasis = total * avgPrice, marketValue = total * price, roi = (price - avgPrice) / avgPrice * 100, ugl = marketValue - costBasis, each quote independently. A price known in two quotes values those two and leaves the others empty, never a zero market value against a real cost basis. Only an instrument with no positive quote at all is reported to the caller's error list, and the position keeps its defaults, so the caller gets the errors instead of an exception.
  14. Weights (updateGlobalPercentages): weight = positionMarketValue / sumMarketValue * 100 per quote, and zero when either side is not positive.
  15. Changes (updateChanges): the market change for the position's instrument is stored under the given frequency label; instruments absent from the change set keep what they had.

Worked example

Grid: t1, t2. Transactions, all in EUR for readability (every other quote behaves the same way, driven by that quote's own price):

At Transaction
t1 Deposit 100000 EUR
t1 Buy 2 BTC, total 60000 EUR, price 30000 EUR/BTC
t2 Sell 1 BTC, total 40000 EUR, price 40000 EUR/BTC
t1 t2
EUR.total 40000 80000
EUR.avgPrice (EUR) 0 0.375
EUR.costBasis (EUR) 40000 80000
EUR.ugl (EUR) 0 0
BTC.total 2 1
BTC.avgPrice (EUR) 30000 30000
BTC.rgl (EUR) 0 10000

The sale realizes (40000 - 30000) * 1 = 10000 EUR and leaves the remaining BTC at its original average price, because average price only changes on the receiving side. The EUR average price becomes (0 * 40000 + 30000 * 1) / 80000 = 0.375, the weighted cost at which the received euros entered the position.

Coherence mode

newInstanceForCoherenceCheck(transactions) replays a candidate list on a single timestamp and tolerates an empty list. ordersStillCoherentWhenAdd, ordersStillCoherentWhenUpdate and ordersStillCoherentWhenDelete mutate the candidate list across every bucket and replay it, throwing NotEnoughException when the change would make the portfolio impossible. This is the check behind rejecting an edit in the UI. Adding converts a LimitOrder to a ClosedOrder first, the only place that conversion happens.

Limits and consequences

  • A trade after the last requested timestamp is dropped. The replay cannot see it, and nothing warns.
  • Same-timestamp ordering is the transaction's own compareTo, not the venue's sequence. A transfer is applied before an order that shares its instant, so a deposit always funds the trade it paid for; two orders in one instant fall back to class name and id, which is deterministic but says nothing about which one the venue executed first.
  • A fiat currency carries no gain. EUR, USD and CHF are valued at face value: cost basis equals market value, so ROI, UGL and realized gain are zero. In the example above the EUR leg's average price is still 0.375, because received euros enter at the seller's average cost, but the valuation ignores it. The platform does not track a cash position's entry rate, so it does not report FX gain on cash. Other quote currencies (BTC or ETH received from a sale) keep average-cost accounting, because they are holdings, not cash.
  • A deposit is only priced when the replay was given prices. A caller that replays without them still gets correct quantities, but an imported holding keeps a zero cost basis and a later sale realizes the whole proceeds as gain. Both portfolio paths pass their prices for this.
  • The output map is live. getTimestampPositions() returns the internal map, so a caller can mutate calculation state; take a copy (Position.copyAt) before handing positions onward.
  • Portfolio weights sum in double precision. FactoryUtils.calculateSumMarketValue sums BigDecimal market values through mapToDouble, so the portfolio total carries floating point error before it is turned back into a BigDecimal. Fine for allocation display, not for an accounting total.
  • Missing prices degrade quietly by design. The valuation stage reports an instrument that has no positive quote at all to a caller supplied error list; the snapshot factories log a count and continue, so a partial snapshot reads as a valid one.

Related: