Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

58 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

HedgeLock β€” Funding-Aware Volatility Harvesting System

CI/CD Pipeline codecov Version

⚑ 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.

πŸ”— Contents

πŸš€ Features

Core Capabilities

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.

Technical Highlights

  • 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.

Tech Stack

Python 3.11 Β· FastAPI Β· Kafka Β· Bybit APIs Β· Prometheus Β· Grafana Β· Docker Compose Β· pytest

πŸ“Š System Architecture

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
Loading

Key Components

  1. Collector: Gathers account data and funding rates from Bybit API
  2. Funding Engine: Analyzes funding rates and detects regime changes
  3. Risk Engine: Calculates funding-adjusted risk scores and states
  4. Hedger: Applies funding-based position multipliers to hedge decisions
  5. Trade Executor: Executes trades on exchange with confirmation tracking

πŸ—οΈ Quick Start

Prerequisites

  • Docker and Docker Compose
  • Python 3.11+
  • Bybit testnet account (optional)

Local Development Flow

  1. Clone & enter

    git clone https://github.com/blackms/HedgeLock.git
    cd HedgeLock
  2. Bootstrap environment

    cp .env.example .env
    # Edit .env with your Bybit API credentials (optional)
  3. Launch the stack

    docker-compose up -d
  4. 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
  5. Peek at the bus

    open http://localhost:8080  # Kafka UI via docker-compose

Command Palette

  • ./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.

πŸ”§ Configuration

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

πŸ“‹ Services

Collector Service (Port 8001)

  • Streams real-time position and market data from Bybit
  • Polls collateral and loan information every 5 seconds
  • Publishes normalized data to account_raw topic

Risk Engine (Port 8002)

  • Consumes account_raw messages
  • Calculates LTV ratio and net delta
  • Determines risk state: NORMAL β†’ CAUTION β†’ DANGER β†’ CRITICAL
  • Publishes risk assessments to risk_state topic

Hedger Service (Port 8003)

  • Consumes risk_state messages
  • Generates hedge orders based on risk level
  • Publishes hedge decisions to hedge_trades topic

Trade Executor Service (Port 8004)

  • Consumes hedge_trades messages
  • Executes actual trades on Bybit exchange
  • Tracks order status until filled
  • Publishes confirmations to trade_confirmations topic
  • Implements rate limiting and safety checks

πŸ§ͺ Testing

# 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

πŸ“ˆ Monitoring

  • Prometheus Metrics: Service-specific ports (909X range) for scrape targets.
  • Grafana Dashboards: Import dashboards in monitoring/grafana/dashboards/*.json.
  • Health Probes: /healthz + /ready endpoints 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.

πŸ—ΊοΈ Roadmap

v1.0.0 (Current)

  • βœ… Complete data pipeline from collection to hedge decisions
  • βœ… Risk state machine with configurable thresholds
  • βœ… Automated hedge order generation
  • βœ… Production-ready monitoring and logging

v1.1.0 (Current - 2025-01-15)

  • βœ… Trade Executor service for order execution
  • βœ… Trade confirmation tracking
  • βœ… Rate limiting and safety checks
  • βœ… Integration tests for complete flow

v1.2.0 (Next)

  • Treasury module for P&L tracking
  • Web dashboard for risk visualization
  • Advanced hedging strategies
  • Multi-exchange support

v1.2.0 (Future)

  • Web dashboard for risk visualization
  • Alert system integration
  • Historical data analysis
  • Machine learning risk models

πŸ“š Documentation

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Built with FastAPI, Apache Kafka, and aiokafka
  • Inspired by high-frequency trading risk management systems
  • Special thanks to all contributors

About

Decentralized loan monitoring and management system with automated liquidation protection

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages