Claude
Skills
Sign in
Back

defi-trading-systems

Included with Lifetime
$97 forever

Designs DeFi trading systems for perpetual futures, liquidity provision, and automated strategies with risk management and MEV protection.

General

What this skill does


# DeFi Trading Systems

This skill provides guidance for building decentralized finance trading systems, with focus on perpetual futures, automated market makers, and risk management.

## Core Competencies

- **Perpetual Futures**: Funding rates, leverage, liquidation mechanics
- **Automated Market Makers**: Liquidity provision, impermanent loss
- **Risk Management**: Position sizing, stop losses, portfolio hedging
- **MEV Protection**: Sandwich attacks, frontrunning mitigation

## DeFi Trading Fundamentals

### Perpetual Futures Mechanics

```
Traditional Futures:              Perpetual Futures:
┌─────────────────┐              ┌─────────────────┐
│   Expiry Date   │              │   No Expiry     │
│   Settlement    │              │   Funding Rate  │
│   Roll Cost     │              │   Continuous    │
└─────────────────┘              └─────────────────┘

Funding Rate = (Mark Price - Index Price) / Index Price × Interval

If funding > 0: Longs pay Shorts
If funding < 0: Shorts pay Longs
```

### Key Concepts

| Term | Definition |
|------|------------|
| Mark Price | Fair value used for liquidation |
| Index Price | Spot price from exchanges |
| Funding Rate | Periodic payment between longs/shorts |
| Maintenance Margin | Minimum equity to avoid liquidation |
| Liquidation Price | Price at which position is forcibly closed |

## Position Management

### Position Sizing

```python
from dataclasses import dataclass
from decimal import Decimal

@dataclass
class Position:
    symbol: str
    side: str  # 'long' or 'short'
    size: Decimal
    entry_price: Decimal
    leverage: int
    margin: Decimal

    @property
    def notional_value(self) -> Decimal:
        return self.size * self.entry_price

    @property
    def liquidation_price(self) -> Decimal:
        """Calculate liquidation price"""
        maintenance_margin_rate = Decimal('0.005')  # 0.5%

        if self.side == 'long':
            # Liq price = Entry × (1 - Initial Margin + Maintenance Margin)
            return self.entry_price * (
                1 - (1 / self.leverage) + maintenance_margin_rate
            )
        else:
            return self.entry_price * (
                1 + (1 / self.leverage) - maintenance_margin_rate
            )

    def unrealized_pnl(self, current_price: Decimal) -> Decimal:
        """Calculate unrealized P&L"""
        if self.side == 'long':
            return self.size * (current_price - self.entry_price)
        else:
            return self.size * (self.entry_price - current_price)

    def roi_percent(self, current_price: Decimal) -> Decimal:
        """Return on investment percentage"""
        pnl = self.unrealized_pnl(current_price)
        return (pnl / self.margin) * 100


class PositionSizer:
    """Calculate position sizes based on risk parameters"""

    def __init__(self, account_balance: Decimal):
        self.balance = account_balance
        self.max_risk_per_trade = Decimal('0.02')  # 2% of account
        self.max_leverage = 10

    def calculate_size(
        self,
        entry_price: Decimal,
        stop_loss_price: Decimal,
        leverage: int
    ) -> dict:
        """Calculate position size for given risk parameters"""
        # Limit leverage
        leverage = min(leverage, self.max_leverage)

        # Risk amount
        risk_amount = self.balance * self.max_risk_per_trade

        # Price distance to stop
        price_distance = abs(entry_price - stop_loss_price)
        price_distance_pct = price_distance / entry_price

        # Position size based on risk
        # size × price_distance = risk_amount
        size = risk_amount / price_distance

        # Check margin requirements
        required_margin = (size * entry_price) / leverage

        if required_margin > self.balance:
            # Reduce size to fit available margin
            size = (self.balance * leverage) / entry_price

        return {
            'size': size,
            'leverage': leverage,
            'margin_required': (size * entry_price) / leverage,
            'risk_amount': size * price_distance,
            'risk_percent': (size * price_distance / self.balance) * 100
        }
```

### Liquidation Prevention

```python
class LiquidationMonitor:
    """Monitor positions for liquidation risk"""

    def __init__(self, warning_threshold: float = 0.8):
        self.warning_threshold = warning_threshold
        self.positions: dict[str, Position] = {}

    def check_health(self, position: Position, current_price: Decimal) -> dict:
        """Calculate position health metrics"""
        liq_price = position.liquidation_price

        if position.side == 'long':
            distance_to_liq = (current_price - liq_price) / current_price
        else:
            distance_to_liq = (liq_price - current_price) / current_price

        # Health ratio: 1.0 = max health, 0.0 = liquidation
        health_ratio = distance_to_liq / (1 / position.leverage)

        return {
            'liquidation_price': liq_price,
            'distance_percent': float(distance_to_liq) * 100,
            'health_ratio': float(health_ratio),
            'at_risk': health_ratio < self.warning_threshold,
            'margin_ratio': self._calculate_margin_ratio(position, current_price)
        }

    def _calculate_margin_ratio(
        self,
        position: Position,
        current_price: Decimal
    ) -> float:
        """Calculate current margin ratio"""
        pnl = position.unrealized_pnl(current_price)
        equity = position.margin + pnl
        return float(equity / position.notional_value)
```

## Funding Rate Strategies

### Funding Rate Arbitrage

```python
from typing import List
import asyncio

@dataclass
class FundingRateInfo:
    exchange: str
    symbol: str
    funding_rate: Decimal
    next_funding_time: int
    mark_price: Decimal
    index_price: Decimal

class FundingArbitrage:
    """Capture funding rate differentials"""

    def __init__(self, exchanges: List[str]):
        self.exchanges = exchanges
        self.min_rate_threshold = Decimal('0.0001')  # 0.01%

    async def find_opportunities(self, symbol: str) -> List[dict]:
        """Find funding rate arbitrage opportunities"""
        rates = await self._fetch_all_rates(symbol)

        opportunities = []

        # Sort by funding rate
        rates.sort(key=lambda x: x.funding_rate)

        # Find extremes
        lowest = rates[0]
        highest = rates[-1]

        spread = highest.funding_rate - lowest.funding_rate

        if spread > self.min_rate_threshold:
            opportunities.append({
                'type': 'cross_exchange',
                'long_exchange': lowest.exchange,
                'short_exchange': highest.exchange,
                'expected_return': spread,
                'annualized_return': spread * 3 * 365  # 8-hour funding
            })

        # Spot-perp basis trade
        for rate in rates:
            if abs(rate.funding_rate) > self.min_rate_threshold:
                opportunities.append({
                    'type': 'basis_trade',
                    'exchange': rate.exchange,
                    'direction': 'short_perp_long_spot' if rate.funding_rate > 0
                                 else 'long_perp_short_spot',
                    'expected_return': abs(rate.funding_rate),
                    'mark_index_spread': rate.mark_price - rate.index_price
                })

        return opportunities

    def calculate_basis_trade_pnl(
        self,
        funding_received: Decimal,
        entry_costs: Decimal,
        price_change_pnl: Decimal
    ) -> dict:
        """Calculate P&L for basis trade"""
        gross_pnl = funding_received + price_change_pnl
        net_pnl = gross_pnl - entry_costs

        return {
            'funding_pnl': funding_received,
            'price_pnl': price_change_pnl,  # Should be ~0 if hedged
            'costs': entry_costs,
            'net_pnl': net_pnl
        }
```

## AMM and Liquidity Provision

Related in General