{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://github.com/fallblu/trading-engine/contracts/v3/journal.schema.json",
  "title": "Trading Engine v3 audit journal record",
  "type": "object",
  "additionalProperties": false,
  "required": ["contract_version", "engine_sequence", "event_id", "causation_ids", "run_id", "recorded_at", "event_type", "payload"],
  "properties": {
    "contract_version": { "const": "3" },
    "engine_sequence": { "$ref": "#/$defs/sequence" },
    "event_id": { "$ref": "#/$defs/identifier" },
    "causation_ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/identifier" } },
    "run_id": { "$ref": "#/$defs/identifier" },
    "recorded_at": { "$ref": "#/$defs/timestamp" },
    "event_type": {
      "enum": ["run_started", "market_slice_received", "target_portfolio_requested", "order_accepted", "order_rejected", "order_cancelled", "split_applied", "cash_dividend_applied", "order_adjusted", "fill_applied", "margin_limited", "borrow_fee_applied", "margin_call", "margin_restored", "intent_rejected", "metric_emitted", "valuation", "run_completed"]
    },
    "payload": { "type": "object" }
  },
  "allOf": [
    { "if": { "properties": { "event_type": { "const": "run_started" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/runStarted" } } } },
    { "if": { "properties": { "event_type": { "const": "market_slice_received" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/marketSlice" } } } },
    { "if": { "properties": { "event_type": { "const": "target_portfolio_requested" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/targetPortfolio" } } } },
    { "if": { "properties": { "event_type": { "enum": ["order_accepted", "order_rejected"] } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/order" } } } },
    { "if": { "properties": { "event_type": { "const": "order_cancelled" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/orderCancelled" } } } },
    { "if": { "properties": { "event_type": { "const": "split_applied" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/splitApplied" } } } },
    { "if": { "properties": { "event_type": { "const": "cash_dividend_applied" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/dividendApplied" } } } },
    { "if": { "properties": { "event_type": { "const": "order_adjusted" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/orderAdjusted" } } } },
    { "if": { "properties": { "event_type": { "const": "fill_applied" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/fill" } } } },
    { "if": { "properties": { "event_type": { "const": "margin_limited" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/marginLimited" } } } },
    { "if": { "properties": { "event_type": { "const": "borrow_fee_applied" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/borrowFee" } } } },
    { "if": { "properties": { "event_type": { "enum": ["margin_call", "margin_restored", "valuation"] } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/valuation" } } } },
    { "if": { "properties": { "event_type": { "const": "intent_rejected" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/intentRejected" } } } },
    { "if": { "properties": { "event_type": { "const": "metric_emitted" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/metric" } } } },
    { "if": { "properties": { "event_type": { "const": "run_completed" } } }, "then": { "properties": { "payload": { "$ref": "#/$defs/runCompleted" } } } }
  ],
  "$defs": {
    "identifier": { "type": "string", "minLength": 1, "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+$" },
    "signedDecimal": { "type": "string", "pattern": "^(?:0|-?(?:0[.][0-9]{0,5}[1-9]|[1-9][0-9]*(?:[.][0-9]{0,5}[1-9])?))$" },
    "unsignedDecimal": { "type": "string", "pattern": "^(?:0|0[.][0-9]{0,5}[1-9]|[1-9][0-9]*(?:[.][0-9]{0,5}[1-9])?)$" },
    "positiveDecimal": { "type": "string", "pattern": "^(?:0[.][0-9]{0,5}[1-9]|[1-9][0-9]*(?:[.][0-9]{0,5}[1-9])?)$" },
    "sequence": { "type": "string", "pattern": "^[1-9][0-9]*$" },
    "nonnegativeSequence": { "type": "string", "pattern": "^(?:0|[1-9][0-9]*)$" },
    "timestamp": { "type": "string", "format": "date-time", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-5][0-9](?:[.][0-9]{1,6})?(?:[zZ]|[+-][0-9]{2}:[0-9]{2})$" },
    "runStarted": {
      "type": "object", "additionalProperties": false,
      "required": ["scenario_sha256", "execution_model"],
      "properties": { "scenario_sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "execution_model": { "const": "completed_bar_v1" } }
    },
    "bar": {
      "type": "object", "additionalProperties": false,
      "required": ["instrument_id", "open", "high", "low", "close", "volume"],
      "properties": {
        "instrument_id": { "$ref": "#/$defs/identifier" }, "open": { "$ref": "#/$defs/positiveDecimal" }, "high": { "$ref": "#/$defs/positiveDecimal" }, "low": { "$ref": "#/$defs/positiveDecimal" }, "close": { "$ref": "#/$defs/positiveDecimal" },
        "volume": { "oneOf": [{ "type": "null" }, { "$ref": "#/$defs/unsignedDecimal" }] }
      }
    },
    "fxRate": {
      "type": "object", "additionalProperties": false, "required": ["currency", "rate"],
      "properties": { "currency": { "$ref": "#/$defs/identifier" }, "rate": { "$ref": "#/$defs/positiveDecimal" } }
    },
    "corporateAction": {
      "oneOf": [
        { "type": "object", "additionalProperties": false, "required": ["type", "action_id", "instrument_id", "numerator", "denominator"], "properties": { "type": { "const": "split" }, "action_id": { "$ref": "#/$defs/identifier" }, "instrument_id": { "$ref": "#/$defs/identifier" }, "numerator": { "$ref": "#/$defs/sequence" }, "denominator": { "$ref": "#/$defs/sequence" } } },
        { "type": "object", "additionalProperties": false, "required": ["type", "action_id", "instrument_id", "amount_per_unit"], "properties": { "type": { "const": "cash_dividend" }, "action_id": { "$ref": "#/$defs/identifier" }, "instrument_id": { "$ref": "#/$defs/identifier" }, "amount_per_unit": { "$ref": "#/$defs/positiveDecimal" } } }
      ]
    },
    "marketSlice": {
      "type": "object", "additionalProperties": false,
      "required": ["slice_sequence", "start_at", "end_at", "available_at", "received_at", "bars", "fx_rates", "corporate_actions"],
      "properties": {
        "slice_sequence": { "$ref": "#/$defs/sequence" }, "start_at": { "$ref": "#/$defs/timestamp" }, "end_at": { "$ref": "#/$defs/timestamp" }, "available_at": { "$ref": "#/$defs/timestamp" }, "received_at": { "$ref": "#/$defs/timestamp" },
        "bars": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/bar" } }, "fx_rates": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/fxRate" } }, "corporate_actions": { "type": "array", "items": { "$ref": "#/$defs/corporateAction" } }
      }
    },
    "targetPortfolio": {
      "type": "object", "additionalProperties": false, "required": ["basis", "targets"],
      "properties": {
        "basis": { "enum": ["weights", "quantities"] },
        "targets": { "type": "array", "minItems": 1, "items": { "type": "object", "additionalProperties": false, "required": ["instrument_id", "weight", "quantity", "reference_price"], "properties": { "instrument_id": { "$ref": "#/$defs/identifier" }, "weight": { "oneOf": [{ "type": "null" }, { "$ref": "#/$defs/signedDecimal" }] }, "quantity": { "$ref": "#/$defs/signedDecimal" }, "reference_price": { "oneOf": [{ "type": "null" }, { "$ref": "#/$defs/positiveDecimal" }] } } } }
      }
    },
    "order": {
      "type": "object", "additionalProperties": false,
      "required": ["order_id", "instrument_id", "side", "quantity", "order_kind", "limit_price", "origin", "created_event_id", "updated_event_id", "created_sequence", "created_at", "eligible_after_slice_sequence", "filled_quantity", "filled_notional", "status", "rejection_reason"],
      "properties": {
        "order_id": { "$ref": "#/$defs/identifier" }, "instrument_id": { "$ref": "#/$defs/identifier" }, "side": { "enum": ["buy", "sell"] }, "quantity": { "$ref": "#/$defs/positiveDecimal" }, "order_kind": { "enum": ["market", "limit"] }, "limit_price": { "oneOf": [{ "type": "null" }, { "$ref": "#/$defs/positiveDecimal" }] }, "origin": { "enum": ["direct", "target_rebalance", "margin_liquidation"] }, "created_event_id": { "$ref": "#/$defs/identifier" }, "updated_event_id": { "$ref": "#/$defs/identifier" }, "created_sequence": { "$ref": "#/$defs/sequence" }, "created_at": { "$ref": "#/$defs/timestamp" }, "eligible_after_slice_sequence": { "$ref": "#/$defs/nonnegativeSequence" }, "filled_quantity": { "$ref": "#/$defs/unsignedDecimal" }, "filled_notional": { "$ref": "#/$defs/unsignedDecimal" }, "status": { "enum": ["working", "partially_filled", "filled", "cancelled", "rejected"] }, "rejection_reason": { "oneOf": [{ "type": "null" }, { "type": "string", "minLength": 1 }] }
      }
    },
    "orderCancelled": {
      "type": "object", "additionalProperties": false, "required": ["order", "reason"],
      "properties": { "order": { "$ref": "#/$defs/order" }, "reason": { "enum": ["strategy_requested", "target_replaced", "market_ioc", "margin_call"] } }
    },
    "splitApplied": {
      "type": "object", "additionalProperties": false, "required": ["action", "previous_quantity", "adjusted_quantity"],
      "properties": { "action": { "$ref": "#/$defs/corporateAction" }, "previous_quantity": { "$ref": "#/$defs/signedDecimal" }, "adjusted_quantity": { "$ref": "#/$defs/signedDecimal" } }
    },
    "dividendApplied": {
      "type": "object", "additionalProperties": false, "required": ["action", "quantity", "cash_amount"],
      "properties": { "action": { "$ref": "#/$defs/corporateAction" }, "quantity": { "$ref": "#/$defs/signedDecimal" }, "cash_amount": { "$ref": "#/$defs/signedDecimal" } }
    },
    "orderAdjusted": {
      "type": "object", "additionalProperties": false, "required": ["order", "action_id"],
      "properties": { "order": { "$ref": "#/$defs/order" }, "action_id": { "$ref": "#/$defs/identifier" } }
    },
    "fill": {
      "type": "object", "additionalProperties": false,
      "required": ["fill_id", "order_id", "instrument_id", "quote_currency", "side", "quantity", "price", "notional", "fee", "executed_at", "slice_sequence"],
      "properties": { "fill_id": { "$ref": "#/$defs/identifier" }, "order_id": { "$ref": "#/$defs/identifier" }, "instrument_id": { "$ref": "#/$defs/identifier" }, "quote_currency": { "$ref": "#/$defs/identifier" }, "side": { "enum": ["buy", "sell"] }, "quantity": { "$ref": "#/$defs/positiveDecimal" }, "price": { "$ref": "#/$defs/positiveDecimal" }, "notional": { "$ref": "#/$defs/positiveDecimal" }, "fee": { "$ref": "#/$defs/unsignedDecimal" }, "executed_at": { "$ref": "#/$defs/timestamp" }, "slice_sequence": { "$ref": "#/$defs/sequence" } }
    },
    "marginLimited": {
      "type": "object", "additionalProperties": false, "required": ["order_id", "instrument_id", "requested_quantity", "permitted_quantity", "price"],
      "properties": { "order_id": { "$ref": "#/$defs/identifier" }, "instrument_id": { "$ref": "#/$defs/identifier" }, "requested_quantity": { "$ref": "#/$defs/positiveDecimal" }, "permitted_quantity": { "$ref": "#/$defs/unsignedDecimal" }, "price": { "$ref": "#/$defs/positiveDecimal" } }
    },
    "borrowFee": {
      "type": "object", "additionalProperties": false, "required": ["instrument_id", "quote_currency", "short_quantity", "reference_price", "borrow_bps", "period_start", "period_end", "fee"],
      "properties": { "instrument_id": { "$ref": "#/$defs/identifier" }, "quote_currency": { "$ref": "#/$defs/identifier" }, "short_quantity": { "$ref": "#/$defs/positiveDecimal" }, "reference_price": { "$ref": "#/$defs/positiveDecimal" }, "borrow_bps": { "type": "integer", "minimum": 1, "maximum": 10000 }, "period_start": { "$ref": "#/$defs/timestamp" }, "period_end": { "$ref": "#/$defs/timestamp" }, "fee": { "$ref": "#/$defs/positiveDecimal" } }
    },
    "cashAttribution": {
      "type": "object", "additionalProperties": false, "required": ["currency", "amount", "fx_rate", "base_value"],
      "properties": { "currency": { "$ref": "#/$defs/identifier" }, "amount": { "$ref": "#/$defs/signedDecimal" }, "fx_rate": { "$ref": "#/$defs/positiveDecimal" }, "base_value": { "$ref": "#/$defs/signedDecimal" } }
    },
    "positionAttribution": {
      "type": "object", "additionalProperties": false,
      "required": ["instrument_id", "quote_currency", "quantity", "mark", "fx_rate", "market_value", "base_market_value", "cost_basis", "base_cost_basis", "realized_pnl", "base_realized_pnl", "unrealized_pnl", "base_unrealized_pnl", "dividend_pnl", "base_dividend_pnl", "execution_fees", "base_execution_fees", "borrow_fees", "base_borrow_fees", "total_fees", "base_total_fees"],
      "properties": {
        "instrument_id": { "$ref": "#/$defs/identifier" }, "quote_currency": { "$ref": "#/$defs/identifier" }, "quantity": { "$ref": "#/$defs/signedDecimal" }, "mark": { "$ref": "#/$defs/positiveDecimal" }, "fx_rate": { "$ref": "#/$defs/positiveDecimal" }, "market_value": { "$ref": "#/$defs/signedDecimal" }, "base_market_value": { "$ref": "#/$defs/signedDecimal" }, "cost_basis": { "$ref": "#/$defs/signedDecimal" }, "base_cost_basis": { "$ref": "#/$defs/signedDecimal" }, "realized_pnl": { "$ref": "#/$defs/signedDecimal" }, "base_realized_pnl": { "$ref": "#/$defs/signedDecimal" }, "unrealized_pnl": { "$ref": "#/$defs/signedDecimal" }, "base_unrealized_pnl": { "$ref": "#/$defs/signedDecimal" }, "dividend_pnl": { "$ref": "#/$defs/signedDecimal" }, "base_dividend_pnl": { "$ref": "#/$defs/signedDecimal" }, "execution_fees": { "$ref": "#/$defs/unsignedDecimal" }, "base_execution_fees": { "$ref": "#/$defs/unsignedDecimal" }, "borrow_fees": { "$ref": "#/$defs/unsignedDecimal" }, "base_borrow_fees": { "$ref": "#/$defs/unsignedDecimal" }, "total_fees": { "$ref": "#/$defs/unsignedDecimal" }, "base_total_fees": { "$ref": "#/$defs/unsignedDecimal" }
      }
    },
    "margin": {
      "type": "object", "additionalProperties": false, "required": ["initial_requirement", "maintenance_requirement", "initial_excess", "maintenance_excess", "margin_call"],
      "properties": { "initial_requirement": { "$ref": "#/$defs/unsignedDecimal" }, "maintenance_requirement": { "$ref": "#/$defs/unsignedDecimal" }, "initial_excess": { "$ref": "#/$defs/signedDecimal" }, "maintenance_excess": { "$ref": "#/$defs/signedDecimal" }, "margin_call": { "type": "boolean" } }
    },
    "valuation": {
      "type": "object", "additionalProperties": false,
      "required": ["base_currency", "cash", "net_market_value", "long_market_value", "short_market_value", "gross_exposure", "cost_basis", "realized_pnl", "unrealized_pnl", "equity", "dividend_pnl", "execution_fees", "borrow_fees", "total_fees", "cash_balances", "positions", "margin"],
      "properties": {
        "base_currency": { "$ref": "#/$defs/identifier" }, "cash": { "$ref": "#/$defs/signedDecimal" }, "net_market_value": { "$ref": "#/$defs/signedDecimal" }, "long_market_value": { "$ref": "#/$defs/unsignedDecimal" }, "short_market_value": { "$ref": "#/$defs/unsignedDecimal" }, "gross_exposure": { "$ref": "#/$defs/unsignedDecimal" }, "cost_basis": { "$ref": "#/$defs/signedDecimal" }, "realized_pnl": { "$ref": "#/$defs/signedDecimal" }, "unrealized_pnl": { "$ref": "#/$defs/signedDecimal" }, "equity": { "$ref": "#/$defs/signedDecimal" }, "dividend_pnl": { "$ref": "#/$defs/signedDecimal" }, "execution_fees": { "$ref": "#/$defs/unsignedDecimal" }, "borrow_fees": { "$ref": "#/$defs/unsignedDecimal" }, "total_fees": { "$ref": "#/$defs/unsignedDecimal" }, "cash_balances": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/cashAttribution" } }, "positions": { "type": "array", "items": { "$ref": "#/$defs/positionAttribution" } }, "margin": { "$ref": "#/$defs/margin" }
      }
    },
    "intentRejected": { "type": "object", "additionalProperties": false, "required": ["reason"], "properties": { "reason": { "type": "string", "minLength": 1 } } },
    "metric": { "type": "object", "additionalProperties": false, "required": ["name", "value"], "properties": { "name": { "type": "string" }, "value": { "type": "string" } } },
    "runCompleted": {
      "type": "object", "additionalProperties": false, "required": ["scenario_sha256", "execution_model", "valuation", "order_counts"],
      "properties": {
        "scenario_sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, "execution_model": { "const": "completed_bar_v1" }, "valuation": { "$ref": "#/$defs/valuation" },
        "order_counts": { "type": "object", "additionalProperties": false, "required": ["total", "active", "filled", "rejected", "cancelled"], "properties": { "total": { "type": "integer", "minimum": 0 }, "active": { "type": "integer", "minimum": 0 }, "filled": { "type": "integer", "minimum": 0 }, "rejected": { "type": "integer", "minimum": 0 }, "cancelled": { "type": "integer", "minimum": 0 } } }
      }
    }
  }
}
