defi-trading-systems
Designs DeFi trading systems for perpetual futures, liquidity provision, and automated strategies with risk management and MEV protection.
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
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.