Skip to content

Transaction Lifecycle

A transaction is the platform's atomic financial fact, and it has four producers on three code paths — a user entering history, a user sending a live order, a strategy, and the synchroniser — plus one inbound edge from the exchange. This page follows each: which calls are made, in what order, under what conditions, and what is left untouched.

Two ledgers, one edge

  • The transaction ledger (order, transfer) is what the platform believes: user intent, strategy intent, and execution as known. It is append-and-patch, user-visible, price-completed, and the only input to positions, ROI, strategy conditions and snapshots.
  • The record ledger (recordOrder, recordTransfer) is what the exchange says. It belongs to worker, is never user-editable, and is kept as provenance after it has been consumed.

The only edge is records → transactions: core reconciles one into the other every minute. Nothing flows back except a read-time stamp — webservice fills RecordTransaction.glacezTransactionId when it serves the record list, by looking the exchangeId up in the ledger.

recordSpot / recordEarn are a third object with no edge at all: current balance snapshots, replaced wholesale on every import, and never converted into transactions. See Known divergence.

The object

Transaction in glacez-lib-model: timestamp, status, lastUpdate, exchangeId, credentialId, walletId, note, fee (QuotedValue), exchange, originator, transactionHash, chain.

Family Subtype Adds
Order ClosedOrder price, total, lift — the executed trade; COMPLETE is what positions are built from
LimitOrder price, lift — a resting order, or one about to be sent
MarketOrder nothing — model-only form
Transfer — currency, amount, type (DEPOSIT / WITHDRAWAL), counterParty

Order stores side, pair, amount and tradeIds; the base/quote currency is derived from the pair and the side.

exchangeId is the platform-wide join key between the two ledgers. Every reconciler path asserts the records carry one. originator records who caused the write — USER, STRATEGY, SYNCHRONISATION, AUTO_GENERATED, GLACEZ — and a user edit never rewrites it: ClosedOrderService.update copies the stored originator onto the incoming document.

status: TO_CONFIRM, TO_PLACE, PLACED, COMPLETE, TO_CANCEL, CANCELED, UNKNOWN, PROCESSING.

Producer 1 — a user enters history

ui add-transaction (AddTransactionView, one tab per form: ClosedOrderBuyForm, ClosedOrderSellForm, DepositForm, WithdrawalForm) → webservice.

Hop Call
webservice ClosedOrderService.add (or DepositService.add / WithdrawalService.add)
webservice local checkUserOwnership, duplicate-id check, field validation, checkCurrenciesExists(pair)
webservice → findata CloseResource.getCloses for the trade's timestamp — a partial price is completed from it
webservice → portfolio TransactionCoherenceResources.checkCoherence(ADD)
webservice local closedOrderRepository.save — this service writes order / transfer, not core
webservice local TransactionTrack event ADD, then disableMustOnboarding

completeNonMandatoryFieldsBeforeAdd forces originator = USER, status = COMPLETE and exchange = UNKNOWN when the form left it empty. The coherence check replays PositionsFactory over the user's COMPLETE transactions: an order or withdrawal that would drive any instrument negative answers NotEnoughException, and unless the caller passed autoDeposit, the write is refused. With autoDeposit, DepositService.addAutomaticDeposit first writes a COMPLETE, AUTO_GENERATED deposit one millisecond before the offending transaction.

Deleting a closed order removes its TransactionTrack rows; a withdrawal or deposit delete writes a DELETE track instead. Both are coherence-checked the same way.

Producer 2 — a user sends a live order

ui add-trade (AddTradeView, LimitOrderBuyForm / LimitOrderSellForm) → webservice LimitOrderService.add.

The order enters TO_PLACE (or TO_CONFIRM) — LimitOrderValidator accepts nothing else — with originator = USER, timestamp = now, exchange taken from the credential, coherence-checked, saved and tracked. Then:

webservice → MQ glacez.trading.queue (TradingJob)
  → worker TradingJobConsumer → TradingService.placeLimitOrder
    → XChange (venue) → exchangeId → status PLACED → status event

The venue's synchronous answer is not the whole story: worker writes PLACED and the exchangeId from it, but whether the order actually filled arrives minutes later through the record leg and the next reconciliation.

Three gates before the venue is touched: glacez.worker.trading.enable (false outside prod — a non-prod stack refuses every trade with "Trading is disabled in this environment"), the credential must not be DISABLE, and the order passes a scale adapter that rounds price and amount to the venue's ExchangeInfo scales before sending. Any exception marks the order failed and emits a CANCELED status event.

Cancel and confirm are the same queue: confirm moves TO_CONFIRM → TO_PLACE, cancel moves PLACED → TO_CANCEL, and either one publishes a TradingJob. An order still in TO_CONFIRM/TO_PLACE is not sent to the venue at all — it is rewritten as a CANCELED ClosedOrder.

Producer 3 — a strategy

core.cron jobs/control/strategies (every 3 min) → StrategyController evaluates each action's conditions → TransactionsFromActionFactory.generateLimitOrder() → OrderServices.addLimitOrder: validate, coherence-check, save, then publish a TradingJob when the status is TO_PLACE and the order has no active lift.

Status at birth is the strategy's own switch: TO_CONFIRM when the strategy asks for user confirmation, TO_PLACE otherwise. Tracks are written with originator = GLACEZ (event GENERATE), the action and strategy record the generated order id, and a GeneratedOrderEvent plus an email job go out.

Producer 4 — the synchroniser

worker imports, core reconciles.

worker.cron → worker /jobs/records/import/* → XChange / Etherscan
  → recordOrder / recordTransfer / recordSpot / recordEarn
core.cron → core /jobs/synchronize/all → RecordService
  → CredentialRecordsSynchronizer | WalletRecordsSynchronizer
    → order / transfer (adds, updates, cancellations) + auto-generated deposits

Two ways in. The cron path above calls worker's import endpoints. The job path is a full import: webservice publishes a RecordJob on glacez.records.queue carrying RecordType = CREDENTIAL, WALLET or FILE, worker's RecordJobConsumer dispatches on it, and the credential's IMPORTING status is what makes the job act — a job for a connexion that is not IMPORTING is logged and ignored.

RecordService.synchroniseCredentialRecords loads the user's whole order and transfer set, the records of this credential, and the Currency symbol set, then hands all three to the synchroniser. The result is five order buckets, three transfer buckets and two auto-generated ones:

Bucket Condition
ordersToAdd closed record whose exchangeId is absent from the credential's orders
closedToUpdate ClosedOrder exists, but status differs or its tradeIds do not contain the record's
limitToExecuted a LimitOrder holds that exchangeId and the record is closed — the limit becomes a ClosedOrder at the same _id
limitToUpdate limit record matches an existing LimitOrder with a different status
limitToCancelled existing LimitOrder, no record, older than 10 minutes, not already CANCELED
transfersToAdd / ToUpdate / ToCancelled same three rules for transfers; the cancel bucket only touches PLACED ones
autoGenToAdd / ToRemove balancing deposits, see below

Before matching, records are merged by exchangeId (trade fragments summed into one order), legacy symbols are remapped, originator is forced to SYNCHRONISATION, and any record whose pair or instrument is not in Currency is dropped without a log line.

Rebranded tickers survive on the currency's own history. A venue keeps reporting the ticker a coin was listed under: BCC before Bitcoin Cash, MFT before HIFI, VEN before VET, GNT before GLM, STRAT before STRAX, MATIC before Polygon's POL, MCO before Cronos' CRO, MKR before Sky's SKY, NPXS before Pundi X's PUNDIX — and whatever a rename through the admin leaves behind. Currency.previousSymbols carries those tickers, appended by the rename itself, and the reconciler applies them to a record's pair source/target and to a transfer's currency before the Currency check above, so a years-old trade under a dead ticker resolves to the current symbol and then meets its ledger entry on exchangeId — without the alias, every one of those records is dropped by that filter, silently. InstrumentUtils.getLegacySymbolsMap() still seeds the same pairs as a fallback for currencies whose backfill has not run; where both name a ticker, the currency document wins.

Keeping the alias on the currency is what makes a rename self-serving: the operator holds the fact at rename time, so no rebrand can be forgotten and no release is needed to teach the reconciler. The remap rewrites no stored row — it happens on the record's in-memory order or transfer, so the next reconcile patches the transaction with the current symbol, and the first run after an alias appears converts the records that were previously dropped. Balances are outside it: a recordSpot / recordEarn under a dead ticker is stored exactly as the venue reported it, and webservice prices the row through the same alias — the symbol stays the venue's, the value comes from the current instrument's series (ADR-006).

Saving is where a manual entry is protected: addPrices fills a closed order's missing quotes from findata's closes at that timestamp (warning when they are invalid), putOldData copies the stored note and lift onto the record version so reconciliation never erases what a user typed, and every bucket writes a TransactionTrack plus a status Event.

Balancing deposits deserve their own line: DepositsFactory replays the ledger — old and incoming transactions together — and whenever a transaction would drive an instrument negative it emits an AUTO_GENERATED COMPLETE deposit one millisecond earlier, then replays from there. The result is compared with the stored auto-generated deposits and the difference is added or deleted. The input is the ledger, never the exchange balance.

Record shapes

Document Written by Shape of its life
RecordOrder / RecordTransfer worker append and patch, matched on exchangeId, consumed by core, never pruned; Origin = API_IMPORT or FILE_IMPORT
RecordSpot / RecordEarn worker delete-then-save full replace on every import; current balance only, no history
RecordFile webservice (upload) → worker (parse) PENDING → SYNCHRONIZED; body in GridFS, one CSV parser per venue format

A file import is the "history first, credentials later" path: the parser builds records with synthetic exchange ids, and the first real credential import matches them by timestamp, pair and amount to take the venue's genuine exchangeId and trade ids.

Cadence

glacez-infra-cron drives every step; nothing in the platform schedules itself. Prod values:

Owner Endpoint Prod
worker /jobs/records/import/credentials/latest every 5 min
worker /jobs/records/import/wallets/latest every 50 min
worker /jobs/records/import/closed-orders daily 03:38
worker /jobs/exchange-info/import daily 08:00
core /jobs/synchronize/all every 1 min
core /jobs/control/lift every 1 min
core /jobs/control/roi every 2 min
core /jobs/control/strategies every 3 min

So a trade is known to the platform within ~6 minutes of the venue settling it: up to 5 for the import, up to 1 more for the reconciliation. Ctlq runs the same chain slower on purpose, to spare the venues and the quota.

core exposes the reconcile three ways — /jobs/synchronize/all, /jobs/synchronize/credentials/{credentialId}, /jobs/synchronize/wallets/{walletId} — and the bulk one only picks connexions whose Auto Synchronize flag is set, so a connexion left manual is never touched by the cron.

Two manual triggers exist and behave differently. POST /records/synchronise requires an ENABLE credential and calls core directly — records already in the database are re-reconciled. POST /records/import sets the credential IMPORTING and publishes a RecordJob; worker then does a full import (all balances, all transfers, all limit and closed orders) and calls core to reconcile when it finishes, flipping the credential back to ENABLE — or to DISABLE on any error. While a credential is IMPORTING, a reconcile request is refused, and a RecordJob for a credential that is not IMPORTING is logged and ignored.

What the ledger feeds

Everything financial downstream reads COMPLETE transactions and derives on read — nothing stores a position, so a write is visible on the next read of each:

Consumer Uses transactions for
portfolio positions, ROI, distribution, portfolio snapshots
core ROI control, and the strategy conditions that inspect order and action status
webservice / ui the transaction grids, the detail views, and the coherence check that guards every new write

Two side channels ride along: TransactionTrack is the per-transaction timeline a user sees (what the reconciler, the user or a strategy did, and when), and status Events are what reach the UI as a badge and the user as an email.

Known divergence

The ledger and the balances describe the same holdings through two independent routes, and they are allowed to disagree:

  • positions, ROI and snapshots come from COMPLETE transactions;
  • the exchange's truth sits in recordSpot / recordEarn;
  • the only bridge is the AUTO_GENERATED deposit, which is derived from the ledger itself.

A record import that missed a period, a trade older than an import window, or a venue that reports a holding the platform never recorded leaves the two numbers apart permanently, with no reconciliation and no warning. This is a known property, not a defect: the ledger is the platform's statement of history, and the balances are the venue's statement of now.

A minted deposit is permanent for that replay. The synchroniser rebuilds the whole set from scratch on every run, but between runs the injected units stay, so a timing gap — a buy recorded before the deposit that funded it, or a deposit that is missing entirely — does not correct itself, it inflates the book. The EUR leg carries 42 such deposits totalling 14 082.60.

The gap is not dust. Measured against the Binance balance snapshot of 2025-11-25 (credential 67a284a7f07b375ecdc97cf1), the ledger held 32.39 BNB against 0.00000328, −33 098 VET, −28 492 VTHO, −14 738.55 USDT against 66.12, +30 000 000 PEPE and +783 681 SHIB against dust. Reconciling the records is its own piece of work; until it lands, no factory number should be read as the wallet's.