diff --git a/.claude/hooks/install-toolchains.sh b/.claude/hooks/install-toolchains.sh new file mode 100644 index 0000000..e5d2903 --- /dev/null +++ b/.claude/hooks/install-toolchains.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# SessionStart non-apt toolchains for sica-fondt. +# +# ECLiPSe CLP is required by M3b/M3f and is not distributed as a reliable +# Ubuntu apt package. Install the official x86_64 Linux binary distribution +# idempotently. Foundry remains separately hosted by design (M3c). +set -euo pipefail + +if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ] && [ "${SICA_INSTALL_TOOLCHAINS:-}" != "true" ]; then + exit 0 +fi + +ECLIPSE_VERSION="7.2_13" +ECLIPSE_ARCH="x86_64_linux" +ECLIPSE_ROOT="/opt/eclipse-clp-${ECLIPSE_VERSION}" +ECLIPSE_BASE="https://eclipseclp.org/Distribution/Builds/${ECLIPSE_VERSION}/${ECLIPSE_ARCH}" + +if ! command -v eclipse >/dev/null 2>&1; then + tmp="$(mktemp -d)" + trap 'rm -rf "$tmp"' EXIT + + curl --fail --location --silent --show-error "${ECLIPSE_BASE}/eclipse_basic.tgz" --output "${tmp}/eclipse_basic.tgz" + + sudo mkdir -p "${ECLIPSE_ROOT}" + sudo tar -xzf "${tmp}/eclipse_basic.tgz" -C "${ECLIPSE_ROOT}" + + sudo tee /usr/local/bin/eclipse >/dev/null < the Drive-Box drivers + tests (src/endocrine/*.R) # * GNU Octave -> the ETR torus + tests (src/endocrine/etr/*.m) +# * GNU Fortran -> M3d/M3e/M3g numerical sims (core/src/economy/sims/*) # # Synchronous + idempotent (safe to re-run; installs only what's missing). # Ada/Alire (mafiabot_core) is intentionally NOT installed here: it is not an apt @@ -20,6 +21,7 @@ export DEBIAN_FRONTEND=noninteractive pkgs=() command -v Rscript >/dev/null 2>&1 || pkgs+=(r-base-core) command -v octave >/dev/null 2>&1 || pkgs+=(octave) +command -v gfortran >/dev/null 2>&1 || pkgs+=(gfortran) if [ "${#pkgs[@]}" -gt 0 ]; then sudo apt-get update -qq @@ -29,3 +31,4 @@ fi # Surface versions in the session log (non-fatal). command -v Rscript >/dev/null 2>&1 && Rscript --version 2>&1 | head -1 || true command -v octave-cli >/dev/null 2>&1 && octave-cli --version 2>&1 | head -1 || true +command -v gfortran >/dev/null 2>&1 && gfortran --version 2>&1 | head -1 || true diff --git a/.github/workflows/m3a-statistical.yml b/.github/workflows/m3a-statistical.yml new file mode 100644 index 0000000..a3be06f --- /dev/null +++ b/.github/workflows/m3a-statistical.yml @@ -0,0 +1,45 @@ +name: M3a Statistical CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/statistical/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".github/workflows/m3a-statistical.yml" + pull_request: + paths: + - "core/src/economy/sims/statistical/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".github/workflows/m3a-statistical.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3a: + name: R statistical engine + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up R + uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + + - name: Run M3a native tests + run: Rscript core/src/economy/sims/statistical/tests.R + + - name: Run M2 → M3a → Hub integration + shell: bash + run: | + set -euo pipefail + tclsh core/src/economy/sims/statistical/integration.test | tee /tmp/m3a-integration.out + grep -Eq 'Total[[:space:]]+5[[:space:]]+Passed[[:space:]]+5.*Failed[[:space:]]+0' /tmp/m3a-integration.out diff --git a/.github/workflows/m3b-sociological.yml b/.github/workflows/m3b-sociological.yml new file mode 100644 index 0000000..3c1f3bc --- /dev/null +++ b/.github/workflows/m3b-sociological.yml @@ -0,0 +1,48 @@ +name: M3b Sociological CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/sociological/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".claude/hooks/install-toolchains.sh" + - ".github/workflows/m3b-sociological.yml" + pull_request: + paths: + - "core/src/economy/sims/sociological/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".claude/hooks/install-toolchains.sh" + - ".github/workflows/m3b-sociological.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3b: + name: ECLiPSe sociological engine + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install ECLiPSe CLP + env: + SICA_INSTALL_TOOLCHAINS: "true" + run: bash .claude/hooks/install-toolchains.sh + + - name: Run M3b native tests + working-directory: core/src/economy/sims/sociological + run: eclipse -b test.ecl -e run_tests + + - name: Run M2 → M3b → Hub integration + shell: bash + run: | + set -euo pipefail + tclsh core/src/economy/sims/sociological/integration.test | tee /tmp/m3b-integration.out + grep -Eq 'Total[[:space:]]+6[[:space:]]+Passed[[:space:]]+6.*Failed[[:space:]]+0' /tmp/m3b-integration.out diff --git a/.github/workflows/m3c-amm.yml b/.github/workflows/m3c-amm.yml new file mode 100644 index 0000000..e99e4d5 --- /dev/null +++ b/.github/workflows/m3c-amm.yml @@ -0,0 +1,77 @@ +name: M3c AMM CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/amm/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".github/workflows/m3c-amm.yml" + pull_request: + paths: + - "core/src/economy/sims/amm/**" + - "core/src/economy/stomach.tcl" + - "core/src/economy/feeds.tcl" + - "core/src/economy/sims/hub.tcl" + - ".github/workflows/m3c-amm.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3c: + name: Solidity AMM engine + runs-on: ubuntu-latest + defaults: + run: + working-directory: core/src/economy/sims/amm + steps: + - uses: actions/checkout@v4 + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Run M3c native tests + run: forge test -vv + + - name: Start local EVM and deploy read-only M3c bridge + shell: bash + run: | + set -euo pipefail + anvil --silent --port 8545 > /tmp/m3c-anvil.log 2>&1 & + echo $! > /tmp/m3c-anvil.pid + ready=0 + for i in $(seq 1 30); do + if cast block-number --rpc-url http://127.0.0.1:8545 >/dev/null 2>&1; then + ready=1 + break + fi + sleep 0.2 + done + test "$ready" = 1 + + wallet="$(cast wallet new 2>&1)" + key="$(printf '%s\n' "$wallet" | awk '/Private key:/ {print $3}')" + addr="$(printf '%s\n' "$wallet" | awk '/Address:/ {print $2}')" + test -n "$key" + test -n "$addr" + + cast rpc anvil_setBalance "$addr" 0x3635C9ADC5DEA00000 --rpc-url http://127.0.0.1:8545 >/dev/null + + deploy="$(forge create src/AMMQuery.sol:AMMQuery --rpc-url http://127.0.0.1:8545 --private-key "$key" --broadcast)" + query_addr="$(printf '%s\n' "$deploy" | awk '/Deployed to:/ {print $3}')" + [[ "$query_addr" =~ ^0x[0-9A-Fa-f]{40}$ ]] + + echo "AMM_RPC_URL=http://127.0.0.1:8545" >> "$GITHUB_ENV" + echo "AMM_QUERY_ADDRESS=$query_addr" >> "$GITHUB_ENV" + + - name: Run M2 → M3c → Hub integration + shell: bash + run: | + set -euo pipefail + tclsh integration.test | tee /tmp/m3c-integration.out + grep -Eq 'Total[[:space:]]+4[[:space:]]+Passed[[:space:]]+4.*Failed[[:space:]]+0' /tmp/m3c-integration.out diff --git a/.github/workflows/m3e-tokenomics.yml b/.github/workflows/m3e-tokenomics.yml new file mode 100644 index 0000000..d0796ee --- /dev/null +++ b/.github/workflows/m3e-tokenomics.yml @@ -0,0 +1,35 @@ +name: M3e Tokenomics CI + +on: + push: + branches: + - feat/stomach-economic-organ + paths: + - "core/src/economy/sims/tokenomics/**" + - ".github/workflows/m3e-tokenomics.yml" + pull_request: + paths: + - "core/src/economy/sims/tokenomics/**" + - ".github/workflows/m3e-tokenomics.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + m3e: + name: Fortran tokenomics engine + runs-on: ubuntu-latest + defaults: + run: + working-directory: core/src/economy/sims/tokenomics + steps: + - uses: actions/checkout@v4 + + - name: Compile M3e native tests + run: | + mkdir -p /tmp/sica-m3e + gfortran -std=f2018 -Wall -Wextra -Werror -pedantic -J /tmp/sica-m3e src/tokenomics_engine.f90 test/test_tokenomics.f90 -o /tmp/sica-m3e/test_tokenomics + + - name: Run M3e native tests + run: /tmp/sica-m3e/test_tokenomics diff --git a/core/docs/plans/M0-economy-organ-hub.md b/core/docs/plans/M0-economy-organ-hub.md index 04cc588..ec554a4 100644 --- a/core/docs/plans/M0-economy-organ-hub.md +++ b/core/docs/plans/M0-economy-organ-hub.md @@ -12,13 +12,15 @@ organism are TBD and out of scope. Brain for permission to trade. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. A `Stomach` primitive exists in Ichor (`src/ichor/envelope.pony:20`) with -one smoke-test wire (`main.pony:29`), but no dedicated organ code. Role C4; implementation C1. +SCAFFOLD · EXECUTABLE. The existing Ichor `Stomach` primitive now has a dedicated +M0–M7 simulation scaffold under `core/src/economy/`. M0 composes the component facades and +emits Ada-bound secretion metadata; external execution and the Pony↔Tcl runtime bridge remain +separate integration work. Role C4; scaffold implementation C2. ## 3. Language & location -TBD · new location e.g. `src/economy/`. The organ is polyglot by nature: trading infrastructure -(APIs, wallets) may differ in language from simulations (numerical computing) and the conductor -(AI supervision). Pony actors provide the Ichor-facing facade. +**Tcl 8.6 scaffold** · `core/src/economy/`. M0 orchestration is Tcl and preserves the +existing polyglot plan for later component engines. Pony remains the Ichor-facing transport layer; +the runtime bridge between Ichor and this scaffold is still open. ## 4. Does / does-not - **Does:** host crypto/NFT trading via the Marketplace (M1); run always-on market prediction @@ -67,8 +69,13 @@ TBD · new location e.g. `src/economy/`. The organ is polyglot by nature: tradin 4. Implement tax stub and Verschwörern Veregeister transfer last. ## 9. Tests -Hub smoke: Marketplace reachable; Sims running and queryable; Wallet bound to Trader; Conductor -receives SAE reports; tax stub logs transfer. Ichor: outbound envelope reaches Ada stub. +Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 17 +tests cover admission ordering, 1:1 binding, simulation-only execution, monitor logging, +supervisor pause/resume, bounded predictions, feed backpressure, exposure limits, tax staging, +Ada-bound secretion, all seven M3 engine registrations, source presence, the six horizon clocks, +and the running scheduler. Native simulator tests are driven by +`tclsh core/src/economy/sims/run_tests.tcl`. Ichor runtime bridging remains a separate +integration test. ## 10. Open items - Reward signal protocol from economy organ to organism (TBD, out of scope). diff --git a/core/docs/plans/M1-marketplace.md b/core/docs/plans/M1-marketplace.md index 6dea5ba..167bd86 100644 --- a/core/docs/plans/M1-marketplace.md +++ b/core/docs/plans/M1-marketplace.md @@ -7,7 +7,9 @@ the Marketplace. Enforces a **deterministic law script** (scoped invariants — own constitution) and integrates the **Conductor's veto** (M6) before execution. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4; implementation C1. +SCAFFOLD · EXECUTABLE SIMULATION. `core/src/economy/marketplace.tcl` implements the single +action ingress, deterministic admission ordering, supervisor veto, monitor logging, and +simulation-only execution. The full law-script loader remains open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/marketplace/`. Needs to interface with blockchain APIs (RPC/REST), wallet diff --git a/core/docs/plans/M2-data-feeds.md b/core/docs/plans/M2-data-feeds.md index dcde588..ac36679 100644 --- a/core/docs/plans/M2-data-feeds.md +++ b/core/docs/plans/M2-data-feeds.md @@ -7,7 +7,9 @@ produces execution data (fills, positions, P&L) that feeds back into Sims, and S predictions that inform Traders operating through the Marketplace. Data Feeds is the bridge. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. +SCAFFOLD · EXECUTABLE. `core/src/economy/feeds.tcl` implements normalized in-session history +and explicit backpressure without silent drop. External stream adapters remain open. Role C3; +scaffold C2. ## 3. Language & location TBD · `src/economy/feeds/`. Needs async I/O for streaming data (WebSockets, SSE, RSS polling). diff --git a/core/docs/plans/M3-sims-hub.md b/core/docs/plans/M3-sims-hub.md index 4e56d8c..2b323fe 100644 --- a/core/docs/plans/M3-sims-hub.md +++ b/core/docs/plans/M3-sims-hub.md @@ -12,8 +12,12 @@ The academic foundations span AMM mechanism design [1,2], MEV game theory [3,4,5 tokenomics via SDEs [6,7], and evolutionary consensus games [8–11]. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. Mathematical foundations C4 (literature -established); specific model parameters C1. +EXECUTABLE KERNEL SET. `core/src/economy/sims/` now contains all seven native engine +trees (M3a–M3g), a seven-engine registry, and a live Tcl event-loop scheduler for all six +horizons at the specified 90:1-or-faster ratios. The hub still validates/publishes bounded +predictions. Advanced model layers called out in the individual sub-specs remain incremental +work; the simulator family is no longer absent. Role C3; kernel implementation C2. +Mathematical foundations C4; live-market parameterization C1. ## 3. Language & location **Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages diff --git a/core/docs/plans/M3a-statistical-sims.md b/core/docs/plans/M3a-statistical-sims.md index 9bd5d41..14ef920 100644 --- a/core/docs/plans/M3a-statistical-sims.md +++ b/core/docs/plans/M3a-statistical-sims.md @@ -8,12 +8,18 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math **stochastic sample paths**, not behavioral agents. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Core quant methods C5 (GBM, GARCH, ARIMA — textbook). Heston stochastic -volatility C5 (closed-form characteristic function; industry standard since 1993). Rough -volatility C4 (Gatheral et al. 2018, heavily cited; crypto implementations exist). HMM regime -detection C4 (established; crypto-specific copula hybrids emerging 2023–2024). Almgren-Chriss -execution C5 (industry standard since 2001). Jump-diffusion C5 (Merton 1976). Parameterization -for crypto markets C1. +IMPLEMENTED · M3a V1 · R. `core/src/economy/sims/statistical/engine.R` now +implements the complete V1 statistical stack: GBM, Merton jump-diffusion, full-truncation Heston +simulation, GARCH(1,1) QMLE, three-state Gaussian HMM training + Viterbi decoding, +Davies–Harte fractional Gaussian noise and fitted rough volatility, fitted DCC dynamic +correlation, t-copula tail dependence with degrees-of-freedom estimation, conjugate Bayesian +return calibration, base-R ARIMA forecasting, historical VaR/Expected Shortfall, jump-intensity +estimation, Heston characteristic-function option pricing + surface calibration, empirical +walk-forward confidence/correctness/certainty scoring, and six concurrent bounded forecast +horizons. All seven declared prediction types are implemented. A Tcl runner provides tested +`M2 price_tick + dex_pool_state → R M3a → M3 hub → Marketplace` integration. Native R CI and +the boundary integration suite are green. Core methods C4/C5; implementation C3; live-market +parameterization remains data-dependent rather than hardcoded. ## 3. Language & location **R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only: @@ -66,8 +72,13 @@ the Hub stdin/stdout protocol is hand-rolled. - Calibration: ingests `price_tick` and `dex_pool_state` from M2 Data Feeds. ## 6. Dependencies & stubs -- M2 Data Feeds — price history for calibration; *stub:* canned price series. -- M3 Sims hub — lifecycle management; *stub:* manual init. +- M2 Data Feeds — normalized `price_tick` and `dex_pool_state` histories are consumed by + the Tcl→R calibration path. Pool observations contribute liquidity-weighted reference price, + dispersion, basis, and certainty calibration. +- M3 Sims hub — typed M3a predictions are published as bounded scalar predictions. Categorical + regime state is carried as a label plus a bounded posterior probability; correlation matrices + retain the matrix as detail while the bounded scalar value is the mean off-diagonal + correlation, preserving the hub's scalar-bound invariant. ## 7. Invariants / laws - **L1 (C5):** bounds are **statistical confidence intervals** — derived from the model's @@ -105,9 +116,14 @@ synthetic regime-switching data. Copula: tail dependence captured (BTC crash → correlation spike). Jump-diffusion: fat tails reproduced. Calibration: new data shifts parameter estimates. Multi-horizon: all six horizons produce concurrent outputs. -## 10. Open items -- Heston calibration method (characteristic function inversion? particle filter?). -- Rough vol computational cost (fBM generation is O(N²) naively; FFT methods needed). -- HMM state count (3 sufficient? 4+ for crypto with "mania" regime?). -- Which copula family for tail dependence ($t$-copula? Clayton? Joe?). -- Computational budget per horizon (GPU for Monte Carlo paths?). +## 10. V1 decisions and future extensions +- **Heston calibration:** resolved with characteristic-function inversion and numerical + option-surface calibration; realized-price proxy calibration remains available when no option + surface exists. +- **Rough-vol cost:** resolved with Davies–Harte circulant embedding / FFT rather than the + O(N²) naive generator. +- **HMM states:** three states (bear / neutral / bull) are canonical for V1. A fourth "mania" + state is an optional future experiment, not a V1 dependency. +- **Tail copula:** Student-t copula is canonical for V1, with fitted degrees of freedom. +- **Compute budget:** Monte Carlo path count is explicit per query and CPU-native in V1. + GPU acceleration is an optional optimization; it is not required for correctness. diff --git a/core/docs/plans/M3b-sociological-sims.md b/core/docs/plans/M3b-sociological-sims.md index 228d9a3..5618a40 100644 --- a/core/docs/plans/M3b-sociological-sims.md +++ b/core/docs/plans/M3b-sociological-sims.md @@ -10,11 +10,17 @@ pressure across **six concurrent time horizons**. Grounded in evolutionary conse MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Evolutionary game theory C4 (Cornell [8]). Hegselmann-Krause bounded -confidence C5 (established 2002). Complex contagion C4 (Centola & Macy 2007; crypto applications -C3). Bandit-replicator hybrid C3 (emerging). Mean-Field Games C4 (Lasry & Lions 2007; tensor-train -solvers C3). Crypto pump-and-dump ABM C3 (3-agent protocol validated on historical data). -Pop behavioral models C1. +IMPLEMENTED · M3b V1 · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl` +implements five abstract behavioral archetypes, replicator dynamics, Hegselmann–Krause bounded +confidence, heterogeneous complex contagion with a multiple-exposure requirement, UCB +bandit-replicator learning, a large-population HJB/Fokker–Planck mean-field equilibrium solver +with damped Newton updates, bounded-rationality pump/dump population dynamics, adaptive +confidence bounds, opinion clustering, and all nine bounded prediction types. The Tcl runner +calibrates from M2 `rss_news` + `price_tick`, preserves per-ticker population state across +queries, advances that state through the native bandit-replicator kernel, evaluates native MFG +stability, and scores correctness by walk-forward social→price agreement. Dedicated CI verifies +both the ECLiPSe kernel and M2→M3b→Hub boundary. Foundations C4/C5; implementation C3; +population parameterization remains evidence-driven rather than hardcoded to literal persons. ## 3. Language & location **ECLiPSe Prolog 7.2** · `src/economy/sims/sociological/`. Libraries: **ic** (interval @@ -77,9 +83,14 @@ mutation, PDE solvers for MFG (HJB + Fokker-Planck), and bandit algorithms (UCB/ `pump_dump_phase`, `mfg_equilibrium_stability`, `narrative_regime`. - Calibration: ingests `rss_news` (sentiment signal) and `price_tick` (realized behavior) from M2. -## 6. Dependencies & stubs -- M2 Data Feeds — sentiment and price data for calibration; *stub:* canned sentiment series. -- M3 Sims hub — lifecycle management; *stub:* manual init. +## 6. Dependencies & runtime boundary +- M2 Data Feeds — normalized `rss_news` carries aggregate source type, sentiment, engagement + and confidence; `price_tick` supplies realized behavioral response. +- M3 Sims hub — every M3b result is published as the common bounded-prediction schema and read + by Traders through Marketplace. Categorical phase/regime results retain a label beside their + bounded numeric code. +- ECLiPSe CLP — installed by the repo toolchain hook and exercised directly by dedicated CI. + M3b has no individual-profile ingestion and no trading/execution surface. ## 7. Invariants / laws - **L1 (C5):** pops are **archetypal individuals, not literal living persons** — no attempt to model or track real @@ -116,10 +127,20 @@ produces adapting populations. MFG: equilibrium converges for large N; matches d small N. Pump-dump: 4-phase cycle detected on synthetic manipulation data. Bounds: all outputs include upper/lower. -## 10. Open items -- Pop archetype catalog (which behavioral types? how many?). -- Network topology for sentiment contagion (small-world? scale-free?). -- Calibration from real market data — how to infer pop distribution from observable price action. >>>We actually use blogs, reddit, and social networks to infer pops<<< -- MFG tensor-train rank $r$ (>>>accuracy<<< vs. compute tradeoff). -- Hegselmann-Krause confidence bound $d$ — fixed or >>>adaptive<<>>Uniswap v3 style<<<) — extends the base model significantly. -- Multi-pool routing (split swaps across pools). >>>yes<<< -- Which specific pools to simulate (>>>ETH<<>and other popular chains<< NOT STABLE/USDC/USDT etc. +## 10. V1 decisions and future extensions +- **Concentrated liquidity:** V1 implements the canonical liquidity-to-token amount equations, + one-sided out-of-range positions, and volatility/horizon-derived optimal ranges. Full + Uniswap-v3-style initialized-tick crossing and fee-growth accounting are a future fidelity + extension, not required by the V1 prediction contract. +- **Multi-pool routing:** V1 implements deterministic optimal exact-input splitting across two + pools by marginal-output equalization. N-way routing is a future scaling extension. +- **Pool universe:** the engine is chain- and pair-agnostic. M2 chooses the concrete pools; + the simulator does not hardcode ETH/USDC, stablecoins, or any particular chain. +- **Execution boundary:** arbitrage and sandwich functions are simulation constructs only. + No native M3c API can submit a real swap. diff --git a/core/docs/plans/M3d-mev-adversarial-sims.md b/core/docs/plans/M3d-mev-adversarial-sims.md index 7f9e26a..b4f1548 100644 --- a/core/docs/plans/M3d-mev-adversarial-sims.md +++ b/core/docs/plans/M3d-mev-adversarial-sims.md @@ -13,10 +13,11 @@ dynamics (non-linear Fokker-Planck with WENO shock capturing), and DSMFG bilevel (leader policy + follower MFG equilibrium). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. PGA-as-all-pay-auction C4 (ACM [3]); knapsack formulation C4 (Cornell -[4,5]); cross-chain arbitrage C4 (ACM SIGMETRICS 2025, 5.5x growth since Dencun); DSMFG bilevel -optimization C3 (emerging — SMFRL solvers); Kolokoltsov adversarial C3 (non-linear Fokker-Planck; -WENO discretization established but crypto application novel). Parameterization C1. +KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/mev/` implements the all-pay +PGA payoff model, exact 0/1 block-building knapsack selection, dual-path cross-chain profit +comparison, sandwich-risk scoring, and aggregate all-pay cost. Native tests compile cleanly +under strict gfortran flags. WENO/Kolokoltsov and DSMFG bilevel solvers remain incremental. +Core game/knapsack foundations C4; implementation C2; parameterization C1. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS** diff --git a/core/docs/plans/M3e-tokenomics-macro-sims.md b/core/docs/plans/M3e-tokenomics-macro-sims.md index 256df1d..663fd76 100644 --- a/core/docs/plans/M3e-tokenomics-macro-sims.md +++ b/core/docs/plans/M3e-tokenomics-macro-sims.md @@ -13,10 +13,12 @@ frameworks [6], Aave/Compound kinked interest rate models (industry standard), a inter-protocol credit propagation (Matzakos et al. 2025). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. SDE state-space framework C4 (Vienna [7]); stock-flow modeling C4 -(ResearchGate [6]); kinked interest rate model C5 (Aave/Compound production standard); -DeXposure inter-protocol credit propagation C3 (emerging, 2025 — high DeFi specificity); -composable yield optimization C4 (Yearn v3, Beefy, production-validated). Specific parameters C1. +KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/tokenomics/` implements +Euler-Maruyama state evolution, stock-flow conservation checks, kinked lending curves, +directional exposure propagation, risk-adjusted yield allocation, and liquidation shortfall. +Native tests compile cleanly under strict gfortran flags. Full state estimation, calibrated VAR +impulse response, and policy-event orchestration remain incremental. Foundations C4/C5; +implementation C2; specific parameters C1. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies: diff --git a/core/docs/plans/M3f-consensus-staking-sims.md b/core/docs/plans/M3f-consensus-staking-sims.md index 1723a44..af6a387 100644 --- a/core/docs/plans/M3f-consensus-staking-sims.md +++ b/core/docs/plans/M3f-consensus-staking-sims.md @@ -8,10 +8,11 @@ financial incentives. Grounded in Cornell evolutionary consensus [8,9], ACM stak theorems [10], and Monash dynamic PBFT modeling [11]. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Evolutionary PoS game theory C4 (Cornell [8]); staking pool Nash -equilibrium proofs C4 (ACM [10]); Markov chain throughput models C4 (Monash [11]); MFG for -validator populations C4 (Lasry & Lions 2007; validator-specific application C3); -simulation parameterization C1. +KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/consensus/engine.ecl` +implements evolutionary honesty updates, validator-state Markov transitions, an explicit +incentive-compatibility slashing threshold, and liveness degradation below an honesty threshold. +Native tests live beside the engine. The large-population HJB/Fokker-Planck MFG layer remains +incremental. Foundations C4; implementation C2; protocol parameterization C1. ## 3. Language & location **ECLiPSe Prolog 7.2** · `src/economy/sims/consensus/`. Libraries: **ic** (interval diff --git a/core/docs/plans/M3g-market-microstructure-sims.md b/core/docs/plans/M3g-market-microstructure-sims.md index 062d966..b3a7c98 100644 --- a/core/docs/plans/M3g-market-microstructure-sims.md +++ b/core/docs/plans/M3g-market-microstructure-sims.md @@ -10,9 +10,11 @@ models pool mechanics, M3g models the *plumbing* of how orders actually execute, concurrent time horizons** at tick-advanced, 90:1 (1s wall = 90s sim). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Order-book microstructure theory C4 (established). Almgren-Chriss -optimal execution C5 (industry standard since 2001; crypto adaptations validated 2023–2024, -Kurz CMC thesis). DEX-specific microstructure C2 (emerging). Implementation C1. +KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/microstructure/` implements +depth-consuming buy slippage, bid/ask spread, Almgren-Chriss execution schedules, exponential +cross-venue arbitrage decay, and live linear impact estimation. Native tests compile cleanly +under strict gfortran flags. Full order-event simulation and venue adapters remain incremental. +Microstructure C4; Almgren-Chriss C5; implementation C2; DEX-specific calibration C1/C2. ## 3. Language & location **Fortran 2018** (gfortran) · `src/economy/sims/microstructure/`. Build: **fpm**. Dependencies: diff --git a/core/docs/plans/M4-wallets.md b/core/docs/plans/M4-wallets.md index 6e1a7c8..f85b545 100644 --- a/core/docs/plans/M4-wallets.md +++ b/core/docs/plans/M4-wallets.md @@ -8,7 +8,9 @@ the Marketplace (M1). Wallets hold keys, sign transactions, and enforce wallet-l Tax is collected on trader income and routed to the Verschwörern Veregeister wallets (stub — M0). ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4 (sovereign custody is a hard requirement); implementation C1. +SCAFFOLD · PARTIAL. `core/src/economy/wallets.tcl` implements permanent 1:1 binding and +independent exposure limits for the simulation scaffold. Custody/signing implementation remains +open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for diff --git a/core/docs/plans/M5-traders.md b/core/docs/plans/M5-traders.md index 12a1c53..5dea4b7 100644 --- a/core/docs/plans/M5-traders.md +++ b/core/docs/plans/M5-traders.md @@ -5,7 +5,9 @@ The economy organ's hands: **specialized AI instances** that buy, sell, and mint NFTs. Each trader is bound to a Wallet (M4), operates through the Marketplace (M1), queries Market to receive predictions (M3), and are monitored by the SAE (M7) via Marketplace. Multiple traders operate concurrently with **different heuristics and specializations**. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C3; implementation C1. +SCAFFOLD · PARTIAL. `core/src/economy/traders.tcl` implements trader identity, +specialization labels, and mechanical pause/resume state. Trader inference remains open. +Role C3; scaffold C2. ## 3. Language & location TBD · `src/economy/traders/`. Traders are AI agents.All use the same `MarketAction` interface through the Marketplace regardless of implementation. Traders are the agentic entities, the determininistic bots are subservient to them. diff --git a/core/docs/plans/M6-conductor.md b/core/docs/plans/M6-conductor.md index 3a347c9..ea2a73f 100644 --- a/core/docs/plans/M6-conductor.md +++ b/core/docs/plans/M6-conductor.md @@ -8,8 +8,9 @@ organism's Brain for trade-level decisions. It supervises; the deterministic law constrains; together they form the multi-layered braking system. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. Role C4 (supervision architecture is clear); implementation C1 (model -selection, training, authority scope). +SCAFFOLD · EXECUTABLE SUPERVISION. `core/src/economy/conductor.tcl` implements veto ordering, +pause/resume, alert intake, and an in-memory decision log. Specialist inference and persistent +audit storage remain open. Role C4; scaffold C2. ## 3. Language & location TBD · `src/economy/conductor/`. The Conductor is an AI actor — likely a fine-tuned LLM with diff --git a/core/docs/plans/M7-sae-monitor.md b/core/docs/plans/M7-sae-monitor.md index d9a985b..05a40e9 100644 --- a/core/docs/plans/M7-sae-monitor.md +++ b/core/docs/plans/M7-sae-monitor.md @@ -11,9 +11,10 @@ Extends the F2 (SAE monitor) pattern to the economy organ's internal domain. F2 subagents at the organism level; M7 watches traders at the stomach level. ## 2. Status / certainty -DESIGN-FIRST · ABSENT. F2 SAE monitor provides the architectural pattern (watch the machinery, -never the homunculus — F2-L1). M7 adapts this: watch the **traders** (the machinery), never the -**Conductor** (the stomach's judgment). Role C3; implementation C1. +SCAFFOLD · PARTIAL. `core/src/economy/sae.tcl` records Marketplace-level trader calls and +constructs alert envelopes consumed by M6. Sparse-autoencoder inference/training remains open. +F2 still provides the architectural pattern: watch traders, never the Conductor. Role C3; +scaffold C2. ## 3. Language & location TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader action embeddings). diff --git a/core/src/economy/AGENTS.md b/core/src/economy/AGENTS.md new file mode 100644 index 0000000..5b1aa16 --- /dev/null +++ b/core/src/economy/AGENTS.md @@ -0,0 +1,22 @@ +# AGENTS.md — M0 economy/stomach organ + +Local guide for `core/src/economy`. The design source of truth is `core/docs/plans/M0-economy-organ-hub.md` plus M1–M7. + +## Hard boundaries + +- This is an **OUTER** organ. Organism-bound output is `Stomach → AdaBorder` with `OrganSecretion` provenance. Never add an inner-bus route. +- Traders never receive RPC, signing, or chain clients. All market actions enter M1 Marketplace. +- M1 deterministic law runs before M6 veto. M6 may veto a legal action; it may not legalize an illegal one. +- M4 wallet brakes are independent of M1/M6. Keep 1:1 trader↔wallet binding literal. +- M7 observes and reports. Enforcement belongs to M6/M1/M4, not the monitor. +- Live key custody and chain broadcast are intentionally absent until the M4 key-storage specification is ratified. Do not smuggle them in as convenience helpers. + +## Build/test + +Tcl 8.6, standard library only: + +```sh +tclsh core/src/economy/tests/stomach.test +``` + +Use test-first changes. Keep `stomach.tcl` as composition/facade; put component behavior in the M1–M7 module that owns it. diff --git a/core/src/economy/README.md b/core/src/economy/README.md new file mode 100644 index 0000000..d621483 --- /dev/null +++ b/core/src/economy/README.md @@ -0,0 +1,38 @@ +# Economy organ — M0 stomach + +Executable scaffold for M0–M7. The stomach is an OUTER organ: its only organism-facing product is an Ada-bound `organ_secretion`; it never joins the inner bus. + +## Implemented now + +- **M1 Marketplace** — single action ingress; wallet-first admission; deterministic action/chain law; wallet brake; Conductor veto after law; simulated execution only. +- **M2 Feeds** — normalized datum history with explicit backpressure instead of silent eviction. +- **M3 Sims** — all seven native engine trees are built in. M3a V1 is complete with calibrated HMM regimes, fitted spectral rough volatility, Heston characteristic-function surface calibration, fitted DCC/t-copula dependence, Bayesian/ARIMA/GARCH risk forecasting, empirical walk-forward quality scoring, all seven prediction types, and tested price+DEX-pool M2→R→Hub routing; M3b V1 is complete with persistent five-archetype populations, native bandit-replicator learning, adaptive bounded-confidence/contagion dynamics, HJB/FP MFG stability, pump/dump ABM behavior, nine bounded prediction types, M2 social+price calibration and empirical walk-forward scoring; M3c V1 is complete with native Solidity constant-product and concentrated-liquidity mechanics, LP/JIT and arbitrage populations, split routing, five bounded prediction types, and tested M2→EVM→Hub routing; M3d is Fortran MEV, M3e Fortran tokenomics, M3f ECLiPSe consensus, and M3g Fortran microstructure. A live Tcl event-loop clock runs all six horizons at 90:1 or faster. +- **M4 Wallets** — permanent 1:1 trader binding plus per-action/session exposure brakes. No private-key field, signer, or RPC surface exists yet. +- **M5 Traders** — trader registry and mechanical pause state. AI trader inference is not implemented here. +- **M6 Conductor** — veto-next, pause/resume, SAE alert intake, append-only in-memory decision log. Specialist inference is not implemented yet. +- **M7 SAE** — records Marketplace tool calls and produces alert envelopes; actual sparse-autoencoder inference/training is not implemented yet. +- **M0** — composes the above, stages tax receipts without moving value, and emits a stomach→Ada status secretion. + +There is deliberately no live transaction broadcaster. A successful action returns `execution simulated` and a deterministic `simtx-*` identifier. Live custody/execution should not appear until the unresolved M4 key-storage design is ratified. + +## Test + +```sh +tclsh core/src/economy/tests/stomach.test +``` + +Expected: `Total 17 Passed 17 ... Failed 0` once the current branch is checked out. + +The simulator family also has its own polyglot driver: + +```sh +tclsh core/src/economy/sims/run_tests.tcl +``` + +It executes Tcl + every native suite whose runtime is installed. Use `--strict` to make missing R/ECLiPSe/Foundry runtimes a failure rather than an explicit skip. + +## Public scaffold API + +`::stomach::Economy` exposes `register_trader`, `bind_wallet`, `submit_action`, `feed_publish`, `feed_history`, `sim_publish`, `query_predictions`, `statistical_runner_available`, `statistical_query`, `statistical_from_feed`, `amm_runner_available`, `amm_from_feed`, `sociological_runner_available`, `sociological_from_feed`, `sim_engines`, `sim_engine_status`, `sim_horizons`, `sim_running`, `sim_advance`, `conductor_veto_next`, `conductor_pause`, `conductor_resume`, `sae_alert`, `tax_event`, and `secretion`. + +`secretion` returns the envelope-compatible metadata `source stomach`, `destination ada_border`, `provenance organ_secretion`. The runtime Pony↔Tcl bridge is still an integration task; no code may shortcut D1 while that bridge is built. diff --git a/core/src/economy/conductor.tcl b/core/src/economy/conductor.tcl new file mode 100644 index 0000000..2d44f96 --- /dev/null +++ b/core/src/economy/conductor.tcl @@ -0,0 +1,43 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Conductor { + variable traders decisions veto_next + constructor {traders_obj} { set traders $traders_obj; set decisions {}; set veto_next {} } + + method veto_next {trader_id reason} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + dict set veto_next $trader_id $reason + return [dict create status armed trader_id $trader_id] + } + method consume_veto {trader_id} { + if {![dict exists $veto_next $trader_id]} { return [dict create approved 1] } + set reason [dict get $veto_next $trader_id] + dict unset veto_next $trader_id + lappend decisions [dict create decision veto trader_id $trader_id reason $reason timestamp [clock seconds]] + return [dict create approved 0 reason $reason] + } + method pause {trader_id reason} { + $traders pause $trader_id + set d [dict create decision pause trader_id $trader_id reason $reason timestamp [clock seconds]] + lappend decisions $d + return $d + } + method resume {trader_id reason} { + $traders resume $trader_id + set d [dict create decision resume trader_id $trader_id reason $reason timestamp [clock seconds]] + lappend decisions $d + return $d + } + method receive_alert {alert} { + set trader_id [dict get $alert trader_id] + if {[dict get $alert severity] >= 8.0} { + $traders pause $trader_id + set d [dict create decision pause trader_id $trader_id reason "sae:[dict get $alert alert_type]" alert $alert timestamp [clock seconds]] + } else { + set d [dict create decision dismiss trader_id $trader_id reason below_pause_threshold alert $alert timestamp [clock seconds]] + } + lappend decisions $d + return $d + } + method log {} { return $decisions } +} diff --git a/core/src/economy/feeds.tcl b/core/src/economy/feeds.tcl new file mode 100644 index 0000000..7d13fb2 --- /dev/null +++ b/core/src/economy/feeds.tcl @@ -0,0 +1,22 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Feeds { + variable history_cap feeds + constructor {cap} { + if {![string is integer -strict $cap] || $cap < 1} { error "history_cap_must_be_positive" } + set history_cap $cap + set feeds {} + } + method publish {feed_type source timestamp payload confidence} { + if {![string is double -strict $confidence] || $confidence < 0 || $confidence > 10} { error "confidence_out_of_range" } + set history [expr {[dict exists $feeds $feed_type] ? [dict get $feeds $feed_type] : {}}] + if {[llength $history] >= $history_cap} { return [dict create status backpressure feed_type $feed_type buffered [llength $history]] } + lappend history [dict create feed_type $feed_type source $source timestamp $timestamp payload $payload confidence $confidence] + dict set feeds $feed_type $history + return [dict create status accepted feed_type $feed_type buffered [llength $history]] + } + method history {feed_type} { + if {![dict exists $feeds $feed_type]} { return {} } + return [dict get $feeds $feed_type] + } +} diff --git a/core/src/economy/marketplace.tcl b/core/src/economy/marketplace.tcl new file mode 100644 index 0000000..e8f2d1b --- /dev/null +++ b/core/src/economy/marketplace.tcl @@ -0,0 +1,49 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Marketplace { + variable traders wallets conductor sae sims executions tx_seq + constructor {traders_obj wallets_obj conductor_obj sae_obj sims_obj} { + set traders $traders_obj; set wallets $wallets_obj; set conductor $conductor_obj; set sae $sae_obj; set sims $sims_obj + set executions {}; set tx_seq 0 + } + method _reject {reason} { return [dict create status failed reason $reason] } + method _law_check {action} { + foreach required {type asset chain amount price} { + if {![dict exists $action $required]} { return [dict create pass 0 reason "missing_$required"] } + } + if {[lsearch -exact {buy sell mint provide_liquidity withdraw_liquidity claim_rewards} [dict get $action type]] < 0} { return [dict create pass 0 reason action_not_allowed] } + if {[lsearch -exact {ethereum solana arbitrum} [dict get $action chain]] < 0} { return [dict create pass 0 reason chain_not_allowed] } + set amount [dict get $action amount]; set price [dict get $action price] + if {![string is double -strict $amount] || ![string is double -strict $price] || $amount <= 0 || $price < 0} { return [dict create pass 0 reason invalid_notional] } + return [dict create pass 1] + } + method submit {trader_id wallet_id action} { + $sae log_tool $trader_id submit_action $action + if {![$traders exists $trader_id]} { return [my _reject unknown_trader] } + if {[$wallets binding_for $trader_id] eq ""} { return [my _reject missing_wallet] } + if {![$wallets binding_matches $trader_id $wallet_id]} { return [my _reject wallet_binding] } + if {[$traders is_paused $trader_id]} { return [my _reject trader_paused] } + set law [my _law_check $action] + if {![dict get $law pass]} { return [my _reject [dict get $law reason]] } + set wc [$wallets spending_check $wallet_id $action] + if {![dict get $wc pass]} { return [my _reject [dict get $wc reason]] } + set veto [$conductor consume_veto $trader_id] + if {![dict get $veto approved]} { return [my _reject [dict get $veto reason]] } + + # Simulation boundary: there is no signer, broadcaster, RPC client, or + # chain-execution method in this scaffold. Success means the proposed + # action cleared the organ's gates and was recorded in the sandbox. + incr tx_seq + set tx_id [format "simtx-%06d" $tx_seq] + $wallets record_spend $wallet_id [dict get $wc notional] + lappend executions [dict create tx_id $tx_id trader_id $trader_id wallet_id $wallet_id action $action execution simulated] + return [dict create status succeeded execution simulated tx_id $tx_id] + } + method predictions {trader_id sim_type} { + $sae log_tool $trader_id query_predictions [dict create sim_type $sim_type] + if {![$traders exists $trader_id]} { error "unknown_trader" } + if {[$traders is_paused $trader_id]} { error "trader_paused" } + return [$sims query $sim_type] + } + method execution_count {} { return [llength $executions] } +} diff --git a/core/src/economy/sae.tcl b/core/src/economy/sae.tcl new file mode 100644 index 0000000..8fe59ac --- /dev/null +++ b/core/src/economy/sae.tcl @@ -0,0 +1,15 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SAEMonitor { + variable events + constructor {} { set events {} } + method log_tool {trader_id tool detail} { + lappend events [dict create trader_id $trader_id tool $tool detail $detail timestamp [clock seconds]] + } + method alert {trader_id alert_type evidence severity timestamp} { + if {![string is double -strict $severity] || $severity < 0 || $severity > 10} { error "severity_out_of_range" } + return [dict create trader_id $trader_id alert_type $alert_type evidence $evidence severity $severity timestamp $timestamp] + } + method log {} { return $events } + method count {} { return [llength $events] } +} diff --git a/core/src/economy/sims/README.md b/core/src/economy/sims/README.md new file mode 100644 index 0000000..d80eaef --- /dev/null +++ b/core/src/economy/sims/README.md @@ -0,0 +1,27 @@ +# M3 simulator family + +Seven native simulator engines live here behind the Tcl M3 hub. + +| ID | Engine | Native language | Implemented kernel | +|---|---|---|---| +| M3a | statistical | R | V1 complete: GBM/Merton/Heston, CF option calibration, GARCH, HMM/Viterbi, fitted rough vol, DCC+t-copula, Bayesian+ARIMA, VaR/ES, empirical scoring, 7 typed predictions, price+DEX-pool calibration | +| M3b | sociological | ECLiPSe Prolog | V1 complete: 5 archetypes, replicator + UCB learning, adaptive HK, complex contagion, HJB/FP MFG, pump/dump ABM, 9 bounded predictions, persistent populations, empirical scoring | +| M3c | AMM/liquidity | Solidity + Foundry | V1 complete: x*y=k, IL/slippage, concentrated positions, LP/JIT strategies, backrun/sandwich pops, two-pool routing, 5 bounded predictions, price+pool calibration | +| M3d | MEV/adversarial | Fortran 2018 | all-pay PGA, block knapsack, cross-chain path comparison, sandwich score | +| M3e | tokenomics/macro | Fortran 2018 | Euler-Maruyama, stock-flow conservation, kinked lending, directional contagion, yield weights | +| M3f | consensus/staking | ECLiPSe Prolog | honesty replicator, validator Markov transitions, incentive threshold, liveness | +| M3g | microstructure | Fortran 2018 | depth/slippage, spread, Almgren-Chriss schedule, arb decay, impact fit | + +`registry.tcl` is the canonical engine inventory. `scheduler.tcl` is the live six-horizon wall→sim clock. It starts at 90 simulated seconds per wall second for tick/hourly and accelerates the longer horizons according to the M3 spec. + +Run all locally available native tests: + +```sh +tclsh core/src/economy/sims/run_tests.tcl +``` + +Pass `--strict` when the environment is expected to contain every external runtime. + +The Fortran engines are verified with `gfortran -std=f2018 -Wall -Wextra -Werror -pedantic`. M3a has a dedicated GitHub Actions R job that runs both the native statistical suite and the `M2 price_tick → R → M3 hub` Tcl integration suite. R is installed by the repo SessionStart hook in remote sessions. ECLiPSe and Foundry remain separately hosted toolchains, matching the existing M3 design. M3c has a dedicated Foundry workflow that runs the native Solidity suite and a Tcl boundary test against a stateless query contract on an ephemeral local Anvil instance; M3b has a dedicated ECLiPSe workflow covering the native sociological suite plus persistent M2→M3b→Hub population evolution and walk-forward correctness. + +This directory contains simulators only. Nothing here broadcasts transactions or bypasses M1 Marketplace, M4 wallet brakes, or D1. diff --git a/core/src/economy/sims/amm/README.md b/core/src/economy/sims/amm/README.md new file mode 100644 index 0000000..4e6f46b --- /dev/null +++ b/core/src/economy/sims/amm/README.md @@ -0,0 +1,27 @@ +# M3c — AMM & liquidity simulator + +M3c V1 is the Solidity-native AMM simulator behind the stomach's `amm_liquidity` prediction type. + +Implemented mechanics: fee-adjusted constant-product swaps; exact fixed-point impermanent loss; nonlinear slippage; IL-derived withdrawal thresholds; active LP rebalance; just-in-time liquidity fee economics; deterministic backrun and sandwich simulation; concentrated-liquidity position amounts and volatility/horizon range forecasts; deterministic exact-input splitting across two pools. + +The five public prediction types are `impermanent_loss`, `pool_return`, `optimal_range`, `slippage_estimate`, and `lp_withdrawal_threshold`. Every publication remains a numeric `BoundedPrediction` with explicit lower/value/upper bounds. + +Calibration consumes normalized M2 `dex_pool_state` and `price_tick` histories. Source confidence sets the uncertainty width; recent literal pool-state history supplies a retrospective correctness score. + +The live simulation boundary is: + +`M2 → AMMRunner (Tcl) → AMMQuery (read-only eth_call) → AMMSim → SimsHub → Marketplace` + +`AMMQuery.sol` is stateless and exposes only pure query methods. It has no transfer, approval, swap, signer, broadcaster, or privileged function. CI deploys it only to a fresh ephemeral local Anvil instance. + +V1 concentrated liquidity covers position/range accounting, not full initialized-tick traversal. V1 multi-pool routing optimizes across two pools; N-way routing is a scaling extension. + +Verification: + +```sh +cd core/src/economy/sims/amm +forge test -vv +tclsh integration.test +``` + +The dedicated M3c workflow enforces both the native Foundry suite and the Tcl M2→M3c→Hub summary. diff --git a/core/src/economy/sims/amm/foundry.toml b/core/src/economy/sims/amm/foundry.toml new file mode 100644 index 0000000..3ede138 --- /dev/null +++ b/core/src/economy/sims/amm/foundry.toml @@ -0,0 +1,6 @@ +[profile.default] +src = "src" +test = "test" +solc_version = "0.8.24" +optimizer = true +optimizer_runs = 200 diff --git a/core/src/economy/sims/amm/integration.test b/core/src/economy/sims/amm/integration.test new file mode 100644 index 0000000..6b11e30 --- /dev/null +++ b/core/src/economy/sims/amm/integration.test @@ -0,0 +1,54 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +proc seed_m3c {s ticker} { + for {set i 0} {$i < 24} {incr i} { + set price [expr {100.0 * exp(0.0008*$i + 0.01*sin($i/4.0))}] + $s feed_publish price_tick synthetic [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.2 + set r0 [expr {1000.0 + 2.0*$i}] + set r1 [expr {$r0 * $price / 100.0}] + $s feed_publish dex_pool_state dex [expr {$i*3600}] [dict create token_ticker $ticker reserve0 $r0 reserve1 $r1 fee_bps 30 volume 5000.0 tvl 2000.0 trade_size 10.0] 8.8 + } +} + +test m3c-runner-available-1.0 {Foundry-backed AMM runner is available in M3c CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s amm_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3c-to-hub-1.0 {pool and price feeds produce bounded pool return in M3 hub} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-amm amm_liquidity + seed_m3c $s TEST + set p [$s amm_from_feed TEST pool_return weekly] + set q [$s query_predictions trader-amm amm_liquidity] + set out [list [dict get $p sim_type] [dict get $p prediction_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $p time_horizon]] + $s destroy + set out +} -result {amm_liquidity pool_return 1 1 TEST 7d} + +test m3c-optimal-range-1.0 {volatility range is exposed as a bounded M3c prediction} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3c $s RANGE + set p [$s amm_from_feed RANGE optimal_range monthly] + set out [list [dict get $p prediction_type] [expr {[dict get $p lower_bound] < [dict get $p value]}] [expr {[dict get $p value] < [dict get $p upper_bound]}] [dict get $p calibration_sources]] + $s destroy + set out +} -result {optimal_range 1 1 price_tick,dex_pool_state} + +test m3c-insufficient-pool-history-1.0 {M3c refuses a query without pool state} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 24} {incr i} { + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s amm_from_feed TEST pool_return weekly} msg] + $s destroy + list $code $msg +} -result {1 insufficient_pool_history} + +cleanupTests diff --git a/core/src/economy/sims/amm/runner.tcl b/core/src/economy/sims/amm/runner.tcl new file mode 100644 index 0000000..c1e98c4 --- /dev/null +++ b/core/src/economy/sims/amm/runner.tcl @@ -0,0 +1,247 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::AMMRunner { + variable runtime rpc address + + constructor {} { + set runtime cast + set rpc "" + set address "" + if {[info exists ::env(AMM_RPC_URL)]} { + set rpc $::env(AMM_RPC_URL) + } + if {[info exists ::env(AMM_QUERY_ADDRESS)]} { + set address $::env(AMM_QUERY_ADDRESS) + } + } + + method available {} { + if {[auto_execok $runtime] eq ""} { return 0 } + if {$rpc eq "" || $address eq ""} { return 0 } + return [regexp {^0x[0-9A-Fa-f]{40}$} $address] + } + + method _prediction_index {prediction_type} { + set names { + impermanent_loss + pool_return + optimal_range + slippage_estimate + lp_withdrawal_threshold + } + set i [lsearch -exact $names $prediction_type] + if {$i < 0} { error "unknown_prediction_type" } + return $i + } + + method _horizon {horizon} { + switch -- $horizon { + tick_hourly { return [list 3600 1h] } + daily { return [list 86400 24h] } + weekly { return [list 604800 7d] } + monthly { return [list 2592000 30d] } + annual { return [list 31536000 1y] } + five_year { return [list 157680000 5y] } + default { error "unknown_horizon" } + } + } + + method _decimal_wad {value} { + set s [string trim $value] + if {[regexp {^([+-]?)([0-9]+)(?:\.([0-9]*))?$} $s -> sign whole frac]} { + if {$frac eq ""} { set frac "" } + set frac [string range "${frac}000000000000000000" 0 17] + set whole_dec [string trimleft $whole 0] + set frac_dec [string trimleft $frac 0] + if {$whole_dec eq ""} { set whole_dec 0 } + if {$frac_dec eq ""} { set frac_dec 0 } + set n [expr {$whole_dec * 1000000000000000000 + $frac_dec}] + if {$sign eq "-"} { set n [expr {-$n}] } + return $n + } + if {![string is double -strict $s]} { error "invalid_decimal" } + return [format %.0f [expr {double($s) * 1.0e18}]] + } + + method _wad_double {value} { + expr {double($value) / 1.0e18} + } + + method _scalar {function_name prediction_index raw} { + if {![my available]} { error "amm_runtime_unavailable" } + if {[llength $raw] != 11} { error "invalid_amm_state" } + set arr "\[[join $raw ,]\]" + set sig "${function_name}(uint8,uint256\[11\])(int256)" + set output [exec $runtime call --rpc-url $rpc $address $sig $prediction_index $arr] + set output [string trim $output] + if {![regexp {^-?[0-9]+} $output value]} { + error "invalid_amm_output" + } + return $value + } + + method _raw_prediction {prediction_type raw} { + set kind [my _prediction_index $prediction_type] + set value [my _scalar queryValue $kind $raw] + set lower [my _scalar queryLower $kind $raw] + set upper [my _scalar queryUpper $kind $raw] + if {$lower > $value || $value > $upper} { error "amm_prediction_out_of_bounds" } + return [dict create value_wad $value lower_wad $lower upper_wad $upper] + } + + method _filter_prices {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $payload price} price] || ![string is double -strict $price] || $price <= 0} { continue } + lappend out [dict create price $price timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _filter_pools {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $payload reserve0} r0] || + [catch {dict get $payload reserve1} r1] || + ![string is double -strict $r0] || + ![string is double -strict $r1] || + $r0 <= 0 || $r1 <= 0} { continue } + lappend out $datum + } + return $out + } + + method _volatility {prices} { + if {[llength $prices] < 3} { return 0.2 } + set returns {} + set spacings {} + for {set i 1} {$i < [llength $prices]} {incr i} { + set a [lindex $prices [expr {$i-1}]] + set b [lindex $prices $i] + set pa [dict get $a price] + set pb [dict get $b price] + if {$pa > 0 && $pb > 0} { + lappend returns [expr {log(double($pb)/double($pa))}] + } + set ta [dict get $a timestamp] + set tb [dict get $b timestamp] + if {[string is double -strict $ta] && [string is double -strict $tb] && $tb > $ta} { + lappend spacings [expr {double($tb)-double($ta)}] + } + } + if {[llength $returns] < 2} { return 0.2 } + set sum 0.0 + foreach x $returns { set sum [expr {$sum+$x}] } + set mean [expr {$sum/double([llength $returns])}] + set ss 0.0 + foreach x $returns { set ss [expr {$ss+($x-$mean)*($x-$mean)}] } + set sd [expr {sqrt($ss/double([llength $returns]-1))}] + set dt 86400.0 + if {[llength $spacings]} { + set total 0.0 + foreach x $spacings { set total [expr {$total+$x}] } + set dt [expr {$total/double([llength $spacings])}] + } + if {$dt <= 0} { set dt 86400.0 } + set annualized [expr {$sd*sqrt(31536000.0/$dt)}] + if {$annualized < 0.0001} { set annualized 0.0001 } + if {$annualized > 5.0} { set annualized 5.0 } + return $annualized + } + + method _uncertainty_bps {price_conf pool_conf} { + set c [expr {(double($price_conf)+double($pool_conf))/2.0}] + if {$c < 0} { set c 0 } + if {$c > 10} { set c 10 } + set bps [expr {round(100.0 + (10.0-$c)*200.0)}] + if {$bps < 50} { set bps 50 } + if {$bps > 2500} { set bps 2500 } + return $bps + } + + method _state_from_pool {pool price_ratio external_price volatility uncertainty_bps horizon_seconds} { + set payload [dict get $pool payload] + set x [my _decimal_wad [dict get $payload reserve0]] + set y [my _decimal_wad [dict get $payload reserve1]] + set fee 30 + if {[dict exists $payload fee_bps]} { set fee [dict get $payload fee_bps] } + if {![string is integer -strict $fee] || $fee < 0 || $fee >= 10000} { error "invalid_pool_fee" } + + set volume 0.0 + if {[dict exists $payload volume]} { set volume [dict get $payload volume] } + set tvl [expr {double([dict get $payload reserve0]) + double([dict get $payload reserve1])}] + if {[dict exists $payload tvl]} { set tvl [dict get $payload tvl] } + if {![string is double -strict $tvl] || $tvl <= 0} { error "invalid_pool_tvl" } + + set trade [expr {double([dict get $payload reserve0]) * 0.01}] + if {[dict exists $payload trade_size]} { set trade [dict get $payload trade_size] } + if {![string is double -strict $trade] || $trade <= 0} { error "invalid_trade_size" } + + return [list $x $y $fee [my _decimal_wad $volume] [my _decimal_wad $tvl] [my _decimal_wad $price_ratio] [my _decimal_wad $external_price] [my _decimal_wad $volatility] [my _decimal_wad $trade] $uncertainty_bps $horizon_seconds] + } + + method _correctness {pools price_ratio external_price volatility uncertainty_bps horizon_seconds} { + set n [llength $pools] + if {$n < 2} { return 5.0 } + set start [expr {max(0,$n-4)}] + set hits 0 + set total 0 + for {set i $start} {$i < $n-1} {incr i} { + set prev [my _state_from_pool [lindex $pools $i] $price_ratio $external_price $volatility $uncertainty_bps $horizon_seconds] + set next [my _state_from_pool [lindex $pools [expr {$i+1}]] $price_ratio $external_price $volatility $uncertainty_bps $horizon_seconds] + set pred [my _raw_prediction slippage_estimate $prev] + set actualKind [my _prediction_index slippage_estimate] + set actual [my _scalar queryValue $actualKind $next] + if {$actual >= [dict get $pred lower_wad] && $actual <= [dict get $pred upper_wad]} { + incr hits + } + incr total + } + if {$total == 0} { return 5.0 } + return [expr {10.0*double($hits)/double($total)}] + } + + method query_history {ticker prediction_type horizon price_history pool_history} { + if {![my available]} { error "amm_runtime_unavailable" } + set prices [my _filter_prices $price_history $ticker] + set pools [my _filter_pools $pool_history $ticker] + if {![llength $pools]} { error "insufficient_pool_history" } + if {[llength $prices] < 2} { error "insufficient_price_history" } + + lassign [my _horizon $horizon] horizon_seconds horizon_label + set first [lindex $prices 0] + set last [lindex $prices end] + set first_price [dict get $first price] + set last_price [dict get $last price] + set price_ratio [expr {double($last_price)/double($first_price)}] + set volatility [my _volatility $prices] + set pool_conf [dict get [lindex $pools end] confidence] + set price_conf [dict get $last confidence] + set uncertainty_bps [my _uncertainty_bps $price_conf $pool_conf] + + set raw [my _state_from_pool [lindex $pools end] $price_ratio $last_price $volatility $uncertainty_bps $horizon_seconds] + set native [my _raw_prediction $prediction_type $raw] + set value [my _wad_double [dict get $native value_wad]] + set lower [my _wad_double [dict get $native lower_wad]] + set upper [my _wad_double [dict get $native upper_wad]] + + set confidence [expr {(double($price_conf)+double($pool_conf))/2.0}] + if {$confidence < 0} { set confidence 0 } + if {$confidence > 10} { set confidence 10 } + set correctness [my _correctness $pools $price_ratio $last_price $volatility $uncertainty_bps $horizon_seconds] + set denom [expr {max(abs($value),1.0e-9)}] + set relative_width [expr {abs($upper-$lower)/$denom}] + set certainty [expr {$confidence/(1.0+min($relative_width,5.0))}] + if {$certainty < 0} { set certainty 0 } + if {$certainty > 10} { set certainty 10 } + + set recent_shift [expr {double($last_price)/double($first_price)-1.0}] + return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type amm_liquidity token_ticker $ticker recent_shift $recent_shift prediction_type $prediction_type calibration_sources price_tick,dex_pool_state timestamp [clock seconds]] + } +} diff --git a/core/src/economy/sims/amm/src/AMMQuery.sol b/core/src/economy/sims/amm/src/AMMQuery.sol new file mode 100644 index 0000000..15499d8 --- /dev/null +++ b/core/src/economy/sims/amm/src/AMMQuery.sol @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; + +import "./AMMSim.sol"; + +/// @notice Read-only ABI bridge for M3c. This contract contains no storage, +/// transfer, approval, swap execution, or privileged method. It exists so the +/// Tcl coordinator can evaluate the Solidity-native simulator with eth_call. +contract AMMQuery { + function _query( + uint8 predictionType, + uint256[11] calldata raw + ) private pure returns (AMMSim.BoundedPrediction memory p) { + require(predictionType < 5, "prediction type"); + AMMSim.PoolState memory s = AMMSim.PoolState({ + x: raw[0], + y: raw[1], + feeBps: raw[2], + volumeWad: raw[3], + tvlWad: raw[4], + priceRatioWad: raw[5], + externalPriceWad: raw[6], + volatilityWad: raw[7], + tradeSizeWad: raw[8], + uncertaintyBps: raw[9], + horizonSeconds: raw[10] + }); + return AMMSim.predict(AMMSim.PredictionType(predictionType), s); + } + + function queryValue( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).value; + } + + function queryLower( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).lower; + } + + function queryUpper( + uint8 predictionType, + uint256[11] calldata raw + ) external pure returns (int256) { + return _query(predictionType, raw).upper; + } +} diff --git a/core/src/economy/sims/amm/src/AMMSim.sol b/core/src/economy/sims/amm/src/AMMSim.sol new file mode 100644 index 0000000..806c1b4 --- /dev/null +++ b/core/src/economy/sims/amm/src/AMMSim.sol @@ -0,0 +1,616 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; + +library AMMSim { + uint256 internal constant WAD = 1e18; + uint256 internal constant BPS = 10_000; + + struct Pool { + uint256 x; + uint256 y; + uint256 feeBps; + } + + struct ArbitrageResult { + bool zeroForOne; + uint256 amountIn; + uint256 amountOut; + int256 profitQuote; + uint256 postPriceWad; + } + + struct SandwichResult { + uint256 frontOut; + uint256 victimOut; + uint256 backOut; + int256 profitToken0; + } + + enum PredictionType { + ImpermanentLoss, + PoolReturn, + OptimalRange, + SlippageEstimate, + LpWithdrawalThreshold + } + + struct PoolState { + uint256 x; + uint256 y; + uint256 feeBps; + uint256 volumeWad; + uint256 tvlWad; + uint256 priceRatioWad; + uint256 externalPriceWad; + uint256 volatilityWad; + uint256 tradeSizeWad; + uint256 uncertaintyBps; + uint256 horizonSeconds; + } + + struct BoundedPrediction { + int256 value; + int256 lower; + int256 upper; + } + + function amountOut(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256 dy) { + require(x > 0 && y > 0 && dx > 0 && feeBps < BPS, "bad pool"); + uint256 dxEff = dx * (BPS - feeBps) / BPS; + dy = y * dxEff / (x + dxEff); + require(dy < y, "drain"); + } + + function sqrt(uint256 a) internal pure returns (uint256 z) { + if (a == 0) return 0; + z = 1 << ((log2(a) + 1) >> 1); + unchecked { + for (uint256 i=0; i<7; ++i) z = (z + a/z) >> 1; + uint256 z1 = a/z; + if (z1 < z) z = z1; + } + } + function log2(uint256 x) internal pure returns (uint256 r) { + while (x > 1) { x >>= 1; ++r; } + } + + function impermanentLossWad(uint256 ratioWad) internal pure returns (int256) { + require(ratioWad > 0, "ratio"); + uint256 rootWad = sqrt(ratioWad * WAD); + uint256 relativeWad = 2 * rootWad * WAD / (WAD + ratioWad); + return int256(relativeWad) - int256(WAD); + } + + function slippageWad(uint256 x, uint256 y, uint256 dx, uint256 feeBps) internal pure returns (uint256) { + uint256 dy = amountOut(x,y,dx,feeBps); + uint256 spotWad = y * WAD / x; + uint256 execWad = dy * WAD / dx; + return execWad >= spotWad ? 0 : (spotWad-execWad)*WAD/spotWad; + } + + function lpShouldWithdraw(uint256 feeIncomeWad, uint256 ratioWad) internal pure returns (bool) { + int256 il = impermanentLossWad(ratioWad); + uint256 loss = il < 0 ? uint256(-il) : 0; + return loss > feeIncomeWad; + } + + + function lpShouldRebalance( + uint256 feeIncomeWad, + uint256 rebalanceCostWad, + uint256 ratioWad + ) internal pure returns (bool) { + int256 il = impermanentLossWad(ratioWad); + uint256 loss = il < 0 ? uint256(-il) : 0; + return loss > feeIncomeWad + rebalanceCostWad; + } + + function jitFeeIncomeWad( + uint256 volumeWad, + uint256 feeBps, + uint256 ownLiquidity, + uint256 totalLiquidity + ) internal pure returns (uint256) { + require(feeBps < BPS, "fee"); + require(totalLiquidity > 0 && ownLiquidity <= totalLiquidity, "liquidity"); + uint256 grossFees = volumeWad * feeBps / BPS; + return grossFees * ownLiquidity / totalLiquidity; + } + + function jitShouldProvide( + uint256 volumeWad, + uint256 feeBps, + uint256 ownLiquidity, + uint256 totalLiquidity, + uint256 entryExitCostWad + ) internal pure returns (bool) { + return jitFeeIncomeWad( + volumeWad, feeBps, ownLiquidity, totalLiquidity + ) > entryExitCostWad; + } + + + function feeYieldWad( + uint256 volumeWad, + uint256 feeBps, + uint256 tvlWad + ) internal pure returns (uint256) { + require(tvlWad > 0 && feeBps < BPS, "yield"); + uint256 fees = volumeWad * feeBps / BPS; + return fees * WAD / tvlWad; + } + + function withdrawalUpperRatioWad( + uint256 feeIncomeWad + ) internal pure returns (uint256) { + require(feeIncomeWad < WAD, "fee income"); + if (feeIncomeWad == 0) return WAD; + + uint256 retained = WAD - feeIncomeWad; + uint256 discriminant = + WAD * WAD - retained * retained; + uint256 root = sqrt(discriminant); + uint256 sqrtRatioWad = + (WAD + root) * WAD / retained; + return sqrtRatioWad * sqrtRatioWad / WAD; + } + + function _int(uint256 x) private pure returns (int256) { + require(x <= uint256(type(int256).max), "int overflow"); + return int256(x); + } + + function _min3( + int256 a, int256 b, int256 c0 + ) private pure returns (int256) { + int256 m = a < b ? a : b; + return m < c0 ? m : c0; + } + + function _max3( + int256 a, int256 b, int256 c0 + ) private pure returns (int256) { + int256 m = a > b ? a : b; + return m > c0 ? m : c0; + } + + function _scaledByUncertainty( + uint256 value, + uint256 uncertaintyBps, + bool upper + ) private pure returns (uint256) { + require(uncertaintyBps < BPS, "uncertainty"); + uint256 factor = upper + ? BPS + uncertaintyBps + : BPS - uncertaintyBps; + return value * factor / BPS; + } + + function _ilPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 loRatio = _scaledByUncertainty( + s.priceRatioWad, s.uncertaintyBps, false + ); + uint256 hiRatio = _scaledByUncertainty( + s.priceRatioWad, s.uncertaintyBps, true + ); + int256 a = impermanentLossWad(loRatio); + int256 b = impermanentLossWad(s.priceRatioWad); + int256 c0 = impermanentLossWad(hiRatio); + p.value = b; + p.lower = _min3(a, b, c0); + p.upper = _max3(a, b, c0); + if (loRatio <= WAD && hiRatio >= WAD) { + p.upper = 0; + } + } + + function _poolReturnPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + BoundedPrediction memory il = _ilPrediction(s); + uint256 lowVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, false + ); + uint256 highVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, true + ); + int256 fee = _int( + feeYieldWad(s.volumeWad, s.feeBps, s.tvlWad) + ); + int256 lowFee = _int( + feeYieldWad(lowVolume, s.feeBps, s.tvlWad) + ); + int256 highFee = _int( + feeYieldWad(highVolume, s.feeBps, s.tvlWad) + ); + p.value = fee + il.value; + p.lower = lowFee + il.lower; + p.upper = highFee + il.upper; + } + + function _optimalRangePrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + require( + s.externalPriceWad > 0 && s.horizonSeconds > 0, + "range" + ); + uint256 yearSeconds = 365 days; + uint256 fractionWad = + s.horizonSeconds * WAD / yearSeconds; + uint256 sqrtTimeWad = sqrt(fractionWad * WAD); + uint256 widthWad = + 2 * s.volatilityWad * sqrtTimeWad / WAD; + if (widthWad > 9e17) widthWad = 9e17; + + p.value = _int(s.externalPriceWad); + p.lower = _int( + s.externalPriceWad * (WAD - widthWad) / WAD + ); + p.upper = _int( + s.externalPriceWad * (WAD + widthWad) / WAD + ); + } + + function _slippagePrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 lowTrade = _scaledByUncertainty( + s.tradeSizeWad, s.uncertaintyBps, false + ); + uint256 highTrade = _scaledByUncertainty( + s.tradeSizeWad, s.uncertaintyBps, true + ); + p.value = _int( + slippageWad(s.x, s.y, s.tradeSizeWad, s.feeBps) + ); + p.lower = _int( + slippageWad(s.x, s.y, lowTrade, s.feeBps) + ); + p.upper = _int( + slippageWad(s.x, s.y, highTrade, s.feeBps) + ); + } + + function _thresholdPrediction( + PoolState memory s + ) private pure returns (BoundedPrediction memory p) { + uint256 lowVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, false + ); + uint256 highVolume = _scaledByUncertainty( + s.volumeWad, s.uncertaintyBps, true + ); + uint256 fee = feeYieldWad( + s.volumeWad, s.feeBps, s.tvlWad + ); + uint256 lowFee = feeYieldWad( + lowVolume, s.feeBps, s.tvlWad + ); + uint256 highFee = feeYieldWad( + highVolume, s.feeBps, s.tvlWad + ); + if (fee >= WAD) fee = WAD - 1; + if (lowFee >= WAD) lowFee = WAD - 1; + if (highFee >= WAD) highFee = WAD - 1; + + p.value = _int(withdrawalUpperRatioWad(fee)); + p.lower = _int(withdrawalUpperRatioWad(lowFee)); + p.upper = _int(withdrawalUpperRatioWad(highFee)); + } + + function predict( + PredictionType predictionType, + PoolState memory s + ) internal pure returns (BoundedPrediction memory) { + require( + s.x > 0 && s.y > 0 && + s.tvlWad > 0 && + s.priceRatioWad > 0 && + s.tradeSizeWad > 0 && + s.feeBps < BPS && + s.uncertaintyBps < BPS, + "bad state" + ); + + if (predictionType == PredictionType.ImpermanentLoss) { + return _ilPrediction(s); + } + if (predictionType == PredictionType.PoolReturn) { + return _poolReturnPrediction(s); + } + if (predictionType == PredictionType.OptimalRange) { + return _optimalRangePrediction(s); + } + if (predictionType == PredictionType.SlippageEstimate) { + return _slippagePrediction(s); + } + return _thresholdPrediction(s); + } + + + + function _optimalInputForMarginal( + Pool memory pool, + uint256 targetMarginalWad + ) private pure returns (uint256) { + if (_marginalOutWad( + pool.x, pool.y, 0, pool.feeBps + ) <= targetMarginalWad) { + return 0; + } + + uint256 lo = 0; + uint256 hi = pool.x; + for (uint256 i = 0; i < 8; ++i) { + if (_marginalOutWad( + pool.x, pool.y, hi, pool.feeBps + ) <= targetMarginalWad) break; + require(hi <= type(uint256).max / 2, "arb range"); + hi *= 2; + } + + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + if (_marginalOutWad( + pool.x, pool.y, mid, pool.feeBps + ) > targetMarginalWad) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } + + function _signedDifference( + uint256 positive, + uint256 negative + ) private pure returns (int256) { + require( + positive <= uint256(type(int256).max) && + negative <= uint256(type(int256).max), + "signed overflow" + ); + return int256(positive) - int256(negative); + } + + function backrunToPrice( + uint256 x, + uint256 y, + uint256 externalPriceWad, + uint256 feeBps + ) internal pure returns (ArbitrageResult memory r) { + require( + x > 0 && y > 0 && externalPriceWad > 0 && feeBps < BPS, + "bad arb" + ); + uint256 poolPriceWad = y * WAD / x; + if (poolPriceWad == externalPriceWad) { + r.postPriceWad = poolPriceWad; + return r; + } + + if (poolPriceWad > externalPriceWad) { + r.zeroForOne = true; + Pool memory pool = Pool({x: x, y: y, feeBps: feeBps}); + r.amountIn = _optimalInputForMarginal( + pool, externalPriceWad + ); + if (r.amountIn == 0) { + r.postPriceWad = poolPriceWad; + return r; + } + r.amountOut = amountOut(x, y, r.amountIn, feeBps); + uint256 newX = x + r.amountIn; + uint256 newY = y - r.amountOut; + r.postPriceWad = newY * WAD / newX; + uint256 externalCost = r.amountIn * externalPriceWad / WAD; + r.profitQuote = _signedDifference( + r.amountOut, externalCost + ); + return r; + } + + uint256 reciprocalPriceWad = WAD * WAD / externalPriceWad; + Pool memory reversePool = Pool({x: y, y: x, feeBps: feeBps}); + r.amountIn = _optimalInputForMarginal( + reversePool, reciprocalPriceWad + ); + if (r.amountIn == 0) { + r.postPriceWad = poolPriceWad; + return r; + } + r.amountOut = amountOut(y, x, r.amountIn, feeBps); + uint256 newY2 = y + r.amountIn; + uint256 newX2 = x - r.amountOut; + r.postPriceWad = newY2 * WAD / newX2; + uint256 externalValue = r.amountOut * externalPriceWad / WAD; + r.profitQuote = _signedDifference( + externalValue, r.amountIn + ); + } + + function simulateSandwich( + uint256 x, + uint256 y, + uint256 victimDx, + uint256 attackerDx, + uint256 feeBps + ) internal pure returns (SandwichResult memory r) { + require( + x > 0 && y > 0 && victimDx > 0 && + attackerDx > 0 && feeBps < BPS, + "bad sandwich" + ); + + r.frontOut = amountOut(x, y, attackerDx, feeBps); + uint256 x1 = x + attackerDx; + uint256 y1 = y - r.frontOut; + + r.victimOut = amountOut(x1, y1, victimDx, feeBps); + uint256 x2 = x1 + victimDx; + uint256 y2 = y1 - r.victimOut; + + r.backOut = amountOut( + y2, x2, r.frontOut, feeBps + ); + r.profitToken0 = _signedDifference( + r.backOut, attackerDx + ); + } + + /// @notice Token amounts represented by concentrated liquidity L at a + /// current sqrt-price. All sqrt-prices are WAD-scaled. + function concentratedAmounts( + uint256 liquidity, + uint256 sqrtLowerWad, + uint256 sqrtPriceWad, + uint256 sqrtUpperWad + ) internal pure returns (uint256 amount0, uint256 amount1) { + require( + liquidity > 0 && + sqrtLowerWad > 0 && + sqrtLowerWad < sqrtUpperWad, + "bad range" + ); + + if (sqrtPriceWad <= sqrtLowerWad) { + amount0 = + liquidity * + (sqrtUpperWad - sqrtLowerWad) / + sqrtLowerWad * + WAD / + sqrtUpperWad; + return (amount0, 0); + } + + if (sqrtPriceWad >= sqrtUpperWad) { + amount1 = + liquidity * + (sqrtUpperWad - sqrtLowerWad) / + WAD; + return (0, amount1); + } + + amount0 = + liquidity * + (sqrtUpperWad - sqrtPriceWad) / + sqrtPriceWad * + WAD / + sqrtUpperWad; + amount1 = + liquidity * + (sqrtPriceWad - sqrtLowerWad) / + WAD; + } + + function _amountOutOrZero( + uint256 x, + uint256 y, + uint256 dx, + uint256 feeBps + ) private pure returns (uint256) { + if (dx == 0) return 0; + return amountOut(x, y, dx, feeBps); + } + + function _marginalOutWad( + uint256 x, + uint256 y, + uint256 dx, + uint256 feeBps + ) private pure returns (uint256) { + require(x > 0 && y > 0 && feeBps < BPS, "bad pool"); + uint256 gamma = BPS - feeBps; + uint256 dxEff = dx * gamma / BPS; + uint256 denom = x + dxEff; + + // d(amountOut)/d(raw input), WAD-scaled. Keeping the divisions late + // preserves enough precision for the router without floating point. + return y * x * gamma * WAD / BPS / denom / denom; + } + + /// @notice Split one exact-input swap across two constant-product pools. + /// The optimum is where their marginal outputs equalize; binary search is + /// deterministic because each pool's marginal output is monotone. + function _routeOutput( + Pool memory a, + Pool memory b, + uint256 dx, + uint256 splitA + ) private pure returns (uint256) { + return + _amountOutOrZero(a.x, a.y, splitA, a.feeBps) + + _amountOutOrZero(b.x, b.y, dx - splitA, b.feeBps); + } + + function _bestSplit( + Pool memory a, + Pool memory b, + uint256 dx + ) private pure returns (uint256 splitA, uint256 totalOut) { + uint256 lo = 0; + uint256 hi = dx; + + for (uint256 i = 0; i < 64 && lo < hi; ++i) { + uint256 mid = lo + (hi - lo) / 2; + if ( + _marginalOutWad(a.x, a.y, mid, a.feeBps) > + _marginalOutWad(b.x, b.y, dx - mid, b.feeBps) + ) { + lo = mid + 1; + } else { + hi = mid; + } + } + + splitA = lo; + totalOut = _routeOutput(a, b, dx, splitA); + + if (splitA > 0) { + uint256 alt = splitA - 1; + uint256 altOut = _routeOutput(a, b, dx, alt); + if (altOut > totalOut) { + splitA = alt; + totalOut = altOut; + } + } + + uint256 onlyA = _routeOutput(a, b, dx, dx); + if (onlyA > totalOut) { + splitA = dx; + totalOut = onlyA; + } + + uint256 onlyB = _routeOutput(a, b, dx, 0); + if (onlyB > totalOut) { + splitA = 0; + totalOut = onlyB; + } + } + + /// @notice Split one exact-input swap across two constant-product pools. + /// The optimum is where their marginal outputs equalize. + function bestSplitTwoPools( + uint256 xA, + uint256 yA, + uint256 xB, + uint256 yB, + uint256 dx, + uint256 feeABps, + uint256 feeBBps + ) internal pure returns (uint256 splitA, uint256 totalOut) { + require( + xA > 0 && yA > 0 && xB > 0 && yB > 0 && + dx > 0 && feeABps < BPS && feeBBps < BPS, + "bad route" + ); + return _bestSplit( + Pool({x: xA, y: yA, feeBps: feeABps}), + Pool({x: xB, y: yB, feeBps: feeBBps}), + dx + ); + }} diff --git a/core/src/economy/sims/amm/test/AMMSim.t.sol b/core/src/economy/sims/amm/test/AMMSim.t.sol new file mode 100644 index 0000000..b9b9cde --- /dev/null +++ b/core/src/economy/sims/amm/test/AMMSim.t.sol @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.24; +import "../src/AMMSim.sol"; +contract AMMSimTest { + function testInvariantDirection() public pure { + uint256 x=1000e18; uint256 y=1000e18; uint256 dx=10e18; + uint256 dy=AMMSim.amountOut(x,y,dx,30); + require(dy>0 && dy= x*y, "k lower by rounding"); + } + function testImpermanentLossKnownRatio() public pure { + int256 il=AMMSim.impermanentLossWad(4e18); + int256 expected=-2e17; + int256 d=il-expected; if (d<0) d=-d; + require(d < 1e10, "IL formula"); + } + function testSlippageGrowsWithSize() public pure { + uint256 a=AMMSim.slippageWad(1000e18,1000e18,1e18,30); + uint256 b=AMMSim.slippageWad(1000e18,1000e18,100e18,30); + require(b>a, "slippage"); + } + function testWithdrawalDerivedFromIL() public pure { + require(AMMSim.lpShouldWithdraw(1e16,4e18), "withdraw"); + require(!AMMSim.lpShouldWithdraw(3e17,4e18), "stay"); + } + function testConcentratedLiquidityAmountsAtMidPrice() public pure { + (uint256 amount0,uint256 amount1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 2e18, 3e18 + ); + require(amount0 == 100e18, "amount0"); + require(amount1 == 600e18, "amount1"); + } + + function testConcentratedLiquidityBecomesOneSidedOutsideRange() public pure { + (uint256 below0,uint256 below1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 5e17, 3e18 + ); + require(below0 == 400e18 && below1 == 0, "below"); + (uint256 above0,uint256 above1)=AMMSim.concentratedAmounts( + 600e18, 1e18, 4e18, 3e18 + ); + require(above0 == 0 && above1 == 1200e18, "above"); + } + + function testSplitRoutingUsesBothPoolsAndImprovesOutput() public pure { + uint256 dx=100e18; + uint256 singleA=AMMSim.amountOut(1000e18,1000e18,dx,30); + uint256 singleB=AMMSim.amountOut(500e18,500e18,dx,30); + (uint256 splitA,uint256 totalOut)=AMMSim.bestSplitTwoPools( + 1000e18,1000e18,500e18,500e18,dx,30,30 + ); + require(splitA > 0 && splitA < dx, "must split"); + require(splitA > dx/2, "deeper pool gets more"); + require(totalOut > singleA && totalOut > singleB, "split improves"); + } + + function testActiveLpRebalanceComparesIlFeesAndCost() public pure { + require( + AMMSim.lpShouldRebalance(1e16, 5e15, 4e18), + "rebalance when IL dominates" + ); + require( + !AMMSim.lpShouldRebalance(25e16, 5e15, 4e18), + "stay when fees dominate" + ); + } + + function testJitLiquidityRequiresPositiveNetFeeShare() public pure { + uint256 income=AMMSim.jitFeeIncomeWad( + 1000e18, 30, 100e18, 1000e18 + ); + require(income == 3e17, "fee share"); + require( + AMMSim.jitShouldProvide( + 1000e18, 30, 100e18, 1000e18, 2e17 + ), + "profitable JIT" + ); + require( + !AMMSim.jitShouldProvide( + 1000e18, 30, 100e18, 1000e18, 4e17 + ), + "costly JIT" + ); + } + + function testBackrunMovesPoolTowardExternalPrice() public pure { + AMMSim.ArbitrageResult memory a=AMMSim.backrunToPrice( + 1000e18, 2000e18, 15e17, 30 + ); + require(a.amountIn > 0 && a.amountOut > 0, "arb size"); + require(a.zeroForOne, "x in"); + require(a.profitQuote > 0, "profitable"); + uint256 pre=2e18; + uint256 preError=pre > 15e17 ? pre-15e17 : 15e17-pre; + uint256 postError=a.postPriceWad > 15e17 + ? a.postPriceWad-15e17 + : 15e17-a.postPriceWad; + require(postError < preError, "price converges"); + } + + function testSandwichSimulationAccountsForBothLegs() public pure { + AMMSim.SandwichResult memory s=AMMSim.simulateSandwich( + 1000e18, 1000e18, 100e18, 10e18, 30 + ); + require(s.frontOut > 0 && s.victimOut > 0 && s.backOut > 0, "legs"); + require(s.profitToken0 > 0, "positive sandwich"); + require(s.victimOut < AMMSim.amountOut(1000e18,1000e18,100e18,30), "victim worsens"); + } + + function _basePoolState() private pure returns (AMMSim.PoolState memory s) { + s.x=1000e18; + s.y=1000e18; + s.feeBps=100; + s.volumeWad=5000e18; + s.tvlWad=1000e18; + s.priceRatioWad=4e18; + s.externalPriceWad=1e18; + s.volatilityWad=5e17; + s.tradeSizeWad=10e18; + s.uncertaintyBps=500; + s.horizonSeconds=7 days; + } + + function testWithdrawalThresholdIsDerivedFromIlFormula() public pure { + uint256 threshold=AMMSim.withdrawalUpperRatioWad(2e17); + uint256 d=threshold > 4e18 ? threshold-4e18 : 4e18-threshold; + require(d < 1e11, "20pct IL threshold"); + int256 il=AMMSim.impermanentLossWad(threshold); + int256 target=-2e17; + int256 e=il-target; if (e<0) e=-e; + require(e < 1e10, "threshold reproduces IL"); + } + + function testPoolReturnCombinesFeesAndImpermanentLoss() public pure { + AMMSim.PoolState memory s=_basePoolState(); + AMMSim.BoundedPrediction memory p=AMMSim.predict( + AMMSim.PredictionType.PoolReturn, s + ); + int256 expected=-15e16; + int256 d=p.value-expected; if (d<0) d=-d; + require(d < 1e12, "fees minus IL"); + require(p.lower <= p.value && p.value <= p.upper, "bounded"); + } + + function testOptimalRangeWidensWithVolatility() public pure { + AMMSim.PoolState memory low=_basePoolState(); + low.priceRatioWad=1e18; + low.volatilityWad=2e17; + AMMSim.PoolState memory high=_basePoolState(); + high.priceRatioWad=1e18; + high.volatilityWad=8e17; + AMMSim.BoundedPrediction memory a=AMMSim.predict( + AMMSim.PredictionType.OptimalRange, low + ); + AMMSim.BoundedPrediction memory b=AMMSim.predict( + AMMSim.PredictionType.OptimalRange, high + ); + require(b.upper-b.lower > a.upper-a.lower, "wider at high vol"); + require(a.lower <= a.value && a.value <= a.upper, "a bounded"); + require(b.lower <= b.value && b.value <= b.upper, "b bounded"); + } + + function testAllM3cPredictionKindsAreBounded() public pure { + AMMSim.PoolState memory s=_basePoolState(); + for (uint256 i=0; i<5; ++i) { + AMMSim.BoundedPrediction memory p=AMMSim.predict( + AMMSim.PredictionType(i), s + ); + require(p.lower <= p.value, "lower"); + require(p.value <= p.upper, "upper"); + } + } + +} diff --git a/core/src/economy/sims/consensus/engine.ecl b/core/src/economy/sims/consensus/engine.ecl new file mode 100644 index 0000000..ae23dbb --- /dev/null +++ b/core/src/economy/sims/consensus/engine.ecl @@ -0,0 +1,25 @@ +% M3f consensus/staking simulator kernels for ECLiPSe Prolog 7.2. + +honesty_step(Honest, HonestPayoff, AttackPayoff, Dt, Next) :- + Avg is Honest*HonestPayoff + (1-Honest)*AttackPayoff, + N0 is Honest + Dt*Honest*(HonestPayoff-Avg), + (N0 < 0 -> Next=0 ; N0 > 1 -> Next=1 ; Next=N0). + +required_slash_probability(HonestReward, AttackGain, SlashPenalty, P) :- + SlashPenalty > 0, + P0 is (AttackGain-HonestReward)/SlashPenalty, + (P0 < 0 -> P=0 ; P0 > 1 -> P=1 ; P=P0). + +markov_step(Dist, Matrix, Next) :- transpose(Matrix, T), dot_rows(T,Dist,Next). +dot_rows([],_,[]). +dot_rows([R|Rs],D,[X|Xs]) :- dot(R,D,X), dot_rows(Rs,D,Xs). +dot([],[],0.0). +dot([A|As],[B|Bs],X) :- dot(As,Bs,T), X is T+A*B. +transpose([],[]). +transpose([[]|_],[]) :- !. +transpose(M,[R|Rs]) :- heads_tails(M,R,T), transpose(T,Rs). +heads_tails([],[],[]). +heads_tails([[H|T]|Rows],[H|Hs],[T|Ts]) :- heads_tails(Rows,Hs,Ts). + +consensus_liveness(HonestFraction, Threshold, Liveness) :- + (HonestFraction >= Threshold -> Liveness=1.0 ; HonestFraction =< 0 -> Liveness=0.0 ; Liveness is HonestFraction/Threshold). diff --git a/core/src/economy/sims/consensus/test.ecl b/core/src/economy/sims/consensus/test.ecl new file mode 100644 index 0000000..2771d74 --- /dev/null +++ b/core/src/economy/sims/consensus/test.ecl @@ -0,0 +1,8 @@ +:- [engine]. +run :- + honesty_step(0.5,2.0,1.0,0.2,H), H > 0.5, + required_slash_probability(2.0,5.0,10.0,P), abs(P-0.3) < 0.000001, + markov_step([1.0,0.0],[[0.9,0.1],[0.2,0.8]],N), N=[A,B], abs(A-0.9)<0.000001, abs(B-0.1)<0.000001, + consensus_liveness(0.5,0.67,L), L < 1.0, + writeln('CONSENSUS TESTS PASSED'). +:- local initialization(run). diff --git a/core/src/economy/sims/hub.tcl b/core/src/economy/sims/hub.tcl new file mode 100644 index 0000000..6460bcf --- /dev/null +++ b/core/src/economy/sims/hub.tcl @@ -0,0 +1,29 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SimsHub { + variable predictions + constructor {} { set predictions {} } + method publish {sim_type prediction} { + foreach required {value lower_bound upper_bound confidence correctness certainty time_horizon token_ticker recent_shift timestamp} { + if {![dict exists $prediction $required]} { error "prediction_missing_$required" } + } + foreach numeric {value lower_bound upper_bound confidence correctness certainty recent_shift timestamp} { + if {![string is double -strict [dict get $prediction $numeric]]} { error "prediction_${numeric}_not_numeric" } + } + set value [dict get $prediction value]; set lo [dict get $prediction lower_bound]; set hi [dict get $prediction upper_bound] + if {$lo > $value || $value > $hi} { error "prediction_out_of_bounds" } + foreach metric {confidence correctness certainty} { + set v [dict get $prediction $metric] + if {$v < 0 || $v > 10} { error "prediction_${metric}_out_of_range" } + } + dict set prediction sim_type $sim_type + dict set prediction running 1 + dict set predictions $sim_type $prediction + return [dict create status published sim_type $sim_type] + } + method query {sim_type} { + if {![dict exists $predictions $sim_type]} { error "prediction_unavailable" } + return [dict get $predictions $sim_type] + } + method count {} { return [dict size $predictions] } +} diff --git a/core/src/economy/sims/mev/src/mev_engine.f90 b/core/src/economy/sims/mev/src/mev_engine.f90 new file mode 100644 index 0000000..47e61c9 --- /dev/null +++ b/core/src/economy/sims/mev/src/mev_engine.f90 @@ -0,0 +1,60 @@ +module mev_engine + implicit none +contains + subroutine pga_all_pay(bids, opportunity_value, profits, winner) + real(8), intent(in) :: bids(:), opportunity_value + real(8), intent(out) :: profits(size(bids)) + integer, intent(out) :: winner + integer :: i + winner = maxloc(bids, dim=1) + do i=1,size(bids) + profits(i) = -bids(i) + end do + profits(winner) = opportunity_value - bids(winner) + end subroutine + + subroutine knapsack_select(values, gas, gas_limit, selected, best_value) + real(8), intent(in) :: values(:) + integer, intent(in) :: gas(:), gas_limit + integer, intent(out) :: selected(size(values)) + real(8), intent(out) :: best_value + real(8), allocatable :: dp(:,:) + integer :: n, i, w + n = size(values) + allocate(dp(0:n,0:gas_limit)); dp = 0d0 + do i=1,n + do w=0,gas_limit + dp(i,w)=dp(i-1,w) + if (gas(i)<=w) dp(i,w)=max(dp(i,w), dp(i-1,w-gas(i))+values(i)) + end do + end do + best_value=dp(n,gas_limit); selected=0; w=gas_limit + do i=n,1,-1 + if (abs(dp(i,w)-dp(i-1,w))>1d-12) then + selected(i)=1; w=w-gas(i) + end if + end do + deallocate(dp) + end subroutine + + subroutine cross_chain_profit(p_src,p_dst,slippage,gas_cost,bridge_fee,depreciation,q,inventory_profit,bridge_profit) + real(8), intent(in) :: p_src,p_dst,slippage,gas_cost,bridge_fee,depreciation,q + real(8), intent(out) :: inventory_profit,bridge_profit + real(8) :: spread + spread = p_src-p_dst + inventory_profit = (spread-slippage-gas_cost)*q + bridge_profit = (spread-bridge_fee-depreciation)*q + end subroutine + + pure real(8) function sandwich_probability(trade_fraction, slippage_tolerance, liquidity_score) result(p) + real(8), intent(in) :: trade_fraction, slippage_tolerance, liquidity_score + real(8) :: z + z = 5d0*max(0d0,trade_fraction) + 3d0*max(0d0,slippage_tolerance) - 2d0*max(0d0,liquidity_score) + p = 1d0/(1d0+exp(-z)) + end function + + pure real(8) function all_pay_social_cost(bids) result(cost) + real(8), intent(in) :: bids(:) + cost = sum(max(bids,0d0)) + end function +end module diff --git a/core/src/economy/sims/mev/test/test_mev.f90 b/core/src/economy/sims/mev/test/test_mev.f90 new file mode 100644 index 0000000..f232d53 --- /dev/null +++ b/core/src/economy/sims/mev/test/test_mev.f90 @@ -0,0 +1,19 @@ +program test_mev + use mev_engine + implicit none + real(8) :: bids(3), profits(3), invp, bridgep + integer :: winner + integer :: gas(3), selected(3) + real(8) :: vals(3), best + bids = [1d0, 2d0, 3d0] + call pga_all_pay(bids, 10d0, profits, winner) + if (winner /= 3) error stop 'winner' + if (abs(profits(1) + 1d0) > 1d-9) error stop 'loser pays' + if (abs(profits(3) - 7d0) > 1d-9) error stop 'winner profit' + gas = [4, 5, 9]; vals = [6d0, 7d0, 12d0] + call knapsack_select(vals, gas, 9, selected, best) + if (abs(best - 13d0) > 1d-9) error stop 'knapsack optimum' + call cross_chain_profit(105d0, 100d0, 0.5d0, 0.2d0, 0.1d0, 0.8d0, 2d0, invp, bridgep) + if (invp <= bridgep) error stop 'inventory latency advantage' + print *, 'MEV TESTS PASSED' +end program diff --git a/core/src/economy/sims/microstructure/fpm.toml b/core/src/economy/sims/microstructure/fpm.toml new file mode 100644 index 0000000..83d6469 --- /dev/null +++ b/core/src/economy/sims/microstructure/fpm.toml @@ -0,0 +1,8 @@ +name = "sica-microstructure-sim" +version = "0.1.0" +[library] +source-dir = "src" +[[test]] +name = "microstructure" +source-dir = "test" +main = "test_microstructure.f90" diff --git a/core/src/economy/sims/microstructure/src/microstructure_engine.f90 b/core/src/economy/sims/microstructure/src/microstructure_engine.f90 new file mode 100644 index 0000000..af077cd --- /dev/null +++ b/core/src/economy/sims/microstructure/src/microstructure_engine.f90 @@ -0,0 +1,69 @@ +module microstructure_engine + implicit none +contains + real(8) function slippage_buy(ask_prices, ask_qty, order_qty) result(slip) + real(8), intent(in) :: ask_prices(:), ask_qty(:), order_qty + real(8) :: remain, take, cost, filled, best, vwap + integer :: i + if (order_qty<=0d0) then; slip=0d0; return; end if + remain=order_qty; cost=0d0; filled=0d0; best=ask_prices(1) + do i=1,size(ask_prices) + if (remain<=0d0) exit + take=min(remain,ask_qty(i)); cost=cost+take*ask_prices(i); filled=filled+take; remain=remain-take + end do + if (filled<=0d0 .or. remain>1d-12) then + slip=huge(1d0) + else + vwap=cost/filled; slip=(vwap-best)/best + end if + end function + + pure real(8) function bid_ask_spread(best_bid,best_ask) result(s) + real(8), intent(in) :: best_bid,best_ask + s=max(0d0,best_ask-best_bid) + end function + + subroutine almgren_chriss_schedule(total_qty,n_buckets,lambda,eta,sigma,risk_aversion,schedule) + real(8), intent(in) :: total_qty,lambda,eta,sigma,risk_aversion + integer, intent(in) :: n_buckets + real(8), intent(out) :: schedule(n_buckets) + real(8) :: kappa, denom, x_prev, x_next, t_next + integer :: i + if (n_buckets<=0) return + if (total_qty<=0d0) then; schedule=0d0; return; end if + if (eta<=0d0 .or. risk_aversion<=0d0 .or. sigma<=0d0) then + schedule=1d0/real(n_buckets,8); return + end if + kappa=sqrt(max(1d-15,(risk_aversion*sigma*sigma+max(lambda,0d0))/eta)) + denom=sinh(kappa) + if (abs(denom)<1d-12) then + schedule=1d0/real(n_buckets,8); return + end if + x_prev=1d0 + do i=1,n_buckets + t_next=real(i,8)/real(n_buckets,8) + x_next=sinh(kappa*(1d0-t_next))/denom + schedule(i)=max(0d0,x_prev-x_next) + x_prev=x_next + end do + if (sum(schedule)>0d0) schedule=schedule/sum(schedule) + end subroutine + + pure real(8) function arb_gap_decay(initial_gap, elapsed, tau) result(gap) + real(8), intent(in) :: initial_gap,elapsed,tau + if (tau<=0d0) then + gap=0d0 + else + gap=initial_gap*exp(-max(0d0,elapsed)/tau) + end if + end function + + subroutine fit_linear_impact(order_flow,price_change,lambda) + real(8), intent(in) :: order_flow(:),price_change(:) + real(8), intent(out) :: lambda + real(8) :: mx,my,varx,cov + mx=sum(order_flow)/size(order_flow); my=sum(price_change)/size(price_change) + varx=sum((order_flow-mx)**2); cov=sum((order_flow-mx)*(price_change-my)) + if (varx<=1d-15) then; lambda=0d0; else; lambda=cov/varx; end if + end subroutine +end module diff --git a/core/src/economy/sims/microstructure/test/test_microstructure.f90 b/core/src/economy/sims/microstructure/test/test_microstructure.f90 new file mode 100644 index 0000000..7dfe173 --- /dev/null +++ b/core/src/economy/sims/microstructure/test/test_microstructure.f90 @@ -0,0 +1,15 @@ +program test_microstructure + use microstructure_engine + implicit none + real(8) :: prices(3), qty(3), s1, s2, sched(5), gap1, gap2 + prices=[100d0,101d0,103d0]; qty=[1d0,2d0,10d0] + s1=slippage_buy(prices,qty,1d0) + s2=slippage_buy(prices,qty,6d0) + if (s2 <= s1) error stop 'slippage monotonic' + call almgren_chriss_schedule(100d0,5,0.01d0,0.05d0,0.02d0,1d0,sched) + if (abs(sum(sched)-1d0)>1d-8) error stop 'schedule sums' + if (minval(sched) < 0d0) error stop 'schedule nonnegative' + gap1=arb_gap_decay(0.05d0,0d0,10d0); gap2=arb_gap_decay(0.05d0,20d0,10d0) + if (gap2 >= gap1) error stop 'arb decays' + print *, 'MICROSTRUCTURE TESTS PASSED' +end program diff --git a/core/src/economy/sims/registry.tcl b/core/src/economy/sims/registry.tcl new file mode 100644 index 0000000..ecc5945 --- /dev/null +++ b/core/src/economy/sims/registry.tcl @@ -0,0 +1,30 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::EngineRegistry { + variable root engines + constructor {root_dir} { + set root [file normalize $root_dir] + set engines [dict create statistical [dict create lang r runtime Rscript source statistical/engine.R test statistical/tests.R] sociological [dict create lang eclipse_prolog runtime eclipse source sociological/engine.ecl test sociological/test.ecl] amm_liquidity [dict create lang solidity runtime forge source amm/src/AMMSim.sol test amm/test/AMMSim.t.sol] mev_adversarial [dict create lang fortran runtime gfortran source mev/src/mev_engine.f90 test mev/test/test_mev.f90] tokenomics_macro [dict create lang fortran runtime gfortran source tokenomics/src/tokenomics_engine.f90 test tokenomics/test/test_tokenomics.f90] consensus_staking [dict create lang eclipse_prolog runtime eclipse source consensus/engine.ecl test consensus/test.ecl] market_microstructure [dict create lang fortran runtime gfortran source microstructure/src/microstructure_engine.f90 test microstructure/test/test_microstructure.f90]] + } + method names {} { return [dict keys $engines] } + method descriptor {name} { + if {![dict exists $engines $name]} { error "unknown_engine" } + set d [dict get $engines $name] + dict set d source [file join $root [dict get $d source]] + dict set d test [file join $root [dict get $d test]] + return $d + } + method source_present {name} { return [file exists [dict get [my descriptor $name] source]] } + method runtime_available {name} { + set cmd [dict get [my descriptor $name] runtime] + expr {[auto_execok $cmd] ne ""} + } + method status {} { + set out {} + foreach name [my names] { + set d [my descriptor $name] + dict set out $name [dict create lang [dict get $d lang] source_present [my source_present $name] runtime_available [my runtime_available $name]] + } + return $out + } +} diff --git a/core/src/economy/sims/run_tests.tcl b/core/src/economy/sims/run_tests.tcl new file mode 100644 index 0000000..a22ab03 --- /dev/null +++ b/core/src/economy/sims/run_tests.tcl @@ -0,0 +1,78 @@ +# Polyglot M3 test driver. Missing externally hosted runtimes are reported as +# SKIP by default; pass --strict to make a missing runtime fail the run. +set here [file dirname [file normalize [info script]]] +set strict [expr {[lsearch -exact $argv --strict] >= 0}] +set failures 0 +set skipped 0 + +proc have {cmd} { expr {[auto_execok $cmd] ne ""} } +proc run_cmd {label cwd cmd} { + global failures + puts "=== $label ===" + set old [pwd] + cd $cwd + set code [catch {exec {*}$cmd 2>@1} out opts] + cd $old + if {$out ne ""} { puts $out } + if {$code} { + incr failures + puts "FAIL: $label" + return 0 + } + if {[string match "*Failed*" $out] && ![regexp {Failed[[:space:]]+0} $out]} { + incr failures + puts "FAIL: $label reported test failures" + return 0 + } + puts "PASS: $label" + return 1 +} +proc require_runtime {label cmd} { + global strict failures skipped + if {[have $cmd]} { return 1 } + if {$strict} { + incr failures + puts "FAIL: $label runtime '$cmd' missing" + } else { + incr skipped + puts "SKIP: $label runtime '$cmd' missing" + } + return 0 +} + +run_cmd "M3 hub registry + clocks" [file join $here tests] [list tclsh hub_runtime.test] + +set build /tmp/sica-m3-build +file mkdir $build +foreach spec { + {M3d-MEV mev mev_engine.f90 test_mev.f90} + {M3e-tokenomics tokenomics tokenomics_engine.f90 test_tokenomics.f90} + {M3g-microstructure microstructure microstructure_engine.f90 test_microstructure.f90} +} { + lassign $spec label dir engine test + if {[require_runtime $label gfortran]} { + set exe [file join $build $dir-test] + set src [file join $here $dir src $engine] + set tst [file join $here $dir test $test] + if {[run_cmd "$label compile" $here [list gfortran -std=f2018 -Wall -Wextra -Werror -pedantic -J $build $src $tst -o $exe]]} { + run_cmd "$label executable" $here [list $exe] + } + } +} + +if {[require_runtime M3a-statistical Rscript]} { + run_cmd M3a-statistical [file join $here statistical] [list Rscript tests.R] +} +if {[require_runtime M3b-sociological eclipse]} { + run_cmd M3b-sociological [file join $here sociological] [list eclipse -b test.ecl -e halt] +} +if {[require_runtime M3f-consensus eclipse]} { + run_cmd M3f-consensus [file join $here consensus] [list eclipse -b test.ecl -e halt] +} +if {[require_runtime M3c-AMM forge]} { + run_cmd M3c-AMM [file join $here amm] [list forge test] +} + +puts "=== M3 RESULT ===" +puts "failures=$failures skipped=$skipped strict=$strict" +exit [expr {$failures > 0 ? 1 : 0}] diff --git a/core/src/economy/sims/scheduler.tcl b/core/src/economy/sims/scheduler.tcl new file mode 100644 index 0000000..dfbebe5 --- /dev/null +++ b/core/src/economy/sims/scheduler.tcl @@ -0,0 +1,50 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::HorizonClock { + variable ratios simulated is_running after_id last_ms interval_ms + constructor {} { + set ratios [dict create tick_hourly 90 daily 2160 weekly 15120 monthly 64800 annual 788000 five_year 3942000] + set simulated {} + dict for {h r} $ratios { dict set simulated $h 0.0 } + set is_running 0 + set after_id "" + set last_ms 0 + set interval_ms 1000 + } + destructor { my stop } + method horizons {} { return [dict keys $ratios] } + method ratio {horizon} { + if {![dict exists $ratios $horizon]} { error "unknown_horizon" } + return [dict get $ratios $horizon] + } + method advance {wall_seconds} { + if {![string is double -strict $wall_seconds] || $wall_seconds < 0} { error "invalid_wall_seconds" } + dict for {h r} $ratios { + dict set simulated $h [expr {[dict get $simulated $h] + $wall_seconds*$r}] + } + return $simulated + } + method start {{pulse_ms 1000}} { + if {![string is integer -strict $pulse_ms] || $pulse_ms < 1} { error "invalid_pulse_ms" } + if {$is_running} { return } + set interval_ms $pulse_ms + set is_running 1 + set last_ms [clock milliseconds] + set after_id [after $interval_ms [list [self] pulse]] + } + method pulse {} { + if {!$is_running} { return } + set now [clock milliseconds] + set elapsed [expr {double($now-$last_ms)/1000.0}] + set last_ms $now + my advance $elapsed + set after_id [after $interval_ms [list [self] pulse]] + } + method stop {} { + if {$after_id ne ""} { after cancel $after_id } + set after_id "" + set is_running 0 + } + method running {} { return $is_running } + method state {} { return $simulated } +} diff --git a/core/src/economy/sims/sociological/README.md b/core/src/economy/sims/sociological/README.md new file mode 100644 index 0000000..6b6dbd3 --- /dev/null +++ b/core/src/economy/sims/sociological/README.md @@ -0,0 +1,26 @@ +# M3b — sociological simulator + +M3b V1 is the ECLiPSe-Prolog population simulator behind the stomach's `sociological` prediction type. + +V1 contains five abstract archetypes: retail herd, contrarian whale, MEV searcher, passive LP, and manipulator. It implements replicator dynamics, UCB bandit-replicator adaptation, adaptive Hegselmann–Krause bounded confidence, heterogeneous complex contagion, a one-dimensional HJB/Fokker–Planck mean-field equilibrium with damped Newton iteration, bounded-rationality pump/dump dynamics, opinion clustering, and nine public prediction types. + +The live boundary is: + +`M2 rss_news + price_tick → SociologicalRunner (Tcl) → ECLiPSe → SimsHub → Marketplace` + +Population state persists per ticker. Each query advances that state through ECLiPSe's native bandit-replicator relation before the requested prediction is evaluated. MFG stability is also computed by ECLiPSe, not reimplemented in Tcl. + +`correctness` is empirical: confidence/engagement-weighted social direction is compared walk-forward against the next realized price move. It is therefore usable as evidence for later cross-sim gating rather than as a source-count heuristic. + +The nine prediction types are `sentiment_index`, `herd_threshold`, `strategy_distribution`, `cascade_probability`, `coordination_stability`, `opinion_cluster_count`, `pump_dump_phase`, `mfg_equilibrium_stability`, and `narrative_regime`. + +No pop represents a literal person. M3b has no trading, signing, broadcasting, or transaction surface. + +Verification: + +```sh +eclipse -b core/src/economy/sims/sociological/test.ecl -e run_tests +tclsh core/src/economy/sims/sociological/integration.test +``` + +Dedicated CI enforces the native ECLiPSe suite and `6 passed / 0 failed` at the M2→M3b→Hub boundary. diff --git a/core/src/economy/sims/sociological/engine.ecl b/core/src/economy/sims/sociological/engine.ecl new file mode 100644 index 0000000..e697d8e --- /dev/null +++ b/core/src/economy/sims/sociological/engine.ecl @@ -0,0 +1,458 @@ +% M3b sociological simulator kernels for ECLiPSe Prolog 7.2. + +sum_list([], 0.0). +sum_list([X|Xs], S) :- sum_list(Xs, T), S is X + T. + +normalize([], []). +normalize(Xs, Ys) :- sum_list(Xs, S), S > 0, normalize_(Xs, S, Ys). +normalize_([], _, []). +normalize_([X|Xs], S, [Y|Ys]) :- Y is X/S, normalize_(Xs,S,Ys). + +weighted_mean([], [], 0.0). +weighted_mean([X|Xs],[P|Ps], M) :- weighted_mean(Xs,Ps,T), M is T + X*P. + +replicator_step(Shares, Payoffs, Dt, Next) :- + weighted_mean(Payoffs, Shares, Avg), + replicator_raw(Shares,Payoffs,Avg,Dt,Raw), normalize(Raw,Next). +replicator_raw([],[],_,_,[]). +replicator_raw([X|Xs],[P|Ps],Avg,Dt,[Y|Ys]) :- + Y0 is X + Dt*X*(P-Avg), (Y0 < 0 -> Y = 0 ; Y = Y0), + replicator_raw(Xs,Ps,Avg,Dt,Ys). + +hk_step(Opinions, Bound, Mu, Next) :- hk_all(Opinions,Opinions,Bound,Mu,Next). +hk_all([],_,_,_,[]). +hk_all([X|Xs],All,D,Mu,[Y|Ys]) :- neighbor_mean(All,X,D,M), Y is X + Mu*(M-X), hk_all(Xs,All,D,Mu,Ys). +neighbor_mean(All,X,D,M) :- collect_neighbors(All,X,D,Ns), sum_list(Ns,S), length(Ns,N), N > 0, M is S/N. +collect_neighbors([],_,_,[]). +collect_neighbors([Y|Ys],X,D,[Y|Ns]) :- abs(Y-X) =< D, !, collect_neighbors(Ys,X,D,Ns). +collect_neighbors([_|Ys],X,D,Ns) :- collect_neighbors(Ys,X,D,Ns). + +complex_contagion(Exposures, Degrees, Thresholds, Adoption) :- contagion_(Exposures,Degrees,Thresholds,Adoption). +contagion_([],[],[],[]). +contagion_([E|Es],[D|Ds],[T|Ts],[A|As]) :- + (D =< 0 -> Frac=0 ; Frac is E/D), + (E >= 2, Frac >= T -> A=1 ; A=0), + contagion_(Es,Ds,Ts,As). + +pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase) :- + (VolumeRatio > 2.0, Sentiment > 0.6, PriceDelta > 0.05 -> Phase=promotion ; + VolumeRatio > 2.0, PriceDelta < -0.05 -> Phase=collapse ; + VolumeRatio > 1.5, PriceDelta >= 0 -> Phase=distribution ; + Phase=accumulation). + + +% V1 behavioral archetypes. These are abstract population roles, never literal +% identities or profiles of real market participants. +archetype_catalog([ + retail_herd, + contrarian_whale, + mev_searcher, + passive_lp, + manipulator +]). + +ucb_score(_, Count, _, _, 1.0e9) :- + Count =< 0, !. +ucb_score(Mean, Count, Total, Explore, Score) :- + Count > 0, + ( Total =< 1 -> + Bonus = 0.0 + ; + Bonus is Explore * sqrt(ln(Total) / Count) + ), + Score is Mean + Bonus. + +ucb_scores([], [], _, _, []). +ucb_scores([Reward|Rewards], [Count|Counts], Total, Explore, [Score|Scores]) :- + ( Count =< 0 -> + Mean = 0.0 + ; + Mean is Reward / Count + ), + ucb_score(Mean, Count, Total, Explore, Score), + ucb_scores(Rewards, Counts, Total, Explore, Scores). + +bandit_replicator_step( + Shares, + RewardSums, + Counts, + Total, + Explore, + Dt, + Next, + Scores +) :- + ucb_scores(RewardSums, Counts, Total, Explore, Scores), + replicator_step(Shares, Scores, Dt, Next). + + +% --- Large-population mean-field game -------------------------------------- + +mfg_valid_population(N) :- integer(N), N >= 100. + +zeros_like([], []). +zeros_like([_|Xs], [0.0|Zs]) :- zeros_like(Xs, Zs). + +nth0_value([X|_], 0, X) :- !. +nth0_value([_|Xs], I, X) :- + I > 0, + I1 is I - 1, + nth0_value(Xs, I1, X). + +reflected_neighbor(List, I, N, X) :- + ( I < 0 -> + nth0_value(List, 0, X) + ; I >= N -> + Last is N - 1, + nth0_value(List, Last, X) + ; + nth0_value(List, I, X) + ). + +hjb_residual_at(M, U, I, N, Diffusion, Coupling, Residual) :- + nth0_value(U, I, Ui), + nth0_value(M, I, Mi), + IL is I - 1, + IR is I + 1, + reflected_neighbor(U, IL, N, UL), + reflected_neighbor(U, IR, N, UR), + Grad is (UR - UL) / 2.0, + Lap is UL - 2.0*Ui + UR, + Residual is Ui + 0.5*Grad*Grad - Coupling*Mi - Diffusion*Lap. + +hjb_residuals(M, U, Diffusion, Coupling, Residuals) :- + length(U, N), + hjb_residuals_(0, N, M, U, Diffusion, Coupling, Residuals). +hjb_residuals_(I, N, _, _, _, _, []) :- I >= N, !. +hjb_residuals_(I, N, M, U, Diffusion, Coupling, [R|Rs]) :- + hjb_residual_at(M, U, I, N, Diffusion, Coupling, R), + I1 is I + 1, + hjb_residuals_(I1, N, M, U, Diffusion, Coupling, Rs). + +newton_value_update([], [], _, _, []). +newton_value_update([U|Us], [R|Rs], Diffusion, Damping, [V|Vs]) :- + Denom is 1.0 + 2.0*Diffusion, + V is U - Damping*R/Denom, + newton_value_update(Us, Rs, Diffusion, Damping, Vs). + +hjb_newton_step(M, U, Diffusion, Coupling, Damping, Next, Residuals) :- + hjb_residuals(M, U, Diffusion, Coupling, Residuals), + newton_value_update(U, Residuals, Diffusion, Damping, Next). + +boltzmann_weights([], _, []). +boltzmann_weights([U|Us], Temperature, [W|Ws]) :- + W is exp(-U / Temperature), + boltzmann_weights(Us, Temperature, Ws). + +fp_stationary_density(U, Diffusion, Density) :- + ( Diffusion < 1.0e-6 -> Temp = 1.0e-6 ; Temp = Diffusion ), + boltzmann_weights(U, Temp, Raw), + normalize(Raw, Density). + +blend_density([], [], _, []). +blend_density([M|Ms], [T|Ts], Damping, [N|Ns]) :- + N0 is (1.0-Damping)*M + Damping*T, + ( N0 < 0.0 -> N = 0.0 ; N = N0 ), + blend_density(Ms, Ts, Damping, Ns). + +density_relax(M, Target, Damping, Next) :- + blend_density(M, Target, Damping, Raw), + normalize(Raw, Next). + +abs_list([], []). +abs_list([X|Xs], [A|As]) :- A is abs(X), abs_list(Xs, As). + +max_list([X|Xs], Max) :- max_list_(Xs, X, Max). +max_list_([], Max, Max). +max_list_([X|Xs], Acc, Max) :- + ( X > Acc -> Acc1 = X ; Acc1 = Acc ), + max_list_(Xs, Acc1, Max). + +list_l1([], [], 0.0). +list_l1([A|As], [B|Bs], D) :- + list_l1(As, Bs, Tail), + D is abs(A-B) + Tail. + +mfg_residual(M, U, Diffusion, Coupling, Residual) :- + hjb_residuals(M, U, Diffusion, Coupling, H), + abs_list(H, AbsH), + max_list(AbsH, HMax), + fp_stationary_density(U, Diffusion, Target), + list_l1(M, Target, FpResidual), + Residual is max(HMax, FpResidual). + +mfg_iter(0, M, U, Diffusion, Coupling, _, M, U, Residual) :- !, + mfg_residual(M, U, Diffusion, Coupling, Residual). +mfg_iter(K, M, U, Diffusion, Coupling, Damping, Density, Value, Residual) :- + K > 0, + hjb_newton_step(M, U, Diffusion, Coupling, Damping, U1, _), + fp_stationary_density(U1, Diffusion, Target), + density_relax(M, Target, Damping, M1), + K1 is K - 1, + mfg_iter(K1, M1, U1, Diffusion, Coupling, Damping, + Density, Value, Residual). + +mfg_equilibrium( + Population, + InitialDensity, + Diffusion, + Coupling, + Damping, + Iterations, + Density, + Value, + Stability, + Residual +) :- + mfg_valid_population(Population), + Diffusion > 0.0, + Coupling >= 0.0, + Damping > 0.0, + Damping =< 1.0, + integer(Iterations), + Iterations > 0, + normalize(InitialDensity, M0), + zeros_like(M0, U0), + mfg_iter(Iterations, M0, U0, Diffusion, Coupling, Damping, + Density, Value, Residual), + Stability is 1.0 / (1.0 + 10.0*Residual). + + +% --- Pump/dump three-population ABM ---------------------------------------- + +pump_phase_payoffs(accumulation, [1.00,1.10,1.30]). +pump_phase_payoffs(promotion, [1.15,1.35,2.00]). +pump_phase_payoffs(distribution, [0.85,1.20,1.45]). +pump_phase_payoffs(collapse, [0.70,1.40,0.20]). + +satisficing_payoff(Payoff, Aspiration, Limit, Effective) :- + Gap is Payoff - Aspiration, + ( Gap > Limit -> + Bounded = Limit + ; Gap < -Limit -> + Bounded is -Limit + ; + Bounded = Gap + ), + Effective is Aspiration + Bounded. + +satisficing_payoffs([], _, _, []). +satisficing_payoffs([P|Ps], Aspiration, Limit, [E|Es]) :- + satisficing_payoff(P, Aspiration, Limit, E), + satisficing_payoffs(Ps, Aspiration, Limit, Es). + +pump_abm_step( + Shares, + PriceDelta, + VolumeRatio, + Sentiment, + Dt, + Next, + Phase +) :- + Shares = [_,_,_], + pump_phase(PriceDelta, VolumeRatio, Sentiment, Phase), + pump_phase_payoffs(Phase, RawPayoffs), + satisficing_payoffs(RawPayoffs, 1.0, 0.75, Payoffs), + replicator_step(Shares, Payoffs, Dt, Next). + + +% --- Adaptive confidence, clusters, and bounded prediction contract -------- + +clamp_value(X, Lo, Hi, Y) :- + ( X < Lo -> Y = Lo + ; X > Hi -> Y = Hi + ; Y = X + ). + +adaptive_confidence_bound(Base, Volatility, Dispersion, Bound) :- + Base > 0.0, + Penalty is 0.35*Volatility + 0.45*Dispersion, + Raw is Base * (1.0 - Penalty), + clamp_value(Raw, 0.01, Base, Bound). + +opinion_cluster_count([], _, 0) :- !. +opinion_cluster_count(Opinions, Bound, Count) :- + Bound >= 0.0, + sort(Opinions, Sorted), + Sorted = [First|Rest], + cluster_count_sorted(Rest, First, Bound, 1, Count). + +cluster_count_sorted([], _, _, Count, Count). +cluster_count_sorted([X|Xs], Previous, Bound, Acc, Count) :- + Gap is X - Previous, + ( Gap > Bound -> Acc1 is Acc + 1 ; Acc1 = Acc ), + cluster_count_sorted(Xs, X, Bound, Acc1, Count). + +sentiment_label(Sentiment, bullish) :- Sentiment > 0.25, !. +sentiment_label(Sentiment, bearish) :- Sentiment < -0.25, !. +sentiment_label(_, neutral). + +narrative_label(Sentiment, PriceShift, bearish) :- + (Sentiment < -0.25 ; PriceShift < -0.05), !. +narrative_label(Sentiment, PriceShift, bullish) :- + Sentiment > 0.25, PriceShift >= 0.0, !. +narrative_label(_, _, neutral). + +dominant_strategy(Shares, Label, Share) :- + archetype_catalog(Labels), + Shares = [S|Ss], + Labels = [L|Ls], + dominant_strategy_(Ss, Ls, L, S, Label, Share). + +dominant_strategy_([], [], Label, Share, Label, Share). +dominant_strategy_([S|Ss], [L|Ls], BestL, BestS, Label, Share) :- + ( S > BestS -> + NextL = L, NextS = S + ; + NextL = BestL, NextS = BestS + ), + dominant_strategy_(Ss, Ls, NextL, NextS, Label, Share). + +bounded_unit(Value0, Width0, Value, Lower, Upper) :- + clamp_value(Value0, 0.0, 1.0, Value), + (Width0 < 0.0 -> Width = 0.0 ; Width = Width0), + L0 is Value - Width, + U0 is Value + Width, + clamp_value(L0, 0.0, 1.0, Lower), + clamp_value(U0, 0.0, 1.0, Upper). + +bounded_ten(Value0, Width0, Value, Lower, Upper) :- + clamp_value(Value0, 0.0, 10.0, Value), + (Width0 < 0.0 -> Width = 0.0 ; Width = Width0), + L0 is Value - Width, + U0 is Value + Width, + clamp_value(L0, 0.0, 10.0, Lower), + clamp_value(U0, 0.0, 10.0, Upper). + +horizon_scale(current, 0.50). +horizon_scale(hourly, 0.65). +horizon_scale(tick_hourly, 0.65). +horizon_scale(daily, 0.80). +horizon_scale(weekly, 1.00). +horizon_scale(monthly, 1.20). +horizon_scale(annual, 1.50). +horizon_scale(five_year, 1.80). + +horizon_width(Horizon, BaseWidth, Width) :- + horizon_scale(Horizon, Scale), + Width is BaseWidth * Scale. + +phase_code(accumulation, 0.25). +phase_code(promotion, 0.50). +phase_code(distribution, 0.75). +phase_code(collapse, 1.00). + +regime_code(bearish, 0.0). +regime_code(neutral, 0.5). +regime_code(bullish, 1.0). + +sociological_prediction( + sentiment_index, + state(Sentiment,Dispersion,_,_,_,_,_,_,_), + Horizon, + Value,Lower,Upper,Label +) :- !, + Raw is (Sentiment + 1.0) * 5.0, + BaseWidth is 0.5 + 4.0*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_ten(Raw, Width, Value, Lower, Upper), + sentiment_label(Sentiment, Label). + +sociological_prediction( + herd_threshold, + state(_,Dispersion,_,Volatility,_,_,_,_,_), + Horizon, + Value,Lower,Upper,herd_activation +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Value), + BaseWidth is 0.10 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Value, Width, Value, Lower, Upper). + +sociological_prediction( + strategy_distribution, + state(_,Dispersion,_,_,_,Shares,_,_,_), + Horizon, + Value,Lower,Upper,Label +) :- !, + dominant_strategy(Shares, Label, Dominant), + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Dominant, Width, Value, Lower, Upper). + +sociological_prediction( + cascade_probability, + state(_,Dispersion,_,Volatility,ExposureRate,_,_,_,_), + Horizon, + Value,Lower,Upper,complex_contagion +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Threshold), + E2 is ExposureRate*ExposureRate, + T2 is Threshold*Threshold, + ( E2 + T2 =< 0.0 -> Raw = 0.0 ; Raw is E2/(E2+T2) ), + BaseWidth is 0.05 + 0.25*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + coordination_stability, + state(_,Dispersion,_,Volatility,_,_,_,MfgStability,_), + Horizon, + Value,Lower,Upper,coordination +) :- !, + Raw is MfgStability * (1.0-Dispersion) * (1.0-0.25*Volatility), + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + opinion_cluster_count, + state(_,Dispersion,_,Volatility,_,_,_,_,Opinions), + Horizon, + Value,Lower,Upper,clusters +) :- !, + adaptive_confidence_bound(0.35, Volatility, Dispersion, Bound), + opinion_cluster_count(Opinions, Bound, Count), + length(Opinions, N), + Value is float(Count), + horizon_scale(Horizon, Scale), + L0 is max(1.0, Value-Scale), + U0 is min(float(N), Value+Scale), + Lower = L0, + Upper = U0. + +sociological_prediction( + pump_dump_phase, + state(Sentiment,Dispersion,PriceShift,_,ExposureRate,_,_,_,_), + Horizon, + Value,Lower,Upper,Phase +) :- !, + VolumeRatio is 1.0 + 2.0*ExposureRate, + pump_phase(PriceShift, VolumeRatio, Sentiment, Phase), + phase_code(Phase, Raw), + BaseWidth is 0.05 + 0.15*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Raw, Width, Value, Lower, Upper). + +sociological_prediction( + mfg_equilibrium_stability, + state(_,Dispersion,_,_,_,_,_,MfgStability,_), + Horizon, + Value,Lower,Upper,mfg +) :- !, + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(MfgStability, Width, Value, Lower, Upper). + +sociological_prediction( + narrative_regime, + state(Sentiment,Dispersion,PriceShift,_,_,_,_,_,_), + Horizon, + Value,Lower,Upper,Label +) :- !, + narrative_label(Sentiment, PriceShift, Label), + regime_code(Label, Raw), + BaseWidth is 0.05 + 0.20*Dispersion, + horizon_width(Horizon, BaseWidth, Width), + bounded_unit(Raw, Width, Value, Lower, Upper). diff --git a/core/src/economy/sims/sociological/integration.test b/core/src/economy/sims/sociological/integration.test new file mode 100644 index 0000000..5b96a7e --- /dev/null +++ b/core/src/economy/sims/sociological/integration.test @@ -0,0 +1,102 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +proc seed_m3b {s ticker} { + for {set i 0} {$i < 30} {incr i} { + set price [expr {100.0 * exp(0.0030*$i + 0.004*sin($i/4.0))}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.4 + } + + set sources {reddit social blog reddit social blog reddit social blog reddit social blog} + set i 0 + foreach source_type $sources { + set sentiment [expr {0.68 + 0.04*sin($i)}] + set engagement [expr {0.78 + 0.05*cos($i)}] + $s feed_publish rss_news $source_type [expr {$i*7200}] [dict create token_ticker $ticker source_type $source_type sentiment $sentiment engagement $engagement] 8.0 + incr i + } +} + +test m3b-runner-available-1.0 {ECLiPSe-backed sociological runner is available in M3b CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s sociological_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3b-to-hub-1.0 {social aggregate and price feeds publish a bounded sentiment state} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-social sociological + seed_m3b $s TEST + set p [$s sociological_from_feed TEST sentiment_index daily] + set q [$s query_predictions trader-social sociological] + set out [list [dict get $p sim_type] [dict get $p prediction_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $p time_horizon] [dict get $p calibration_sources]] + $s destroy + set out +} -result {sociological sentiment_index 1 1 TEST 24h rss_news,price_tick} + +test m3b-pump-phase-label-1.0 {aggregate promotion signature carries categorical phase label} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b $s PUMP + set p [$s sociological_from_feed PUMP pump_dump_phase daily] + set out [list [dict get $p prediction_type] [dict get $p label] [expr {[dict get $p lower_bound] <= [dict get $p value] && [dict get $p value] <= [dict get $p upper_bound]}]] + $s destroy + set out +} -result {pump_dump_phase promotion 1} + +test m3b-insufficient-social-history-1.0 {M3b refuses calibration without aggregate social evidence} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 20} {incr i} { + $s feed_publish price_tick exchange $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s sociological_from_feed TEST sentiment_index daily} msg] + $s destroy + list $code $msg +} -result {1 insufficient_social_history} + +test m3b-bandit-population-evolves-1.0 {live population state evolves through bandit-replicator learning} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b $s EVOLVE + set first [$s sociological_from_feed EVOLVE strategy_distribution daily] + + for {set i 30} {$i < 42} {incr i} { + set price [expr {110.0 * exp(0.008*($i-30))}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker EVOLVE price $price] 9.5 + $s feed_publish rss_news social [expr {$i*3600}] [dict create token_ticker EVOLVE source_type social sentiment 0.95 engagement 0.98] 9.2 + } + + set second [$s sociological_from_feed EVOLVE strategy_distribution daily] + set out [list [dict get $first population_model] [dict get $first population_epoch] [dict get $second population_epoch] [expr {[dict get $first population_shares] ne [dict get $second population_shares]}]] + $s destroy + set out +} -result {bandit_replicator 1 2 1} + +proc seed_m3b_accuracy {s ticker direction} { + for {set i 0} {$i < 16} {incr i} { + set sign [expr {$direction eq "up" ? 1.0 : -1.0}] + set price [expr {100.0 * exp($sign*0.008*$i)}] + $s feed_publish price_tick exchange [expr {$i*3600}] [dict create token_ticker $ticker price $price] 9.5 + } + set sources {reddit social blog reddit social blog reddit social blog} + set i 0 + foreach source_type $sources { + $s feed_publish rss_news $source_type [expr {($i+1)*3600-60}] [dict create token_ticker $ticker source_type $source_type sentiment 0.90 engagement 0.85] 9.0 + incr i + } +} + +test m3b-correctness-walk-forward-1.0 {correctness measures whether social direction predicts subsequent price movement} -body { + set s [::stomach::Economy new -history_cap 256] + seed_m3b_accuracy $s GOOD up + seed_m3b_accuracy $s BAD down + set good [$s sociological_from_feed GOOD sentiment_index daily] + set bad [$s sociological_from_feed BAD sentiment_index daily] + set out [list [expr {[dict get $good correctness] > 8.0}] [expr {[dict get $bad correctness] < 2.0}] [expr {[dict get $good correctness] > [dict get $bad correctness] + 6.0}]] + $s destroy + set out +} -result {1 1 1} + +cleanupTests diff --git a/core/src/economy/sims/sociological/runner.tcl b/core/src/economy/sims/sociological/runner.tcl new file mode 100644 index 0000000..9eccf7a --- /dev/null +++ b/core/src/economy/sims/sociological/runner.tcl @@ -0,0 +1,344 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::SociologicalRunner { + variable engine runtime populations epochs + + constructor {engine_path {runtime_cmd eclipse}} { + set engine [file normalize $engine_path] + set runtime $runtime_cmd + set populations {} + set epochs {} + } + + method available {} { + expr {[file exists $engine] && [auto_execok $runtime] ne ""} + } + + method _clamp {x lo hi} { + if {$x < $lo} { return $lo } + if {$x > $hi} { return $hi } + return $x + } + + method _fmt {x} { + if {![string is double -strict $x]} { error "invalid_numeric_state" } + format %.17g [expr {double($x)}] + } + + method _list_fmt {xs} { + set out {} + foreach x $xs { lappend out [my _fmt $x] } + return [format {[%s]} [join $out ,]] + } + + method _prediction_type {name} { + set allowed { + sentiment_index herd_threshold strategy_distribution + cascade_probability coordination_stability opinion_cluster_count + pump_dump_phase mfg_equilibrium_stability narrative_regime + } + if {[lsearch -exact $allowed $name] < 0} { error "unknown_prediction_type" } + return $name + } + + method _horizon {name} { + switch -- $name { + current { return [list current current] } + tick_hourly - + hourly { return [list hourly 1h] } + daily { return [list daily 24h] } + weekly { return [list weekly 7d] } + monthly { return [list monthly 30d] } + annual { return [list annual 1y] } + five_year { return [list five_year 5y] } + default { error "unknown_horizon" } + } + } + + method _filter_prices {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set p [dict get $datum payload] + if {[catch {dict get $p token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $p price} price] || + ![string is double -strict $price] || $price <= 0} { continue } + lappend out [dict create price [expr {double($price)}] timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _filter_social {history ticker} { + set out {} + foreach datum $history { + if {![dict exists $datum payload]} { continue } + set p [dict get $datum payload] + if {[catch {dict get $p token_ticker} token] || $token ne $ticker} { continue } + if {[catch {dict get $p sentiment} sentiment] || + ![string is double -strict $sentiment]} { continue } + set engagement 0.5 + if {[dict exists $p engagement] && + [string is double -strict [dict get $p engagement]]} { + set engagement [dict get $p engagement] + } + set source_type unknown + if {[dict exists $p source_type]} { set source_type [dict get $p source_type] } + lappend out [dict create sentiment [my _clamp [expr {double($sentiment)}] -1.0 1.0] engagement [my _clamp [expr {double($engagement)}] 0.0 1.0] source_type $source_type timestamp [dict get $datum timestamp] confidence [dict get $datum confidence]] + } + return $out + } + + method _weighted_social {social} { + set sumw 0.0 + set sums 0.0 + set sume 0.0 + foreach d $social { + set c [my _clamp [expr {double([dict get $d confidence])}] 0.0 10.0] + set e [dict get $d engagement] + set w [expr {max(0.05,$e) * max(0.1,$c/10.0)}] + set s [dict get $d sentiment] + set sumw [expr {$sumw+$w}] + set sums [expr {$sums+$w*$s}] + set sume [expr {$sume+$w*$e}] + } + if {$sumw <= 0} { error "invalid_social_weights" } + set mean [expr {$sums/$sumw}] + set exposure [expr {$sume/$sumw}] + set var 0.0 + foreach d $social { + set c [my _clamp [expr {double([dict get $d confidence])}] 0.0 10.0] + set e [dict get $d engagement] + set w [expr {max(0.05,$e) * max(0.1,$c/10.0)}] + set delta [expr {[dict get $d sentiment]-$mean}] + set var [expr {$var+$w*$delta*$delta}] + } + set dispersion [expr {sqrt($var/$sumw)}] + return [list [my _clamp $mean -1.0 1.0] [my _clamp $dispersion 0.0 1.0] [my _clamp $exposure 0.0 1.0]] + } + + method _price_stats {prices} { + set first [dict get [lindex $prices 0] price] + set last [dict get [lindex $prices end] price] + set shift [expr {$last/$first-1.0}] + set returns {} + set spacings {} + for {set i 1} {$i < [llength $prices]} {incr i} { + set a [lindex $prices [expr {$i-1}]] + set b [lindex $prices $i] + set pa [dict get $a price] + set pb [dict get $b price] + lappend returns [expr {log($pb/$pa)}] + set ta [dict get $a timestamp] + set tb [dict get $b timestamp] + if {[string is double -strict $ta] && + [string is double -strict $tb] && $tb > $ta} { + lappend spacings [expr {double($tb)-double($ta)}] + } + } + set vol 0.0 + if {[llength $returns] >= 2} { + set total 0.0 + foreach x $returns { set total [expr {$total+$x}] } + set mean [expr {$total/double([llength $returns])}] + set ss 0.0 + foreach x $returns { set ss [expr {$ss+($x-$mean)*($x-$mean)}] } + set sd [expr {sqrt($ss/double([llength $returns]-1))}] + set dt 86400.0 + if {[llength $spacings]} { + set sumdt 0.0 + foreach x $spacings { set sumdt [expr {$sumdt+$x}] } + set dt [expr {$sumdt/double([llength $spacings])}] + } + if {$dt <= 0} { set dt 86400.0 } + set vol [expr {$sd*sqrt(31536000.0/$dt)}] + } + return [list [my _clamp $shift -1.0 1.0] [my _clamp $vol 0.0001 1.0]] + } + + method _normalize {weights} { + set total 0.0 + foreach w $weights { set total [expr {$total+max(0.0,$w)}] } + if {$total <= 0} { error "invalid_population_weights" } + set out {} + foreach w $weights { lappend out [expr {max(0.0,$w)/$total}] } + return $out + } + + method _shares {sentiment volatility exposure} { + set a [expr {abs($sentiment)}] + set pos [expr {max(0.0,$sentiment)}] + return [my _normalize [list [expr {0.20+0.30*$a+0.15*$exposure}] [expr {0.15+0.25*(1.0-$a)}] [expr {0.10+0.25*$volatility}] [expr {0.25+0.25*(1.0-$volatility)}] [expr {0.05+0.25*$pos*$exposure}]]] + } + + method _pump_shares {sentiment exposure} { + set manip [expr {0.10+0.25*max(0.0,$sentiment)*$exposure}] + set analyst [expr {0.15+0.10*$exposure}] + set normal [expr {max(0.10,1.0-$analyst-$manip)}] + return [my _normalize [list $normal $analyst $manip]] + } + + method _mean_confidence {items} { + if {![llength $items]} { return 0.0 } + set total 0.0 + foreach d $items { set total [expr {$total+double([dict get $d confidence])}] } + my _clamp [expr {$total/double([llength $items])}] 0.0 10.0 + } + + method _walk_forward_correctness {prices social} { + set correct 0.0 + set total_weight 0.0 + foreach event $social { + set sentiment [dict get $event sentiment] + if {abs($sentiment) < 0.10} { continue } + set ts [dict get $event timestamp] + if {![string is double -strict $ts]} { continue } + + set before "" + set after "" + foreach point $prices { + set pts [dict get $point timestamp] + if {![string is double -strict $pts]} { continue } + if {$pts <= $ts} { + set before $point + continue + } + set after $point + break + } + if {$before eq "" || $after eq ""} { continue } + + set p0 [dict get $before price] + set p1 [dict get $after price] + set move [expr {$p1/$p0-1.0}] + if {abs($move) < 0.0005} { continue } + + set predicted [expr {$sentiment > 0 ? 1 : -1}] + set actual [expr {$move > 0 ? 1 : -1}] + set engagement [dict get $event engagement] + set confidence [my _clamp [expr {double([dict get $event confidence])}] 0.0 10.0] + set weight [expr {max(0.05,$engagement)*max(0.1,$confidence/10.0)}] + set total_weight [expr {$total_weight+$weight}] + if {$predicted == $actual} { + set correct [expr {$correct+$weight}] + } + } + if {$total_weight <= 0.0} { return 5.0 } + return [my _clamp [expr {10.0*$correct/$total_weight}] 0.0 10.0] + } + + method _bandit_update { + ticker initial_shares sentiment price_shift volatility exposure evidence_count + } { + if {![my available]} { error "eclipse_runtime_unavailable" } + + if {[dict exists $populations $ticker]} { + set shares [dict get $populations $ticker] + } else { + set shares $initial_shares + } + + set n [expr {max(1,int($evidence_count))}] + set positive [expr {max(0.0,$sentiment)}] + set aligned [expr {max(0.0,$sentiment*$price_shift)}] + set payoffs [list [expr {0.75+1.20*$aligned+0.35*$exposure}] [expr {0.80+0.60*abs($sentiment-$price_shift)}] [expr {0.70+1.40*$volatility}] [expr {1.15-0.65*$volatility}] [expr {0.45+1.60*$positive*$exposure+0.80*max(0.0,$price_shift)}]] + set reward_sums {} + foreach payoff $payoffs { + lappend reward_sums [expr {$payoff*$n}] + } + set counts [lrepeat 5 $n] + set total [expr {5*$n}] + + set goal [format { + bandit_replicator_step(%s,%s,%s,%d,0.6,0.25,[A,B,C,D,E],_), + printf("BANDIT %%w %%w %%w %%w %%w%%n",[A,B,C,D,E]) + } [my _list_fmt $shares] [my _list_fmt $reward_sums] [my _list_fmt $counts] $total] + set output [exec $runtime -b $engine -e $goal] + if {![regexp {BANDIT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)} $output -> a b cc d e]} { + error "invalid_bandit_output" + } + set next [my _normalize [list [expr {double($a)}] [expr {double($b)}] [expr {double($cc)}] [expr {double($d)}] [expr {double($e)}]]] + dict set populations $ticker $next + + set epoch 1 + if {[dict exists $epochs $ticker]} { + set epoch [expr {[dict get $epochs $ticker]+1}] + } + dict set epochs $ticker $epoch + return [list $next $epoch] + } + + method _mfg_stability {shares} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set density [my _list_fmt $shares] + set goal [format { + mfg_equilibrium(500,%s,0.12,0.08,0.35,60,_,_,S,_), + printf("MFG %%w%%n",[S]) + } $density] + set output [exec $runtime -b $engine -e $goal] + if {![regexp {MFG[[:space:]]+([-+0-9.eE]+)} $output -> value] || + ![string is double -strict $value]} { + error "invalid_mfg_output" + } + return [my _clamp [expr {double($value)}] 0.0 1.0] + } + + method _prediction {prediction_type state horizon_atom} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set type [my _prediction_type $prediction_type] + set goal [format { + sociological_prediction(%s,%s,%s,V,L,U,Label), + printf("RESULT %%w %%w %%w %%w%%n",[V,L,U,Label]) + } $type $state $horizon_atom] + set output [exec $runtime -b $engine -e $goal] + if {![regexp {RESULT[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([-+0-9.eE]+)[[:space:]]+([^[:space:]]+)} $output -> value lower upper label]} { + error "invalid_sociological_output" + } + foreach x [list $value $lower $upper] { + if {![string is double -strict $x]} { error "invalid_sociological_output" } + } + return [dict create value [expr {double($value)}] lower [expr {double($lower)}] upper [expr {double($upper)}] label $label] + } + + method query_history {ticker prediction_type horizon price_history social_history} { + if {![my available]} { error "eclipse_runtime_unavailable" } + set prices [my _filter_prices $price_history $ticker] + set social [my _filter_social $social_history $ticker] + if {[llength $social] < 3} { error "insufficient_social_history" } + if {[llength $prices] < 3} { error "insufficient_price_history" } + + lassign [my _horizon $horizon] horizon_atom horizon_label + lassign [my _weighted_social $social] sentiment dispersion exposure + lassign [my _price_stats $prices] price_shift volatility + set initial_shares [my _shares $sentiment $volatility $exposure] + lassign [my _bandit_update $ticker $initial_shares $sentiment $price_shift $volatility $exposure [llength $social]] shares population_epoch + set pump_shares [my _pump_shares $sentiment $exposure] + set stability [my _mfg_stability $shares] + + set opinions {} + foreach d $social { + lappend opinions [my _clamp [expr {([dict get $d sentiment]+1.0)/2.0}] 0.0 1.0] + } + set state [format {state(%s,%s,%s,%s,%s,%s,%s,%s,%s)} [my _fmt $sentiment] [my _fmt $dispersion] [my _fmt $price_shift] [my _fmt $volatility] [my _fmt $exposure] [my _list_fmt $shares] [my _list_fmt $pump_shares] [my _fmt $stability] [my _list_fmt $opinions]] + + set native [my _prediction $prediction_type $state $horizon_atom] + set value [dict get $native value] + set lower [dict get $native lower] + set upper [dict get $native upper] + if {$lower > $value || $value > $upper} { + error "sociological_prediction_out_of_bounds" + } + + set social_conf [my _mean_confidence $social] + set price_conf [my _mean_confidence $prices] + set confidence [my _clamp [expr {0.65*$social_conf+0.35*$price_conf}] 0.0 10.0] + set width [expr {abs($upper-$lower)}] + set scale [expr {max(abs($value),1.0)}] + set certainty [my _clamp [expr {$confidence/(1.0+$width/$scale)}] 0.0 10.0] + + # Empirical correctness: does signed aggregate social evidence predict + # the next observed price move in walk-forward order? + set correctness [my _walk_forward_correctness $prices $social] + + return [dict create value $value lower_bound $lower upper_bound $upper confidence $confidence correctness $correctness certainty $certainty time_horizon $horizon_label sim_type sociological token_ticker $ticker recent_shift $price_shift prediction_type $prediction_type label [dict get $native label] calibration_sources rss_news,price_tick population_model bandit_replicator population_epoch $population_epoch population_shares [join $shares ,] timestamp [clock seconds]] + } +} diff --git a/core/src/economy/sims/sociological/test.ecl b/core/src/economy/sims/sociological/test.ecl new file mode 100644 index 0000000..b42541d --- /dev/null +++ b/core/src/economy/sims/sociological/test.ecl @@ -0,0 +1,191 @@ +:- [engine]. + +approx(A, B, Eps) :- Diff is abs(A-B), Diff =< Eps. + +must(Name, Goal) :- + ( call(Goal) -> + true + ; + printf(error, "FAILED: %w%n", [Name]), + fail + ). + +prediction_types([ + sentiment_index, + herd_threshold, + strategy_distribution, + cascade_probability, + coordination_stability, + opinion_cluster_count, + pump_dump_phase, + mfg_equilibrium_stability, + narrative_regime +]). + +check_prediction_types([], _, _). +check_prediction_types([Type|Types], State, Horizon) :- + sociological_prediction(Type,State,Horizon,V,L,U,_), + number(V), number(L), number(U), + L =< V, V =< U, + check_prediction_types(Types,State,Horizon). + +run_tests :- + must(replicator_normalizes, + (replicator_step([0.5,0.5],[1.0,2.0],0.2,N), + N=[A,B], Sum is A+B, approx(Sum,1.0,1.0e-9), B > 0.5)), + + must(hk_clusters_local_neighbors, + (hk_step([0.0,0.1,0.9,1.0],0.2,1.0,H), + H=[H1,H2,H3,H4], + approx(H1,0.05,1.0e-9), + approx(H2,0.05,1.0e-9), + approx(H3,0.95,1.0e-9), + approx(H4,0.95,1.0e-9))), + + must(complex_contagion_needs_threshold, + (complex_contagion([1,3],[4,4],[0.5,0.5],Ad), + Ad=[0,1])), + + must(complex_contagion_requires_multiple_exposures, + (complex_contagion([1,2,3],[1,2,4],[0.1,0.5,0.75],Multi), + Multi=[0,1,1])), + + must(pump_phase_promotion, + pump_phase(0.10,2.5,0.8,promotion)), + + must(archetype_catalog_v1, + archetype_catalog([ + retail_herd, + contrarian_whale, + mev_searcher, + passive_lp, + manipulator + ])), + + must(ucb_rewards_exploration, + (ucb_score(0.2,10,100,0.7,S1), + ucb_score(0.8,10,100,0.7,S2), + S2 > S1)), + + must(bandit_replicator_adapts, + (bandit_replicator_step( + [0.5,0.5], + [2.0,9.0], + [10,10], + 20, + 0.6, + 0.25, + Next, + Scores + ), + Next=[N1,N2], + Scores=[U1,U2], + U2 > U1, + N2 > N1, + SumN is N1+N2, + approx(SumN,1.0,1.0e-9))), + + + must(mfg_population_guard, + (not(mfg_valid_population(99)), + mfg_valid_population(100), + mfg_valid_population(1000))), + + must(mfg_equilibrium_normalized_and_stable, + (mfg_equilibrium( + 250, + [0.10,0.20,0.40,0.20,0.10], + 0.12, + 0.08, + 0.35, + 80, + Density, + Value, + Stability, + Residual + ), + Density=[D1,D2,D3,D4,D5], + SumD is D1+D2+D3+D4+D5, + approx(SumD,1.0,1.0e-6), + D1 >= 0.0, D2 >= 0.0, D3 >= 0.0, D4 >= 0.0, D5 >= 0.0, + length(Value,5), + Stability >= 0.0, Stability =< 1.0, + Residual >= 0.0, Residual < 0.25)), + + + must(pump_abm_promotion_selects_manipulators, + (pump_abm_step( + [0.80,0.10,0.10], + 0.10,3.0,0.85,0.25, + Promotion,promotion + ), + Promotion=[_,_,PromoMP], + PromoMP > 0.10)), + + must(pump_abm_collapse_selects_against_manipulators, + (pump_abm_step( + [0.70,0.15,0.15], + -0.12,3.2,0.20,0.25, + Collapse,collapse + ), + Collapse=[_,_,CollapseMP], + CollapseMP < 0.15)), + + + must(adaptive_hk_tightens_under_uncertainty, + (adaptive_confidence_bound(0.35,0.20,0.10,Loose), + adaptive_confidence_bound(0.35,0.90,0.50,Tight), + Tight < Loose, + Tight > 0.01)), + + must(opinion_cluster_count_detects_groups, + (opinion_cluster_count([0.10,0.12,0.50,0.52,0.90],0.08,Clusters), + Clusters =:= 3)), + + must(all_m3b_prediction_types_bounded, + (State=state( + 0.70, + 0.20, + 0.08, + 0.60, + 0.65, + [0.40,0.20,0.15,0.15,0.10], + [0.70,0.15,0.15], + 0.80, + [0.10,0.12,0.50,0.52,0.90] + ), + prediction_types(Types), + check_prediction_types(Types,State,weekly))), + + must(categorical_predictions_keep_labels, + (State2=state( + 0.85,0.15,0.10,0.50,0.75, + [0.45,0.15,0.10,0.10,0.20], + [0.70,0.10,0.20], + 0.75, + [0.70,0.72,0.75,0.80] + ), + sociological_prediction(pump_dump_phase,State2,daily,PV,PL,PU,PLabel), + PL =< PV, PV =< PU, + PLabel = promotion, + sociological_prediction(narrative_regime,State2,monthly,NV,NL,NU,NLabel), + NL =< NV, NV =< NU, + NLabel = bullish)), + + + must(multi_horizon_uncertainty_widens, + (HState=state( + 0.40,0.15,0.03,0.45,0.50, + [0.45,0.20,0.15,0.15,0.05], + [0.80,0.10,0.10], + 0.85, + [0.35,0.40,0.45,0.50] + ), + sociological_prediction(sentiment_index,HState,hourly,HV,HL,HU,_), + sociological_prediction(sentiment_index,HState,five_year,FV,FL,FU,_), + approx(HV,FV,1.0e-9), + HWidth is HU-HL, + FWidth is FU-FL, + FWidth > HWidth)), + + writeln("SOCIOLOGICAL TESTS PASSED"). diff --git a/core/src/economy/sims/statistical/README.md b/core/src/economy/sims/statistical/README.md new file mode 100644 index 0000000..8e56090 --- /dev/null +++ b/core/src/economy/sims/statistical/README.md @@ -0,0 +1,24 @@ +# M3a — statistical simulator + +M3a V1 is the R-native quantitative simulator behind the stomach's statistical prediction type. + +Implemented models: GBM; Merton jump diffusion; Heston full-truncation SDE; Heston characteristic-function call pricing and option-surface calibration; GARCH(1,1) QMLE; three-state Gaussian HMM with Viterbi decoding; Davies–Harte fractional Gaussian noise; fitted rough-vol H and eta; fitted DCC correlation; Student-t copula tail dependence; conjugate Bayesian return calibration; ARIMA; historical VaR / Expected Shortfall; jump-intensity estimation; empirical walk-forward quality scoring. + +The seven public prediction types are `price_forecast`, `volatility_surface`, `var_calculation`, `correlation_matrix`, `regime_state`, `rough_vol_estimate`, and `jump_intensity`. Every hub publication remains numerically bounded. Regime labels and matrix detail are metadata, not exceptions to the hub bound invariant. + +Calibration consumes normalized M2 `price_tick` history and optional `dex_pool_state` observations. Pool price is liquidity weighted and cross-venue disagreement reduces certainty rather than replacing literal price-tick ground truth. + +The live boundary is: + +`M2 → StatisticalRunner (Tcl) → engine.R → SimsHub → Marketplace` + +No function in M3a signs, broadcasts, routes, or submits transactions. + +Verification: + +```sh +Rscript core/src/economy/sims/statistical/tests.R +tclsh core/src/economy/sims/statistical/integration.test +``` + +GitHub Actions enforces both the native R suite and the Tcl summary (`5 passed / 0 failed`). diff --git a/core/src/economy/sims/statistical/engine.R b/core/src/economy/sims/statistical/engine.R new file mode 100644 index 0000000..9593f99 --- /dev/null +++ b/core/src/economy/sims/statistical/engine.R @@ -0,0 +1,1480 @@ +# M3a statistical & quantitative simulator. +# Base R only: no Python bridge and no runtime dependency on CRAN packages. +# The heavier CRAN stack in the design remains optional acceleration/validation. + +clamp <- function(x, lo, hi) pmin(hi, pmax(lo, x)) +eps <- 1e-12 + +safe_sd <- function(x, floor=1e-8) { + s <- sd(as.numeric(x)) + if (!is.finite(s) || s < floor) floor else s +} + +normalize_prob <- function(x) { + x <- pmax(as.numeric(x), 1e-300) + x / sum(x) +} + +returns_from_prices <- function(prices) { + prices <- as.numeric(prices) + stopifnot(length(prices) >= 3, all(is.finite(prices)), all(prices > 0)) + diff(log(prices)) +} + +# --- Monte Carlo price kernels --------------------------------------------- + +gbm_terminal <- function(s0, mu, sigma, dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, sigma >= 0, dt > 0, steps >= 1, paths >= 2) + set.seed(seed) + z <- matrix(rnorm(steps * paths), nrow=steps) + lr <- (mu - 0.5 * sigma^2) * dt + sigma * sqrt(dt) * z + s0 * exp(colSums(lr)) +} + +merton_terminal <- function(s0, mu, sigma, lambda, jump_mu, jump_sigma, + dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, sigma >= 0, lambda >= 0, jump_sigma >= 0, + dt > 0, steps >= 1, paths >= 2) + set.seed(seed) + z <- matrix(rnorm(steps * paths), nrow=steps) + n <- matrix(rpois(steps * paths, lambda * dt), nrow=steps) + jump_z <- matrix(rnorm(steps * paths), nrow=steps) + jumps <- n * jump_mu + sqrt(pmax(n, 0)) * jump_sigma * jump_z + compensator <- lambda * (exp(jump_mu + 0.5 * jump_sigma^2) - 1) + drift <- (mu - 0.5*sigma^2 - compensator) * dt + s0 * exp(colSums(drift + sigma*sqrt(dt)*z + jumps)) +} + +heston_terminal <- function(s0, v0, mu, kappa, theta, xi, rho, + dt, steps, paths, seed=1L) { + stopifnot(s0 > 0, v0 >= 0, kappa >= 0, theta >= 0, xi >= 0, + abs(rho) <= 1, dt > 0, steps >= 1, paths >= 2) + set.seed(seed) + s <- rep(s0, paths) + v <- rep(v0, paths) + for (i in seq_len(steps)) { + z1 <- rnorm(paths) + z2 <- rho*z1 + sqrt(max(0, 1-rho^2))*rnorm(paths) + vp <- pmax(v, 0) + s <- s * exp((mu - 0.5*vp)*dt + sqrt(vp*dt)*z1) + v <- pmax(v + kappa*(theta-vp)*dt + xi*sqrt(vp*dt)*z2, 0) + } + s +} + +# --- GARCH ----------------------------------------------------------------- + +garch11_filter <- function(r, omega, alpha, beta, mean_return=mean(r)) { + r <- as.numeric(r) + e <- r - mean_return + h <- numeric(length(r)) + h[1] <- max(var(e), eps) + if (length(r) >= 2) { + for (i in 2:length(r)) { + h[i] <- max(eps, omega + alpha*e[i-1]^2 + beta*h[i-1]) + } + } + h +} + +garch11_fit <- function(r) { + r <- as.numeric(r) + stopifnot(length(r) >= 20, all(is.finite(r))) + mean_return <- mean(r) + e <- r - mean_return + v0 <- max(var(e), 1e-10) + + unpack <- function(p) { + alpha <- 0.98 * plogis(p[2]) + beta <- (0.999 - alpha) * plogis(p[3]) + c(omega=exp(p[1]), alpha=alpha, beta=beta) + } + + nll <- function(p) { + q <- unpack(p) + h <- garch11_filter(r, q["omega"], q["alpha"], q["beta"], mean_return) + 0.5 * sum(log(2*pi) + log(h) + e^2/h) + } + + init_alpha <- 0.08 + init_beta <- 0.88 + init <- c( + log(max(v0 * (1-init_alpha-init_beta), 1e-12)), + qlogis(init_alpha/0.98), + qlogis(init_beta/(0.999-init_alpha)) + ) + opt <- tryCatch(optim(init, nll, method="BFGS", control=list(maxit=500)), + error=function(e) NULL) + if (is.null(opt) || !is.finite(opt$value)) { + q <- c(omega=max(v0*0.04,1e-12), alpha=0.08, beta=0.88) + convergence <- 1L + } else { + q <- unpack(opt$par) + convergence <- opt$convergence + } + h <- garch11_filter(r, q["omega"], q["alpha"], q["beta"], mean_return) + list( + omega=unname(q["omega"]), + alpha=unname(q["alpha"]), + beta=unname(q["beta"]), + mean=mean_return, + variance=h, + sigma=sqrt(h), + standardized=(r-mean_return)/sqrt(h), + convergence=convergence + ) +} + +garch11_forecast <- function(fit, last_return, steps=1L) { + stopifnot(steps >= 1) + out <- numeric(steps) + h <- tail(fit$variance, 1) + e2 <- (last_return-fit$mean)^2 + for (i in seq_len(steps)) { + h <- fit$omega + fit$alpha*e2 + fit$beta*h + out[i] <- max(h, eps) + e2 <- h + } + out +} + +# --- Three-state Gaussian HMM ---------------------------------------------- + +hmm_forward_backward <- function(x, initial, transition, state_mean, state_sd) { + x <- as.numeric(x) + n <- length(x) + k <- length(state_mean) + emission <- sapply(seq_len(k), function(j) { + pmax(dnorm(x, mean=state_mean[j], sd=max(state_sd[j],1e-8)), 1e-300) + }) + if (k == 1) emission <- matrix(emission, ncol=1) + + forward <- matrix(0, n, k) + scale <- numeric(n) + forward[1,] <- initial * emission[1,] + scale[1] <- max(sum(forward[1,]), 1e-300) + forward[1,] <- forward[1,] / scale[1] + + if (n >= 2) { + for (t in 2:n) { + forward[t,] <- as.numeric(forward[t-1,] %*% transition) * emission[t,] + scale[t] <- max(sum(forward[t,]), 1e-300) + forward[t,] <- forward[t,] / scale[t] + } + } + + backward <- matrix(1, n, k) + if (n >= 2) { + for (t in (n-1):1) { + backward[t,] <- as.numeric( + transition %*% (emission[t+1,] * backward[t+1,]) + ) / scale[t+1] + } + } + + gamma <- forward * backward + gamma <- gamma / rowSums(gamma) + + xi_sum <- matrix(0, k, k) + if (n >= 2) { + for (t in 1:(n-1)) { + xi <- transition * outer( + forward[t,], + emission[t+1,] * backward[t+1,] + ) + den <- sum(xi) + if (den > 0) xi_sum <- xi_sum + xi/den + } + } + + list( + emission=emission, + forward=forward, + backward=backward, + posterior=gamma, + xi_sum=xi_sum, + loglik=sum(log(scale)) + ) +} + +hmm3_fit <- function(returns, max_iter=80L, tol=1e-7) { + x <- as.numeric(returns) + stopifnot(length(x) >= 60, all(is.finite(x))) + state_names <- c("bear","neutral","bull") + state_mean <- as.numeric(quantile(x, c(0.15,0.50,0.85), names=FALSE)) + base_sd <- safe_sd(x) + state_sd <- rep(base_sd, 3) + initial <- rep(1/3, 3) + transition <- matrix(0.015, 3, 3) + diag(transition) <- 0.97 + previous_ll <- -Inf + + for (iter in seq_len(max_iter)) { + fb <- hmm_forward_backward(x, initial, transition, state_mean, state_sd) + w <- colSums(fb$posterior) + initial <- normalize_prob(fb$posterior[1,]) + + transition <- fb$xi_sum + transition <- transition / pmax(rowSums(transition), 1e-300) + transition[!is.finite(transition)] <- 1/3 + transition <- t(apply(transition, 1, normalize_prob)) + + new_mean <- colSums(fb$posterior * x) / pmax(w, 1e-12) + new_sd <- numeric(3) + for (j in 1:3) { + new_sd[j] <- sqrt( + sum(fb$posterior[,j] * (x-new_mean[j])^2) / max(w[j],1e-12) + ) + } + state_mean <- new_mean + state_sd <- pmax(new_sd, base_sd*0.05, 1e-8) + + ord <- order(state_mean) + state_mean <- state_mean[ord] + state_sd <- state_sd[ord] + initial <- initial[ord] + transition <- transition[ord,ord,drop=FALSE] + + if (is.finite(previous_ll) && abs(fb$loglik-previous_ll) < tol) break + previous_ll <- fb$loglik + } + + fb <- hmm_forward_backward(x, initial, transition, state_mean, state_sd) + names(state_mean) <- state_names + names(state_sd) <- state_names + names(initial) <- state_names + dimnames(transition) <- list(state_names,state_names) + colnames(fb$posterior) <- state_names + + list( + initial=initial, + transition=transition, + state_mean=state_mean, + state_sd=state_sd, + posterior=fb$posterior, + loglik=fb$loglik + ) +} + +hmm3_viterbi <- function(returns, model) { + x <- as.numeric(returns) + names_state <- names(model$state_mean) + k <- length(names_state) + n <- length(x) + log_trans <- log(pmax(model$transition,1e-300)) + log_initial <- log(pmax(model$initial,1e-300)) + emit <- sapply(seq_len(k), function(j) { + dnorm(x, model$state_mean[j], model$state_sd[j], log=TRUE) + }) + if (k == 1) emit <- matrix(emit,ncol=1) + + delta <- matrix(-Inf,n,k) + psi <- matrix(1L,n,k) + delta[1,] <- log_initial + emit[1,] + if (n >= 2) { + for (t in 2:n) { + for (j in seq_len(k)) { + candidate <- delta[t-1,] + log_trans[,j] + psi[t,j] <- which.max(candidate) + delta[t,j] <- max(candidate) + emit[t,j] + } + } + } + path <- integer(n) + path[n] <- which.max(delta[n,]) + if (n >= 2) { + for (t in (n-1):1) path[t] <- psi[t+1,path[t+1]] + } + names_state[path] +} + +regime_state <- function(returns) { + x <- as.numeric(returns) + if (length(x) < 60) { + m <- mean(x) + s <- safe_sd(x) + if (m > 0.25*s) "bull" else if (m < -0.25*s) "bear" else "neutral" + } else { + model <- hmm3_fit(x) + tail(hmm3_viterbi(x,model),1) + } +} + +# --- Rough volatility ------------------------------------------------------- + +hurst_variogram <- function(x, max_lag=NULL) { + x <- as.numeric(x) + n <- length(x) + stopifnot(n >= 32, all(is.finite(x))) + if (is.null(max_lag)) max_lag <- min(64L, floor(n/8)) + max_lag <- max(4L, min(as.integer(max_lag), floor(n/3))) + raw_lags <- unique(as.integer(round(exp(seq(log(1),log(max_lag),length.out=12))))) + lags <- raw_lags[raw_lags >= 1 & raw_lags < n] + variogram <- sapply(lags, function(lag) { + mean((x[(lag+1):n] - x[1:(n-lag)])^2) + }) + keep <- is.finite(variogram) & variogram > 0 + if (sum(keep) < 3) return(0.5) + slope <- unname(coef(lm(log(variogram[keep]) ~ log(lags[keep])))[2]) + clamp(slope/2, 0.02, 0.98) +} + +hurst_rs <- function(x) { + # Kept for API compatibility; variogram estimator is more appropriate for + # the realized-variance rough-vol path used by M3a. + hurst_variogram(cumsum(as.numeric(x)-mean(x))) +} + +fgn_davies_harte <- function(n, H, seed=1L) { + n <- as.integer(n) + stopifnot(n >= 1, H > 0, H < 1) + if (n == 1) { + set.seed(seed) + return(rnorm(1)) + } + k <- 0:n + gamma <- 0.5 * ( + abs(k-1)^(2*H) - 2*abs(k)^(2*H) + abs(k+1)^(2*H) + ) + circulant <- c(gamma, rev(gamma[2:n])) + lambda <- Re(fft(circulant)) + if (min(lambda) < -1e-8) stop("davies_harte_negative_eigenvalue") + lambda <- pmax(lambda,0) + + set.seed(seed) + w <- complex(length=2*n) + w[1] <- sqrt(lambda[1]/(2*n))*rnorm(1) + w[n+1] <- sqrt(lambda[n+1]/(2*n))*rnorm(1) + if (n > 1) { + for (j in 2:n) { + z <- rnorm(2) + w[j] <- sqrt(lambda[j]/(4*n)) * (z[1] + 1i*z[2]) + mirror <- 2*n-j+2 + w[mirror] <- Conj(w[j]) + } + } + Re(fft(w))[1:n] +} + +rough_vol_terminal <- function(s0, mu, v0, H, eta, dt, steps, paths, seed=1L) { + stopifnot( + s0 > 0, v0 > 0, H > 0, H < 1, eta >= 0, + dt > 0, steps >= 1, paths >= 2 + ) + steps <- as.integer(steps) + paths <- as.integer(paths) + terminal <- numeric(paths) + for (p in seq_len(paths)) { + fgn <- fgn_davies_harte(steps,H,seed+p-1L) + set.seed(seed+100000L+p) + price_noise <- rnorm(steps) + logv <- log(v0) + logp <- log(s0) + for (i in seq_len(steps)) { + logv <- logv + eta*(dt^H)*fgn[i] + v <- max(exp(logv),eps) + logp <- logp + (mu-0.5*v)*dt + sqrt(v*dt)*price_noise[i] + } + terminal[p] <- exp(logp) + } + terminal +} + +realized_variance <- function(returns, window=24L) { + x <- as.numeric(returns) + stopifnot(window >= 2, length(x) >= window) + idx <- window:length(x) + vapply(idx, function(i) mean(x[(i-window+1):i]^2), numeric(1)) +} + +rough_vol_state <- function(realized_variance_series) { + rv <- pmax(as.numeric(realized_variance_series), eps) + stopifnot(length(rv) >= 32) + logv <- log(rv) + H <- hurst_variogram(logv) + center <- mean(logv) + if (length(logv) > 2) { + phi <- suppressWarnings(cor(logv[-length(logv)], logv[-1])) + if (!is.finite(phi)) phi <- 0 + } else { + phi <- 0 + } + phi <- clamp(phi, -0.99, 0.99) + forecast_log <- center + phi*(tail(logv,1)-center) + list( + hurst=H, + persistence=phi, + current_variance=tail(rv,1), + forecast_variance=exp(forecast_log), + vol_of_log_vol=safe_sd(diff(logv)) + ) +} + +fit_rough_volatility <- function(realized_variance_series,dt,max_lag=NULL) { + rv <- pmax(as.numeric(realized_variance_series),eps) + stopifnot(length(rv) >= 64, dt > 0, all(is.finite(rv))) + logv <- log(rv) + n <- length(logv) + if (is.null(max_lag)) max_lag <- min(64L,floor(n/8)) + max_lag <- max(4L,min(as.integer(max_lag),floor(n/3))) + lags <- unique(as.integer(round(exp(seq(log(1),log(max_lag),length.out=14))))) + lags <- lags[lags >= 1 & lags < n] + variogram <- vapply(lags,function(lag) { + mean((logv[(lag+1):n]-logv[1:(n-lag)])^2) + },numeric(1)) + keep <- is.finite(variogram) & variogram > 0 + if (sum(keep) < 3) stop("rough_vol_insufficient_variogram") + x <- log(lags[keep]*dt) + y <- log(variogram[keep]) + fit <- lm(y ~ x) + slope <- unname(coef(fit)[2]) + intercept <- unname(coef(fit)[1]) + H <- clamp(slope/2,0.02,0.98) + eta <- sqrt(max(exp(intercept),eps)) + r2 <- summary(fit)$r.squared + if (!is.finite(r2)) r2 <- 0 + slope_se <- summary(fit)$coefficients["x","Std. Error"] + if (!is.finite(slope_se)) slope_se <- 0 + list( + hurst=H, + hurst_se=max(slope_se/2,0), + eta=eta, + r_squared=clamp(r2,0,1), + lags=lags[keep], + variogram=variogram[keep] + ) +} + +# --- DCC correlation + t-copula -------------------------------------------- + +dcc_core <- function(standardized_returns, a, b) { + z <- as.matrix(standardized_returns) + stopifnot(nrow(z) >= 20, ncol(z) >= 2, a >= 0, b >= 0, a+b < 1) + z[!is.finite(z)] <- 0 + qbar <- cov(z) + diag(1e-10,ncol(z)) + q <- qbar + n <- nrow(z) + p <- ncol(z) + history <- array(0,dim=c(p,p,n)) + nll <- 0 + + for (t in seq_len(n)) { + if (t >= 2) { + q <- (1-a-b)*qbar + a*tcrossprod(z[t-1,]) + b*q + } + d <- sqrt(pmax(diag(q),eps)) + r <- q/outer(d,d) + diag(r) <- 1 + history[,,t] <- r + + if (t >= 2) { + det_r <- determinant(r,logarithm=TRUE) + if (det_r$sign <= 0) { + nll <- Inf + } else if (is.finite(nll)) { + solved <- tryCatch(solve(r,z[t,]),error=function(e) NULL) + if (is.null(solved)) { + nll <- Inf + } else { + quad <- sum(z[t,]*solved) + nll <- nll + 0.5*(as.numeric(det_r$modulus)+quad) + } + } + } + } + + list(z=z,qbar=qbar,history=history,nll=nll) +} + +dcc_fit <- function(standardized_returns, a=0.02, b=0.97) { + core <- dcc_core(standardized_returns,a,b) + p <- dim(core$history)[1] + n <- dim(core$history)[3] + correlation <- if (p == 2) { + as.numeric(core$history[1,2,]) + } else { + core$history + } + list( + a=a, + b=b, + qbar=cov2cor(core$qbar), + correlation=correlation, + last_correlation=core$history[,,n,drop=TRUE], + loglik=-core$nll + ) +} + +dcc_estimate <- function(standardized_returns, start=c(a=0.03,b=0.94)) { + z <- as.matrix(standardized_returns) + stopifnot(nrow(z) >= 20, ncol(z) >= 2) + a0 <- unname(start["a"]) + b0 <- unname(start["b"]) + if (!is.finite(a0) || !is.finite(b0) || a0 < 0 || b0 < 0 || a0+b0 >= 0.999) { + a0 <- 0.03 + b0 <- 0.94 + } + rest0 <- max(1-a0-b0,1e-4) + p0 <- log(c(a0/rest0,b0/rest0)) + + unpack <- function(p) { + p <- clamp(p,-30,30) + ea <- exp(p[1]) + eb <- exp(p[2]) + den <- 1+ea+eb + c(a=0.999*ea/den,b=0.999*eb/den) + } + objective <- function(p) { + q <- unpack(p) + dcc_core(z,q["a"],q["b"])$nll + } + + opt <- tryCatch( + optim(p0,objective,method="BFGS",control=list(maxit=300,reltol=1e-8)), + error=function(e) NULL + ) + if (is.null(opt) || !is.finite(opt$value)) { + q <- c(a=a0,b=b0) + convergence <- 1L + } else { + q <- unpack(opt$par) + convergence <- opt$convergence + } + fit <- dcc_fit(z,unname(q["a"]),unname(q["b"])) + fit$convergence <- convergence + fit +} + +t_copula_tail_dependence <- function(rho, df=6) { + stopifnot(df > 0) + rho <- clamp(rho,-0.999999,0.999999) + 2 * pt(-sqrt((df+1)*(1-rho)/(1+rho)),df=df+1) +} + +estimate_t_df <- function(x) { + x <- as.numeric(x) + x <- x[is.finite(x)] + stopifnot(length(x) >= 50) + centered <- x-mean(x) + m2 <- mean(centered^2) + if (m2 <= eps) return(50) + excess <- mean(centered^4)/(m2^2)-3 + if (!is.finite(excess) || excess <= 0) return(50) + clamp(4+6/excess,4.1,100) +} + +calibrate_cross_asset <- function(return_matrix, a=NULL, b=NULL) { + x <- as.matrix(return_matrix) + stopifnot(nrow(x) >= 20, ncol(x) >= 2) + fits <- lapply(seq_len(ncol(x)), function(j) garch11_fit(x[,j])) + z <- do.call(cbind,lapply(fits,function(f) f$standardized)) + dcc <- if (is.null(a) || is.null(b)) dcc_estimate(z) else dcc_fit(z,a,b) + df <- estimate_t_df(as.numeric(z)) + tail_dependence <- matrix(0,ncol(z),ncol(z)) + for (i in seq_len(ncol(z))) { + for (j in seq_len(ncol(z))) { + tail_dependence[i,j] <- if (i == j) 1 else + t_copula_tail_dependence(dcc$last_correlation[i,j],df) + } + } + list( + univariate=fits, + standardized=z, + dcc=dcc, + t_df=df, + tail_dependence=tail_dependence, + last_correlation=dcc$last_correlation + ) +} + +# --- Bayesian calibration + time series ------------------------------------ + +normal_inverse_gamma_prior <- function(mu=0, kappa=1, alpha=2, beta=1e-4) { + stopifnot(kappa > 0, alpha > 0, beta > 0) + list(mu=mu,kappa=kappa,alpha=alpha,beta=beta) +} + +bayes_return_update <- function(prior, observations) { + x <- as.numeric(observations) + stopifnot(length(x) >= 1, all(is.finite(x))) + n <- length(x) + xb <- mean(x) + ss <- sum((x-xb)^2) + kappa_n <- prior$kappa+n + mu_n <- (prior$kappa*prior$mu+n*xb)/kappa_n + alpha_n <- prior$alpha+n/2 + beta_n <- prior$beta + 0.5*ss + + prior$kappa*n*(xb-prior$mu)^2/(2*kappa_n) + list(mu=mu_n,kappa=kappa_n,alpha=alpha_n,beta=beta_n) +} + +arima_forecast_base <- function(x, horizon=1L, order=c(1L,0L,0L)) { + x <- as.numeric(x) + stopifnot(length(x) >= 20, horizon >= 1) + fit <- tryCatch( + arima(x, order=order, include.mean=TRUE, method="ML"), + error=function(e) NULL + ) + if (is.null(fit)) { + return(list( + mean=rep(mean(x),horizon), + sd=rep(safe_sd(x),horizon), + fit=NULL + )) + } + pred <- predict(fit,n.ahead=horizon) + list(mean=as.numeric(pred$pred),sd=pmax(as.numeric(pred$se),0),fit=fit) +} + +# --- Heston characteristic-function pricing -------------------------------- + +black_scholes_call <- function(spot,strike,maturity,rate=0,dividend=0,sigma) { + stopifnot( + spot > 0, strike > 0, maturity >= 0, + is.finite(rate), is.finite(dividend), sigma >= 0 + ) + if (maturity == 0) return(max(spot-strike,0)) + discounted_spot <- spot*exp(-dividend*maturity) + discounted_strike <- strike*exp(-rate*maturity) + if (sigma <= 1e-14) return(max(discounted_spot-discounted_strike,0)) + vol_t <- sigma*sqrt(maturity) + d1 <- (log(spot/strike)+(rate-dividend+0.5*sigma^2)*maturity)/vol_t + d2 <- d1-vol_t + discounted_spot*pnorm(d1)-discounted_strike*pnorm(d2) +} + +heston_characteristic <- function( + u,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0) { + stopifnot( + spot > 0, maturity >= 0, kappa >= 0, theta >= 0, + xi > 0, abs(rho) <= 1, v0 >= 0 + ) + iu <- 1i*u + drift <- log(spot)+(rate-dividend)*maturity + d <- sqrt((kappa-rho*xi*iu)^2 + xi^2*(u^2+iu)) + g <- (kappa-rho*xi*iu-d)/(kappa-rho*xi*iu+d) + exp_dt <- exp(-d*maturity) + one_minus_g <- 1-g + one_minus_gexp <- 1-g*exp_dt + + C <- iu*drift + + (kappa*theta/xi^2) * ( + (kappa-rho*xi*iu-d)*maturity - + 2*log(one_minus_gexp/one_minus_g) + ) + D <- ((kappa-rho*xi*iu-d)/xi^2) * + ((1-exp_dt)/one_minus_gexp) + exp(C + D*v0) +} + +trapz_real <- function(x,y) { + x <- as.numeric(x) + y <- as.numeric(y) + stopifnot(length(x) == length(y), length(x) >= 2) + sum(diff(x)*(head(y,-1)+tail(y,-1))*0.5) +} + +heston_call_price <- function( + spot,strike,maturity,rate=0,dividend=0, + kappa,theta,xi,rho,v0, + integration_points=1024L,integration_limit=100) { + stopifnot( + spot > 0, strike > 0, maturity >= 0, + kappa >= 0, theta >= 0, xi >= 0, abs(rho) <= 1, v0 >= 0, + integration_points >= 64, integration_limit > 0 + ) + if (maturity == 0) return(max(spot-strike,0)) + + # With no vol-of-vol, variance is deterministic under CIR mean reversion. + if (xi <= 1e-12) { + integrated_variance <- if (kappa <= 1e-12) { + v0*maturity + } else { + theta*maturity + (v0-theta)*(1-exp(-kappa*maturity))/kappa + } + sigma_eff <- sqrt(max(integrated_variance/maturity,0)) + return(black_scholes_call( + spot,strike,maturity,rate,dividend,sigma_eff + )) + } + + n <- as.integer(integration_points) + u <- seq(1e-5,integration_limit,length.out=n) + phi_u <- heston_characteristic( + u,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + phi_u_minus_i <- heston_characteristic( + u-1i,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + phi_minus_i <- heston_characteristic( + -1i,spot,maturity,rate,dividend,kappa,theta,xi,rho,v0 + ) + oscillation <- exp(-1i*u*log(strike)) + + integrand1 <- Re( + oscillation*phi_u_minus_i/(1i*u*phi_minus_i) + ) + integrand2 <- Re( + oscillation*phi_u/(1i*u) + ) + p1 <- 0.5 + trapz_real(u,integrand1)/pi + p2 <- 0.5 + trapz_real(u,integrand2)/pi + + raw <- spot*exp(-dividend*maturity)*p1 - + strike*exp(-rate*maturity)*p2 + lower <- max( + spot*exp(-dividend*maturity)-strike*exp(-rate*maturity),0 + ) + upper <- spot*exp(-dividend*maturity) + clamp(Re(raw),lower,upper) +} + +heston_params_vector <- function(params) { + q <- unlist(params[c("kappa","theta","xi","rho","v0")],use.names=TRUE) + if (length(q) != 5 || any(!is.finite(q))) stop("invalid_heston_params") + q +} + +heston_surface_rmse <- function( + params,surface,spot,rate=0,dividend=0,integration_points=512L) { + q <- heston_params_vector(params) + required <- c("strike","maturity","price") + if (!all(required %in% names(surface))) stop("invalid_option_surface") + predicted <- mapply( + function(strike,maturity) { + heston_call_price( + spot,strike,maturity,rate,dividend, + q["kappa"],q["theta"],q["xi"],q["rho"],q["v0"], + integration_points=integration_points + ) + }, + surface$strike,surface$maturity + ) + weights <- if ("weight" %in% names(surface)) { + pmax(as.numeric(surface$weight),0) + } else { + rep(1,nrow(surface)) + } + if (sum(weights) <= 0) stop("invalid_surface_weights") + sqrt(sum(weights*(predicted-surface$price)^2)/sum(weights)) +} + +calibrate_heston_surface <- function( + surface,spot,rate=0,dividend=0, + start=c(kappa=1.5,theta=0.04,xi=0.3,rho=-0.5,v0=0.04), + integration_points=512L,maxit=200L) { + start <- heston_params_vector(start) + stopifnot( + start["kappa"] > 0, start["theta"] > 0, + start["xi"] >= 0, abs(start["rho"]) < 1, start["v0"] > 0 + ) + + encode <- function(q) { + c( + log(max(q["kappa"],1e-8)), + log(max(q["theta"],1e-8)), + log(max(q["xi"],1e-8)), + atanh(clamp(q["rho"],-0.999,0.999)), + log(max(q["v0"],1e-8)) + ) + } + decode <- function(p) { + c( + kappa=exp(clamp(p[1],-12,8)), + theta=exp(clamp(p[2],-12,2)), + xi=exp(clamp(p[3],-12,3)), + rho=tanh(p[4]), + v0=exp(clamp(p[5],-12,2)) + ) + } + objective <- function(p) { + q <- decode(p) + err <- tryCatch( + heston_surface_rmse( + q,surface,spot,rate,dividend,integration_points + ), + error=function(e) Inf + ) + if (!is.finite(err)) 1e12 else err + } + + initial_rmse <- objective(encode(start)) + opt <- tryCatch( + optim( + encode(start),objective,method="Nelder-Mead", + control=list(maxit=as.integer(maxit),reltol=1e-7) + ), + error=function(e) NULL + ) + if (is.null(opt) || !is.finite(opt$value)) { + params <- start + rmse <- initial_rmse + convergence <- 1L + } else { + params <- decode(opt$par) + rmse <- objective(opt$par) + convergence <- opt$convergence + } + + list( + params=as.list(params), + rmse=rmse, + start_rmse=initial_rmse, + convergence=convergence, + observations=nrow(surface) + ) +} + +# --- Risk and parameter proxies -------------------------------------------- + +historical_var_es <- function(returns, alpha=0.99) { + x <- as.numeric(returns) + stopifnot(length(x) >= 20, alpha > 0.5, alpha < 1) + q <- unname(quantile(x,1-alpha,type=8,na.rm=TRUE)) + tail_x <- x[x <= q] + var_loss <- max(0,-q) + es <- if (length(tail_x)) max(var_loss,-mean(tail_x)) else var_loss + list(var=var_loss,expected_shortfall=es,quantile=q,alpha=alpha) +} + +estimate_jump_intensity <- function(returns, threshold=4) { + x <- as.numeric(returns) + stopifnot(length(x) >= 20, threshold > 0) + center <- median(x) + scale <- mad(x,center=center,constant=1.4826) + if (!is.finite(scale) || scale < eps) scale <- safe_sd(x) + idx <- which(abs(x-center) > threshold*scale) + jumps <- x[idx] + list( + lambda=length(idx)/length(x), + count=length(idx), + jump_mu=if (length(jumps)) mean(jumps) else 0, + jump_sigma=if (length(jumps) > 1) sd(jumps) else 0, + threshold=threshold*scale + ) +} + +fit_heston_proxy <- function(prices, window=24L) { + r <- returns_from_prices(prices) + window <- min(as.integer(window), max(4L,floor(length(r)/4))) + rv <- realized_variance(r,window) + theta <- max(mean(rv),eps) + v0 <- max(tail(rv,1),eps) + + if (length(rv) >= 3) { + phi <- suppressWarnings(cor(rv[-length(rv)],rv[-1])) + if (!is.finite(phi)) phi <- 0 + phi <- clamp(phi,-0.99,0.999) + kappa <- max(0,1-phi) + + drv <- diff(rv) + aligned_r <- tail(r,length(drv)) + rho <- suppressWarnings(cor(aligned_r,drv)) + if (!is.finite(rho)) rho <- 0 + rho <- clamp(rho,-0.999,0.999) + + base <- pmax(rv[-length(rv)],eps) + xi <- safe_sd(drv/sqrt(base)) + } else { + kappa <- 0 + rho <- 0 + xi <- 0 + } + + list(v0=v0,theta=theta,kappa=kappa,xi=max(xi,0),rho=rho) +} + +coverage_correctness <- function(standardized_returns, target=0.95) { + z <- as.numeric(standardized_returns) + z <- z[is.finite(z)] + if (!length(z)) return(5) + observed <- mean(abs(z) <= 1.959964) + clamp(10 - 25*abs(observed-target),0,10) +} + +backtest_quality_scores <- function( + prices,dt,min_train=80L,max_points=24L,target_coverage=0.95) { + p <- as.numeric(prices) + stopifnot( + length(p) >= 40, all(is.finite(p)), all(p > 0), dt > 0, + max_points >= 5, target_coverage > 0.5, target_coverage < 1 + ) + r <- returns_from_prices(p) + min_train <- as.integer(min(min_train,length(r)-5L)) + min_train <- max(20L,min_train) + if (length(r) <= min_train) stop("insufficient_backtest_history") + + base_fit <- garch11_fit(r[seq_len(min_train)]) + perturb_start <- max(1L,as.integer(floor(min_train*0.1))) + perturbed_fit <- garch11_fit(r[perturb_start:min_train]) + + h_base <- tail(base_fit$variance,1) + h_pert <- tail(perturbed_fit$variance,1) + rows <- vector("list",length(r)-min_train) + + for (t in (min_train+1L):length(r)) { + prev_base_error <- r[t-1L]-base_fit$mean + prev_pert_error <- r[t-1L]-perturbed_fit$mean + h_base <- max( + eps, + base_fit$omega + + base_fit$alpha*prev_base_error^2 + + base_fit$beta*h_base + ) + h_pert <- max( + eps, + perturbed_fit$omega + + perturbed_fit$alpha*prev_pert_error^2 + + perturbed_fit$beta*h_pert + ) + + sigma_base <- sqrt(h_base) + sigma_pert <- sqrt(h_pert) + lo <- base_fit$mean-qnorm((1+target_coverage)/2)*sigma_base + hi <- base_fit$mean+qnorm((1+target_coverage)/2)*sigma_base + actual <- r[t] + rows[[t-min_train]] <- c( + covered=as.numeric(actual >= lo && actual <= hi), + relative_error=abs(exp(actual)-exp(base_fit$mean)), + relative_width=exp(hi)-exp(lo), + perturbation=abs(sigma_base-sigma_pert)/max(sigma_base,eps) + ) + } + + mat <- do.call(rbind,rows) + if (nrow(mat) > max_points) { + mat <- tail(mat,as.integer(max_points)) + } + coverage <- mean(mat[,"covered"]) + med_err <- median(mat[,"relative_error"]) + med_width <- median(mat[,"relative_width"]) + med_perturb <- median(mat[,"perturbation"]) + + coverage_score <- clamp( + 10 - 40*abs(coverage-target_coverage),0,10 + ) + error_score <- 10*exp(-med_err/0.03) + sharpness_score <- 10*exp(-med_width/0.20) + correctness <- clamp( + 0.55*coverage_score + 0.45*error_score,0,10 + ) + confidence <- clamp( + 0.65*coverage_score + 0.35*sharpness_score,0,10 + ) + certainty <- clamp(10*exp(-4*med_perturb),0,10) + + list( + source="walk_forward", + observations=nrow(mat), + coverage=coverage, + median_relative_error=med_err, + median_relative_width=med_width, + median_perturbation=med_perturb, + confidence=confidence, + correctness=correctness, + certainty=certainty + ) +} + +pool_calibration <- function(pool_prices,pool_liquidity=NULL,reference_spot) { + px <- as.numeric(pool_prices) + if (!length(px)) { + return(list( + observations=0L,spot=NA_real_,basis=0,dispersion=0, + total_liquidity=0,agreement=1 + )) + } + keep <- is.finite(px) & px > 0 + px <- px[keep] + if (!length(px)) stop("invalid_pool_prices") + liq <- if (is.null(pool_liquidity) || !length(pool_liquidity)) { + rep(1,length(px)) + } else { + raw <- as.numeric(pool_liquidity) + if (length(raw) != length(keep)) stop("pool_liquidity_length") + raw <- raw[keep] + ifelse(is.finite(raw) & raw > 0,raw,0) + } + if (sum(liq) <= 0) liq <- rep(1,length(px)) + spot <- weighted.mean(px,liq) + dispersion <- sqrt(weighted.mean((px-spot)^2,liq))/spot + basis <- spot/reference_spot-1 + list( + observations=length(px), + spot=spot, + basis=basis, + dispersion=dispersion, + total_liquidity=sum(liq), + agreement=exp(-20*abs(basis)) + ) +} + +# --- Calibration state ------------------------------------------------------ + +calibrate_market <- function( + prices,dt=1/365,ticker="ASSET",quality_points=16L, + pool_prices=numeric(),pool_liquidity=numeric()) { + p <- as.numeric(prices) + stopifnot(length(p) >= 80, all(is.finite(p)), all(p > 0), dt > 0) + r <- returns_from_prices(p) + g <- garch11_fit(r) + hmm_window <- tail(r,min(length(r),900)) + hmm <- hmm3_fit(hmm_window,max_iter=60,tol=1e-6) + path <- hmm3_viterbi(hmm_window,hmm) + regime <- tail(path,1) + + rv_window <- min(24L,max(4L,floor(length(r)/10))) + rv <- realized_variance(r,rv_window) + rough <- rough_vol_state(rv) + rough_fit <- fit_rough_volatility(rv,dt) + rough$hurst <- rough_fit$hurst + rough$eta <- rough_fit$eta + rough$r_squared <- rough_fit$r_squared + + prior <- normal_inverse_gamma_prior(mu=0,kappa=1,alpha=2,beta=max(var(r),1e-6)) + posterior <- bayes_return_update(prior,r) + jump <- estimate_jump_intensity(r) + heston_step <- fit_heston_proxy(p,rv_window) + + # Convert per-observation estimates into per-unit-time rates used by SDEs. + mu_rate <- posterior$mu/dt + sigma_rate <- sqrt(max(tail(g$variance,1),eps)/dt) + heston <- heston_step + heston$v0 <- heston$v0/dt + heston$theta <- heston$theta/dt + heston$kappa <- heston$kappa/dt + heston$xi <- heston$xi/sqrt(dt) + jump$lambda <- jump$lambda/dt + + recent_n <- min(24L,length(p)-1) + recent_shift <- tail(p,1)/p[length(p)-recent_n]-1 + last_posterior <- tail(hmm$posterior,1) + regime_certainty <- max(last_posterior) + + bt_min_train <- min( + 80L,max(20L,as.integer(floor(length(r)*0.60))) + ) + quality <- backtest_quality_scores( + p,dt,min_train=bt_min_train, + max_points=max(5L,as.integer(quality_points)) + ) + pool <- pool_calibration( + pool_prices,pool_liquidity,reference_spot=tail(p,1) + ) + calibration_sources <- c( + "price_tick", + if (pool$observations > 0) "dex_pool_state" else NULL + ) + pool_certainty_factor <- 0.75 + 0.25*pool$agreement + quality$certainty <- clamp( + quality$certainty*pool_certainty_factor,0,10 + ) + + list( + ticker=ticker, + spot=tail(p,1), + dt=dt, + returns=r, + mu=mu_rate, + sigma=sigma_rate, + garch=g, + hmm=hmm, + regime=regime, + regime_certainty=regime_certainty, + rough=rough, + posterior=posterior, + jump=jump, + heston=heston, + risk=historical_var_es(r,0.99), + pool=pool, + calibration_sources=calibration_sources, + quality=quality, + confidence=quality$confidence, + correctness=quality$correctness, + certainty=quality$certainty, + recent_shift=recent_shift, + calibrated_at=as.numeric(Sys.time()) + ) +} + +# --- Six concurrent forecast horizons -------------------------------------- + +m3a_horizon_specs <- function() { + data.frame( + name=c("tick_hourly","daily","weekly","monthly","annual","five_year"), + label=c("1h","24h","7d","30d","1y","5y"), + years=c(1/(24*365),1/365,7/365,30/365,1,5), + model=c("rough","heston","merton","merton","heston","gbm"), + stringsAsFactors=FALSE + ) +} + +bounded_from_samples <- function(samples, state, label, model) { + q <- as.numeric(quantile(samples,c(.025,.5,.975),names=FALSE,type=8)) + width <- (q[3]-q[1])/max(abs(q[2]),eps) + confidence <- clamp( + 0.75*state$confidence + + 0.25*10*(1-clamp(width,0,1)), + 0,10 + ) + certainty <- clamp( + 0.75*state$certainty + + 0.25*10*(1-clamp(width,0,1)), + 0,10 + ) + list( + value=q[2], + lower_bound=q[1], + upper_bound=q[3], + confidence=confidence, + correctness=clamp(state$correctness,0,10), + certainty=certainty, + time_horizon=label, + sim_type="statistical", + token_ticker=state$ticker, + recent_shift=state$recent_shift, + model=model, + regime=state$regime + ) +} + +forecast_horizon <- function(state, horizon_name, paths=4000L, seed=1L) { + specs <- m3a_horizon_specs() + row <- specs[specs$name==horizon_name,,drop=FALSE] + if (!nrow(row)) stop("unknown_horizon") + years <- row$years[1] + model <- row$model[1] + label <- row$label[1] + + steps <- max(1L,min(365L,as.integer(ceiling(years*365)))) + step_dt <- years/steps + + samples <- switch( + model, + rough=rough_vol_terminal( + state$spot, + state$mu, + max(state$rough$current_variance/state$dt,eps), + state$rough$hurst, + max(state$rough$eta,0), + step_dt,steps,paths,seed + ), + heston=heston_terminal( + state$spot, + max(state$heston$v0,eps), + state$mu, + max(state$heston$kappa,0), + max(state$heston$theta,eps), + max(state$heston$xi,0), + state$heston$rho, + step_dt,steps,paths,seed + ), + merton=merton_terminal( + state$spot,state$mu,state$sigma, + max(state$jump$lambda,0), + state$jump$jump_mu, + max(state$jump$jump_sigma,0), + step_dt,steps,paths,seed + ), + gbm=gbm_terminal( + state$spot,state$mu,state$sigma, + step_dt,steps,paths,seed + ), + stop("unknown_model") + ) + bounded_from_samples(samples,state,label,model) +} + +forecast_all_horizons <- function(state, paths=4000L, seed=1L) { + specs <- m3a_horizon_specs() + out <- lapply(seq_len(nrow(specs)), function(i) { + forecast_horizon(state,specs$name[i],paths,seed+i-1L) + }) + names(out) <- specs$name + out +} + +bounded_price_prediction <- function(s0, mu, sigma, dt, steps, + paths=4000L, seed=1L, + horizon="24h", ticker="ASSET") { + sims <- gbm_terminal(s0,mu,sigma,dt,steps,paths,seed) + q <- as.numeric(quantile(sims,c(.025,.5,.975),names=FALSE,type=8)) + width <- (q[3]-q[1])/max(q[2],eps) + list( + value=q[2], + lower_bound=q[1], + upper_bound=q[3], + confidence=clamp(10-5*width,0,10), + correctness=5, + certainty=clamp(10-8*width,0,10), + time_horizon=horizon, + sim_type="statistical", + token_ticker=ticker, + recent_shift=0 + ) +} + +horizon_metadata <- function(horizon) { + if (horizon == "current") { + return(list(label="current",years=0,steps=0L)) + } + specs <- m3a_horizon_specs() + row <- specs[specs$name == horizon,,drop=FALSE] + if (!nrow(row)) stop("unknown_horizon") + list( + label=row$label[1], + years=row$years[1], + steps=max(1L,min(365L,as.integer(ceiling(row$years[1]*365)))) + ) +} + +bounded_scalar_prediction <- function( + state,prediction_type,value,lower,upper,horizon, + label=NULL,matrix=NULL,detail=NULL) { + if (!is.finite(value) || !is.finite(lower) || !is.finite(upper)) { + stop("nonfinite_prediction") + } + if (lower > value || value > upper) stop("prediction_out_of_bounds") + h <- horizon_metadata(horizon) + out <- list( + value=as.numeric(value), + lower_bound=as.numeric(lower), + upper_bound=as.numeric(upper), + confidence=clamp(state$confidence,0,10), + correctness=clamp(state$correctness,0,10), + certainty=clamp(state$certainty,0,10), + time_horizon=h$label, + sim_type="statistical", + token_ticker=state$ticker, + recent_shift=state$recent_shift, + prediction_type=prediction_type, + calibration_sources=paste(state$calibration_sources,collapse=",") + ) + if (!is.null(label)) out$label <- label + if (!is.null(matrix)) out$matrix <- matrix + if (!is.null(detail)) out$detail <- detail + out +} + +heston_variance_terminal <- function( + v0,kappa,theta,xi,dt,steps,paths,seed=1L) { + stopifnot( + v0 >= 0,kappa >= 0,theta >= 0,xi >= 0, + dt > 0,steps >= 1,paths >= 2 + ) + set.seed(seed) + v <- rep(v0,paths) + for (i in seq_len(steps)) { + vp <- pmax(v,0) + v <- pmax( + v + kappa*(theta-vp)*dt + xi*sqrt(vp*dt)*rnorm(paths), + 0 + ) + } + v +} + +statistical_prediction <- function( + state,prediction_type="price_forecast", + horizon="daily",paths=4000L,seed=1L) { + allowed <- c( + "price_forecast","volatility_surface","var_calculation", + "correlation_matrix","regime_state","rough_vol_estimate", + "jump_intensity" + ) + if (!(prediction_type %in% allowed)) stop("unknown_prediction_type") + + if (prediction_type == "price_forecast") { + p <- forecast_horizon(state,horizon,paths,seed) + p$prediction_type <- prediction_type + p$calibration_sources <- paste(state$calibration_sources,collapse=",") + return(p) + } + + if (prediction_type == "volatility_surface") { + h <- horizon_metadata(horizon) + years <- max(h$years,state$dt) + steps <- max(1L,h$steps) + vars <- heston_variance_terminal( + max(state$heston$v0,eps), + max(state$heston$kappa,0), + max(state$heston$theta,eps), + max(state$heston$xi,0), + years/steps,steps,paths,seed + ) + vols <- sqrt(pmax(vars,0)) + q <- as.numeric(quantile(vols,c(.025,.5,.975),names=FALSE,type=8)) + return(bounded_scalar_prediction( + state,prediction_type,q[2],q[1],q[3],horizon, + detail=sprintf("heston_vol;rho=%.6g",state$heston$rho) + )) + } + + if (prediction_type == "var_calculation") { + h <- horizon_metadata(horizon) + scale <- sqrt(max(h$years/state$dt,1)) + r95 <- historical_var_es(state$returns,0.95) + r99 <- state$risk + return(bounded_scalar_prediction( + state,prediction_type, + r99$var*scale, + min(r95$var,r99$var)*scale, + max(r99$expected_shortfall,r99$var)*scale, + horizon, + detail="historical_var_99" + )) + } + + if (prediction_type == "regime_state") { + posterior <- tail(state$hmm$posterior,1) + p <- as.numeric(posterior[1,state$regime]) + n_eff <- max(1,nrow(state$hmm$posterior)) + se <- sqrt(max(p*(1-p)/n_eff,0)) + lo <- clamp(p-1.96*se,0,1) + hi <- clamp(p+1.96*se,0,1) + return(bounded_scalar_prediction( + state,prediction_type,p,lo,hi,horizon,label=state$regime + )) + } + + if (prediction_type == "rough_vol_estimate") { + h <- state$rough$hurst + se <- if (!is.null(state$rough$hurst_se)) state$rough$hurst_se else 0 + return(bounded_scalar_prediction( + state,prediction_type,h, + clamp(h-1.96*se,0.001,0.999), + clamp(h+1.96*se,0.001,0.999), + horizon, + detail=sprintf("eta=%.6g;r2=%.6g",state$rough$eta,state$rough$r_squared) + )) + } + + if (prediction_type == "jump_intensity") { + exposure <- length(state$returns)*state$dt + lambda <- state$jump$lambda + se <- sqrt(max(state$jump$count,1))/max(exposure,eps) + return(bounded_scalar_prediction( + state,prediction_type,lambda, + max(0,lambda-1.96*se), + lambda+1.96*se, + horizon, + detail=sprintf("jumps=%d",state$jump$count) + )) + } + + if (prediction_type == "correlation_matrix") { + if (is.null(state$cross_asset)) stop("cross_asset_unavailable") + m <- state$cross_asset$last_correlation + if (!is.matrix(m) || nrow(m) < 2) stop("cross_asset_unavailable") + vals <- m[upper.tri(m)] + value <- mean(vals) + return(bounded_scalar_prediction( + state,prediction_type,value,min(vals),max(vals),horizon, + matrix=m, + detail=paste( + apply(m,1,function(row) paste(format(row,digits=8),collapse=",")), + collapse=";" + ) + )) + } + + stop("unreachable_prediction_type") +} + +# --- Minimal hand-rolled JSON line protocol -------------------------------- + +json_number <- function(line, key, default) { + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] + if (length(z) < 2) default else as.numeric(z[2]) +} + +json_string <- function(line, key, default) { + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*"([^"]*)"') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] + if (length(z) < 2) default else z[2] +} + +json_number_array <- function(line, key) { + pat <- paste0('"',key,'"[[:space:]]*:[[:space:]]*\\[([^]]*)\\]') + m <- regexec(pat,line,perl=TRUE) + z <- regmatches(line,m)[[1]] + if (length(z) < 2 || !nzchar(trimws(z[2]))) return(numeric()) + as.numeric(strsplit(z[2],",",fixed=TRUE)[[1]]) +} + +json_escape <- function(x) { + x <- gsub("\\\\","\\\\\\\\",as.character(x)) + gsub('"','\\\\"',x,fixed=TRUE) +} + +emit_prediction <- function(p) { + fields <- c( + sprintf('"value":%.10g',p$value), + sprintf('"lower_bound":%.10g',p$lower_bound), + sprintf('"upper_bound":%.10g',p$upper_bound), + sprintf('"confidence":%.4f',p$confidence), + sprintf('"correctness":%.4f',p$correctness), + sprintf('"certainty":%.4f',p$certainty), + sprintf('"time_horizon":"%s"',json_escape(p$time_horizon)), + '"sim_type":"statistical"', + sprintf('"token_ticker":"%s"',json_escape(p$token_ticker)), + sprintf('"recent_shift":%.10g',p$recent_shift), + sprintf('"prediction_type":"%s"',json_escape( + if (is.null(p$prediction_type)) "price_forecast" else p$prediction_type + )), + sprintf('"calibration_sources":"%s"',json_escape( + if (is.null(p$calibration_sources)) "price_tick" else p$calibration_sources + )) + ) + if (!is.null(p$label)) { + fields <- c(fields,sprintf('"label":"%s"',json_escape(p$label))) + } + if (!is.null(p$detail)) { + fields <- c(fields,sprintf('"detail":"%s"',json_escape(p$detail))) + } + cat(sprintf("{%s}\n",paste(fields,collapse=","))) +} + +main <- function() { + line <- readLines(file("stdin"),n=1,warn=FALSE) + if (!length(line)) quit(status=2) + + prices <- json_number_array(line,"prices") + if (length(prices) >= 80) { + dt <- json_number(line,"dt",1/365) + ticker <- json_string(line,"token_ticker","ASSET") + horizon <- json_string(line,"horizon","daily") + prediction_type <- json_string(line,"prediction_type","price_forecast") + paths <- as.integer(json_number(line,"paths",4000)) + seed <- as.integer(json_number(line,"seed",1)) + pool_prices <- json_number_array(line,"pool_prices") + pool_liquidity <- json_number_array(line,"pool_liquidity") + state <- calibrate_market( + prices,dt,ticker, + pool_prices=pool_prices,pool_liquidity=pool_liquidity + ) + emit_prediction(statistical_prediction( + state,prediction_type,horizon,paths,seed + )) + } else { + p <- bounded_price_prediction( + json_number(line,"spot",100), + json_number(line,"mu",0), + json_number(line,"sigma",0.2), + json_number(line,"dt",1/365), + as.integer(json_number(line,"steps",1)), + as.integer(json_number(line,"paths",4000)), + as.integer(json_number(line,"seed",1)), + json_string(line,"time_horizon","24h"), + json_string(line,"token_ticker","ASSET") + ) + p$prediction_type <- "price_forecast" + p$calibration_sources <- "price_tick" + emit_prediction(p) + } +} + +if (sys.nframe() == 0) main() diff --git a/core/src/economy/sims/statistical/integration.test b/core/src/economy/sims/statistical/integration.test new file mode 100644 index 0000000..342702b --- /dev/null +++ b/core/src/economy/sims/statistical/integration.test @@ -0,0 +1,68 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. .. stomach.tcl] + +test m3a-runner-available-1.0 {R-backed statistical runner is available in M3a CI} -body { + set s [::stomach::Economy new -history_cap 256] + set out [$s statistical_runner_available] + $s destroy + set out +} -result 1 + +test m2-to-m3a-to-hub-1.0 {price ticks calibrate M3a and publish a bounded prediction into the hub} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + set base 100.0 + for {set i 0} {$i < 120} {incr i} { + set price [expr {$base * exp(0.0005*$i + 0.01*sin($i/7.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + set p [$s statistical_from_feed TEST daily 1200 77] + set q [$s query_predictions trader-a statistical] + set out [list [dict get $p sim_type] [expr {[dict get $p lower_bound] <= [dict get $p value]}] [expr {[dict get $p value] <= [dict get $p upper_bound]}] [dict get $q token_ticker] [dict get $q time_horizon]] + $s destroy + set out +} -result {statistical 1 1 TEST 24h} + +test m3a-insufficient-history-1.0 {M3a refuses calibration from a too-short M2 price history} -body { + set s [::stomach::Economy new -history_cap 256] + for {set i 0} {$i < 20} {incr i} { + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price [expr {100.0+$i}]] 9.0 + } + set code [catch {$s statistical_from_feed TEST daily 500 1} msg] + $s destroy + list $code $msg +} -result {1 insufficient_price_history} + +test m2-pool-to-m3a-1.0 {DEX pool state participates in M3a calibration} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + for {set i 0} {$i < 120} {incr i} { + set price [expr {100.0 * exp(0.0003*$i + 0.006*sin($i/9.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + foreach {ts price liq} {100 103.1 1000000 101 103.3 1500000 102 103.2 2000000} { + $s feed_publish dex_pool_state dex $ts [dict create token_ticker TEST price $price liquidity $liq] 8.5 + } + set p [$s statistical_from_feed_type TEST volatility_surface daily 700 91] + set out [list [dict get $p prediction_type] [dict get $p calibration_sources]] + $s destroy + set out +} -result {volatility_surface price_tick,dex_pool_state} + +test m3a-regime-query-1.0 {categorical regime is carried as label on a bounded numeric posterior} -body { + set s [::stomach::Economy new -history_cap 256] + $s register_trader trader-a statistical + for {set i 0} {$i < 120} {incr i} { + set price [expr {100.0 * exp(-0.0008*$i + 0.003*sin($i/5.0))}] + $s feed_publish price_tick synthetic $i [dict create token_ticker TEST price $price] 9.0 + } + set p [$s statistical_from_feed_type TEST regime_state current 700 92] + set out [list [dict get $p prediction_type] [expr {[lsearch -exact {bear neutral bull} [dict get $p label]] >= 0}] [expr {[dict get $p lower_bound] <= [dict get $p value] && [dict get $p value] <= [dict get $p upper_bound]}]] + $s destroy + set out +} -result {regime_state 1 1} + +cleanupTests diff --git a/core/src/economy/sims/statistical/runner.tcl b/core/src/economy/sims/statistical/runner.tcl new file mode 100644 index 0000000..60f002e --- /dev/null +++ b/core/src/economy/sims/statistical/runner.tcl @@ -0,0 +1,99 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::StatisticalRunner { + variable engine runtime + + constructor {engine_path {runtime_cmd Rscript}} { + set engine [file normalize $engine_path] + set runtime $runtime_cmd + } + + method available {} { + expr {[file exists $engine] && [auto_execok $runtime] ne ""} + } + + method _number {json key} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*(-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)} $key] + if {![regexp -- $pattern $json -> value]} { error "prediction_missing_$key" } + return $value + } + + method _string {json key} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*"([^"]*)"} $key] + if {![regexp -- $pattern $json -> value]} { error "prediction_missing_$key" } + return $value + } + + method _optional_string {json key {default ""}} { + set pattern [format {"%s"[[:space:]]*:[[:space:]]*"([^"]*)"} $key] + if {![regexp -- $pattern $json -> value]} { return $default } + return $value + } + + method parse_prediction {json} { + set p [dict create] + foreach key {value lower_bound upper_bound confidence correctness certainty recent_shift} { + dict set p $key [my _number $json $key] + } + foreach key {time_horizon sim_type token_ticker prediction_type calibration_sources} { + dict set p $key [my _string $json $key] + } + foreach key {label detail} { + set value [my _optional_string $json $key] + if {$value ne ""} { dict set p $key $value } + } + dict set p timestamp [clock seconds] + return $p + } + + method query_typed { + prices ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + {pool_prices {}} {pool_liquidity {}} + } { + if {![my available]} { error "r_runtime_unavailable" } + if {[llength $prices] < 80} { error "insufficient_price_history" } + if {![regexp {^[A-Za-z0-9_.:-]+$} $ticker]} { error "invalid_ticker" } + if {[lsearch -exact { + price_forecast volatility_surface var_calculation correlation_matrix + regime_state rough_vol_estimate jump_intensity + } $prediction_type] < 0} { error "unknown_prediction_type" } + if {[lsearch -exact {current tick_hourly daily weekly monthly annual five_year} $horizon] < 0} { + error "unknown_horizon" + } + if {$prediction_type eq "price_forecast" && $horizon eq "current"} { + error "unknown_horizon" + } + if {![string is integer -strict $paths] || $paths < 100} { error "invalid_paths" } + if {![string is integer -strict $seed]} { error "invalid_seed" } + if {![string is double -strict $dt] || $dt <= 0} { error "invalid_dt" } + + set encoded {} + foreach price $prices { + if {![string is double -strict $price] || $price <= 0} { error "invalid_price" } + lappend encoded [format %.17g $price] + } + set encoded_pool {} + foreach price $pool_prices { + if {![string is double -strict $price] || $price <= 0} { error "invalid_pool_price" } + lappend encoded_pool [format %.17g $price] + } + set encoded_liquidity {} + foreach liquidity $pool_liquidity { + if {![string is double -strict $liquidity] || $liquidity < 0} { error "invalid_pool_liquidity" } + lappend encoded_liquidity [format %.17g $liquidity] + } + if {[llength $encoded_pool] != [llength $encoded_liquidity] && [llength $encoded_liquidity] > 0} { + error "pool_liquidity_length" + } + + set payload [format {"prices":[%s],"pool_prices":[%s],"pool_liquidity":[%s],"dt":%.17g,"token_ticker":"%s","prediction_type":"%s","horizon":"%s","paths":%d,"seed":%d} [join $encoded ,] [join $encoded_pool ,] [join $encoded_liquidity ,] $dt $ticker $prediction_type $horizon $paths $seed] + + set output [exec $runtime $engine << $payload] + return [my parse_prediction $output] + } + + method query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my query_typed $prices $ticker price_forecast $horizon $paths $seed $dt {} {}] + } +} diff --git a/core/src/economy/sims/statistical/tests.R b/core/src/economy/sims/statistical/tests.R new file mode 100644 index 0000000..7e33fd8 --- /dev/null +++ b/core/src/economy/sims/statistical/tests.R @@ -0,0 +1,280 @@ +args <- commandArgs(trailingOnly=FALSE) +f <- sub("^--file=", "", args[grep("^--file=", args)]) +source(file.path(dirname(normalizePath(f)), "engine.R")) + +near <- function(x, y, tol) abs(x-y) <= tol + +# Existing stochastic kernels ------------------------------------------------- +x <- gbm_terminal(100,0.05,0.2,1/252,252,20000,7) +expected <- 100*exp(0.05) +stopifnot(abs(mean(x)-expected)/expected < 0.02) + +j <- merton_terminal(100,0.05,0.15,2,-0.08,0.15,1/252,252,10000,9) +kurtosis <- mean((j-mean(j))^4)/(var(j)^2) +stopifnot(kurtosis > 3) + +h <- heston_terminal(100,0.04,0.03,2,0.04,0.3,-0.6,1/252,252,5000,3) +stopifnot(all(h > 0)) + +set.seed(12) +r <- c(rnorm(100,0,.01), rnorm(100,0,.05)) +fit <- garch11_fit(r) +stopifnot(fit$alpha >= 0, fit$beta >= 0, fit$alpha+fit$beta < 1) +stopifnot(length(fit$variance) == length(r)) +stopifnot(all(fit$variance > 0)) + +p <- bounded_price_prediction(100,.03,.2,1/365,30,5000,4,"30d","TEST") +stopifnot(p$lower_bound <= p$value, p$value <= p$upper_bound) + +# HMM regime filter ----------------------------------------------------------- +set.seed(40) +regime_returns <- c( + rnorm(160,-0.012,0.006), + rnorm(160, 0.000,0.004), + rnorm(160, 0.012,0.006) +) +hmm <- hmm3_fit(regime_returns, max_iter=40, tol=1e-6) +path <- hmm3_viterbi(regime_returns, hmm) +stopifnot(identical(sort(names(hmm$state_mean)), c("bear","bull","neutral"))) +stopifnot(mean(path[1:140] == "bear") > 0.70) +stopifnot(mean(path[181:300] == "neutral") > 0.60) +stopifnot(mean(path[341:480] == "bull") > 0.70) +stopifnot(all(abs(rowSums(hmm$transition)-1) < 1e-8)) + +# Rough-vol / Hurst estimation ------------------------------------------------ +set.seed(41) +brownian <- cumsum(rnorm(2048)) +H <- hurst_variogram(brownian) +stopifnot(is.finite(H), H > 0.30, H < 0.70) + +rv <- exp(arima.sim(model=list(ar=-0.55), n=800, sd=0.2)) +rough <- rough_vol_state(rv) +stopifnot(rough$hurst > 0.01, rough$hurst < 0.80) +stopifnot(rough$forecast_variance > 0) + +fgn <- fgn_davies_harte(4096, H=0.35, seed=410) +fgn_h <- hurst_variogram(cumsum(fgn)) +stopifnot(abs(fgn_h-0.35) < 0.10) +stopifnot(abs(var(fgn)-1) < 0.12) + +rough_terminal <- rough_vol_terminal( + s0=100, mu=0.03, v0=0.04, H=0.35, eta=0.25, + dt=1/365, steps=24, paths=300, seed=411 +) +stopifnot(length(rough_terminal) == 300) +stopifnot(all(is.finite(rough_terminal)), all(rough_terminal > 0)) + +# Cross-asset DCC and t-copula tail dependence ------------------------------- +set.seed(42) +n <- 700 +z1 <- rnorm(n) +rho <- c(rep(0.10,350),rep(0.85,350)) +z2 <- rho*z1 + sqrt(1-rho^2)*rnorm(n) +dcc <- dcc_fit(cbind(z1,z2), a=0.03, b=0.94) +stopifnot(length(dcc$correlation) == n) +stopifnot(mean(dcc$correlation[500:700]) > mean(dcc$correlation[50:250]) + 0.15) + +dcc_qml <- dcc_estimate(cbind(z1,z2)) +stopifnot(dcc_qml$a >= 0, dcc_qml$b >= 0, dcc_qml$a+dcc_qml$b < 1) +stopifnot(is.finite(dcc_qml$loglik)) +stopifnot(mean(dcc_qml$correlation[500:700]) > + mean(dcc_qml$correlation[50:250]) + 0.15) + +td_lo <- t_copula_tail_dependence(0.2, 6) +td_hi <- t_copula_tail_dependence(0.8, 6) +stopifnot(td_hi > td_lo, td_lo >= 0, td_hi <= 1) + +set.seed(420) +df_hat <- estimate_t_df(rt(6000,df=7)) +stopifnot(df_hat > 4.1, df_hat < 15) + +# Bayesian calibration + AR forecast ----------------------------------------- +set.seed(43) +prior <- normal_inverse_gamma_prior(mu=0, kappa=1, alpha=2, beta=0.001) +post_pos <- bayes_return_update(prior, rnorm(300,0.01,0.02)) +post_neg <- bayes_return_update(prior, rnorm(300,-0.01,0.02)) +stopifnot(post_pos$mu > 0, post_neg$mu < 0) +stopifnot(post_pos$alpha > prior$alpha, post_pos$beta > 0) + +ar_data <- as.numeric(arima.sim(model=list(ar=0.75), n=500, sd=0.01)) +arf <- arima_forecast_base(ar_data, horizon=5) +stopifnot(length(arf$mean) == 5, length(arf$sd) == 5) +stopifnot(all(is.finite(arf$mean)), all(arf$sd >= 0)) + +# Risk measures --------------------------------------------------------------- +set.seed(44) +risk_returns <- rt(5000, df=5) * 0.02 +risk <- historical_var_es(risk_returns, alpha=0.99) +stopifnot(risk$var > 0, risk$expected_shortfall >= risk$var) + +# Jump + Heston calibration proxies ------------------------------------------ +set.seed(45) +plain <- rnorm(1000,0,0.01) +jumpy <- plain +jumpy[seq(50,1000,by=100)] <- jumpy[seq(50,1000,by=100)] - 0.10 +ji_plain <- estimate_jump_intensity(plain) +ji_jump <- estimate_jump_intensity(jumpy) +stopifnot(ji_jump$lambda > ji_plain$lambda) + +prices_proxy <- 100*exp(cumsum(rnorm(1000,0,0.01))) +hp <- fit_heston_proxy(prices_proxy, window=24) +stopifnot(hp$v0 > 0, hp$theta > 0, hp$kappa >= 0, hp$xi >= 0, abs(hp$rho) <= 1) + +# Full calibration and six concurrent horizons ------------------------------- +set.seed(46) +returns <- c( + rnorm(500,0.0004,0.012), + rnorm(400,-0.0002,0.025) +) +prices <- 100*exp(cumsum(returns)) +state <- calibrate_market(prices, dt=1/365, ticker="TEST") +stopifnot(state$spot > 0) +stopifnot(state$garch$alpha + state$garch$beta < 1) +stopifnot(state$rough$hurst > 0, state$rough$hurst < 1) +stopifnot(state$heston$theta > 0) +stopifnot(state$jump$lambda >= 0) +stopifnot(state$regime %in% c("bear","neutral","bull")) + +forecasts <- forecast_all_horizons(state, paths=2500, seed=90) +expected_horizons <- c("tick_hourly","daily","weekly","monthly","annual","five_year") +stopifnot(identical(names(forecasts), expected_horizons)) +for (name in names(forecasts)) { + q <- forecasts[[name]] + stopifnot(q$lower_bound <= q$value, q$value <= q$upper_bound) + stopifnot(q$confidence >= 0, q$confidence <= 10) + stopifnot(q$correctness >= 0, q$correctness <= 10) + stopifnot(q$certainty >= 0, q$certainty <= 10) + stopifnot(q$sim_type == "statistical") + stopifnot(q$token_ticker == "TEST") +} + +# DCC accepts calibrated GARCH residuals from a return matrix ----------------- +set.seed(47) +m <- cbind( + rnorm(450,0,0.015), + 0.6*rnorm(450,0,0.015) + 0.4*rnorm(450,0,0.015), + rnorm(450,0,0.020) +) +cross <- calibrate_cross_asset(m) +stopifnot(all(dim(cross$last_correlation) == c(3,3))) +stopifnot(max(abs(diag(cross$last_correlation)-1)) < 1e-10) +stopifnot(max(abs(cross$last_correlation-t(cross$last_correlation))) < 1e-10) + + +# Heston characteristic-function pricing + option-surface calibration -------- +bs <- black_scholes_call(100,100,1,0.01,0,0.20) +heston_bs <- heston_call_price( + spot=100,strike=100,maturity=1,rate=0.01,dividend=0, + kappa=2,theta=0.04,xi=0,rho=-0.5,v0=0.04 +) +stopifnot(abs(bs-heston_bs) < 1e-8) + +true_heston <- list(kappa=1.8,theta=0.04,xi=0.35,rho=-0.55,v0=0.045) +surface <- expand.grid( + strike=c(90,100,110), + maturity=c(0.25,0.75,1.25) +) +surface$price <- mapply(function(k,t) { + heston_call_price( + 100,k,t,0.01,0, + true_heston$kappa,true_heston$theta,true_heston$xi, + true_heston$rho,true_heston$v0, + integration_points=768 + ) +}, surface$strike, surface$maturity) +start_heston <- c(kappa=0.8,theta=0.08,xi=0.18,rho=-0.1,v0=0.08) +start_rmse <- heston_surface_rmse( + start_heston,surface,spot=100,rate=0.01,dividend=0, + integration_points=384 +) +hcal <- calibrate_heston_surface( + surface,spot=100,rate=0.01,dividend=0,start=start_heston, + integration_points=384,maxit=120 +) +stopifnot(is.finite(hcal$rmse), hcal$rmse < start_rmse*0.45) +stopifnot(hcal$params$theta > 0, hcal$params$xi >= 0) +stopifnot(hcal$params$rho < 0, abs(hcal$params$rho) <= 1) +stopifnot(abs(hcal$params$theta-true_heston$theta) < 0.04) + + +# Rough-vol parameter calibration -------------------------------------------- +set.seed(480) +rough_true_h <- 0.28 +rough_true_eta <- 0.55 +rough_dt <- 1/365 +rough_noise <- fgn_davies_harte(4096,rough_true_h,481) +rough_logv <- log(0.04) + + rough_true_eta*(rough_dt^rough_true_h)*cumsum(rough_noise) +rough_fit <- fit_rough_volatility(exp(rough_logv),rough_dt) +stopifnot(abs(rough_fit$hurst-rough_true_h) < 0.08) +stopifnot(abs(rough_fit$eta-rough_true_eta)/rough_true_eta < 0.35) +stopifnot(rough_fit$r_squared > 0.80) + +# Walk-forward empirical quality scores -------------------------------------- +set.seed(482) +bt_returns <- rnorm(420,0.0004,0.012) +bt_prices <- 100*exp(cumsum(bt_returns)) +quality <- backtest_quality_scores( + bt_prices,dt=1/365,min_train=120,max_points=24 +) +stopifnot(quality$source == "walk_forward") +stopifnot(quality$observations >= 20) +stopifnot(quality$coverage >= 0, quality$coverage <= 1) +stopifnot(quality$median_relative_error >= 0) +for (metric in c("confidence","correctness","certainty")) { + stopifnot(quality[[metric]] >= 0, quality[[metric]] <= 10) +} + +quality_state <- calibrate_market( + bt_prices,dt=1/365,ticker="BACKTEST",quality_points=24 +) +stopifnot(quality_state$quality$source == "walk_forward") +stopifnot(abs(quality_state$correctness-quality_state$quality$correctness) < 1e-12) +stopifnot(abs(quality_state$confidence-quality_state$quality$confidence) < 1e-12) +stopifnot(abs(quality_state$certainty-quality_state$quality$certainty) < 1e-12) + + +# Full M3a prediction-type contract + DEX pool calibration ------------------- +pool_prices <- c(99.8,100.1,100.0,100.2) +pool_liquidity <- c(1.0e6,2.0e6,1.5e6,0.5e6) +pool_state <- calibrate_market( + bt_prices,dt=1/365,ticker="POOL", + pool_prices=pool_prices,pool_liquidity=pool_liquidity, + quality_points=12 +) +stopifnot(pool_state$pool$observations == 4) +stopifnot(abs(pool_state$pool$spot-weighted.mean(pool_prices,pool_liquidity)) < 1e-10) +stopifnot(all(c("price_tick","dex_pool_state") %in% pool_state$calibration_sources)) + +typed <- c( + "price_forecast","volatility_surface","var_calculation", + "regime_state","rough_vol_estimate","jump_intensity" +) +for (prediction_type in typed) { + q <- statistical_prediction( + pool_state,prediction_type,horizon="daily",paths=800,seed=520 + ) + stopifnot(q$prediction_type == prediction_type) + stopifnot(is.numeric(q$value),length(q$value) == 1,is.finite(q$value)) + stopifnot(q$lower_bound <= q$value,q$value <= q$upper_bound) + stopifnot(q$confidence >= 0,q$confidence <= 10) + stopifnot(q$correctness >= 0,q$correctness <= 10) + stopifnot(q$certainty >= 0,q$certainty <= 10) +} +regime_prediction <- statistical_prediction( + pool_state,"regime_state",horizon="current",paths=800,seed=521 +) +stopifnot(regime_prediction$label %in% c("bear","neutral","bull")) +stopifnot(regime_prediction$value >= 0,regime_prediction$value <= 1) + +cross_state <- pool_state +cross_state$cross_asset <- cross +corr_prediction <- statistical_prediction( + cross_state,"correlation_matrix",horizon="current",paths=800,seed=522 +) +stopifnot(corr_prediction$prediction_type == "correlation_matrix") +stopifnot(all(dim(corr_prediction$matrix) == c(3,3))) +stopifnot(corr_prediction$lower_bound <= corr_prediction$value) +stopifnot(corr_prediction$value <= corr_prediction$upper_bound) + +cat("STATISTICAL TESTS PASSED\n") diff --git a/core/src/economy/sims/tests/hub_runtime.test b/core/src/economy/sims/tests/hub_runtime.test new file mode 100644 index 0000000..b7d06a9 --- /dev/null +++ b/core/src/economy/sims/tests/hub_runtime.test @@ -0,0 +1,69 @@ +package require tcltest 2 +namespace import ::tcltest::* +set here [file dirname [file normalize [info script]]] +source [file join $here .. registry.tcl] +source [file join $here .. scheduler.tcl] +set simsRoot [file normalize [file join $here ..]] + +test registry-seven-1.0 {all seven M3 engines are registered} -body { + set r [::stomach::EngineRegistry new $simsRoot] + set n [llength [$r names]] + $r destroy + set n +} -result 7 + +test registry-sources-1.0 {all registered engine sources are built into the tree} -body { + set r [::stomach::EngineRegistry new $simsRoot] + set present {} + foreach n [$r names] { lappend present [$r source_present $n] } + $r destroy + expr {[lsearch -exact $present 0] < 0} +} -result 1 + +test six-horizons-1.0 {scheduler contains all six concurrent horizon clocks} -body { + set c [::stomach::HorizonClock new] + set n [llength [$c horizons]] + $c destroy + set n +} -result 6 + +test minimum-speed-1.0 {no simulation horizon advances below the 90:1 base ratio} -body { + set c [::stomach::HorizonClock new] + set ok 1 + foreach h [$c horizons] { if {[$c ratio $h] < 90} { set ok 0 } } + $c destroy + set ok +} -result 1 + +test concurrent-advance-1.0 {one wall tick advances every horizon concurrently} -body { + set c [::stomach::HorizonClock new] + set st [$c advance 1.0] + set out [list [dict get $st tick_hourly] [dict get $st daily] [dict get $st five_year]] + $c destroy + set out +} -result {90.0 2160.0 3942000.0} + +test clock-start-stop-1.0 {horizon clock is a live event-loop clock, not just a counter} -body { + set c [::stomach::HorizonClock new] + set before [$c running] + $c start 10 + set during [$c running] + $c stop + set after [$c running] + $c destroy + list $before $during $after +} -result {0 1 0} + +test clock-pulse-1.0 {a running clock advances simulated time from wall time} -body { + set c [::stomach::HorizonClock new] + $c start 10 + after 30 {set ::m3_clock_done 1} + vwait ::m3_clock_done + unset ::m3_clock_done + set st [$c state] + $c stop + $c destroy + expr {[dict get $st tick_hourly] > 0} +} -result 1 + +cleanupTests diff --git a/core/src/economy/sims/tokenomics/fpm.toml b/core/src/economy/sims/tokenomics/fpm.toml new file mode 100644 index 0000000..19609ba --- /dev/null +++ b/core/src/economy/sims/tokenomics/fpm.toml @@ -0,0 +1,8 @@ +name = "sica-tokenomics-sim" +version = "0.1.0" +[library] +source-dir = "src" +[[test]] +name = "tokenomics" +source-dir = "test" +main = "test_tokenomics.f90" diff --git a/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 new file mode 100644 index 0000000..da22baf --- /dev/null +++ b/core/src/economy/sims/tokenomics/src/tokenomics_engine.f90 @@ -0,0 +1,213 @@ +module tokenomics_engine + implicit none + + type :: token_state + real(8) :: circulating + real(8) :: staked + real(8) :: locked + real(8) :: burned + real(8) :: total_minted + end type token_state + +contains + + subroutine token_state_step(state, emission, burn, stake_delta, lock_delta, next_state) + type(token_state), intent(in) :: state + real(8), intent(in) :: emission, burn, stake_delta, lock_delta + type(token_state), intent(out) :: next_state + real(8) :: available + + if (emission < 0d0 .or. burn < 0d0) error stop 'negative policy flow' + + next_state = state + next_state%total_minted = state%total_minted + emission + next_state%circulating = state%circulating + emission + + available = next_state%circulating + if (burn > available) error stop 'burn exceeds circulating' + next_state%circulating = next_state%circulating - burn + next_state%burned = state%burned + burn + + if (stake_delta >= 0d0) then + if (stake_delta > next_state%circulating) error stop 'stake exceeds circulating' + next_state%circulating = next_state%circulating - stake_delta + next_state%staked = state%staked + stake_delta + else + if (-stake_delta > state%staked) error stop 'unstake exceeds staked' + next_state%staked = state%staked + stake_delta + next_state%circulating = next_state%circulating - stake_delta + end if + + if (lock_delta >= 0d0) then + if (lock_delta > next_state%circulating) error stop 'lock exceeds circulating' + next_state%circulating = next_state%circulating - lock_delta + next_state%locked = state%locked + lock_delta + else + if (-lock_delta > state%locked) error stop 'unlock exceeds locked' + next_state%locked = state%locked + lock_delta + next_state%circulating = next_state%circulating - lock_delta + end if + end subroutine token_state_step + + pure real(8) function halving_emission_rate(base_rate, time, interval) result(rate) + real(8), intent(in) :: base_rate, time, interval + integer :: halvings + if (base_rate <= 0d0) then + rate = 0d0 + return + end if + if (interval <= 0d0) then + rate = base_rate + return + end if + halvings = int(floor(max(0d0,time) / interval)) + rate = base_rate * 0.5d0**halvings + end function halving_emission_rate + pure real(8) function lending_rate(utilization, r0, slope1, slope2, uopt) result(r) + real(8), intent(in) :: utilization,r0,slope1,slope2,uopt + real(8) :: u + u=min(1d0,max(0d0,utilization)) + if (u<=uopt) then + r=r0+slope1*u + else + r=r0+slope1*uopt+slope2*(u-uopt) + end if + end function + + pure logical function stock_flow_conserved(circulating,staked,locked,burned,total,tol) result(ok) + real(8), intent(in) :: circulating,staked,locked,burned,total,tol + ok = abs((circulating+staked+locked+burned)-total) <= tol + end function + + subroutine euler_maruyama(x0, drift, sigma, dt, shocks, path) + real(8), intent(in) :: x0,drift,sigma,dt,shocks(:) + real(8), intent(out) :: path(size(shocks)+1) + integer :: i + path(1)=x0 + do i=1,size(shocks) + path(i+1)=path(i)+drift*dt+sigma*sqrt(max(dt,0d0))*shocks(i) + end do + end subroutine + + subroutine kalman_scalar_update(prior_mean, prior_var, observation, observation_var, & + process_var, posterior_mean, posterior_var) + real(8), intent(in) :: prior_mean, prior_var, observation, observation_var, process_var + real(8), intent(out) :: posterior_mean, posterior_var + real(8) :: predicted_var, gain + + if (prior_var < 0d0 .or. observation_var <= 0d0 .or. process_var < 0d0) & + error stop 'invalid kalman variance' + + predicted_var = prior_var + process_var + gain = predicted_var / (predicted_var + observation_var) + posterior_mean = prior_mean + gain*(observation-prior_mean) + posterior_var = max(0d0,(1d0-gain)*predicted_var) + end subroutine kalman_scalar_update + + subroutine contagion_step(exposure, shock, propagated) + real(8), intent(in) :: exposure(:,:), shock(:) + real(8), intent(out) :: propagated(size(shock)) + propagated = shock + matmul(exposure, shock) + end subroutine + + subroutine liquidation_cascade(collateral, borrowed, ltv, exposure, iterations, losses) + real(8), intent(in) :: collateral(:), borrowed(:), ltv(:), exposure(:,:) + integer, intent(in) :: iterations + real(8), intent(out) :: losses(size(collateral)) + real(8) :: initial(size(collateral)), next_losses(size(collateral)) + integer :: step, n + + n = size(collateral) + if (size(borrowed) /= n .or. size(ltv) /= n) error stop 'cascade vector shape' + if (size(exposure,1) /= n .or. size(exposure,2) /= n) error stop 'cascade matrix shape' + if (iterations < 0) error stop 'negative cascade iterations' + if (any(collateral < 0d0) .or. any(borrowed < 0d0)) error stop 'negative balance' + if (any(ltv < 0d0) .or. any(ltv > 1d0)) error stop 'invalid ltv' + if (any(exposure < 0d0)) error stop 'negative exposure' + + initial = max(0d0, borrowed - collateral*ltv) + losses = initial + do step=1,iterations + next_losses = initial + matmul(exposure, losses) + losses = max(0d0, next_losses) + end do + end subroutine liquidation_cascade + + subroutine var_impulse_response(a, shock, steps, response) + real(8), intent(in) :: a(:,:), shock(:) + integer, intent(in) :: steps + real(8), intent(out) :: response(size(shock),steps+1) + integer :: t, n + + n = size(shock) + if (size(a,1) /= n .or. size(a,2) /= n) error stop 'var matrix shape' + if (steps < 0) error stop 'negative impulse steps' + + response(:,1) = shock + do t=1,steps + response(:,t+1) = matmul(a, response(:,t)) + end do + end subroutine var_impulse_response + + subroutine yield_weights(apy, vol, risk_aversion, weights) + real(8), intent(in) :: apy(:), vol(:), risk_aversion + real(8), intent(out) :: weights(size(apy)) + real(8) :: denom(size(apy)), mu, inv_sum, return_sum + logical :: active(size(apy)), changed + integer :: i, iter, n, best + + n = size(apy) + if (size(vol) /= n .or. n < 1) error stop 'yield vector shape' + if (risk_aversion < 0d0 .or. any(vol < 0d0)) error stop 'invalid yield risk' + + weights = 0d0 + if (risk_aversion <= 1d-15) then + best = maxloc(apy, dim=1) + weights(best) = 1d0 + return + end if + + denom = 2d0*risk_aversion*max(vol*vol,1d-12) + active = .true. + + do iter=1,n + inv_sum = 0d0 + return_sum = 0d0 + do i=1,n + if (active(i)) then + inv_sum = inv_sum + 1d0/denom(i) + return_sum = return_sum + apy(i)/denom(i) + end if + end do + if (inv_sum <= 0d0) exit + + mu = (return_sum-1d0)/inv_sum + changed = .false. + weights = 0d0 + do i=1,n + if (active(i)) then + weights(i) = (apy(i)-mu)/denom(i) + if (weights(i) <= 0d0) then + active(i) = .false. + weights(i) = 0d0 + changed = .true. + end if + end if + end do + if (.not. changed) exit + end do + + if (sum(weights) <= 1d-15) then + best = maxloc(apy, dim=1) + weights = 0d0 + weights(best) = 1d0 + else + weights = weights/sum(weights) + end if + end subroutine + + pure real(8) function liquidation_shortfall(collateral,ltv,borrowed) result(shortfall) + real(8), intent(in) :: collateral,ltv,borrowed + shortfall=max(0d0,borrowed-collateral*ltv) + end function +end module diff --git a/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 new file mode 100644 index 0000000..a533671 --- /dev/null +++ b/core/src/economy/sims/tokenomics/test/test_tokenomics.f90 @@ -0,0 +1,81 @@ +program test_tokenomics + use tokenomics_engine + implicit none + real(8) :: shock(3), exposure(3,3), propagated(3), w(3), apy(3), vol(3) + real(8) :: collateral(4), borrowed(4), ltv(4), cascade_exposure(4,4), losses(4) + real(8) :: var_a(3,3), impulse(3,4) + real(8) :: opt_apy(3), opt_vol(3), opt_w(3), marginal(3) + real(8) :: est_mean, est_var, next_mean, next_var + integer :: est_i + type(token_state) :: state0, state1 + real(8) :: e_before, e_half, e_quarter + if (abs(lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)-0.052d0) > 1d-9) error stop 'below kink' + if (lending_rate(0.90d0,0.02d0,0.04d0,0.60d0,0.80d0) <= lending_rate(0.80d0,0.02d0,0.04d0,0.60d0,0.80d0)) error stop 'kink slope' + if (.not. stock_flow_conserved(100d0,50d0,20d0,30d0,200d0,1d-9)) error stop 'conservation' + exposure = 0d0; exposure(2,1)=0.5d0; shock=[1d0,0d0,0d0] + call contagion_step(exposure, shock, propagated) + if (propagated(2) <= 0d0 .or. abs(propagated(3)) > 1d-12) error stop 'directional contagion' + apy=[0.04d0,0.08d0,0.06d0]; vol=[0.01d0,0.10d0,0.03d0] + call yield_weights(apy,vol,4d0,w) + if (abs(sum(w)-1d0)>1d-9) error stop 'weights normalize' + + state0 = token_state(600d0,250d0,100d0,50d0,1000d0) + call token_state_step(state0,20d0,5d0,10d0,-4d0,state1) + if (abs(state1%total_minted-1020d0)>1d-9) error stop 'minted supply' + if (abs(state1%burned-55d0)>1d-9) error stop 'burn accounting' + if (abs(state1%staked-260d0)>1d-9) error stop 'stake flow' + if (abs(state1%locked-96d0)>1d-9) error stop 'unlock flow' + if (.not. stock_flow_conserved(state1%circulating,state1%staked,state1%locked, & + state1%burned,state1%total_minted,1d-9)) error stop 'state conservation' + + e_before = halving_emission_rate(20d0,99d0,100d0) + e_half = halving_emission_rate(20d0,100d0,100d0) + e_quarter = halving_emission_rate(20d0,200d0,100d0) + if (abs(e_before-20d0)>1d-12) error stop 'pre-halving emission' + if (abs(e_half-10d0)>1d-12) error stop 'first halving' + if (abs(e_quarter-5d0)>1d-12) error stop 'second halving' + + + collateral = [100d0,100d0,100d0,100d0] + borrowed = [90d0,50d0,20d0,20d0] + ltv = [0.80d0,0.80d0,0.80d0,0.80d0] + cascade_exposure = 0d0 + cascade_exposure(2,1) = 0.50d0 + cascade_exposure(3,2) = 0.50d0 + call liquidation_cascade(collateral,borrowed,ltv,cascade_exposure,3,losses) + if (abs(losses(1)-10d0)>1d-9) error stop 'initial liquidation' + if (losses(2) <= 0d0) error stop 'first contagion hop' + if (losses(3) <= 0d0) error stop 'second contagion hop' + if (abs(losses(4)) > 1d-12) error stop 'isolated protocol' + + var_a = 0d0 + var_a(2,1) = 0.40d0 + var_a(3,2) = 0.50d0 + call var_impulse_response(var_a,[1d0,0d0,0d0],3,impulse) + if (abs(impulse(1,1)-1d0)>1d-12) error stop 'impulse origin' + if (abs(impulse(2,2)-0.40d0)>1d-12) error stop 'var first hop' + if (abs(impulse(3,3)-0.20d0)>1d-12) error stop 'var second hop' + if (abs(impulse(1,4))+abs(impulse(2,4))+abs(impulse(3,4)) > 1d-12) & + error stop 'impulse decay' + + + opt_apy = [0.06d0,0.08d0,0.07d0] + opt_vol = [0.10d0,0.12d0,0.08d0] + call yield_weights(opt_apy,opt_vol,2d0,opt_w) + if (abs(sum(opt_w)-1d0)>1d-10) error stop 'optimal weights normalize' + if (minval(opt_w) <= 0d0) error stop 'expected active set' + marginal = opt_apy - 4d0*opt_vol*opt_vol*opt_w + if (maxval(marginal)-minval(marginal) > 1d-8) error stop 'yield KKT stationarity' + + + est_mean = 0d0 + est_var = 100d0 + do est_i=1,20 + call kalman_scalar_update(est_mean,est_var,100d0,4d0,1d0,next_mean,next_var) + est_mean = next_mean + est_var = next_var + end do + if (abs(est_mean-100d0)>0.5d0) error stop 'state estimate convergence' + if (est_var >= 4d0) error stop 'state estimate uncertainty' + print *, 'TOKENOMICS TESTS PASSED' +end program diff --git a/core/src/economy/stomach.tcl b/core/src/economy/stomach.tcl new file mode 100644 index 0000000..41d1962 --- /dev/null +++ b/core/src/economy/stomach.tcl @@ -0,0 +1,148 @@ +# M0 stomach/economy organ composition for sica-fondt. +# The stomach is an OUTER organ. Market execution remains simulation-only here; +# M3's native engines are registered as subordinate simulation processes. +namespace eval ::stomach { variable version 0.2; variable root } +set __stomach_dir [file dirname [file normalize [info script]]] +set ::stomach::root $__stomach_dir +foreach __stomach_file { + traders.tcl wallets.tcl sae.tcl conductor.tcl feeds.tcl + sims/registry.tcl sims/scheduler.tcl sims/hub.tcl + sims/statistical/runner.tcl sims/amm/runner.tcl + sims/sociological/runner.tcl marketplace.tcl +} { + source [file join $__stomach_dir $__stomach_file] +} +unset __stomach_file + +oo::class create ::stomach::Economy { + variable traders wallets sae conductor feeds sims registry clock statistical_runner amm_runner sociological_runner market taxes + constructor {args} { + set cap 256 + if {[llength $args] % 2 != 0} { error "options must be key/value pairs" } + foreach {k v} $args { + switch -- $k { + -history_cap { set cap $v } + default { error "unknown option $k" } + } + } + set traders [::stomach::Traders new] + set wallets [::stomach::Wallets new] + set sae [::stomach::SAEMonitor new] + set conductor [::stomach::Conductor new $traders] + set feeds [::stomach::Feeds new $cap] + set sims [::stomach::SimsHub new] + set registry [::stomach::EngineRegistry new [file join $::stomach::root sims]] + set clock [::stomach::HorizonClock new] + $clock start + set statistical_runner [::stomach::StatisticalRunner new [file join $::stomach::root sims statistical engine.R]] + set amm_runner [::stomach::AMMRunner new] + set sociological_runner [::stomach::SociologicalRunner new [file join $::stomach::root sims sociological engine.ecl]] + set market [::stomach::Marketplace new $traders $wallets $conductor $sae $sims] + set taxes {} + } + destructor { + foreach obj [list $market $sociological_runner $amm_runner $statistical_runner $clock $registry $sims $feeds $conductor $sae $wallets $traders] { + catch {$obj destroy} + } + } + method register_trader {id specialization} { return [$traders register $id $specialization] } + method bind_wallet {wallet_id trader_id daily_limit per_action_limit} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + return [$wallets bind $wallet_id $trader_id $daily_limit $per_action_limit] + } + method submit_action {trader_id wallet_id action} { return [$market submit $trader_id $wallet_id $action] } + method conductor_veto_next {trader_id reason} { return [$conductor veto_next $trader_id $reason] } + method conductor_pause {trader_id reason} { return [$conductor pause $trader_id $reason] } + method conductor_resume {trader_id reason} { return [$conductor resume $trader_id $reason] } + method sae_alert {trader_id alert_type evidence severity timestamp} { + if {![$traders exists $trader_id]} { error "unknown_trader" } + return [$conductor receive_alert [$sae alert $trader_id $alert_type $evidence $severity $timestamp]] + } + method feed_publish {args} { return [$feeds publish {*}$args] } + method feed_history {feed_type} { return [$feeds history $feed_type] } + method sim_publish {sim_type prediction} { return [$sims publish $sim_type $prediction] } + method statistical_runner_available {} { return [$statistical_runner available] } + method amm_runner_available {} { return [$amm_runner available] } + method sociological_runner_available {} { return [$sociological_runner available] } + method sociological_from_feed {ticker prediction_type horizon} { + set p [$sociological_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history rss_news]] + $sims publish sociological $p + return $p + } + method amm_from_feed {ticker prediction_type horizon} { + set p [$amm_runner query_history $ticker $prediction_type $horizon [$feeds history price_tick] [$feeds history dex_pool_state]] + $sims publish amm_liquidity $p + return $p + } + method statistical_query_type { + prices ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + {pool_prices {}} {pool_liquidity {}} + } { + set p [$statistical_runner query_typed $prices $ticker $prediction_type $horizon $paths $seed $dt $pool_prices $pool_liquidity] + $sims publish statistical $p + return $p + } + method statistical_query {prices ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my statistical_query_type $prices $ticker price_forecast $horizon $paths $seed $dt {} {}] + } + method statistical_from_feed_type { + ticker prediction_type horizon + {paths 4000} {seed 1} {dt 0.0027397260273972603} + } { + set prices {} + foreach datum [$feeds history price_tick] { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token]} { continue } + if {$token ne $ticker} { continue } + if {[catch {dict get $payload price} price]} { continue } + if {![string is double -strict $price] || $price <= 0} { continue } + lappend prices $price + } + if {[llength $prices] < 80} { error "insufficient_price_history" } + + set pool_prices {} + set pool_liquidity {} + foreach datum [$feeds history dex_pool_state] { + if {![dict exists $datum payload]} { continue } + set payload [dict get $datum payload] + if {[catch {dict get $payload token_ticker} token]} { continue } + if {$token ne $ticker} { continue } + if {[catch {dict get $payload price} price]} { continue } + if {![string is double -strict $price] || $price <= 0} { continue } + set liquidity 1.0 + if {![catch {dict get $payload liquidity} raw_liquidity] && + [string is double -strict $raw_liquidity] && $raw_liquidity >= 0} { + set liquidity $raw_liquidity + } + lappend pool_prices $price + lappend pool_liquidity $liquidity + } + + return [my statistical_query_type $prices $ticker $prediction_type $horizon $paths $seed $dt $pool_prices $pool_liquidity] + } + method statistical_from_feed {ticker horizon {paths 4000} {seed 1} {dt 0.0027397260273972603}} { + return [my statistical_from_feed_type $ticker price_forecast $horizon $paths $seed $dt] + } + method query_predictions {trader_id sim_type} { return [$market predictions $trader_id $sim_type] } + method sim_engines {} { return [$registry names] } + method sim_engine_status {} { return [$registry status] } + method sim_horizons {} { return [$clock horizons] } + method sim_running {} { return [$clock running] } + method sim_advance {wall_seconds} { return [$clock advance $wall_seconds] } + method tax_event {trader_id amount source_wallet dest_wallet} { + if {![string is double -strict $amount] || $amount < 0} { error "invalid_tax_amount" } + set receipt [dict create receipt_id [format "tax-%06d" [expr {[llength $taxes] + 1}]] status staged transferred 0 trader_id $trader_id amount $amount source_wallet $source_wallet dest_wallet $dest_wallet] + lappend taxes $receipt + return $receipt + } + method secretion {} { + return [dict create source stomach destination ada_border provenance organ_secretion live_execution 0 traders [$traders count] wallets [$wallets count] sim_engines [llength [$registry names]] predictions [$sims count] executions [$market execution_count] paused_traders [$traders paused_count] tax_receipts [llength $taxes]] + } + method sae_log {} { return [$sae log] } + method decision_log {} { return [$conductor log] } + method execution_count {} { return [$market execution_count] } + method live_execution {} { return 0 } +} +unset __stomach_dir diff --git a/core/src/economy/tests/stomach.test b/core/src/economy/tests/stomach.test new file mode 100644 index 0000000..bb9387d --- /dev/null +++ b/core/src/economy/tests/stomach.test @@ -0,0 +1,173 @@ +package require tcltest 2 +namespace import ::tcltest::* + +set here [file dirname [file normalize [info script]]] +source [file join $here .. stomach.tcl] + +proc new_stomach {{cap 2}} { + set s [::stomach::Economy new -history_cap $cap] + $s register_trader trader-a statistical + $s register_trader trader-b microstructure + return $s +} + +test walletless-rejected-1.0 {M1 L3 rejects a trader with no wallet before execution} -body { + set s [new_stomach] + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 0.1 price 100.0]] + set out [list [dict get $result status] [dict get $result reason] [$s execution_count]] + $s destroy + set out +} -result {failed missing_wallet 0} + +test binding-rejected-1.0 {M4 one-to-one binding prevents use of another trader's wallet} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s bind_wallet wallet-b trader-b 1000.0 500.0 + set result [$s submit_action trader-a wallet-b [dict create type buy asset ETH chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $result status] [dict get $result reason]] + $s destroy + set out +} -result {failed wallet_binding} + +test valid-dry-run-1.0 {valid market action traverses M1/M4/M6 and remains simulated} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 2.0 price 100.0]] + set out [list [dict get $result status] [dict get $result execution] [dict get $result tx_id] [$s execution_count]] + $s destroy + set out +} -result {succeeded simulated simtx-000001 1} + +test law-before-veto-1.0 {M1 rejects a law violation before M6 veto is consumed} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s conductor_veto_next trader-a strategic_risk + set bad [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain forbidden-chain amount 1.0 price 10.0]] + set good [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $bad reason] [dict get $good reason] [$s execution_count]] + $s destroy + set out +} -result {chain_not_allowed strategic_risk 0} + +test every-action-logged-1.0 {M7 receives pass and fail marketplace submissions} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s submit_action trader-a wallet-a [dict create type buy asset BTC chain forbidden-chain amount 1.0 price 10.0] + $s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0] + set events [$s sae_log] + set out [list [llength $events] [dict get [lindex $events 0] tool] [dict get [lindex $events 1] tool]] + $s destroy + set out +} -result {2 submit_action submit_action} + +test severe-sae-alert-pauses-1.0 {M7 severe alert reaches M6 and mechanically pauses trader} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + set decision [$s sae_alert trader-a frequency_spike {burst of calls} 9 1700000000] + set attempt [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [list [dict get $decision decision] [dict get $attempt reason]] + $s destroy + set out +} -result {pause trader_paused} + +test resume-1.0 {M6 pause is reversible} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s conductor_pause trader-a manual_review + $s conductor_resume trader-a cleared + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 10.0]] + set out [dict get $result status] + $s destroy + set out +} -result succeeded + +test bounded-prediction-1.0 {M3 rejects a point estimate outside its explicit bounds} -body { + set s [new_stomach] + set code [catch {$s sim_publish statistical [dict create value 11.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 7.0 certainty 7.0 time_horizon 4h token_ticker BTC recent_shift 0.0 timestamp 1700000000]} msg] + set out [list $code $msg] + $s destroy + set out +} -result {1 prediction_out_of_bounds} + +test marketplace-prediction-query-1.0 {trader reads bounded predictions through Marketplace, not sim hub directly} -body { + set s [new_stomach] + $s sim_publish statistical [dict create value 7.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 8.0 certainty 6.0 time_horizon 4h token_ticker BTC recent_shift -0.02 timestamp 1700000000] + set p [$s query_predictions trader-a statistical] + set out [list [dict get $p value] [dict get $p lower_bound] [dict get $p upper_bound]] + $s destroy + set out +} -result {7.0 5.0 10.0} + +test feed-backpressure-1.0 {M2 returns backpressure without silently dropping buffered data} -body { + set s [new_stomach 2] + set a [$s feed_publish price_tick source-a 1 {BTC 100} 9.0] + set b [$s feed_publish price_tick source-a 2 {BTC 101} 9.0] + set c [$s feed_publish price_tick source-a 3 {BTC 102} 9.0] + set h [$s feed_history price_tick] + set out [list [dict get $a status] [dict get $b status] [dict get $c status] [llength $h] [dict get [lindex $h 1] timestamp]] + $s destroy + set out +} -result {accepted accepted backpressure 2 2} + +test wallet-limit-1.0 {M4 wallet-level per-action limit independently brakes exposure} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 50.0 + set result [$s submit_action trader-a wallet-a [dict create type buy asset BTC chain ethereum amount 1.0 price 100.0]] + set out [list [dict get $result status] [dict get $result reason]] + $s destroy + set out +} -result {failed wallet_limit} + +test tax-stub-1.0 {M0 tax hook produces a receipt but does not transfer value} -body { + set s [new_stomach] + set r [$s tax_event trader-a 12.5 wallet-a verein-wallet] + set out [list [dict get $r status] [dict get $r transferred] [dict get $r amount]] + $s destroy + set out +} -result {staged 0 12.5} + +test secretion-1.0 {M0 produces an Ada-bound organ secretion summary} -body { + set s [new_stomach] + $s bind_wallet wallet-a trader-a 1000.0 500.0 + $s sim_publish statistical [dict create value 7.0 lower_bound 5.0 upper_bound 10.0 confidence 7.0 correctness 8.0 certainty 6.0 time_horizon 4h token_ticker BTC recent_shift -0.02 timestamp 1700000000] + set secretion [$s secretion] + set out [list [dict get $secretion source] [dict get $secretion destination] [dict get $secretion provenance] [dict get $secretion live_execution]] + $s destroy + set out +} -result {stomach ada_border organ_secretion 0} + +test sim-engine-registry-1.0 {M0 exposes all seven built-in M3 engine identities} -body { + set s [new_stomach] + set n [llength [$s sim_engines]] + $s destroy + set n +} -result 7 + +test sim-engine-sources-1.0 {all seven registered native engine sources are present in the organ tree} -body { + set s [new_stomach] + set status [$s sim_engine_status] + set ok 1 + dict for {name state} $status { + if {![dict get $state source_present]} { set ok 0 } + } + $s destroy + set ok +} -result 1 + +test sim-six-horizons-1.0 {M0 advances all six forecast clocks and preserves 90:1 minimum speed} -body { + set s [new_stomach] + set horizons [$s sim_horizons] + set state [$s sim_advance 1.0] + set out [list [llength $horizons] [dict get $state tick_hourly] [dict get $state five_year]] + $s destroy + set out +} -result {6 90.0 3942000.0} + +test sim-clock-running-1.0 {M3 horizon scheduler starts with the stomach} -body { + set s [new_stomach] + set running [$s sim_running] + $s destroy + set running +} -result 1 + +cleanupTests diff --git a/core/src/economy/traders.tcl b/core/src/economy/traders.tcl new file mode 100644 index 0000000..9ed45dd --- /dev/null +++ b/core/src/economy/traders.tcl @@ -0,0 +1,31 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Traders { + variable records paused + constructor {} { set records {}; set paused {} } + + method register {trader_id specialization} { + if {[dict exists $records $trader_id]} { error "trader_exists" } + dict set records $trader_id [dict create specialization $specialization] + dict set paused $trader_id 0 + return [dict create status registered trader_id $trader_id specialization $specialization] + } + method exists {trader_id} { return [dict exists $records $trader_id] } + method pause {trader_id} { + if {![my exists $trader_id]} { error "unknown_trader" } + dict set paused $trader_id 1 + } + method resume {trader_id} { + if {![my exists $trader_id]} { error "unknown_trader" } + dict set paused $trader_id 0 + } + method is_paused {trader_id} { + expr {[dict exists $paused $trader_id] && [dict get $paused $trader_id]} + } + method count {} { return [dict size $records] } + method paused_count {} { + set n 0 + dict for {id p} $paused { if {$p} { incr n } } + return $n + } +} diff --git a/core/src/economy/wallets.tcl b/core/src/economy/wallets.tcl new file mode 100644 index 0000000..340c71e --- /dev/null +++ b/core/src/economy/wallets.tcl @@ -0,0 +1,39 @@ +namespace eval ::stomach {} + +oo::class create ::stomach::Wallets { + variable wallets wallet_for_trader spend + constructor {} { set wallets {}; set wallet_for_trader {}; set spend {} } + + method bind {wallet_id trader_id daily_limit per_action_limit} { + if {[dict exists $wallets $wallet_id]} { error "wallet_already_bound" } + if {[dict exists $wallet_for_trader $trader_id]} { error "trader_already_bound" } + foreach {name value} [list daily_limit $daily_limit per_action_limit $per_action_limit] { + if {![string is double -strict $value] || $value <= 0} { error "${name}_must_be_positive" } + } + # No key material exists here. Binding/limits are implemented first; local + # key generation/signing waits for the still-open M4 storage specification. + dict set wallets $wallet_id [dict create trader_id $trader_id daily_limit $daily_limit per_action_limit $per_action_limit] + dict set wallet_for_trader $trader_id $wallet_id + dict set spend $wallet_id 0.0 + return [dict create status bound wallet_id $wallet_id trader_id $trader_id] + } + method binding_for {trader_id} { + if {![dict exists $wallet_for_trader $trader_id]} { return "" } + return [dict get $wallet_for_trader $trader_id] + } + method binding_matches {trader_id wallet_id} { + expr {[dict exists $wallet_for_trader $trader_id] && [dict get $wallet_for_trader $trader_id] eq $wallet_id && [dict exists $wallets $wallet_id] && [dict get $wallets $wallet_id trader_id] eq $trader_id} + } + method spending_check {wallet_id action} { + set w [dict get $wallets $wallet_id] + set notional [expr {double([dict get $action amount]) * double([dict get $action price])}] + if {$notional > double([dict get $w per_action_limit])} { return [dict create pass 0 reason wallet_limit] } + set used [dict get $spend $wallet_id] + if {$used + $notional > double([dict get $w daily_limit])} { return [dict create pass 0 reason wallet_daily_limit] } + return [dict create pass 1 notional $notional] + } + method record_spend {wallet_id notional} { + dict set spend $wallet_id [expr {[dict get $spend $wallet_id] + $notional}] + } + method count {} { return [dict size $wallets] } +} diff --git a/docmap.yaml b/docmap.yaml index afc5958..3d72890 100644 --- a/docmap.yaml +++ b/docmap.yaml @@ -39,6 +39,11 @@ organs: lang: [r, octave] role: endocrine array — R Drive-Box + Octave ETR build: "src/endocrine/run_tests.sh ; src/endocrine/etr/run_etr_tests.sh" + - path: core/src/economy + agents_md: core/src/economy/AGENTS.md + lang: tcl + role: M0 stomach/economy organ scaffold — M1–M7 simulation and Ada-bound secretion + build: "tclsh core/src/economy/tests/stomach.test" - path: core agents_md: core/AGENTS.md lang: [ada, cobol]