Deribit MCP with Claude Session injection

by schroejahr2

Not rated
GitHub

About

Claude Opus full auto trading

Details

Author
schroejahr2
Categories
Finance, Other

Setup

Install Deribit MCP with Claude Session injection in your MCP client (Claude Desktop, Cursor, Windsurf, and others).

Repository: https://github.com/schroejahr2/deribit-mcp

Follow the installation instructions in the repository README, then restart your MCP client.

Deribit MCP with Claude Session injection

"Deribit" is a trademark of Deribit. This project is independent and not affiliated with, endorsed by, or sponsored by Deribit or Coinbase.

Hand Claude Opus the keys to a Deribit account.

πŸ€–Fully automatic crypto spot, futures, and options trading from a single prompt.

πŸ“‘Alerts and news ticker injected straight into the session β€” no slow polling loops.

🧠Tell Opus your strategy. Walk away. It runs the book.

πŸ“°Pipe your own news, signals, or regime models into the session via webhook.

πŸ–₯️Watch health, positions, alerts, decisions, trades, news, and outbox state in a browser dashboard.

A Model Context Protocol server that turns Claude Opus into a fully autonomous derivatives trader onDeribitβ€” live tickers, OHLCV candles, order books, options Greeks, funding rates, account state β€” paired with aClaude Code Sidecarthat pushes alerts straight back into the running session as native channel notifications. The agent doesn't poll. It sleeps until the market wakes it up.

Opus places its own orders. Sets its own stop-losses, take-profits, and trailing stops. Schedules its own time-based alerts to wake itself up later. Records every decision into an audit trail before the order hits the wire. Survives container restarts with full state intact.

TheCloud Channel / Sidecar wakeup pipelinedepends on Claude Code'sChannels Research Previewβ€” an unreleased /alphafeature surface inside Claude Code. The transport contract (notifications/claude/channel) and the sidecar plugin model may change without notice. Today this works; next month it might not.

Trading is real money.WhenDERIBIT_TEST_MODE=false, every mutating tool call hits the live Deribit exchange. Use the kill switch (DERIBIT_TRADING_ENABLED=false), the testnet (DERIBIT_TEST_MODE=true), and the per-callconfirm_live_trade=truerequirement on Mainnet. Set hard caps onDERIBIT_MAX_AMOUNT_andDERIBIT_MAX_NOTIONAL_USD.You are responsible for what your model does with this access.

⚠️ This is Experimental research-grade infrastructure for an algorithmic trading agent through generative AI. It is not a Robinhood replacement. ⚠️

The headline features, ranked by importance

-

60+ MCP toolscovering Deribit's full surface β€” read-only market data, account state, every mutating order primitive (market, limit, stop_market, stop_limit, take_market, trailing_stop, brackets, combos), label-based edit/cancel, mass-cancel scoping, position close, settlement and trigger-order history.

Pre-trade decision audit.Mutating tools require adecision_idminted byrecord_decision, validated against the database before the Deribit call. Every order writes a row intoorder_auditbeforeandafter the call. Thedecision_idrides through Deribit as the orderlabel, so post-hoc analysis joins trivially.

Cloud channel wakeup pipeline (Alpha β€” see warning).Alerts taggednotification_channel="outbox"flow into a SQLite outbox, stream over your private network to a sidecar plugin running on the Claude-Code machine, and surface inside the session as a native<channel>block. The agent doesn't poll; it sleeps until the market wakes it up.

Self-scheduling alerts.The agent callsset_price_alertfor threshold/cross/percentage-change conditions,set_time_alertto schedule its own future wakeups (e.g."check funding in 4 hours"), and the alert engine fires asynchronously through the same channel pipeline.

External news webhook.POST /news(admin-bearer-protected) lets any external system stash a news item β€” headline + summary + structured payload β€” and optionally push it straight to the agent's session via the outbox channel. Optionaldedupe_keymakes cyclic aggregator pushes idempotent. SeeNews Webhookanddocs/webhook-contract.md.

Trading safety harness.Per-call amount and USD-notional caps, instrument-family-aware sizing (inverse vs linear vs option), trigger-order worst-case notional checks, idempotency keys forclient_order_idsurvival across restarts, mass-cancelconfirm_cancel_all=truerequirement, mainnetconfirm_live_trade=truedouble-tap.

News storage layer.Pushed news items persist into a queryablenewstable with source, instrument scope, URL, score, tags, and compact + full payload variants. Optionaldedupe_keywith a unique partial index makes cyclic ingest idempotent. Push to Telegram, console, or outbox channel on demand.

Browser dashboard./dashboard/serves an operator view for health, registered sidecar consumers, held symbols, open positions, alerts, timers, recent decisions, MCP order audits, Deribit user trades, outbox events, and latest news. It also includes a news push form that persists the item through/newsand pushes it to the agent session vianotification_channel="outbox".

+--------------------------------+ +--------------------------------+ | Claude Code session | | Deribit MCP (port 8000) | | MCP client | | | | | | REST + WS to Deribit | | tool calls --------------------------->| /mcp (X-Deribit-MCP-Secret) | | stdio or streamable HTTP | | | | | | SQLite | | channel sidecar <----------------------| /events/stream + /events/ack | | notifications/claude/channel | | outbox + alerts + audit + news | +--------------------------------+ +--------------------------------+ ^ ^ | | News aggregator -----------------------------------+ | POST /news (admin Bearer token, optional dedupe_key) | | Operator browser -------------------------------------------------+ GET /dashboard/ (admin Bearer token for JSON + news push)

Tool path:Claude Code is the MCP client. It loads this server either directly over stdio (MCP_TRANSPORT=stdio) or over streamable-http β€” optionally through an MCP gateway in front. The HTTP transport is protected by anX-Deribit-MCP-Secretshared secret. The server is gateway-agnostic; wire it up however your setup prefers.

Wakeup path (sidecar plugin):Alerts taggednotification_channel="outbox"write structured events to a durable SQLite outbox. A small Bun/TS plugin loaded into the same Claude Code session streams those events from/events/stream, emits them as nativenotifications/claude/channelblocks inside the session, and ACKs back. Sidecar lives inchannel-plugin/β€” seeHANDOFF.md.

News-injection path:Any external pipelinePOSTs a news item to/newswithpush=true. The MCP persists it, then pushes a short summary through the same channel pipeline so the agent wakes up with the news in context. Optionaldedupe_keymakes retries idempotent β€” duplicate posts return the existing row and do not push again.

Browser dashboard:/dashboard/serves the local Deribit MCP dashboard. Its JSON data and news-push form useDERIBIT_EVENT_ADMIN_TOKENas a Bearer token. The UI is intentionally read-heavy: it shows service health, registered sidecar consumers, held symbols, positions, alerts, timers, recent decisions, recent Deribit trades, MCP order audits, latest news, and outbox events. The news form stores a row through/newsand pushes it to the agent session through the outbox channel.

Anything that can hit an HTTPS endpoint can wake the trading agent with structured context.

# Stash a news item AND push it to the agent's session curl -sS -X POST http://<deribit-host>:8000/news \ -H "Authorization: Bearer $DERIBIT_EVENT_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "headline": "BTC ETF inflows hit $1.2B record", "summary": "BlackRock IBIT absorbed $487M in 24h; spot reclaiming $98k.", "source": "newsapi", "instrument": "BTC-PERPETUAL", "url": "https://example.com/btc-etf-record", "score": 0.85, "tags": ["btc", "etf", "institutional"], "dedupe_key": "newsapi:btc-etf-2026-05-11", "notification_channel": "outbox", "push": true }'

Use it for: news scraper output, custom regime models, economic calendar reminders, oncall handoffs, social-sentiment digests, or anything else you want the agent to readnow. Withdedupe_keyset, retries are idempotent β€” a duplicatePOSTreturns the existing row withduplicate: trueand doesnotpush the event again.

The agent then sees a native<channel>block with the news headline and meta, callsnews_list(id=<news_id>, include_full=true)to pull the full structured payload, and decides.

Full contract β€” payload schema, auth, dedupe semantics, retry behavior, examples β€” seedocs/webhook-contract.md.

Tools are exposed both via stdio MCP and the streamable-http transport. Some MCP gateways prefix tool names β€” check your gateway's conventions.

Same backing table as theNews Webhook.

⚑ Trading (mutating, behind safety guards)

Mutating order responses are intentionally compact: they return order IDs, state, fill/average-price details, SL/TP child resolution, and aggregate trade summaries. Full Deribit payloads stay inorder_auditfor debugging and replay without flooding agent sessions.

- DERIBIT_TRADING_ENABLED=falseblocks every mutating tool by default.
- All four caps (DERIBIT_MAX_AMOUNT_INVERSE / LINEAR / OPTIONandDERIBIT_MAX_NOTIONAL_USD) must be positive numbers β€” startup fails fast otherwise.
- Mainnet (DERIBIT_TEST_MODE=false) requiresconfirm_live_trade=trueon each call.
- Notional guard for trigger orders uses worst-case execution price (max oftrigger_priceandprice) so a stop above current mark cannot under-check the cap.
- Mutating orders without a validdecision_idare rejected before the Deribit call.
- post_onlyorders defaultreject_post_only=true: a crossing limit is rejected instead of being silently repriced by Deribit to the next maker price. Applies tobuy/sell(reject_post_only) andplace_bracketentries (entry_reject_post_only); pass the field explicitly asfalseto opt back into the reprice behaviour.

Example β€” long with a stop-loss at mark Γ— 0.97:

record_decision(...) β†’ did_entry, did_sl buy(BTC-PERPETUAL, amount=10, order_type="market", decision_id=did_entry, confirm_live_trade=true) sell(BTC-PERPETUAL, amount=10, order_type="stop_market", trigger="mark_price", trigger_price=<mark0.97>, reduce_only=true, decision_id=did_sl, confirm_live_trade=true)

Example β€” exchange-side breakout bracket with asymmetric trigger feeds. Entry waits forlast_priceto cross 80100 (clean market touch), then SL/TP protect onmark_price(wick-resistant). The bracket sits on Deribit until the entry fires, so wake-latency and MCP downtime do not miss the setup:

record_decision( instrument="BTC-PERPETUAL", reasoning="80100 break-up + 79200 reclaim long", action_taken="place_bracket", ) β†’ did place_bracket( decision_id=did, instrument="BTC-PERPETUAL", side="buy", amount=10, entry_type="stop_market", entry_trigger_price=80100, # break trigger sl_type="stop_market", sl_trigger_price=79200, # reclaim invalid tp_type="take_market", tp_trigger_price=82500, trigger_source="mark_price", # default for SL + TP legs entry_trigger_source="last_price", # entry uses real-trade prints confirm_live_trade=true, )

Abuywhoseentry_trigger_priceis already at or below current price is rejected before the Deribit call (mirror logic forsell). The current-price read bypasses the cache so a stale WS feed cannot mask the divergence.

πŸ’‘Hand the install to Claude Code.Point any LLM agent atllms.txtand it will walk through the full setup β€” clone, configure, build, smoke-test against testnet, and verify the sidecar wakeup path. You only fill the secrets.

This server runs as a long-lived container exposing streamable-http MCP. Stdio (MCP_TRANSPORT=stdio) is supported for local dev or direct stdio launchers.

# 1) Configure cp .env.example .env # Edit: DERIBIT_API_KEY/SECRET, TELEGRAM_BOT_TOKEN/CHAT_ID, # MCP_SHARED_SECRET (openssl rand -hex 32), # DERIBIT_EVENT_ADMIN_TOKEN (openssl rand -hex 32), # trading limits if you flip TRADING_ENABLED=true # 2) Pull the published image and start docker compose pull docker compose up -d # 3) Health curl http://<deribit-host>:8000/health # β†’ {"ok":true} # 4) Open the operator dashboard # http://<deribit-host>:8000/dashboard/ # Use DERIBIT_EVENT_ADMIN_TOKEN when the dashboard asks for a token. # 5) Wire it into your MCP client / gateway: # transport: streamable-http # url: http://<deribit-host>:8000/mcp/ # headers: {"X-Deribit-MCP-Secret": "<MCP_SHARED_SECRET>"} # 6) Verify everything end-to-end on the testnet # See SMOKE-PLAYBOOK.md β€” designed for autonomous execution by # another Claude Code session against test.deribit.com. Run it # BEFORE you ever flip DERIBIT_TEST_MODE=false.

For local development of the container image, setDERIBIT_MCP_IMAGE=deribit-mcp-server:localand rundocker compose up -d --buildfrom a checkout.

/mcpand/sseare protected byMCP_SHARED_SECRETβ€” only callers with the correctX-Deribit-MCP-Secretheader reach the MCP surface./events/*uses per-consumer Bearer tokens for the sidecar pipeline and can be exposed across a private network (e.g. Tailscale, VPN, overlay) to wherever the sidecar runs.

⚠️ TheSMOKE-PLAYBOOK.mdend-to-end test runs against theDeribit testnet(test.deribit.com) withDERIBIT_TEST_MODE=true. It places real testnet orders, exercises every mutating tool, and cleans up after itself. Never run it against mainnet.

All configuration lives in.env. Settings are validated at startup β€” the container fails fast on missing or inconsistent values.

DERIBIT_TRADING_ENABLED=falseis the safe default. Mutating tools (buy,sell,edit_order,cancel_order,cancel_all_orders,close_position,place_bracket,create_combo) refuse to run unless trading is explicitly enabledandall four limits below are positive numbers.

On Mainnet (DERIBIT_TEST_MODE=false), each mutating tool call also requiresconfirm_live_trade=trueβ€” defense against accidental Mainnet calls from a session configured for testnet.

Telegram for the human user, outbox for the agent wakeup pipeline:

These variables are consumed bydocker-compose.yml, not by the Python app itself:

When an alert withnotification_channel="outbox"fires, the server writes a payload-allowlisted event to theevent_outboxtable. The sidecar plugin running on the Claude machine:
- Holds a long stream open atGET /events/stream?consumer_id=<id>(Bearer auth, per-consumer token).
- Receives the event as NDJSON.
- Emitsnotifications/claude/channelwithcontent=payload.messageandmeta= identifier-keyed metadata (alert_id,instrument,severity,event_id,event_type).
- CallsPOST /events/{event_id}/ackso the server stops re-delivering.

# Mint or rotate a consumer token curl -sS -X POST http://<deribit-host>:8000/events/register \ -H "Authorization: Bearer $DERIBIT_EVENT_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{"consumer_id":"<uuid4>","display_name":"trading-claude-laptop"}'

Themetakeys must match[A-Za-z0-9_]. Server-side severity is deterministic:percentage_changewith|threshold| >= 5β†’warning, otherwiseinfo. Event payload allowlist is insrc/event_outbox.py:ALLOWED_PAYLOAD_KEYSβ€” anything not listed is dropped before persisting.

News pushes withnotification_channel="outbox"emitnews_readyevents. They are deduped server-side bynews:{url}when the news row has a URL, otherwise bynews:{news_id}. They carry only allowlisted news metadata:news_id,source,instrument,headline,summary,url,score,tags,message.

Stored news items are queryable through the FastAPI wrapper:

curl -sS 'http://<deribit-host>:8000/news?limit=10' curl -sS 'http://<deribit-host>:8000/news/<news_id>?include_full=true' curl -sS 'http://<deribit-host>:8000/news?source=newsapi&instrument=BTC-PERPETUAL' curl -sS -X POST http://<deribit-host>:8000/news/<news_id>/push \ -H "Authorization: Bearer $DERIBIT_EVENT_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d '{"notification_channel":"outbox"}'

The save and push endpoints both require the admin bearer token; the read endpoints are unauthenticated (the HTTP transport is already behindX-Deribit-MCP-Secretfor the MCP path; read endpoints sit on the same bind).

Full payload schema, dedupe semantics, retry behavior, error codes β€” seedocs/webhook-contract.md.

Single SQLite database mounted on a host volume. Tables:

Unit tests(tests/, ~200 cases): trading guards including amount/notional limits per instrument family, cancel_all routing, decision repo + outcome enum, idempotency cache, outbox dedupe + allowlist, news persistence/dedupe/push routing, mass-cancel audit semantics, http_app shared-secret middleware, lifespan passthrough, GET-array bracket encoding.

python3 -m venv .venv && source .venv/bin/activate pip install -e ".[dev]" pytest tests/

The published GHCR runtime image intentionally does not include the test suite or development dependencies. Use the local venv for unit tests, or build a temporary development image from the checkout.

End-to-end smoke playbook(SMOKE-PLAYBOOK.md): multi-phase autonomous execution by another Claude session, covering every read-only tool, every mutating order lifecycle, all four trading-safety negative tests, channel burst, time alert wakeup, and a cleanup phase. Designed to leave the testnet account in the same state it started.

# Container health docker logs deribit-mcp --tail 30 curl http://<deribit-host>:8000/health # Inspect the MCP tool list directly curl -s -X POST http://<deribit-host>:8000/mcp/ \ -H "X-Deribit-MCP-Secret: $MCP_SHARED_SECRET" \ -H "Accept: application/json, text/event-stream" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' # Inspect SQLite directly (read-only) docker exec deribit-mcp sqlite3 'file:/data/deribit.db?mode=ro' \ "SELECT id,instrument,condition,status FROM alerts ORDER BY created_at DESC LIMIT 10" # Inspect deliveries for a sidecar consumer docker exec deribit-mcp sqlite3 'file:/data/deribit.db?mode=ro' \ "SELECT consumer_id,event_id,delivered_at,acked_at,attempts \ FROM event_deliveries ORDER BY delivered_at DESC LIMIT 5" # Trigger a synthetic outbox event (server-side, useful for sidecar tests) docker exec deribit-mcp python3 -c " import asyncio from src.persistence import Database from src.event_outbox import EventOutboxRepo async def main(): db = Database('/data/deribit.db'); await db.connect() repo = EventOutboxRepo(db) eid = await repo.insert_event( 'price_alert_triggered', {'message':'manual smoke','alert_id':'manual','instrument':'BTC-PERPETUAL'}, severity='info', ) print('inserted', eid) await db.close() asyncio.run(main()) "

Originally based onOishh/telegram-signal-mcp-server(MIT). Deribit REST/WS clients adapted from upstream; cloud channel / event outbox, persistence, trading guards, news ingestion, market streams, notes, and gateway integration are new work. Full attribution inNOTICE.

- Default:GNU Affero General Public License v3.0. Free to use, modify, and self-host. If you operate Deribit MCP as a network service, AGPL-3.0 requires you to make the complete corresponding source β€” including your modifications and the surrounding service code β€” available to your users.
- Commercial license:if AGPL-3.0 is unattractive for your production deployment (closed-source service, paid product, internal trading platform, hosted offering, formal SLA / warranty / indemnification), buy a commercial license fromGS Technik GmbH. See
COMMERCIAL.mdβ€” also covers managed High-Performance hosting and 24/7 operation. Contact:info@schroejahr.de.
- Third-party hosting:AGPL or a commercial license governs your rights to this code only. Hosting this software for other users, or operating it with third-party Deribit API keys, may require separate exchange, KYC, API-usage, or commercial agreements with Deribit/Coinbase. Contact the exchange directly; this project cannot grant those rights.

Upstream portions derived fromtelegram-signal-mcp-server by Oishhremain under the original MIT terms preserved inLICENSE-MIT. Substantial new work β€” outbox/channel pipeline, persistence, audited trading, news ingestion, market streams, gateway integration β€” is the AGPL-3.0 work. Full attribution inNOTICE.

Deribit and Coinbase are trademarks of their respective owners. This project is independent and is not affiliated with, endorsed by, or sponsored by Deribit, Deribit B.V., Coinbase, or Coinbase Global, Inc.

This software talks to a live derivatives exchange. Trading cryptocurrency derivatives carries substantial risk of loss. Nothing in this repository is financial advice. The authors accept no liability for any losses, missed alerts, model errors, sidecar disconnects, or any other consequence of using this software.You are responsible for what your model does with this access.Use the testnet, the kill switch, and the trading caps. Read the code before you flipDERIBIT_TRADING_ENABLED=true.

Built byGeorg SchrΓΆjahrβ€”schroejahr.de.

Issues, ideas, and pull requests welcome atgithub.com/schroejahr2/deribit-mcp.

Coinrule Agentic Trading MCP enables investors to create, backtest, execute, and manage trading agents through natural language across stocks, crypto and ETFs

Remote MCP server for historical crypto & prediction-market data: search ~500K instruments, live market stats (OHLC, turnover, spreads, depth, slippage) and tick-data purchase. Keyless for catalog & stats; optional OAuth for account tools. Endpoint: https://cryptostruct.com/mcp

Read-only MCP server for your Evibe investment portfolio + live market data (holdings, performance, dividends, benchmarks, screeners). Works with Claude & ChatGPT.

Institutional squeeze scanner, options flow, IWM 0DTE, AI council verdicts. Pay per call in RLUSD on XRPL β€” no API keys. Agent Credit Bureau, signal marketplace, hiring protocol.

No reviews yet β€” be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.