Medici Protocol

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.

RegimestrikeRatioP/N SplitLanguageCharacter
Neutral / Sideways ~0.50~50/50 balancedTypeScript Steady-state treasury management, moderate duration, symmetric rebalancing
Bearish / Risk-off ~0.30–0.40~30–40/70–60 N-heavyPython Capital preservation, tight stops, short duration, defensive from inception
Bullish / Risk-on ~0.70–0.85~70–85/30–15 P-heavyGo 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):

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.

TypeScript Python Go Neutral Bearish Bullish

Intent CLI

Scriptable intent CRUD with JSON output, cron-ready. Six subcommands (create, list, status, pause, resume, cancel) with regime-specific defaults.

TypeScript Python Go Neutral Bearish Bullish

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.

TypeScript Python Go Neutral Bearish Bullish

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.

TypeScript Python Go Neutral Bearish Bullish

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.

TypeScript Python Go Neutral Bearish Bullish

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.

TypeScript Python Go Neutral Bearish Bullish

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.

TypeScript Python Go Neutral Bearish Bullish

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):

DeploymentIdentityRegimestrikeRatio
treasury-bot-neutralalice_treasuryNeutral0.50
treasury-bot-bearishbob_hedgeBearish0.35
treasury-bot-bullishcarol_leverageBullish0.75
monitor-neutralalice_treasuryNeutral
monitor-bearishbob_hedgeBearish
monitor-bullishcarol_leverageBullish
market-maker-neutralmm_neutralNeutral0.50
market-maker-bearishmm_bearishBearish0.35
market-maker-bullishmm_bullishBullish0.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:

CronJobSchedule (UTC)LanguageExample
intent-cli-ts03:03TypeScriptIntent CLI
intent-cli-py03:18PythonIntent CLI
intent-cli-go03:33GoIntent CLI
cip103-flow-ts04:00TypeScriptCIP-103 Flow
cip103-flow-py04:15PythonCIP-103 Flow
cip103-flow-go04:30GoCIP-103 Flow
onboarding-ts05:00TypeScriptOnboarding
onboarding-py05:15PythonOnboarding
onboarding-go05:30GoOnboarding
sdk-ts06:00TypeScriptGo SDK
sdk-py06:15PythonGo SDK
sdk-go06:30GoGo 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:

IdentityRoleRegimestrikeRatio
alice_treasuryTreasury managerNeutral0.50
bob_hedgeRisk managerBearish0.35
carol_leverageGrowth managerBullish0.75
mm_neutralMarket makerNeutral0.50
mm_bearishMarket makerBearish0.35
mm_bullishMarket makerBullish0.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:

VariablePurposeDefault (dev)
LEDGER_URLLedger Service base URLhttps://ledger.dev.medici.loan
KC_URLKeycloak base URLhttps://keycloak.dev.medici.loan
KC_CLIENT_IDKeycloak client IDapp-user-validator
KC_CLIENT_SECRETKeycloak client secret(required)
OWNER_PARTYCanton party owning intents/vaults(required)
PACKAGE_IDDAML package identifier#option-index-tracker-v10
TICKERPrice tickerETH/USD
WEBHOOK_URLOptional 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:

DirectoryProvides
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:

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.