Production Examples
Seven standalone programs demonstrating every Medici protocol operation, in three languages across three market regimes.
Three Market Regimes
All seven examples encode market posture through a single parameter: strikeRatio. This controls how the P (call) and N (put) token value splits at inception — lower values are defensive, higher values are aggressive. There is no explicit "direction" field; the regime is expressed purely through strikeRatio, maturity duration, rebalance thresholds, and stop-loss bands.
| Regime | strikeRatio | P/N Split | Language | Character |
|---|---|---|---|---|
| Neutral / Sideways | ~0.50 | ~50/50 balanced | TypeScript | Steady-state treasury management, moderate duration, symmetric rebalancing |
| Bearish / Risk-off | ~0.30–0.40 | ~30–40/70–60 N-heavy | Python | Capital preservation, tight stops, short duration, defensive from inception |
| Bullish / Risk-on | ~0.70–0.85 | ~70–85/30–15 P-heavy | Go | Aggressive growth, wide stops, long duration, maximise upside capture |
How P/N Manipulation Works
The protocol creates both P and N tokens simultaneously from collateral when a SplitRequest executes. The value each side receives at settlement is determined by strikeRatio (strike price divided by spot price):
- Lower
strikeRatio(e.g. 0.35): more value flows to N (puts) — defensive, downside protection - Balanced
strikeRatio(e.g. 0.50): equal split — neutral, treasury management - Higher
strikeRatio(e.g. 0.75): more value flows to P (calls) — aggressive, upside capture
At settlement, the DAML payout functions guarantee: P_share = strikeRatio, N_share = 1 − strikeRatio, with the invariant P + N = collateral always holding.
The Parameter SDK constrains strikeRatio to [0.01, 1.0]. Values are validated before any on-chain action.
For the full strikeRatio mechanics, SDK constraints, and DAML settlement math, see the Strategy Engine guide.
Examples
Treasury Bot
Automated intent lifecycle: create, roll, stop-loss, webhook alerts. Each language variant encodes its market regime through strikeRatio, maturity duration, rebalance thresholds, and stop-loss bands.
Intent CLI
Scriptable intent CRUD with JSON output, cron-ready. Six subcommands (create, list, status, pause, resume, cancel) with regime-specific defaults.
Portfolio Monitor
Continuous exposure monitoring with regime-specific alerts. Neutral watches drift bands, bearish flags drawdown and N-share erosion, bullish tracks momentum and P-share acceleration.
CIP-103 Flow
Non-custodial external signing walkthrough. Full 6-step flow: keygen → onboard (2 steps) → prepare → sign → execute → verify. TypeScript and Python use the dev wallet; Go uses native crypto/ed25519.
Onboarding
Full user journey: login, decode JWT, onboard, first action. Neutral performs read-only exploration, bearish creates a hedge intent, bullish creates a leverage intent.
Go SDK
5-operation API walkthrough: token acquisition, health check, contract read, price query, command submit (SplitRequest). Each language submits the same template with a regime-appropriate strike.
Market Maker
Liquidity provision with asymmetric spreads across regimes. Neutral quotes symmetric 10 bps, bearish widens P-spread and tightens N-spread (25/5 bps), bullish inverts (5/25 bps). Exercises all five market-making templates.
Deployment Status
Running 24×7 in medici-dev-examples
These examples run as persistent Kubernetes Deployments against the dev Canton participant, one per regime per example (9 pods total):
| Deployment | Identity | Regime | strikeRatio |
|---|---|---|---|
treasury-bot-neutral | alice_treasury | Neutral | 0.50 |
treasury-bot-bearish | bob_hedge | Bearish | 0.35 |
treasury-bot-bullish | carol_leverage | Bullish | 0.75 |
monitor-neutral | alice_treasury | Neutral | — |
monitor-bearish | bob_hedge | Bearish | — |
monitor-bullish | carol_leverage | Bullish | — |
market-maker-neutral | mm_neutral | Neutral | 0.50 |
market-maker-bearish | mm_bearish | Bearish | 0.35 |
market-maker-bullish | mm_bullish | Bullish | 0.75 |
All deployed via FluxCD from the medici-examples repo.
Live dashboard: simulation.medici.loan — the Simulation Monitor shows bot liveness, identity summaries, intent management, and a real-time activity feed.
On-Demand (CronJob-verified daily)
These run as daily Kubernetes CronJobs that verify the full flow end-to-end, pushing metrics to a Prometheus Pushgateway for alerting:
| CronJob | Schedule (UTC) | Language | Example |
|---|---|---|---|
intent-cli-ts | 03:03 | TypeScript | Intent CLI |
intent-cli-py | 03:18 | Python | Intent CLI |
intent-cli-go | 03:33 | Go | Intent CLI |
cip103-flow-ts | 04:00 | TypeScript | CIP-103 Flow |
cip103-flow-py | 04:15 | Python | CIP-103 Flow |
cip103-flow-go | 04:30 | Go | CIP-103 Flow |
onboarding-ts | 05:00 | TypeScript | Onboarding |
onboarding-py | 05:15 | Python | Onboarding |
onboarding-go | 05:30 | Go | Onboarding |
sdk-ts | 06:00 | TypeScript | Go SDK |
sdk-py | 06:15 | Python | Go SDK |
sdk-go | 06:30 | Go | Go SDK |
Each CronJob pushes a verification metric on completion:
medici_example_verification{example="intent-cli", language="ts", status="success"} 1
Alertmanager fires if status="failure" for any CronJob in the last 24 hours.
Quick Start
1. Provision demo identities (one-time)
# Creates 6 Keycloak users + onboards each one via the Ledger Service. # Idempotent — safe to re-run. LEDGER_URL=https://ledger.dev.medici.loan \ KC_URL=https://keycloak.dev.medici.loan/auth \ KC_ADMIN_USER=admin \ KC_ADMIN_PASSWORD=<from keycloak-credentials secret> \ KC_CLIENT_SECRET=<from medici-dev-examples-secrets> \ KC_REALM=AppUser \ PACKAGE_ID='#option-index-tracker-v10' \ bash scripts/bootstrap-dev-simulation.sh
The bootstrap provisions these identities:
| Identity | Role | Regime | strikeRatio |
|---|---|---|---|
alice_treasury | Treasury manager | Neutral | 0.50 |
bob_hedge | Risk manager | Bearish | 0.35 |
carol_leverage | Growth manager | Bullish | 0.75 |
mm_neutral | Market maker | Neutral | 0.50 |
mm_bearish | Market maker | Bearish | 0.35 |
mm_bullish | Market maker | Bullish | 0.75 |
2. Run any example
# Each example authenticates via password grant, onboards (gets its own # Canton party + rights), and operates as that party.
# Clone the examples repo git clone https://github.com/jojig-dao/medici-examples cd medici-examples # Examples are grouped by language: go/ ts/ python/ shell/ cd go/treasury-bot KC_USERNAME=alice_treasury KC_PASSWORD=def456 go run main.go cd ../../ts/treasury-bot KC_USERNAME=alice_treasury KC_PASSWORD=def456 npx tsx main.ts cd ../../python/treasury-bot KC_USERNAME=bob_hedge KC_PASSWORD=def456 python main.py
All examples share the same environment variable names:
| Variable | Purpose | Default (dev) |
|---|---|---|
LEDGER_URL | Ledger Service base URL | https://ledger.dev.medici.loan |
KC_URL | Keycloak base URL | https://keycloak.dev.medici.loan |
KC_CLIENT_ID | Keycloak client ID | app-user-validator |
KC_CLIENT_SECRET | Keycloak client secret | (required) |
OWNER_PARTY | Canton party owning intents/vaults | (required) |
PACKAGE_ID | DAML package identifier | #option-index-tracker-v10 |
TICKER | Price ticker | ETH/USD |
WEBHOOK_URL | Optional webhook for alerts | (empty) |
Each regime variant accepts optional overrides: STRIKE_RATIO, MATURITY_DAYS, REBALANCE_THRESHOLD, STOP_LOSS_DRIFT_BPS, INTERVAL_SECONDS.
Shared Library
Each language directory provides shared plumbing so examples focus on protocol logic, not auth and HTTP boilerplate:
| Directory | Provides |
|---|---|
ts/shared/ | TypeScript token cache, HTTP client, error normalisation |
python/shared/ | Python token cache, session management, error normalisation |
go/shared/ | Go token cache, HTTP client with context, error normalisation |
Each shared library handles:
- Keycloak
client_credentialstoken acquisition with automatic refresh - HTTP client setup with default timeouts
- Canton JSON API response normalisation (payload unwrapping, error-in-body detection)
- Structured error types with status code and operation context
Using the shared library eliminates ~60% of the auth/retry boilerplate that would otherwise be duplicated across every example. See each example's source for usage patterns.