암호화폐 파생상품 거래에서 증거금 관리는 리스크 관리의 핵심입니다. OKX의 현물 선물(Delivery Futures)과 옵션을 조합하여 거래할 때, 체계적 증거금 계산은 강제 청산을 방지하고 자본 효율을 극대화하는 데 필수적입니다. 이 튜토리얼에서는 OKX API를 활용한 증거금 계산 방법, HolySheep AI를 통한 최적의 AI 모델 활용, 그리고 실전에서 자주 발생하는 문제 해결 방안을 상세히 다룹니다.
HolySheep AI vs 공식 OKX API vs 기타 중개 서비스 비교
| 비교 항목 | HolySheep AI | 공식 OKX API | 기타 중개 서비스 |
|---|---|---|---|
| 주요 용도 | AI API 통합 게이트웨이 | 거래소 API 직접 연결 | API 프록시/중계 |
| 지원 모델 | GPT-4.1, Claude, Gemini, DeepSeek 등 | OKX 전용 | 제한적 |
| 결제 방식 | 로컬 결제 지원 (신용카드 불필요) | криптовалюта only | 다양함 |
| 단일 API 키 | ✓ 모든 모델 통합 | ✗ 거래소별 개별 키 | 제한적 |
| 비용 최적화 | DeepSeek V3.2 $0.42/MTok | API 사용료 별도 | 마진上加 |
| 개발자 친화성 | 높음 (다양한 SDK 지원) | 중간 (문서 복잡) | 다양함 |
이런 팀에 적합 / 비적합
✓ 이 튜토리얼이 적합한 팀
- OKX에서 현물 선물과 옵션을 조합 거래하는 Quantitative 트레이더
- 암호화폐 파생상품용 자동 거래 시스템(ATS)을 개발하는 개발자
- AI 기반 리스크 관리 솔루션을 구축하려는 데이터 사이언티스트
- 포트폴리오 증거금 최적화를 자동화하려는 헤지 펀드 및 가족 사무실
- HTX, Binance 등 다중 거래소 증거금 전략을 비교하려는 트레이더
✗ 이 튜토리얼이 적합하지 않은 경우
- 단순 현물 거래만 진행하는 사용자 (証拠금 관리 불필요)
- OKX API 사용 경험이 전혀 없는 초보자 (기초 튜토리얼 먼저 권장)
- 미국 규제 관할권下的 거래자 (OKX 제한 사유)
OKX 현물 선물과 옵션 조합 증거금 구조 이해
OKX에서 현물 선물(Delivery Futures)은 만기일에 실물 자산이 인도되는 파생상품입니다. 옵션과 조합하면 다양한 헤지 및 스프레드 전략을 구성할 수 있으며, 이때 체계적 증거금 계산이 중요해집니다.
증거금 유형 구분
| 증거금 유형 | 설명 | 계산 기준 | 비고 |
|---|---|---|---|
| 초기 증거금 (IM) | 포지션 오픈 시 필요 최소 증거금 | 계약 가치 × 초기 증거금률 | BTC: 1%, ETH: 2% |
| 유지 증거금 (MM) | 포지션 유지 필수 최소 증거금 | 계약 가치 × 유지 증거금률 | 강제 청산 임계값 |
| 옵션 프리미엄 | 옵션 매수/매도 시 결제 금액 | 프리미엄 × 수량 | 만기일 이전 청산 불가 |
| 스프레드 할인 | qualifier spreads 적용 시 | 전략별 차등 적용 | 콜 스프레드, 풋 스프레드 등 |
실전 코드: OKX 증거금 계산 API 연동
저는 실제 거래 시스템 구축 시 HolySheep AI의 통합 API를 활용하여 실시간 시장 데이터 분석과 증거금 시뮬레이션을 동시에 처리합니다. 아래는 Python 기반 완전한 구현 예제입니다.
# okx_margin_calculator.py
OKX 현물 선물 및 옵션 조합 증거금 계산기
HolySheep AI API를 활용한 시장 데이터 분석 통합
import requests
import json
import time
from datetime import datetime, timedelta
from typing import Dict, List, Optional
========================================
HolySheep AI API 설정 (모든 주요 모델 통합)
========================================
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
DeepSeek V3.2 활용: $0.42/MTok (비용 최적화)
Claude Sonnet 활용: $15/MTok (고급 분석)
class OKXMarginCalculator:
"""OKX 현물 선물 및 옵션 조합 증거금 계산기"""
def __init__(self, api_key: str, secret_key: str, passphrase: str, use_sandbox: bool = False):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
self.base_url = "https://www.okx.com" if not use_sandbox else "https://www.okx.com/sandbox"
# HolySheep AI 클라이언트 초기화
self._init_holysheep_client()
def _init_holysheep_client(self):
"""HolySheep AI API 클라이언트 설정"""
self.holysheep_headers = {
"Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
"Content-Type": "application/json"
}
def get_account_positions(self, inst_type: str = "FUTURES") -> List[Dict]:
"""현재 포지션 조회"""
endpoint = "/api/v5/account/positions"
params = {"instType": inst_type}
# 실제 구현 시 HMAC 서명 필요
response = self._signed_request("GET", endpoint, params)
return response.get("data", [])
def calculate_futures_margin(self, inst_id: str, notional: float, leverage: int = 10) -> Dict:
"""현물 선물 증거금 계산
Args:
inst_id: 선물 계약 ID (예: BTC-USDT-241227)
notional: 명목 가치 (USDT)
leverage: 레버리지 배율
Returns:
증거금 상세 정보
"""
# 시장 데이터 조회
ticker = self.get_ticker(inst_id)
mark_price = float(ticker.get("last", 0))
# 계약 정보 조회
inst_info = self.get_instrument_info(inst_id)
tick_size = float(inst_info.get("tickSize", "0.1"))
contract_size = float(inst_info.get("contractVal", "0.01"))
# 증거금 계산 공식
position_value = notional / mark_price * contract_size
initial_margin = position_value / leverage
maintenance_margin = initial_margin * 0.5 # 유지 증거금률 50%
return {
"inst_id": inst_id,
"mark_price": mark_price,
"position_value": position_value,
"leverage": leverage,
"initial_margin": initial_margin,
"maintenance_margin": maintenance_margin,
"liquidation_ratio": 1 / leverage * 0.8 # 청산 비율
}
def calculate_option_margin(self, inst_id: str, pos_side: str, sz: int) -> Dict:
"""옵션 증거금 계산
Args:
inst_id: 옵션 계약 ID (예: BTC-USD-241227-80000-C)
pos_side: 포지션 방향 (long/short)
sz: 수량
Returns:
옵션 증거금 상세
"""
# 옵션 시장 데이터 조회
ticker = self.get_ticker(inst_id)
last_price = float(ticker.get("last", 0))
# 옵션 프리미엄 계산
option_premium = last_price * sz
if pos_side == "long":
# 롱 포지션: 프리미엄만 지불
return {
"inst_id": inst_id,
"pos_side": pos_side,
"size": sz,
"last_price": last_price,
"premium_paid": option_premium,
"initial_margin": option_premium,
"max_loss": option_premium
}
else:
# 숏 포지션: 추가 증거금 필요
underlying_price = self.get_underlying_price(inst_id)
# 숏 옵션 증거금 계산 (SPAN 기반 근사)
option_value = last_price * sz
underlying_value = underlying_price * sz
margin_requirement = max(
option_value * 0.1, # 최소 10% 프리미엄
underlying_value * 0.05 # 기초자산 대비 5%
)
return {
"inst_id": inst_id,
"pos_side": pos_side,
"size": sz,
"last_price": last_price,
"premium_received": option_premium,
"additional_margin": margin_requirement,
"total_margin_required": margin_requirement - option_premium
}
def calculate_portfolio_margin(self, futures_positions: List[Dict], option_positions: List[Dict]) -> Dict:
"""조합 증거금 계산
현물 선물과 옵션을 종합한 총 증거금 및 위험도 평가
"""
total_initial_margin = 0
total_maintenance_margin = 0
total_premium = 0
# 선물 포지션 합산
for pos in futures_positions:
margin = self.calculate_futures_margin(
pos["instId"],
float(pos["notionalUsd"]),
int(pos.get("lever", "10"))
)
total_initial_margin += margin["initial_margin"]
total_maintenance_margin += margin["maintenance_margin"]
# 옵션 포지션 합산
for pos in option_positions:
margin = self.calculate_option_margin(
pos["instId"],
pos["posSide"],
int(pos["sz"])
)
if pos["posSide"] == "long":
total_premium -= margin["premium_paid"] # 프리미엄 지출
else:
total_premium += margin["premium_received"] # 프리미엄 수취
total_initial_margin += margin["additional_margin"]
# 순 증거금 요구량
net_margin_required = total_initial_margin - max(0, total_premium)
return {
"total_initial_margin": total_initial_margin,
"total_maintenance_margin": total_maintenance_margin,
"net_premium": total_premium,
"net_margin_required": max(0, net_margin_required),
"futures_count": len(futures_positions),
"option_count": len(option_positions),
"timestamp": datetime.now().isoformat()
}
def get_ticker(self, inst_id: str) -> Dict:
"""시장 데이터 조회 (공용 API)"""
endpoint = f"{self.base_url}/api/v5/market/ticker"
params = {"instId": inst_id}
response = requests.get(endpoint, params=params)
data = response.json()
return data.get("data", [{}])[0] if data.get("data") else {}
def get_instrument_info(self, inst_id: str) -> Dict:
"""계약 정보 조회"""
inst_type = "FUTURES" if "-USDT-" in inst_id or "-USD-" in inst_id else "OPTION"
endpoint = f"{self.base_url}/api/v5/public/instrument"
params = {"instId": inst_id, "instType": inst_type}
response = requests.get(endpoint, params=params)
data = response.json()
return data.get("data", [{}])[0] if data.get("data") else {}
def get_underlying_price(self, inst_id: str) -> float:
"""기초자산 현재가 조회"""
# BTC-USD-241227-80000-C → BTC-USD
parts = inst_id.split("-")
underlying = f"{parts[0]}-{parts[1]}"
endpoint = f"{self.base_url}/api/v5/market/ticker"
params = {"instId": underlying}
response = requests.get(endpoint, params=params)
data = response.json()
if data.get("data"):
return float(data["data"][0].get("last", 0))
return 0.0
def _signed_request(self, method: str, endpoint: str, params: Dict = None) -> Dict:
"""서명된 API 요청 (실제 거래 시 필수)"""
# 실제 구현: HMAC-SHA256 서명 생성
# timestamp = str(time.time())
# sign = hmac.new(self.secret_key.encode(), ...)
headers = {
"OK-ACCESS-KEY": self.api_key,
"OK-ACCESS-PASSPHRASE": self.passphrase,
# "OK-ACCESS-SIGN": calculated_signature,
# "OK-ACCESS-TIMESTAMP": timestamp,
"Content-Type": "application/json"
}
url = f"{self.base_url}{endpoint}"
if method == "GET":
response = requests.get(url, headers=headers, params=params)
else:
response = requests.post(url, headers=headers, json=params)
return response.json()
========================================
HolySheep AI 통합: AI 기반 증거금 최적화 분석
========================================
class HolySheepMarginAnalyzer:
"""HolySheep AI를 활용한 증거금 최적화 분석기"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = HOLYSHEEP_BASE_URL
def analyze_margin_optimization(self, portfolio_data: Dict) -> Dict:
"""AI를 활용한 포트폴리오 증거금 최적화 제안
DeepSeek V3.2 ($0.42/MTok) 활용 - 비용 효율적 분석
"""
prompt = f"""
현재 암호화폐 포트폴리오 증거금 분석 결과를 바탕으로 최적화 방안을 제안해주세요.
현재 상태:
- 총 초기 증거금: ${portfolio_data['total_initial_margin']:.2f}
- 총 유지 증거금: ${portfolio_data['total_maintenance_margin']:.2f}
- 선물 포지션 수: {portfolio_data['futures_count']}
- 옵션 포지션 수: {portfolio_data['option_count']}
- 순 프리미엄: ${portfolio_data['net_premium']:.2f}
분석 요청 사항:
1. 현재 증거금 효율성 평가
2. 스프레드 전략 적용 가능성
3. 레버리지 조정 제안
4. 강제 청산 위험도 평가
JSON 형식으로 응답해주세요.
"""
payload = {
"model": "deepseek/deepseek-chat-v3",
"messages": [
{"role": "system", "content": "당신은 암호화폐 파생상품 전문가입니다. 구체적이고 실행 가능한 조언을 제공해주세요."},
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"max_tokens": 1500
}
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
result = response.json()
return {
"status": "success",
"analysis": result["choices"][0]["message"]["content"],
"model": "deepseek/deepseek-chat-v3",
"usage": result.get("usage", {})
}
return {
"status": "error",
"message": f"API 호출 실패: {response.status_code}"
}
def generate_risk_report(self, positions: List[Dict]) -> str:
"""고급 리스크 분석 리포트 생성
Claude Sonnet ($15/MTok) 활용 - 복잡한 분석
"""
prompt = f"""
다음 거래 포지션들에 대한 상세 리스크 분석 리포트를 작성해주세요:
포지션 상세:
{json.dumps(positions, indent=2)}
포함할 내용:
1. VaR (Value at Risk) 추정
2. 시나리오 분석 (시장 하락 10%, 20%, 30% 시)
3. 상관관계 기반 포트폴리오 위험도
4. 증거금 충족 가능성 평가
5. 구체적 리스크 완화 제안
Markdown 형식으로 상세한 보고서를 작성해주세요.
"""
payload = {
"model": "anthropic/claude-sonnet-4-20250514",
"messages": [
{"role": "user", "content": prompt}
],
"max_tokens": 2000
}
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
result = response.json()
return result["choices"][0]["message"]["content"]
return "리포트 생성 실패"
========================================
메인 실행 예제
========================================
if __name__ == "__main__":
# HolySheep AI API 키 설정
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"
# OKX API credentials (실제 사용 시 환경변수 권장)
OKX_API_KEY = "your_okx_api_key"
OKX_SECRET_KEY = "your_okx_secret_key"
OKX_PASSPHRASE = "your_okx_passphrase"
# 초기화
calculator = OKXMarginCalculator(OKX_API_KEY, OKX_SECRET_KEY, OKX_PASSPHRASE)
analyzer = HolySheepMarginAnalyzer(HOLYSHEEP_API_KEY)
print("=" * 60)
print("OKX 현물 선물 & 옵션 조합 증거금 계산기")
print("=" * 60)
# 예시: BTC 현물 선물 포지션
futures_margin = calculator.calculate_futures_margin(
inst_id="BTC-USDT-241227",
notional=50000, # 50,000 USDT 명목 가치
leverage=10
)
print(f"\n[BTC-USDT-241227 현물 선물]")
print(f" 현재가: ${futures_margin['mark_price']:,.2f}")
print(f" 포지션 가치: ${futures_margin['position_value']:,.2f}")
print(f" 레버리지: {futures_margin['leverage']}x")
print(f" 초기 증거금: ${futures_margin['initial_margin']:,.2f}")
print(f" 유지 증거금: ${futures_margin['maintenance_margin']:,.2f}")
# 예시: BTC 옵션 포지션
call_option_margin = calculator.calculate_option_margin(
inst_id="BTC-USD-241227-80000-C",
pos_side="long",
sz=1
)
print(f"\n[BTC-USD-241227-80000-C 콜 옵션 (Long)]")
print(f" 权利金: ${call_option_margin['premium_paid']:,.2f}")
print(f" 최대 손실: ${call_option_margin['max_loss']:,.2f}")
# HolySheep AI를 통한 최적화 분석
print(f"\n[HolySheep AI 분석 요청 중...]")
analysis = analyzer.analyze_margin_optimization({
"total_initial_margin": futures_margin["initial_margin"] + call_option_margin["premium_paid"],
"total_maintenance_margin": futures_margin["maintenance_margin"],
"futures_count": 1,
"option_count": 1,
"net_premium": -call_option_margin["premium_paid"]
})
if analysis["status"] == "success":
print(f"\n[AI 분석 결과]")
print(analysis["analysis"][:500] + "..." if len(analysis["analysis"]) > 500 else analysis["analysis"])
print(f"\n[사용 모델]: {analysis['model']}")
print(f"[토큰 사용량]: {analysis['usage']}")
실전 시나리오: 선물-옵션 조합 전략 증거금 계산
# scenario_bull_call_spread.py
#強気 Calendar Spread: 현물 선물 + 콜 옵션 스프레드 전략
import requests
from datetime import datetime, timedelta
class BullCallSpreadCalculator:
"""強気콜 스프레드 전략 증거금 계산기
전략 구성:
- Long: BTC 80000 Call (만기 1개월)
- Short: BTC 85000 Call (만기 1개월)
- 헤지: BTC-USDT 현물 선물 숏 포지션
목표: 제한적 위험으로 상승 수익 극대화
"""
def __init__(self, base_url: str = "https://www.okx.com"):
self.base_url = base_url
def calculate_bull_call_spread(
self,
underlying_price: float,
long_strike: float,
short_strike: float,
expiry_date: str,
spot_position_value: float,
spot_leverage: int = 5
) -> Dict:
"""強気콜 스프레드 증거금 및 손익분기점 계산"""
# 시장 데이터 조회 (실제 API 연동)
long_option_price = self._get_option_price(underlying_price, long_strike, expiry_date, "C")
short_option_price = self._get_option_price(underlying_price, short_strike, expiry_date, "C")
# 순 bersih 프리미엄 ( netto premium)
net_premium = short_option_price - long_option_price
# 최대 이익: 두 행사가격 차이 - 순 프리미엄
max_profit = (short_strike - long_strike) - net_premium
# 최대 손실: 순 프리미엄
max_loss = net_premium
# 손익분기점
break_even = long_strike + net_premium
# 현물 선물 숏 포지션 증거금
futures_margin = spot_position_value / spot_leverage
# 현물 선물 숏 포지션 유지 증거금
maintenance_margin = futures_margin * 0.5
# 옵션 조합 증거금 (스프레드 할인 적용)
# 스프레드 전략 시 증거금 할인율: 30~50%
spread_discount = 0.4 # 40% 할인
option_margin_saved = (long_option_price + short_option_price) * spread_discount
return {
"strategy": "Bull Call Spread with Futures Hedge",
"underlying_price": underlying_price,
"long_strike": long_strike,
"short_strike": short_strike,
"expiry_date": expiry_date,
"net_premium": net_premium,
"max_profit": max_profit,
"max_loss": max_loss,
"break_even": break_even,
"profit_loss_ratio": max_profit / max_loss if max_loss > 0 else 0,
"spot_position": {
"value": spot_position_value,
"leverage": spot_leverage,
"initial_margin": futures_margin,
"maintenance_margin": maintenance_margin
},
"margin_summary": {
"futures_margin": futures_margin,
"option_spread_discount": option_margin_saved,
"total_margin_required": futures_margin - option_margin_saved,
"margin_efficiency": (max_profit / futures_margin * 100) if futures_margin > 0 else 0
}
}
def calculate_iron_condor(self, params: Dict) -> Dict:
"""Iron Condor 전략 증거금 계산
풀 proteção Iron Condor:
- Long Put (하단 방어)
- Short Put (하단 보호)
- Short Call (상단 보호)
- Long Call (상단 방어)
"""
underlying_price = params["underlying_price"]
# 구성 요소 가격 조회
long_put_price = self._get_option_price(underlying_price, params["long_put_strike"], params["expiry"], "P")
short_put_price = self._get_option_price(underlying_price, params["short_put_strike"], params["expiry"], "P")
short_call_price = self._get_option_price(underlying_price, params["short_call_strike"], params["expiry"], "C")
long_call_price = self._get_option_price(underlying_price, params["long_call_strike"], params["expiry"], "C")
# 네트 프리미엄
net_credit = (short_put_price + short_call_price) - (long_put_price + long_call_price)
# 최대 손실: wing 폭 - net credit
put_wing = params["short_put_strike"] - params["long_put_strike"]
call_wing = params["long_call_strike"] - params["short_call_strike"]
max_risk = max(put_wing, call_wing) - net_credit
# 잠김 수익률 (BEP 대비)
upper_break_even = params["short_call_strike"] + net_credit
lower_break_even = params["short_put_strike"] - net_credit
return {
"strategy": "Iron Condor",
"net_credit": net_credit,
"max_profit": net_credit,
"max_loss": max_risk,
"reward_risk_ratio": net_credit / max_risk if max_risk > 0 else 0,
"break_even_points": {
"upper": upper_break_even,
"lower": lower_break_even
},
"probability_analysis": {
"profit_zone_width": (params["short_call_strike"] - params["short_put_strike"]) + 2 * net_credit,
"loss_zone_probability": "estimated via IV analysis"
}
}
def _get_option_price(self, spot: float, strike: float, expiry: str, option_type: str) -> float:
"""옵션 가격 조회 (실제 구현: OKX API 호출)
실제 거래 시 OKX 공개 API 활용:
GET /api/v5/market/ticker?instId=BTC-USD-{expiry}-{strike}-{type}
"""
# 블랙-숄즈 근사치 (데모용)
time_to_expiry = 30 / 365 # 30일
volatility = 0.5 # 가정 IV
risk_free_rate = 0.05
# 단순 근사값 (실제 구현 시 proper pricing model 사용)
moneyness = spot / strike if option_type == "C" else strike / spot
intrinsic = max(0, spot - strike) if option_type == "C" else max(0, strike - spot)
# 외형 가치 근사
time_value = abs(spot - strike) * 0.1 * (1 - abs(1 - moneyness))
return intrinsic + time_value
def calculate_portfolio_risk_metrics(self, strategies: List[Dict]) -> Dict:
"""다중 전략 조합 위험도 메트릭스
HolySheep AI DeepSeek 모델 활용하여 종합 분석
"""
total_margin = sum(s.get("margin_summary", {}).get("total_margin_required", 0) for s in strategies)
total_max_loss = sum(s.get("max_loss", 0) for s in strategies)
total_max_profit = sum(s.get("max_profit", 0) for s in strategies)
return {
"portfolio_summary": {
"total_strategies": len(strategies),
"total_margin_required": total_margin,
"total_max_profit": total_max_profit,
"total_max_loss": total_max_loss,
"overall_reward_risk": total_max_profit / total_max_loss if total_max_loss > 0 else 0,
"margin_utilization_estimate": (total_max_loss / total_margin * 100) if total_margin > 0 else 0
},
"diversification_score": self._calculate_diversification(strategies),
"risk_alerts": self._generate_risk_alerts(strategies, total_margin)
}
def _calculate_diversification(self, strategies: List[Dict]) -> float:
"""분산투자 점수 계산 (0~100)"""
if len(strategies) < 2:
return 50 # 단일 전략
# 헤지 계수 기반 분산 평가
hedged_strategies = sum(1 for s in strategies if "hedge" in s.get("strategy", "").lower())
spread_strategies = sum(1 for s in strategies if "spread" in s.get("strategy", "").lower())
diversification = (hedged_strategies + spread_strategies * 0.5) / len(strategies) * 100
return min(100, diversification)
def _generate_risk_alerts(self, strategies: List[Dict], total_margin: float) -> List[Dict]:
"""위험 알람 생성"""
alerts = []
# 레버리지 경고
high_leverage = [s for s in strategies if s.get("spot_position", {}).get("leverage", 1) > 10]
if high_leverage:
alerts.append({
"level": "warning",
"message": f"높은 레버리지 포지션 감지: {len(high_leverage)}개 (10x 초과)"
})
# 증거금 집중도 경고
for strategy in strategies:
margin_ratio = strategy.get("margin_summary", {}).get("total_margin_required", 0) / total_margin
if margin_ratio > 0.5:
alerts.append({
"level": "critical",
"message": f"단일 전략 증거금 집중도 과다: {strategy['strategy']} ({margin_ratio*100:.1f}%)"
})
return alerts
실행 예제
if __name__ == "__main__":
calculator = BullCallSpreadCalculator()
print("=" * 70)
print("OKX 현물 선물 & 옵션 조합 증거금 시뮬레이터")
print("=" * 70)
# 시나리오 1: Bull Call Spread + Futures Hedge
print("\n[시나리오 1: Bull Call Spread with Futures Hedge]")
result = calculator.calculate_bull_call_spread(
underlying_price=65000, # BTC 현재가
long_strike=65000, # 롱 콜 행사가
short_strike=70000, # 숏 콜 행사가
expiry_date="241227",
spot_position_value=65000, # 65,000 USDT 현물 선물
spot_leverage=5 # 5배 레버리지
)
print(f" 기초자산 현재가: ${result['underlying_price']:,.2f}")
print(f" 롱 콜 행사가: ${result['long_strike']:,.2f}")
print(f" 숏 콜 행사가: ${result['short_strike']:,.2f}")
print(f" 순 프리미엄: ${result['net_premium']:,.2f}")
print(f" 최대 이익: ${result['max_profit']:,.2f}")
print(f" 최대 손실: ${result['max_loss']:,.2f}")
print(f" 손익분기점: ${result['break_even']:,.2f}")
print(f" 수익/손실 비율: {result['profit_loss_ratio']:.2f}x")
print(f"\n [証拠金 요약]")
print(f" 현물 선물 증거금: ${result['margin_summary']['futures_margin']:,.2f}")
print(f" 스프레드 할인: ${result['margin_summary']['option_spread_discount']:,.2f}")
print(f" 총 필요 증거금: ${result['margin_summary']['total_margin_required']:,.2f}")
print(f" 증거금 효율성: {result['margin_summary']['margin_efficiency']:.2f}%")
# 시나리오 2: Iron Condor
print("\n" + "-" * 70)
print("[시나리오 2: Iron Condor]")
iron_condor = calculator.calculate_iron_condor({
"underlying_price": 65000,
"long_put_strike": 60000,
"short_put_strike": 62000,
"short_call_strike": 68000,
"long_call_strike": 70000,
"expiry": "241227"
})
print(f" 순 신용(수익): ${iron_condor['net_credit']:,.2f}")
print(f" 최대 이익: ${iron_condor['max_profit']:,.2f}")
print(f" 최대 손실: ${iron_condor['max_loss']:,.2f}")
print(f" 상단 손익분기: ${iron_condor['break_even_points']['