Installation | Quick Start | Strategies | Backtesting | Docs
English | 中文 | Français | Español
Almanak is an intent-based Python framework for developing, testing, and deploying autonomous DeFi strategies. Express trading logic as high-level intents - the framework handles compilation, execution, and state management across 19 chains and 46 protocol connectors.
- Intent-Based Architecture: Express trading logic as high-level intents (Swap, LP, Borrow, etc.) - the framework handles compilation and execution
- Three-Tier State Management: Automatic persistence with HOT/WARM/COLD tiers for reliability
- Comprehensive Backtesting: PnL simulation, paper trading on Anvil forks, and parameter sweeps
- Multi-Chain Support: 19 chains across EVM and SVM — Ethereum, Arbitrum, Optimism, Base, Avalanche, Polygon, BSC, Mantle, X-Layer, Monad, 0G, Solana, HyperEVM, Linea, Robinhood, plus Sonic, Blast, Berachain, Plasma (chain configs present; protocol coverage pending).
- Protocol Integration: Uniswap V3, Aave V3, Morpho Blue, GMX V2, Lido, Ethena, Polymarket, Kraken, and more
- Non-Custodial Design: Full control over your funds through Safe smart accounts
- Agentic DeFAI Trading: Build autonomous LLM-driven agents with 41 built-in tools and policy-enforced safety (BYO LLM API key)
- Production-Ready: Built-in alerting, stuck detection, emergency management, and canary deployments
pipx install almanakOptional features ship as extras:
pipx install 'almanak[dashboard,backtest]' # web dashboard + backtest charts/optimization| Extra | Enables |
|---|---|
dashboard |
almanak dashboard and the strategy/backtest web dashboards (streamlit, plotly) |
backtest |
backtest chart export and almanak strat backtest optimize (matplotlib, plotly, optuna) |
code |
Python LSP for almanak code (pyright) |
Using an AI coding agent? Teach it the SDK in one command:
almanak agent installThis auto-detects your platform (Claude Code, Codex, Cursor, Copilot, and 6 more) and installs the strategy builder skill.
-
Create a New Strategy (scaffolds a self-contained Python project with
pyproject.toml,.venv/,uv.lock)almanak strat new
-
Test Your Strategy
A managed gateway is auto-started in the background when you run a strategy. Use
--dashboardto launch a live monitoring dashboard alongside execution:uv run almanak strat run -d almanak/demo_strategies/uniswap_lp --network anvil --dashboard --once
This single command auto-starts Anvil + gateway, opens the dashboard in your browser, and runs one iteration of the strategy.
New here? Start with the
uniswap_rsidemo strategy - a fully commented tutorial that walks through RSI-based trading on Uniswap V3.
Strategies implement the decide() method, which receives a MarketSnapshot and returns an Intent (or None to skip the cycle):
from decimal import Decimal
from almanak.framework.intents import Intent
from almanak.framework.market import MarketSnapshot
from almanak.framework.strategies import IntentStrategy
class MyStrategy(IntentStrategy):
"""A simple mean-reversion strategy."""
def decide(self, market: MarketSnapshot) -> Intent | None:
eth_price = market.price("ETH")
usdc = market.balance("USDC")
if eth_price < Decimal("2000") and usdc.balance_usd > Decimal("500"):
return Intent.swap(
from_token="USDC",
to_token="ETH",
amount_usd=Decimal("500"),
)
return Intent.hold(reason="Waiting for better conditions")| Intent | Description |
|---|---|
SwapIntent |
Token swaps on DEXs |
HoldIntent |
No action, wait for next cycle |
LPOpenIntent / LPCloseIntent |
Open/close liquidity positions |
CollectFeesIntent |
Collect accrued fees on an open LP position |
BorrowIntent / RepayIntent |
Borrow/repay on lending protocols |
SupplyIntent / WithdrawIntent |
Supply/withdraw from lending protocols |
StakeIntent / UnstakeIntent |
Stake/unstake tokens |
PerpOpenIntent / PerpCloseIntent |
Open/close perpetuals positions |
BridgeIntent |
Cross-chain asset bridging |
VaultDepositIntent / VaultRedeemIntent |
Deposit into / redeem from ERC-4626-style vaults |
FlashLoanIntent |
Flash loan operations (experimental — not yet listed as supported in almanak info matrix; pending testing) |
PredictionBuyIntent / PredictionSellIntent / PredictionRedeemIntent |
Prediction market trading (experimental — not yet listed as supported in almanak info matrix; pending testing) |
# Gateway (auto-started by strat run, or start standalone)
almanak gateway # Start standalone gateway server
almanak gateway --network anvil # Start standalone for local Anvil testing
# Direct DeFi actions (no strategy files needed)
almanak ax price ETH # Get token price
almanak ax balance USDC --chain base # Check wallet balance
almanak ax pool 0x0b1c...2d69 --chain base # Exact pool identity, state, and analytics
almanak ax swap USDC ETH 100 --dry-run # Simulate a swap
almanak ax swap USDC ETH 100 # Execute after confirmation
almanak ax --chain polygon lending-reserves # Which Aave reserves are borrowable/active before you configure a strategy
almanak ax --chain ethereum lending-reserves --protocol morpho_blue --collateral sUSDe # Find a Morpho market_id to pin
almanak ax -c arbitrum perp-market gmx_v2 XMR/USD # Resolve a perp market via live venue discovery (on-chain verified)
almanak ax -n "swap 5 USDC to WETH on base" # Natural language mode
# Strategy development
almanak strat new # Create new strategy from template
almanak strat run --once # Run single iteration (auto-starts gateway)
almanak strat run --network anvil --once # Run on local Anvil fork (auto-starts Anvil + gateway)
almanak strat run --network anvil --dashboard # Run with live dashboard
almanak strat run --network anvil --confirm-start # Inspect funded wallet before starting execution
# Strategy reporting (reads the persisted local SQLite state DB; no gateway call)
almanak strat pnl -s <deployment_id> # Per-strategy PnL breakdown (human text)
almanak strat pnl -s <deployment_id> --json # Same payload as machine-readable JSON
# JSON is version-stamped (`schema_version`) and includes `net_strategy_nav_usd`
# (positive position value minus lending debt; equals total_value_usd when the
# strategy holds no borrow positions).
# Backtesting
almanak strat backtest pnl # Historical price simulation
almanak strat backtest sweep # Parameter optimization
almanak strat backtest paper # Paper trading on Anvil
# Advanced backtesting
almanak strat backtest monte-carlo # Statistical robustness analysis
almanak strat backtest optimize # Bayesian parameter optimization
almanak strat backtest scenario # Crisis scenario stress testing
almanak strat backtest dashboard # Interactive results dashboard
v1 (beta) — enabled by default since v2.19.1. The PnL engine is conservation-certified on the network-free Trust Matrix. Treat results as carrying documented variance bounds (LP fees ±10-15%, perp funding ±15%, lending APY ±10%, large-trade slippage ±30%, gas ±20%) and certify on the paper trader before going live. Perp support is beta.
The SDK provides a dual-engine backtesting system for institutional-grade strategy validation:
| Engine | Best For | Requirements |
|---|---|---|
| PnL Backtester | Historical analysis with price data | No Anvil required |
| Paper Trader | Live-like simulation with real execution | Anvil fork |
from almanak.framework.backtesting import PnLBacktester, PnLBacktestConfig
from datetime import datetime, UTC
from decimal import Decimal
config = PnLBacktestConfig(
start_time=datetime(2024, 1, 1, tzinfo=UTC),
end_time=datetime(2024, 6, 1, tzinfo=UTC),
token_funding=[
{
"symbol": "USDC",
"address": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
"chain": "arbitrum",
"amount": "10000",
"amount_type": "usd",
}
],
)
backtester = PnLBacktester(data_provider, fee_models, slippage_models)
result = await backtester.backtest(strategy, config)
print(f"Total Return: {result.metrics.total_return_pct:.2f}%")
print(f"Sharpe Ratio: {result.metrics.sharpe_ratio:.2f}")
print(f"Max Drawdown: {result.metrics.max_drawdown_pct:.2f}%")For a connector-native perp strategy, pass timeframe="auto" to choose the
finest native cadence with complete coverage. The result artifact records the
resolved value; an explicit canonical timeframe never silently downgrades. Price
cadence is independent from interval_seconds, which remains the strategy's
decision/simulation tick. Full BacktestService runs default eligible strategies
with an explicit connector-native perp market to this policy; callers can pin
price_timeframe when an exact cadence is needed.
# Historical PnL backtest
almanak strat backtest pnl -s my_strategy --start 2024-01-01 --end 2024-06-01
# Coverage-aware native cadence (an explicit timeframe never downgrades)
almanak strat backtest pnl -s my_gmx_strategy --start 2024-01-01 --end 2024-08-01 --timeframe auto
# Parameter sweep optimization
almanak strat backtest sweep -s my_strategy --param "window:10,20,30"
# Paper trading on Anvil fork
almanak strat backtest paper start -s my_strategy --chain arbitrum
# Monte Carlo simulation (1000 price paths)
almanak strat backtest monte-carlo -s my_strategy --n-paths 1000
# Crisis scenario stress testing
almanak strat backtest scenario -s my_strategy --scenario terra_collapseThe demo strategies under almanak/demo_strategies/ are
runnable end to end (see the Demo Strategies table above) and double as backtest
subjects:
# From inside a demo directory (the backtester reads token_funding from config.json)
cd almanak/demo_strategies/uniswap_rsi
uv run almanak strat backtest pnl -s demo_uniswap_rsi --start 2024-01-01 --end 2024-06-01
# Other runnable subjects: uniswap_lp (-s demo_uniswap_lp), morpho_looping (-s demo_morpho_looping)Standalone backtest example scripts are being reorganized into a dedicated
Tutorials/folder (VIB-5332). For complete documentation, seealmanak/framework/backtesting/README.md.
uv run almanak strat test --actions open,close,open --teardown requires successful
execution evidence for every requested action by default. Strategies testing a
specific guard can run uv run almanak strat test --actions open with this
declaration captured before execution:
test_action_expectations = {
"open": {"expected_to_hold": True, "reason": "The stale reference guard must reject entry."},
}The mapping is validated and copied before the run. Repeated action names share
one expectation; the mapping cannot express different outcomes for successive
open steps. Missing entries require execution;
a declared HOLD fails if the action executes. Declarations never excuse runtime/data
errors or failed, residual, missing, or unmeasured teardown. A measured empty teardown
passes cleanup assertions but provides no unwind coverage. Cleanup and risk-reducing
teardown still run after an action failure.
JSON summary.test_action_expectations echoes the snapshot (including default
expectations), and each requested action step includes its expectation and actual
coverage. all_passed and the exit code report assertion success.
coverage.requested_paths_exercised reports actual requested execution coverage.
deployment_ready requires successful assertions, at least one requested action,
all requested actions executed, and a requested, measured position unwind. It covers
only this local lifecycle test, not production/provider/accounting qualification.
Natural --inject decisions without forced actions may safely hold but cannot by
themselves establish deployment readiness. Deployment consumers must gate on
deployment_ready, while guard-test consumers may use all_passed.
19 chains have first-class ChainDescriptor configs. Chains marked with * have one or more registered protocol connectors today; the others have chain configs in place but no protocol coverage yet.
EVM
- Ethereum *
- Arbitrum *
- Optimism *
- Base *
- Avalanche *
- Polygon *
- BSC *
- Mantle *
- X-Layer *
- Monad *
- 0G *
- Sonic
- Blast
- Linea *
- Berachain
- Plasma
- HyperEVM *
- Robinhood *
SVM
- Solana *
For the authoritative per-protocol chain matrix, see the connector reference.
46 connectors are registered today in the connector descriptor registry. See the connector reference for the full matrix of chains × intent types per connector.
- DEXs / AMMs: Uniswap V3, Uniswap V4, SushiSwap V3, PancakeSwap V3, TraderJoe V2, Aerodrome, Camelot, Curve, Fluid, Pendle, Orca, Meteora, Raydium CLMM
- Swap aggregators: Jupiter, Enso, LiFi
- Lending: Aave V3, Morpho Blue, Compound V3, Spark, Euler V2, Fluid, BenQi, Silo V2, Curvance, Kamino
- Liquid Staking & yield-bearing assets: Lido, Ethena, Gimo
- Yield tokenization: Pendle
- Perpetuals: GMX V2, Hyperliquid, Aster Perps, PancakeSwap Perps, Drift
- CEX Integration: Kraken
- Bridges: Across, Stargate, LiFi
- Vaults: Morpho Vault, Lagoon
Pending testing (not currently listed as supported): Prediction Markets (Polymarket) and Flash loans (Balancer, Aave V3, Morpho Blue) are undergoing further validation and are temporarily withheld from the supported matrix (
almanak info matrix). The connectors remain in the codebase but should be treated as experimental until re-listed.
The SDK includes educational demo strategies to help you learn:
| Strategy | Description | Chain | Protocol |
|---|---|---|---|
uniswap_rsi |
Config-driven RSI swap — buy oversold, sell overbought | Ethereum | Uniswap V3 |
uniswap_lp |
Concentrated liquidity position management | Arbitrum | Uniswap V3 |
uniswap_v4_hooks |
Hook-aware V4 LP — dynamic-fee hooks + typed hookData | Base | Uniswap V4 |
traderjoe_lp |
Liquidity Book position management | Avalanche | TraderJoe V2 |
morpho_looping |
Leveraged yield farming via recursive borrowing | Ethereum | Morpho Blue |
morpho_blue_collateral_rotator_ethereum |
Rotate collateral across Morpho Blue markets | Ethereum | Morpho Blue |
metamorpho_base_yield |
MetaMorpho USDC yield via Moonwell Flagship vault | Base | Morpho |
spark_lender |
Supply DAI for lending yield | Ethereum | Spark |
euler_v2_supply_ethereum |
Supply/withdraw USDC lifecycle | Ethereum | Euler V2 |
benqi_lending_lifecycle |
Borrow → repay → withdraw lending lifecycle | Avalanche | BENQI |
benqi_looping |
Leveraged AVAX loop — supply, borrow, swap back, health-factor-aware unwind | Avalanche | BENQI |
curve_3pool_lp |
3-coin stable liquidity on Curve 3pool (DAI/USDC/USDT) | Ethereum | Curve |
pancakeswap_aave_carry_bsc |
Borrow → swap → repay carry trade | BSC | PancakeSwap V3, Aave V3 |
lido_staker |
Stake ETH for liquid staking yield | Ethereum | Lido |
gmx_perp_lifecycle |
Perpetual futures lifecycle (open + close) | Arbitrum | GMX V2 |
gmx_v2_directional_perp |
Directional perp — EMA crossover, close-before-reverse, funding gate, stop-loss | Arbitrum | GMX V2 |
hyperliquid_trailing_perp |
Perp with ratcheting trailing-stop, take-profit, and hard stop via CoreWriter | HyperEVM | Hyperliquid |
mantle_mnt_accumulator |
Multi-signal MNT accumulation | Mantle | Agni Finance |
0g_swap |
Wrap native A0GI into W0G | 0G Chain | 0G |
Run any demo with:
cd almanak/demo_strategies/<strategy_name>
uv run almanak strat run --once --dry-runalmanak/
framework/ # V2 Strategy Framework
strategies/ # IntentStrategy base class
intents/ # Intent vocabulary & compiler
state/ # Three-tier state management
execution/ # Transaction orchestration
backtesting/ # PnL, paper trading, sweeps
data/ # Price oracles, indicators
alerting/ # Slack/Telegram notifications
services/ # Stuck detection, emergency mgmt
connectors/ # Protocol adapters (SDK, adapter, receipt parser)
gateway/ # gRPC gateway sidecar
core/ # Enums, models, utilities
cli/ # Command-line interface
- All strategy code is encrypted at rest and in transit
- Agent EOA private keys are encrypted and never accessible to humans
- Fine-grained permission controls through Zodiac Roles Modifier
- Non-custodial design ensures users maintain full control of funds
All strategies run through a gateway-only architecture for security:
- Gateway Sidecar: Holds all secrets (API keys, private keys), exposes controlled gRPC API
- Strategy Container: Runs user code with no secrets and no internet access
This ensures strategy code cannot access secrets directly - all external access is mediated through the gateway.
# Run your strategy (auto-starts gateway in background)
cd my_strategy
almanak strat run --once
# Or run a standalone gateway for shared use
almanak gateway
# For full container isolation (production-like)
docker-compose -f deploy/docker/docker-compose.yml upFor more details, visit sdk.docs.almanak.co.
Supercharge your strategy development with AI agent support. The Almanak strategy builder skill teaches AI coding agents (Claude Code, Codex, Cursor, Copilot, and others) how to write strategies using the SDK.
# Claude Code / Codex / any skills.sh-compatible agent
npx skills add almanak-co/almanak-sdk
# Or via the Almanak CLI (auto-detects your agent platform)
almanak agent installOnce installed, your agent understands the full intent vocabulary, market data API, backtesting tools, and CLI commands. Just describe what you want to build.
The SDK also supports LLM-driven autonomous agents. Instead of writing decide() logic,
you write a system prompt and let the LLM reason over market data and call tools.
Requirements: Your own LLM API key (OpenAI, Anthropic, or any OpenAI-compatible provider).
The almanak ax CLI exposes a natural language mode that drives the agentic LLM
infrastructure for one-shot DeFi actions without writing any strategy files:
AGENT_LLM_API_KEY=sk-... almanak ax -n "swap 5 USDC to WETH on base"
AGENT_LLM_API_KEY=sk-... almanak ax -n "what's the price of ETH?"Full agentic-agent example strategies are being reorganized into a dedicated
Tutorials/folder (VIB-5332) and will be linked here once they land.
We welcome contributions. See CONTRIBUTING.md for development setup, coding standards, and the PR process.
For detailed documentation, visit sdk.docs.almanak.co