β‘ HedgeLock hunts for funding-rate edge, automates portfolio defense, and keeps operators in the loop with rich telemetry.
π Built for safety-first quant experimentation with explicit risk guardrails.
π°οΈ Modular microservices, Kafka glue, Prometheus/Grafana visibility.
- Features
- System Architecture
- Quick Start
- Configuration
- Services
- Testing
- Monitoring
- Roadmap
- Documentation
- Contributing
| Capability | Why it matters |
|---|---|
| Funding Rate Awareness | Regime detection (NEUTRAL β NORMAL β HEATED β MANIA β EXTREME) drives timing on hedges. |
| Dynamic Position Sizing | Position multipliers expand/contract exposure as funding costs change. |
| Emergency Exit System | Auto-flips positions when funding blows past 300% APR to stop the bleed. |
| Real-time Risk Monitoring | Continuous LTV + delta tracking ensures leverage stays inside guardrails. |
| Automated Hedging | Generates hedge orders and pipelines them to the executor with traceability. |
- Event-Driven Everything: Kafka topics glue microservices together with sub-150β―ms latency.
- Exchange Integration: Bybit WebSocket + REST adapters power live market context.
- Operational Hygiene: Health/ready endpoints, JSON logging, Prometheus metrics per service.
- Resilience-first: Auto-reconnect, idempotent consumers, message dedupe, replay-safe processors.
- CI Discipline: Unit + integration suites, coverage reporting, and GitHub Actions gating.
Python 3.11 Β· FastAPI Β· Kafka Β· Bybit APIs Β· Prometheus Β· Grafana Β· Docker Compose Β· pytest
graph LR
A[Bybit APIs] -->|WebSocket/REST| B[Collector]
B -->|account_raw| C[Kafka]
B -->|funding_rates| C
C -->|consume| D[Funding Engine]
D -->|funding_context| C
C -->|consume| E[Risk Engine]
E -->|risk_state| C
C -->|consume| F[Hedger]
F -->|hedge_trades| C
C -->|consume| G[Trade Executor]
G -->|execute| A
G -->|trade_confirmations| C
- Collector: Gathers account data and funding rates from Bybit API
- Funding Engine: Analyzes funding rates and detects regime changes
- Risk Engine: Calculates funding-adjusted risk scores and states
- Hedger: Applies funding-based position multipliers to hedge decisions
- Trade Executor: Executes trades on exchange with confirmation tracking
- Docker and Docker Compose
- Python 3.11+
- Bybit testnet account (optional)
-
Clone & enter
git clone https://github.com/blackms/HedgeLock.git cd HedgeLock -
Bootstrap environment
cp .env.example .env # Edit .env with your Bybit API credentials (optional) -
Launch the stack
docker-compose up -d
-
Smoke-test services
curl http://localhost:8001/healthz # Collector curl http://localhost:8002/healthz # Risk Engine curl http://localhost:8003/healthz # Hedger curl http://localhost:8004/healthz # Trade Executor
-
Peek at the bus
open http://localhost:8080 # Kafka UI via docker-compose
./run_all_tests.shβ full validation sweep (unit + integration)../run_core_tests.shβ tight loop for critical flows.make docker-build(or service-specific Dockerfiles) β container builds../scripts/run_collector_soak_test.shβ stress the collector for 5β―min.
All services use environment variables for configuration. Key settings:
# Kafka
KAFKA__BOOTSTRAP_SERVERS=localhost:9092
# Bybit (optional - runs in simulation mode without)
BYBIT__API_KEY=your_testnet_key
BYBIT__API_SECRET=your_testnet_secret
BYBIT__TESTNET=true
# Risk Thresholds
RISK__LTV_CAUTION_THRESHOLD=0.65 # 65% LTV triggers CAUTION
RISK__LTV_DANGER_THRESHOLD=0.8 # 80% LTV triggers DANGER
RISK__LTV_CRITICAL_THRESHOLD=0.9 # 90% LTV triggers CRITICAL
# Hedging Parameters
HEDGER__CAUTION_HEDGE_SIZE_BTC=0.02
HEDGER__MAX_POSITION_SIZE_BTC=10.0- Streams real-time position and market data from Bybit
- Polls collateral and loan information every 5 seconds
- Publishes normalized data to
account_rawtopic
- Consumes
account_rawmessages - Calculates LTV ratio and net delta
- Determines risk state: NORMAL β CAUTION β DANGER β CRITICAL
- Publishes risk assessments to
risk_statetopic
- Consumes
risk_statemessages - Generates hedge orders based on risk level
- Publishes hedge decisions to
hedge_tradestopic
- Consumes
hedge_tradesmessages - Executes actual trades on Bybit exchange
- Tracks order status until filled
- Publishes confirmations to
trade_confirmationstopic - Implements rate limiting and safety checks
# Run unit tests
poetry run pytest
# Run integration tests
poetry run pytest tests/integration/
# Run collector soak test (5 minutes)
./scripts/run_collector_soak_test.sh- Prometheus Metrics: Service-specific ports (909X range) for scrape targets.
- Grafana Dashboards: Import dashboards in
monitoring/grafana/dashboards/*.json. - Health Probes:
/healthz+/readyendpoints across services. - Logs: JSON lines with trace IDs to follow end-to-end flows.
- Kafka UI: http://localhost:8080 keeps eyes on lag and payloads.
- β Complete data pipeline from collection to hedge decisions
- β Risk state machine with configurable thresholds
- β Automated hedge order generation
- β Production-ready monitoring and logging
- β Trade Executor service for order execution
- β Trade confirmation tracking
- β Rate limiting and safety checks
- β Integration tests for complete flow
- Treasury module for P&L tracking
- Web dashboard for risk visualization
- Advanced hedging strategies
- Multi-exchange support
- Web dashboard for risk visualization
- Alert system integration
- Historical data analysis
- Machine learning risk models
- CHANGELOG.md - Version history
- Project Memory - System architecture and design decisions
- Sprint Planning - Development roadmap
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with FastAPI, Apache Kafka, and aiokafka
- Inspired by high-frequency trading risk management systems
- Special thanks to all contributors