mirror of
https://github.com/SHOGGOTH-SECTOR/sica-fondt.git
synced 2026-11-30 00:35:10 +00:00
Merge pull request #18 from SHOGGOTH-SECTOR/feat/stomach-economic-organ
Implement stomach/economy organ and M3 simulator family
This commit is contained in:
@@ -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 <<EOF
|
||||||
|
#!/bin/sh
|
||||||
|
ECLIPSEDIR="${ECLIPSE_ROOT}"
|
||||||
|
export ECLIPSEDIR
|
||||||
|
export LD_LIBRARY_PATH="${ECLIPSE_ROOT}/lib/${ECLIPSE_ARCH}:\${LD_LIBRARY_PATH:-}"
|
||||||
|
exec "${ECLIPSE_ROOT}/lib/${ECLIPSE_ARCH}/eclipse.exe" -D "${ECLIPSE_ROOT}" "\$@"
|
||||||
|
EOF
|
||||||
|
sudo chmod 0755 /usr/local/bin/eclipse
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Fail loudly if the installed runtime cannot execute a noninteractive goal.
|
||||||
|
eclipse -e 'writeln("ECLIPSE_TOOLCHAIN_READY")'
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
# in Claude Code on the web:
|
# in Claude Code on the web:
|
||||||
# * R (Rscript) -> the Drive-Box drivers + tests (src/endocrine/*.R)
|
# * R (Rscript) -> the Drive-Box drivers + tests (src/endocrine/*.R)
|
||||||
# * GNU Octave -> the ETR torus + tests (src/endocrine/etr/*.m)
|
# * 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).
|
# 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
|
# Ada/Alire (mafiabot_core) is intentionally NOT installed here: it is not an apt
|
||||||
@@ -20,6 +21,7 @@ export DEBIAN_FRONTEND=noninteractive
|
|||||||
pkgs=()
|
pkgs=()
|
||||||
command -v Rscript >/dev/null 2>&1 || pkgs+=(r-base-core)
|
command -v Rscript >/dev/null 2>&1 || pkgs+=(r-base-core)
|
||||||
command -v octave >/dev/null 2>&1 || pkgs+=(octave)
|
command -v octave >/dev/null 2>&1 || pkgs+=(octave)
|
||||||
|
command -v gfortran >/dev/null 2>&1 || pkgs+=(gfortran)
|
||||||
|
|
||||||
if [ "${#pkgs[@]}" -gt 0 ]; then
|
if [ "${#pkgs[@]}" -gt 0 ]; then
|
||||||
sudo apt-get update -qq
|
sudo apt-get update -qq
|
||||||
@@ -29,3 +31,4 @@ fi
|
|||||||
# Surface versions in the session log (non-fatal).
|
# Surface versions in the session log (non-fatal).
|
||||||
command -v Rscript >/dev/null 2>&1 && Rscript --version 2>&1 | head -1 || true
|
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 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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -12,13 +12,15 @@ organism are TBD and out of scope.
|
|||||||
Brain for permission to trade.
|
Brain for permission to trade.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. A `Stomach` primitive exists in Ichor (`src/ichor/envelope.pony:20`) with
|
SCAFFOLD · EXECUTABLE. The existing Ichor `Stomach` primitive now has a dedicated
|
||||||
one smoke-test wire (`main.pony:29`), but no dedicated organ code. Role C4; implementation C1.
|
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
|
## 3. Language & location
|
||||||
TBD · new location e.g. `src/economy/`. The organ is polyglot by nature: trading infrastructure
|
**Tcl 8.6 scaffold** · `core/src/economy/`. M0 orchestration is Tcl and preserves the
|
||||||
(APIs, wallets) may differ in language from simulations (numerical computing) and the conductor
|
existing polyglot plan for later component engines. Pony remains the Ichor-facing transport layer;
|
||||||
(AI supervision). Pony actors provide the Ichor-facing facade.
|
the runtime bridge between Ichor and this scaffold is still open.
|
||||||
|
|
||||||
## 4. Does / does-not
|
## 4. Does / does-not
|
||||||
- **Does:** host crypto/NFT trading via the Marketplace (M1); run always-on market prediction
|
- **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.
|
4. Implement tax stub and Verschwörern Veregeister transfer last.
|
||||||
|
|
||||||
## 9. Tests
|
## 9. Tests
|
||||||
Hub smoke: Marketplace reachable; Sims running and queryable; Wallet bound to Trader; Conductor
|
Executable contract suite: `tclsh core/src/economy/tests/stomach.test`. The current 17
|
||||||
receives SAE reports; tax stub logs transfer. Ichor: outbound envelope reaches Ada stub.
|
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
|
## 10. Open items
|
||||||
- Reward signal protocol from economy organ to organism (TBD, out of scope).
|
- Reward signal protocol from economy organ to organism (TBD, out of scope).
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ the Marketplace. Enforces a **deterministic law script** (scoped invariants —
|
|||||||
own constitution) and integrates the **Conductor's veto** (M6) before execution.
|
own constitution) and integrates the **Conductor's veto** (M6) before execution.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 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
|
## 3. Language & location
|
||||||
TBD · `src/economy/marketplace/`. Needs to interface with blockchain APIs (RPC/REST), wallet
|
TBD · `src/economy/marketplace/`. Needs to interface with blockchain APIs (RPC/REST), wallet
|
||||||
|
|||||||
@@ -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.
|
predictions that inform Traders operating through the Marketplace. Data Feeds is the bridge.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 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
|
## 3. Language & location
|
||||||
TBD · `src/economy/feeds/`. Needs async I/O for streaming data (WebSockets, SSE, RSS polling).
|
TBD · `src/economy/feeds/`. Needs async I/O for streaming data (WebSockets, SSE, RSS polling).
|
||||||
|
|||||||
@@ -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].
|
tokenomics via SDEs [6,7], and evolutionary consensus games [8–11].
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Role C3; implementation C1. Mathematical foundations C4 (literature
|
EXECUTABLE KERNEL SET. `core/src/economy/sims/` now contains all seven native engine
|
||||||
established); specific model parameters C1.
|
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
|
## 3. Language & location
|
||||||
**Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages
|
**Tcl** · `src/economy/sims/`. The hub is a syntax-agnostic coordinator: Tcl manages
|
||||||
|
|||||||
@@ -8,12 +8,18 @@ stochastic volatility, regime detection, and cross-asset correlation**. The math
|
|||||||
**stochastic sample paths**, not behavioral agents.
|
**stochastic sample paths**, not behavioral agents.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Core quant methods C5 (GBM, GARCH, ARIMA — textbook). Heston stochastic
|
IMPLEMENTED · M3a V1 · R. `core/src/economy/sims/statistical/engine.R` now
|
||||||
volatility C5 (closed-form characteristic function; industry standard since 1993). Rough
|
implements the complete V1 statistical stack: GBM, Merton jump-diffusion, full-truncation Heston
|
||||||
volatility C4 (Gatheral et al. 2018, heavily cited; crypto implementations exist). HMM regime
|
simulation, GARCH(1,1) QMLE, three-state Gaussian HMM training + Viterbi decoding,
|
||||||
detection C4 (established; crypto-specific copula hybrids emerging 2023–2024). Almgren-Chriss
|
Davies–Harte fractional Gaussian noise and fitted rough volatility, fitted DCC dynamic
|
||||||
execution C5 (industry standard since 2001). Jump-diffusion C5 (Merton 1976). Parameterization
|
correlation, t-copula tail dependence with degrees-of-freedom estimation, conjugate Bayesian
|
||||||
for crypto markets C1.
|
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
|
## 3. Language & location
|
||||||
**R 4.x** (apt `r-base-core`) · `src/economy/sims/statistical/`. Vital CRAN packages only:
|
**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.
|
- Calibration: ingests `price_tick` and `dex_pool_state` from M2 Data Feeds.
|
||||||
|
|
||||||
## 6. Dependencies & stubs
|
## 6. Dependencies & stubs
|
||||||
- M2 Data Feeds — price history for calibration; *stub:* canned price series.
|
- M2 Data Feeds — normalized `price_tick` and `dex_pool_state` histories are consumed by
|
||||||
- M3 Sims hub — lifecycle management; *stub:* manual init.
|
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
|
## 7. Invariants / laws
|
||||||
- **L1 (C5):** bounds are **statistical confidence intervals** — derived from the model's
|
- **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
|
correlation spike). Jump-diffusion: fat tails reproduced. Calibration: new data shifts parameter
|
||||||
estimates. Multi-horizon: all six horizons produce concurrent outputs.
|
estimates. Multi-horizon: all six horizons produce concurrent outputs.
|
||||||
|
|
||||||
## 10. Open items
|
## 10. V1 decisions and future extensions
|
||||||
- Heston calibration method (characteristic function inversion? particle filter?).
|
- **Heston calibration:** resolved with characteristic-function inversion and numerical
|
||||||
- Rough vol computational cost (fBM generation is O(N²) naively; FFT methods needed).
|
option-surface calibration; realized-price proxy calibration remains available when no option
|
||||||
- HMM state count (3 sufficient? 4+ for crypto with "mania" regime?).
|
surface exists.
|
||||||
- Which copula family for tail dependence ($t$-copula? Clayton? Joe?).
|
- **Rough-vol cost:** resolved with Davies–Harte circulant embedding / FFT rather than the
|
||||||
- Computational budget per horizon (GPU for Monte Carlo paths?).
|
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.
|
||||||
|
|||||||
@@ -10,11 +10,17 @@ pressure across **six concurrent time horizons**. Grounded in evolutionary conse
|
|||||||
MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs.
|
MFG theory (Lasry & Lions 2007), and crypto manipulation ABMs.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Evolutionary game theory C4 (Cornell [8]). Hegselmann-Krause bounded
|
IMPLEMENTED · M3b V1 · ECLiPSe Prolog. `core/src/economy/sims/sociological/engine.ecl`
|
||||||
confidence C5 (established 2002). Complex contagion C4 (Centola & Macy 2007; crypto applications
|
implements five abstract behavioral archetypes, replicator dynamics, Hegselmann–Krause bounded
|
||||||
C3). Bandit-replicator hybrid C3 (emerging). Mean-Field Games C4 (Lasry & Lions 2007; tensor-train
|
confidence, heterogeneous complex contagion with a multiple-exposure requirement, UCB
|
||||||
solvers C3). Crypto pump-and-dump ABM C3 (3-agent protocol validated on historical data).
|
bandit-replicator learning, a large-population HJB/Fokker–Planck mean-field equilibrium solver
|
||||||
Pop behavioral models C1.
|
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
|
## 3. Language & location
|
||||||
**ECLiPSe Prolog 7.2** · `src/economy/sims/sociological/`. Libraries: **ic** (interval
|
**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`.
|
`pump_dump_phase`, `mfg_equilibrium_stability`, `narrative_regime`.
|
||||||
- Calibration: ingests `rss_news` (sentiment signal) and `price_tick` (realized behavior) from M2.
|
- Calibration: ingests `rss_news` (sentiment signal) and `price_tick` (realized behavior) from M2.
|
||||||
|
|
||||||
## 6. Dependencies & stubs
|
## 6. Dependencies & runtime boundary
|
||||||
- M2 Data Feeds — sentiment and price data for calibration; *stub:* canned sentiment series.
|
- M2 Data Feeds — normalized `rss_news` carries aggregate source type, sentiment, engagement
|
||||||
- M3 Sims hub — lifecycle management; *stub:* manual init.
|
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
|
## 7. Invariants / laws
|
||||||
- **L1 (C5):** pops are **archetypal individuals, not literal living persons** — no attempt to model or track real
|
- **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
|
small N. Pump-dump: 4-phase cycle detected on synthetic manipulation data. Bounds: all outputs
|
||||||
include upper/lower.
|
include upper/lower.
|
||||||
|
|
||||||
## 10. Open items
|
## 10. V1 decisions and future extensions
|
||||||
- Pop archetype catalog (which behavioral types? how many?).
|
- **Archetypes:** V1 canonically uses retail herd, contrarian whale, MEV searcher, passive LP,
|
||||||
- Network topology for sentiment contagion (small-world? scale-free?).
|
and manipulator populations. These are abstract strategy populations, never real-person
|
||||||
- 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<<<
|
profiles.
|
||||||
- MFG tensor-train rank $r$ (>>>accuracy<<< vs. compute tradeoff).
|
- **Social evidence:** M2 source types such as blog, Reddit and social-network aggregates infer
|
||||||
- Hegselmann-Krause confidence bound $d$ — fixed or >>>adaptive<<<?
|
population pressures. The runner combines engagement/confidence-weighted sentiment with
|
||||||
- Cross-sim interaction: do sociological predictions feed into M3c (AMM) or M3d (MEV)? [conditional on prediction accuracy over time]
|
realized price response and keeps state per ticker.
|
||||||
|
- **Network topology:** V1 complex contagion consumes heterogeneous exposure/degree evidence
|
||||||
|
without committing to one universal graph topology. Explicit small-world/scale-free graph
|
||||||
|
reconstruction is a future fidelity layer.
|
||||||
|
- **MFG dimensionality:** V1 uses a one-dimensional finite-difference HJB/FP equilibrium with
|
||||||
|
damped Newton iteration. Tensor-train compression and rank selection become relevant only
|
||||||
|
when adding genuinely high-dimensional MFG state.
|
||||||
|
- **Confidence bound:** adaptive in V1; volatility and opinion dispersion tighten the bound.
|
||||||
|
- **Cross-sim use:** M3b now emits empirical walk-forward `correctness`, so downstream
|
||||||
|
cross-sim coupling can be gated by measured accuracy. Automatic M3b→M3c/M3d intervention is
|
||||||
|
intentionally a future hub-policy decision, not embedded inside the sociological engine.
|
||||||
|
|||||||
@@ -7,9 +7,16 @@ loss, and the non-cooperative game between liquidity providers and arbitrageurs*
|
|||||||
literature [1,2].
|
literature [1,2].
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Mathematical foundations C5 (constant product invariant is proven);
|
IMPLEMENTED · M3c V1 · Solidity/Foundry. `core/src/economy/sims/amm/src/AMMSim.sol`
|
||||||
impermanent loss formula C5 (closed-form: $\text{IL}(r) = \frac{2\sqrt{r}}{1+r} - 1$);
|
implements fee-adjusted constant-product swaps, exact fixed-point impermanent loss, nonlinear
|
||||||
simulation parameterization C1.
|
slippage, IL-derived withdrawal thresholds, active LP rebalance, just-in-time liquidity economics,
|
||||||
|
deterministic backrun and sandwich populations, concentrated-liquidity position/range accounting,
|
||||||
|
two-pool optimal split routing, and all five bounded M3c prediction types. `AMMQuery.sol` is a
|
||||||
|
read-only EVM ABI bridge; `runner.tcl` calibrates from M2 `price_tick` + `dex_pool_state`,
|
||||||
|
evaluates the Solidity engine via `eth_call`, and publishes the result into the M3 hub for
|
||||||
|
Marketplace consumption. Dedicated Foundry CI verifies both native math and the M2→M3c→Hub
|
||||||
|
boundary on an ephemeral local Anvil instance. Mathematical foundations C5; implementation C3;
|
||||||
|
live-market parameterization remains data-dependent.
|
||||||
|
|
||||||
## 3. Language & location
|
## 3. Language & location
|
||||||
**Solidity** + **Foundry** (forge, anvil) · `src/economy/sims/amm/`. Foundry is hosted
|
**Solidity** + **Foundry** (forge, anvil) · `src/economy/sims/amm/`. Foundry is hosted
|
||||||
@@ -47,9 +54,15 @@ execute, eliminating precision-mismatch bugs between sim and production contract
|
|||||||
`lp_withdrawal_threshold`.
|
`lp_withdrawal_threshold`.
|
||||||
- Calibration: ingests `dex_pool_state` and `price_tick` from M2.
|
- Calibration: ingests `dex_pool_state` and `price_tick` from M2.
|
||||||
|
|
||||||
## 6. Dependencies & stubs
|
## 6. Dependencies & runtime boundary
|
||||||
- M2 Data Feeds — pool state and price data; *stub:* canned pool snapshots.
|
- M2 Data Feeds — normalized `dex_pool_state` supplies reserves, fee tier, volume, TVL and
|
||||||
- M3 Sims hub — lifecycle management; *stub:* manual init.
|
representative trade size; `price_tick` supplies external price, realized movement and
|
||||||
|
volatility calibration.
|
||||||
|
- M3 Sims hub — every M3c result is converted to the common bounded-prediction schema and
|
||||||
|
published as `amm_liquidity`; Traders read it through Marketplace.
|
||||||
|
- Foundry — hosted separately by design. CI uses a fresh local Anvil chain and deploys only the
|
||||||
|
stateless/read-only `AMMQuery` bridge. M3c has no live-chain signer, broadcaster, approval,
|
||||||
|
transfer, or swap-execution surface.
|
||||||
|
|
||||||
## 7. Invariants / laws
|
## 7. Invariants / laws
|
||||||
- **L1 (C5):** the **constant product invariant** $x \cdot y = k$ (adjusted for fees $\gamma$)
|
- **L1 (C5):** the **constant product invariant** $x \cdot y = k$ (adjusted for fees $\gamma$)
|
||||||
@@ -72,7 +85,14 @@ Invariant: every swap satisfies $(x + \gamma \Delta x)(y - \Delta y) = k$. IL fo
|
|||||||
closed-form for known price ratios. Slippage: large swaps produce greater slippage than small.
|
closed-form for known price ratios. Slippage: large swaps produce greater slippage than small.
|
||||||
LP threshold: LP withdraws when IL exceeds fee income. Bounds: all outputs bounded.
|
LP threshold: LP withdraws when IL exceeds fee income. Bounds: all outputs bounded.
|
||||||
|
|
||||||
## 10. Open items
|
## 10. V1 decisions and future extensions
|
||||||
- Concentrated liquidity (>>>Uniswap v3 style<<<) — extends the base model significantly.
|
- **Concentrated liquidity:** V1 implements the canonical liquidity-to-token amount equations,
|
||||||
- Multi-pool routing (split swaps across pools). >>>yes<<<
|
one-sided out-of-range positions, and volatility/horizon-derived optimal ranges. Full
|
||||||
- Which specific pools to simulate (>>>ETH<<</USDC? stablecoin pairs?). >>and other popular chains<< NOT STABLE/USDC/USDT etc.
|
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.
|
||||||
|
|||||||
@@ -13,10 +13,11 @@ dynamics (non-linear Fokker-Planck with WENO shock capturing), and DSMFG bilevel
|
|||||||
(leader policy + follower MFG equilibrium).
|
(leader policy + follower MFG equilibrium).
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. PGA-as-all-pay-auction C4 (ACM [3]); knapsack formulation C4 (Cornell
|
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/mev/` implements the all-pay
|
||||||
[4,5]); cross-chain arbitrage C4 (ACM SIGMETRICS 2025, 5.5x growth since Dencun); DSMFG bilevel
|
PGA payoff model, exact 0/1 block-building knapsack selection, dual-path cross-chain profit
|
||||||
optimization C3 (emerging — SMFRL solvers); Kolokoltsov adversarial C3 (non-linear Fokker-Planck;
|
comparison, sandwich-risk scoring, and aggregate all-pay cost. Native tests compile cleanly
|
||||||
WENO discretization established but crypto application novel). Parameterization C1.
|
under strict gfortran flags. WENO/Kolokoltsov and DSMFG bilevel solvers remain incremental.
|
||||||
|
Core game/knapsack foundations C4; implementation C2; parameterization C1.
|
||||||
|
|
||||||
## 3. Language & location
|
## 3. Language & location
|
||||||
**Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS**
|
**Fortran 2018** (gfortran) · `src/economy/sims/mev/`. Build: **fpm**. Dependencies: **OpenBLAS**
|
||||||
|
|||||||
@@ -13,10 +13,12 @@ frameworks [6], Aave/Compound kinked interest rate models (industry standard), a
|
|||||||
inter-protocol credit propagation (Matzakos et al. 2025).
|
inter-protocol credit propagation (Matzakos et al. 2025).
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. SDE state-space framework C4 (Vienna [7]); stock-flow modeling C4
|
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/tokenomics/` implements
|
||||||
(ResearchGate [6]); kinked interest rate model C5 (Aave/Compound production standard);
|
Euler-Maruyama state evolution, stock-flow conservation checks, kinked lending curves,
|
||||||
DeXposure inter-protocol credit propagation C3 (emerging, 2025 — high DeFi specificity);
|
directional exposure propagation, risk-adjusted yield allocation, and liquidation shortfall.
|
||||||
composable yield optimization C4 (Yearn v3, Beefy, production-validated). Specific parameters C1.
|
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
|
## 3. Language & location
|
||||||
**Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies:
|
**Fortran 2018** (gfortran) · `src/economy/sims/tokenomics/`. Build: **fpm**. Dependencies:
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ financial incentives. Grounded in Cornell evolutionary consensus [8,9], ACM stak
|
|||||||
theorems [10], and Monash dynamic PBFT modeling [11].
|
theorems [10], and Monash dynamic PBFT modeling [11].
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Evolutionary PoS game theory C4 (Cornell [8]); staking pool Nash
|
KERNEL IMPLEMENTED · ECLiPSe Prolog. `core/src/economy/sims/consensus/engine.ecl`
|
||||||
equilibrium proofs C4 (ACM [10]); Markov chain throughput models C4 (Monash [11]); MFG for
|
implements evolutionary honesty updates, validator-state Markov transitions, an explicit
|
||||||
validator populations C4 (Lasry & Lions 2007; validator-specific application C3);
|
incentive-compatibility slashing threshold, and liveness degradation below an honesty threshold.
|
||||||
simulation parameterization C1.
|
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
|
## 3. Language & location
|
||||||
**ECLiPSe Prolog 7.2** · `src/economy/sims/consensus/`. Libraries: **ic** (interval
|
**ECLiPSe Prolog 7.2** · `src/economy/sims/consensus/`. Libraries: **ic** (interval
|
||||||
|
|||||||
@@ -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).
|
concurrent time horizons** at tick-advanced, 90:1 (1s wall = 90s sim).
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Order-book microstructure theory C4 (established). Almgren-Chriss
|
KERNEL IMPLEMENTED · Fortran 2018. `core/src/economy/sims/microstructure/` implements
|
||||||
optimal execution C5 (industry standard since 2001; crypto adaptations validated 2023–2024,
|
depth-consuming buy slippage, bid/ask spread, Almgren-Chriss execution schedules, exponential
|
||||||
Kurz CMC thesis). DEX-specific microstructure C2 (emerging). Implementation C1.
|
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
|
## 3. Language & location
|
||||||
**Fortran 2018** (gfortran) · `src/economy/sims/microstructure/`. Build: **fpm**. Dependencies:
|
**Fortran 2018** (gfortran) · `src/economy/sims/microstructure/`. Build: **fpm**. Dependencies:
|
||||||
|
|||||||
@@ -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).
|
Tax is collected on trader income and routed to the Verschwörern Veregeister wallets (stub — M0).
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 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
|
## 3. Language & location
|
||||||
TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for
|
TBD · `src/economy/wallets/`. Needs cryptographic key management (secp256k1 for EVM, ed25519 for
|
||||||
|
|||||||
@@ -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**.
|
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
|
## 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
|
## 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.
|
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.
|
||||||
|
|||||||
@@ -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.
|
constrains; together they form the multi-layered braking system.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. Role C4 (supervision architecture is clear); implementation C1 (model
|
SCAFFOLD · EXECUTABLE SUPERVISION. `core/src/economy/conductor.tcl` implements veto ordering,
|
||||||
selection, training, authority scope).
|
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
|
## 3. Language & location
|
||||||
TBD · `src/economy/conductor/`. The Conductor is an AI actor — likely a fine-tuned LLM with
|
TBD · `src/economy/conductor/`. The Conductor is an AI actor — likely a fine-tuned LLM with
|
||||||
|
|||||||
@@ -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.
|
subagents at the organism level; M7 watches traders at the stomach level.
|
||||||
|
|
||||||
## 2. Status / certainty
|
## 2. Status / certainty
|
||||||
DESIGN-FIRST · ABSENT. F2 SAE monitor provides the architectural pattern (watch the machinery,
|
SCAFFOLD · PARTIAL. `core/src/economy/sae.tcl` records Marketplace-level trader calls and
|
||||||
never the homunculus — F2-L1). M7 adapts this: watch the **traders** (the machinery), never the
|
constructs alert envelopes consumed by M6. Sparse-autoencoder inference/training remains open.
|
||||||
**Conductor** (the stomach's judgment). Role C3; implementation C1.
|
F2 still provides the architectural pattern: watch traders, never the Conductor. Role C3;
|
||||||
|
scaffold C2.
|
||||||
|
|
||||||
## 3. Language & location
|
## 3. Language & location
|
||||||
TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader action embeddings).
|
TBD · `src/economy/sae/`. ML interpretability (sparse autoencoder over trader action embeddings).
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -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]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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] }
|
||||||
|
}
|
||||||
@@ -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] }
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[profile.default]
|
||||||
|
src = "src"
|
||||||
|
test = "test"
|
||||||
|
solc_version = "0.8.24"
|
||||||
|
optimizer = true
|
||||||
|
optimizer_runs = 200
|
||||||
@@ -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
|
||||||
@@ -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]]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
);
|
||||||
|
}}
|
||||||
@@ -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<y, "swap");
|
||||||
|
uint256 dxEff=dx*9970/10000;
|
||||||
|
require((x+dxEff)*(y-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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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).
|
||||||
@@ -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).
|
||||||
@@ -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] }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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"
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}]
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -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).
|
||||||
@@ -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
|
||||||
@@ -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]]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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").
|
||||||
@@ -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`).
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||||
@@ -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 {} {}]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")
|
||||||
@@ -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
|
||||||
@@ -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"
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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] }
|
||||||
|
}
|
||||||
@@ -39,6 +39,11 @@ organs:
|
|||||||
lang: [r, octave]
|
lang: [r, octave]
|
||||||
role: endocrine array — R Drive-Box + Octave ETR
|
role: endocrine array — R Drive-Box + Octave ETR
|
||||||
build: "src/endocrine/run_tests.sh ; src/endocrine/etr/run_etr_tests.sh"
|
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
|
- path: core
|
||||||
agents_md: core/AGENTS.md
|
agents_md: core/AGENTS.md
|
||||||
lang: [ada, cobol]
|
lang: [ada, cobol]
|
||||||
|
|||||||
Reference in New Issue
Block a user