บทนำ: ทำไมต้องติดตาม OKX Options Chain

ตลาดออปชันคริปโตเติบโตอย่างก้าวกระโดดในปี 2025 โดย OKX กลายเป็นหนึ่งใน Exchange ที่มี Volume สูงที่สุดสำหรับ BTC และ ETH Options การวิเคราะห์ Greeks (Delta, Gamma, Theta, Vega) และ Risk Indicators (IV, Max Pain, PCR) ช่วยให้นักเทรดและ Market Maker ตัดสินใจได้แม่นยำยิ่งขึ้น บทความนี้จะสอนวิธีดึงข้อมูล Options Chain จาก OKX Public API, คำนวณ Greeks ด้วย Black-Scholes Model และใช้ AI ช่วยวิเคราะห์ความเสี่ยงแบบ Real-time
💡 HolySheep AI สามารถช่วยประมวลผลข้อมูลออปชันจำนวนมากและสร้างรายงานวิเคราะห์อัตโนมัติ ลดเวลาคำนวณจาก 30 นาทีเหลือ <50 มิลลิวินาที
---

กรณีศึกษา: ทีม Quant Trading จากกรุงเทพฯ

บริบทธุรกิจ

ทีมสตาร์ทอัพ Quant Trading ในกรุงเทพฯ พัฒนาระบบเทรดออปชันอัตโนมัติสำหรับกองทุน Private Wealth กลุ่มลูกค้ารายย่อยระดับ High-Net-Worth ทีมมีโปรแกรมเมอร์ 3 คน งบประมาณจำกัด แต่ต้องการระบบที่รองรับ Real-time Greeks Calculation สำหรับ BTC และ ETH Options ทั้งหมดบน OKX

จุดเจ็บปวดกับโซลูชันเดิม

ทีมเคยใช้ AWS Lambda + Python Script ดึงข้อมูลจาก OKX WebSocket แต่พบปัญหาหลายประการ: - ค่าใช้จ่ายสูงเกินไป: AWS คิดเงินตาม Lambda Invocations ทำให้บิลรายเดือนพุ่งถึง $4,200 - ความหน่วงสูง: Cold Start ทำให้ latency สูงถึง 420ms ไม่เพียงพอสำหรับการเทรด Intra-day - โค้ดซับซ้อน: ต้องเขียน API Gateway + Lambda + CloudWatch หลายส่วน ยากต่อการ Maintain

การย้ายมาใช้ HolySheep AI

หลังจากทดลองใช้ HolySheep AI ทีมพบว่าสามารถรวมทุกอย่างใน Python Script เดียว:
# Base URL สำหรับ HolySheep AI
BASE_URL = "https://api.holysheep.ai/v1"

การหมุน API Key ผ่าน Environment Variable

import os HOLYSHEEP_API_KEY = os.getenv("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY") headers = { "Authorization": f"Bearer {HOLYSHEEP_API_KEY}", "Content-Type": "application/json" }

ผลลัพธ์ 30 วันหลังการย้าย

| ตัวชี้วัด | ก่อนย้าย | หลังย้าย | การปรับปรุง | |-----------|----------|----------|-------------| | Latency | 420ms | 180ms | -57% | | ค่าใช้จ่ายรายเดือน | $4,200 | $680 | -84% | | เวลา Deploy | 15 นาที | 2 นาที | -87% | | ความถี่อัปเดต Greeks | ทุก 5 วินาที | ทุก 1 วินาที | +400% | ---

ความเข้าใจพื้นฐาน: Greeks คืออะไร

ก่อนเข้าสู่โค้ด เรามาทำความเข้าใจ Greeks ทั้ง 4 ตัวที่สำคัญที่สุด:

1. Delta (Δ)

อัตราการเปลี่ยนแปลงของราคา Option ต่อการเปลี่ยนแปลงราคา Underlying 1 หน่วย - Call Option: Delta อยู่ระหว่าง 0 ถึง 1 - Put Option: Delta อยู่ระหว่าง -1 ถึง 0

2. Gamma (Γ)

อัตราการเปลี่ยนแปลงของ Delta ต่อการเปลี่ยนแปลงราคา Underlying 1 หน่วย สำคัญสำหรับนักเทรดที่ต้องการ Hedge ตำแหน่ง

3. Theta (Θ)

มูลค่าที่ Option สูญเสียไปทุกวัน (Time Decay) แสดงเป็นค่าลบ

4. Vega (ν)

ความไวของราคา Option ต่อการเปลี่ยนแปลง Implied Volatility (IV) 1% ---

ดึงข้อมูล OKX Options Chain

OKX มี Public REST API ที่ไม่ต้องยืนยันตัวตนสำหรับดึงข้อมูล Options พื้นฐาน มาดูวิธีการดึงข้อมูล Strike Price และ Premium สำหรับ BTC Options:
import requests
import json
from datetime import datetime, timedelta

class OKXOptionsData:
    """Class สำหรับดึงข้อมูล Options Chain จาก OKX"""
    
    BASE_URL = "https://www.okx.com"
    
    def __init__(self, api_key='', api_secret='', passphrase='', use_sandbox=False):
        self.api_key = api_key
        self.api_secret = api_secret
        self.passphrase = passphrase
        self.use_sandbox = use_sandbox
    
    def get_option_instruments(self, underlying="BTC", exp_date=None):
        """
        ดึงรายการ Options Instruments ทั้งหมด
        
        Args:
            underlying: 'BTC' หรือ 'ETH'
            exp_date: วันหมดอายุ เช่น '20250328'
        """
        endpoint = "/api/v5/public/instruments"
        params = {
            "instType": "OPT",
            "underlying": underlying,
        }
        if exp_date:
            params["exp"] = exp_date
        
        url = f"{self.BASE_URL}{endpoint}"
        response = requests.get(url, params=params)
        
        if response.status_code == 200:
            data = response.json()
            if data.get("code") == "0":
                return data.get("data", [])
            else:
                print(f"API Error: {data.get('msg')}")
                return []
        else:
            print(f"HTTP Error: {response.status_code}")
            return []
    
    def get_option_ticker(self, inst_id):
        """
        ดึงข้อมูล Ticker ของ Option เดี่ยว
        รวมถึง Last Price, Best Bid/Ask, Volume
        """
        endpoint = "/api/v5/market/ticker"
        params = {"instId": inst_id}
        
        url = f"{self.BASE_URL}{endpoint}"
        response = requests.get(url, params=params)
        
        if response.status_code == 200:
            data = response.json()
            if data.get("code") == "0":
                return data.get("data", [{}])[0]
        return {}
    
    def get_underlying_index(self, underlying="BTC-USD"):
        """
        ดึงราคา Index ปัจจุบันของ Underlying
        """
        endpoint = "/api/v5/market/index-ticker"
        params = {"instId": underlying + "-USD"}
        
        url = f"{self.BASE_URL}{endpoint}"
        response = requests.get(url, params=params)
        
        if response.status_code == 200:
            data = response.json()
            if data.get("code") == "0":
                ticker = data.get("data", [{}])[0]
                return float(ticker.get("last", 0))
        return 0

ตัวอย่างการใช้งาน

okx = OKXOptionsData()

ดึงราคา BTC Index ปัจจุบัน

btc_price = okx.get_underlying_index("BTC") print(f"BTC Index Price: ${btc_price:,.2f}")

ดึง Options ที่หมดอายุวันที่ 28 มีนาคม 2025

expiry = "20250328" options = okx.get_option_instruments("BTC", expiry) print(f"พบ {len(options)} Options สำหรับ BTC Expiry {expiry}")

แสดงตัวอย่าง Options

for opt in options[:5]: print(f" {opt['instId']}: Strike ${float(opt['strike']):,.0f} | Last: ${float(opt.get('last', 0)):.2f}")
---

คำนวณ Greeks ด้วย Black-Scholes Model

หลังจากได้ข้อมูล Options Chain แล้ว ต่อไปจะเป็นการคำนวณ Greeks ทั้งหมด สำหรับ Option แต่ละตัว:
import math
from scipy.stats import norm
from dataclasses import dataclass
from typing import Optional, List

@dataclass
class GreeksResult:
    """Data class สำหรับเก็บผลลัพธ์การคำนวณ Greeks"""
    inst_id: str
    option_type: str  # 'C' หรือ 'P'
    strike: float
    time_to_expiry: float  # หน่วย: ปี
    spot_price: float
    risk_free_rate: float
    implied_volatility: float
    
    # Greeks
    delta: float
    gamma: float
    theta: float
    vega: float
    
    # ราคา
    theoretical_price: float
    premium: float = 0  # จากตลาดจริง

class BlackScholesGreeks:
    """คำนวณ Greeks ด้วย Black-Scholes Model"""
    
    def __init__(self, risk_free_rate: float = 0.05):
        """
        Args:
            risk_free_rate: อัตราดอกเบี้ยปลอดภัย (ต่อปี) ค่าเริ่มต้น 5%
        """
        self.risk_free_rate = risk_free_rate
    
    def d1_d2(self, S, K, T, r, sigma):
        """คำนวณ d1 และ d2 สำหรับ Black-Scholes"""
        if T <= 0 or sigma <= 0:
            return 0, 0
        d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
        d2 = d1 - sigma * math.sqrt(T)
        return d1, d2
    
    def option_price(self, S, K, T, r, sigma, option_type='C'):
        """
        คำนวณราคา Option ตาม Black-Scholes
        
        Args:
            S: ราคา Spot ปัจจุบัน
            K: Strike Price
            T: Time to Expiry (ปี)
            r: Risk-free rate
            sigma: Implied Volatility
            option_type: 'C' สำหรับ Call, 'P' สำหรับ Put
        """
        if T <= 0:
            # คำนวณราคา Intrinsic
            if option_type == 'C':
                return max(0, S - K)
            else:
                return max(0, K - S)
        
        d1, d2 = self.d1_d2(S, K, T, r, sigma)
        
        if option_type == 'C':
            price = S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
        else:
            price = K * math.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
        
        return price
    
    def calculate_all_greeks(self, S, K, T, r, sigma, option_type='C'):
        """
        คำนวณ Greeks ทั้งหมด (Delta, Gamma, Theta, Vega)
        
        Returns:
            dict ที่มี delta, gamma, theta, vega และ price
        """
        if T <= 0:
            return {
                'delta': 1 if option_type == 'C' and S > K else (-1 if option_type == 'P' and S < K else 0),
                'gamma': 0,
                'theta': 0,
                'vega': 0,
                'price': self.option_price(S, K, T, r, sigma, option_type)
            }
        
        d1, d2 = self.d1_d2(S, K, T, r, sigma)
        sqrt_T = math.sqrt(T)
        
        # Delta
        if option_type == 'C':
            delta = norm.cdf(d1)
        else:
            delta = norm.cdf(d1) - 1
        
        # Gamma (เหมือนกันทั้ง Call และ Put)
        gamma = norm.pdf(d1) / (S * sigma * sqrt_T)
        
        # Theta (ต่อวัน = หารด้วย 365)
        if option_type == 'C':
            theta = (-S * norm.pdf(d1) * sigma / (2 * sqrt_T)
                    - r * K * math.exp(-r * T) * norm.cdf(d2)) / 365
        else:
            theta = (-S * norm.pdf(d1) * sigma / (2 * sqrt_T)
                    + r * K * math.exp(-r * T) * norm.cdf(-d2)) / 365
        
        # Vega (ต่อ 1% change = หารด้วย 100)
        vega = S * norm.pdf(d1) * sqrt_T / 100
        
        # ราคา
        price = self.option_price(S, K, T, r, sigma, option_type)
        
        return {
            'delta': delta,
            'gamma': gamma,
            'theta': theta,
            'vega': vega,
            'price': price
        }
    
    def calculate_iv(self, S, K, T, r, market_price, option_type='C', 
                    tol=1e-6, max_iter=100):
        """
        คำนวณ Implied Volatility จากราคาตลาดโดยใช้ Newton-Raphson
        
        Args:
            market_price: ราคา Option จริงจากตลาด
        """
        sigma = 0.5  # Initial guess
        
        for _ in range(max_iter):
            price = self.option_price(S, K, T, r, sigma, option_type)
            vega = S * norm.pdf((math.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma*math.sqrt(T))) * math.sqrt(T) / 100
            
            if abs(vega) < 1e-10:
                break
            
            diff = market_price - price
            if abs(diff) < tol:
                return sigma
            
            sigma = sigma + diff / vega
            
            # จำกัดค่า IV
            sigma = max(0.01, min(sigma, 5.0))
        
        return sigma

ตัวอย่างการใช้งาน

bs = BlackScholesGreeks(risk_free_rate=0.05)

Parameters สำหรับ BTC Call Option

S = 65000 # BTC Spot Price K = 70000 # Strike Price T = 30 / 365 # 30 วัน sigma = 0.8 # 80% IV r = 0.05 greeks = bs.calculate_all_greeks(S, K, T, r, sigma, 'C') print(f"=== BTC Call Option Greeks ===") print(f"Spot: ${S:,.0f} | Strike: ${K:,.0f} | T: {T:.4f} ปี | IV: {sigma:.1%}") print(f"─────────────────────────────────") print(f"Delta: {greeks['delta']:.4f}") print(f"Gamma: {greeks['gamma']:.6f}") print(f"Theta: {greeks['theta']:.4f} (ต่อวัน)") print(f"Vega: {greeks['vega']:.4f} (ต่อ 1% IV)") print(f"Price: ${greeks['price']:,.2f}")
---

สร้าง Risk Dashboard สำหรับ OKX Options Portfolio

ต่อไปจะเป็นการรวมทุกอย่างเข้าด้วยกัน สร้าง Dashboard ที่แสดง Greeks ของ Options ทั้งหมดใน Portfolio:
import pandas as pd
from datetime import datetime

class OKXOptionsRiskDashboard:
    """Dashboard สำหรับวิเคราะห์ความเสี่ยง Options Portfolio"""
    
    def __init__(self, risk_free_rate=0.05):
        self.bs = BlackScholesGreeks(risk_free_rate)
        self.positions = []
    
    def add_position(self, inst_id, option_type, strike, expiry_date, 
                     quantity, entry_price):
        """เพิ่ม Position ลงใน Portfolio"""
        self.positions.append({
            'inst_id': inst_id,
            'type': option_type,  # 'C' หรือ 'P'
            'strike': strike,
            'expiry': expiry_date,
            'quantity': quantity,  # บวก = Long, ลบ = Short
            'entry_price': entry_price,
            'multiplier': 1  # BTC Options มี multiplier = 1
        })
    
    def calculate_time_to_expiry(self, expiry_date):
        """คำนวณ T เป็นปี จากวันหมดอายุ"""
        if isinstance(expiry_date, str):
            expiry = datetime.strptime(expiry_date, '%Y%m%d')
        else:
            expiry = expiry_date
        
        T = (expiry - datetime.now()).total_seconds() / (365 * 24 * 3600)
        return max(T, 0)
    
    def calculate_portfolio_greeks(self, spot_price, avg_iv=0.7):
        """
        คำนวณ Portfolio Greeks รวมทั้งหมด
        
        Args:
            spot_price: ราคา Spot ปัจจุบันของ Underlying
            avg_iv: Implied Volatility เฉลี่ย (สำหรับ Options ที่ไม่มี IV จาก API)
        """
        total_delta = 0
        total_gamma = 0
        total_theta = 0
        total_vega = 0
        total_premium = 0
        total_pnl = 0
        
        position_details = []
        
        for pos in self.positions:
            T = self.calculate_time_to_expiry(pos['expiry'])
            strike = float(pos['strike'])
            
            # คำนวณ Greeks
            greeks = self.bs.calculate_all_greeks(
                spot_price, strike, T, 
                self.bs.risk_free_rate, avg_iv, pos['type']
            )
            
            # คูณด้วย Quantity และ Multiplier
            qty = pos['quantity']
            multiplier = pos['multiplier']
            
            delta = greeks['delta'] * qty * multiplier
            gamma = greeks['gamma'] * qty * multiplier
            theta = greeks['theta'] * qty * multiplier
            vega = greeks['vega'] * qty * multiplier
            
            # P&L (mark-to-market)
            current_price = greeks['price']
            entry_price = float(pos['entry_price'])
            pnl = (current_price - entry_price) * qty * multiplier
            
            total_delta += delta
            total_gamma += gamma
            total_theta += theta
            total_vega += vega
            total_premium += current_price * abs(qty) * multiplier
            total_pnl += pnl
            
            position_details.append({
                'inst_id': pos['inst_id'],
                'type': pos['type'],
                'strike': strike,
                'qty': qty,
                'delta': delta,
                'gamma': gamma,
                'theta': theta,
                'vega': vega,
                'pnl': pnl,
                'iv': avg_iv
            })
        
        return {
            'total_delta': total_delta,
            'total_gamma': total_gamma,
            'total_theta': total_theta,
            'total_vega': total_vega,
            'total_premium': total_premium,
            'total_pnl': total_pnl,
            'delta_per_1pct_move': total_delta * spot_price * 0.01,
            'gamma_risk_per_1pct_move': total_gamma * (spot_price * 0.01)**2,
            'positions': position_details
        }
    
    def get_max_pain(self, spot_price, expiry_date, strikes):
        """
        คำนวณ Max Pain Price
        
        Max Pain คือ Strike Price ที่ทำให้ Total Value ของ Options ที่หมดอายุ
        (ทั้ง Calls และ Puts) มีค่าสูงสุด หรือก็คือทำให้ผู้ถือ Options สูญเสียมากที่สุด
        """
        max_pain = 0
        min_total_value = float('inf')
        
        for strike in strikes:
            call_value = sum(max(strike - spot_price, 0) for s in strikes if s > strike)
            put_value = sum(max(spot_price - strike, 0) for s in strikes if s < strike)
            total_value = call_value + put_value
            
            if total_value < min_total_value:
                min_total_value = total_value
                max_pain = strike
        
        return max_pain
    
    def get_put_call_ratio(self, puts_volume, calls_volume):
        """คำนวณ Put/Call Ratio"""
        if calls_volume == 0:
            return float('inf')
        return puts_volume / calls_volume
    
    def generate_report(self, spot_price, avg_iv=0.7):
        """สร้างรายงาน Risk ฉบับเต็ม"""
        portfolio = self.calculate_portfolio_greeks(spot_price, avg_iv)
        
        report = f"""
╔══════════════════════════════════════════════════════════════════╗
║            OKX OPTIONS PORTFOLIO RISK REPORT                      ║
╠══════════════════════════════════════════════════════════════════╣
║  Spot Price: ${spot_price:>10,.2f}  |  Avg IV: {avg_iv:>6.1%}                ║
╠══════════════════════════════════════════════════════════════════╣
║  PORTFOLIO GREEKS                                                  ║
║  ────────────────────────────────────────────────────────────────  ║
║  Delta:          {portfolio['total_delta']:>10.4f}                                        ║
║  Gamma:          {portfolio['total_gamma']:>10.6f}                                      ║
║  Theta:          {portfolio['total_theta']:>10.4f} (ต่อวัน)                        ║
║  Vega:           {portfolio['total_vega']:>10.4f} (ต่อ 1% IV)                      ║
╠══════════════════════════════════════════════════════════════════╣
║  RISK METRICS                                                      ║
║  ────────────────────────────────────────────────────────────────  ║
║  P&L (Mark-to-Market):  ${portfolio['total_pnl']:>10,.2f}                               ║
║  Total Premium:         ${portfolio['total_premium']:>10,.2f}                               ║
║  Δ/1% Spot Move:        ${portfolio['delta_per_1pct_move']:>10,.2f}                               ║
║  Γ Risk/1% Move:        ${portfolio['gamma_risk_per_1pct_move']:>10,.2f}                               ║
╚══════════════════════════════════════════════════════════════════╝
"""
        return report

ตัวอย่างการใช้งาน

dashboard = OKXOptionsRiskDashboard(risk_free_rate=0.05)

เพิ่ม Positions ตัวอย่าง

dashboard.add_position( inst_id="BTC-20250328-65000-C", option_type='C', strike=65000, expiry_date='20250328', quantity=5, # Long 5 Contracts entry_price=2500 ) dashboard.add_position( inst_id="BTC-20250328-70000-C", option_type='C', strike=70000, expiry_date='20250328', quantity=-3, # Short 3 Contracts entry_price=1200 ) dashboard.add_position( inst_id="BTC-20250328-60000-P", option_type='P', strike=60000, expiry_date='20250328', quantity=2, entry_price=1800 )

สร้างรายงาน

report = dashboard.generate_report(spot_price=65000, avg_iv=0.75) print(report)

แสดงรายละเอียดแต่ละ Position

portfolio = dashboard.calculate_portfolio_greeks(spot_price=65000, avg_iv=0.75) print("\n=== Position Details ===") df = pd.DataFrame(portfolio['positions']) print(df.to_string(index=False))
---

ใช้ AI วิเคราะห์ Greeks และเตือนความเสี่ยง

นอกจากการคำนวณเชิงปริมาณแล้ว เรายังสามารถใช้ AI ช่วยวิเคราะห์เชิงคุณภาพ เช่น: - อธิบายสถานการณ์ที่เป็นไปได้ - เสนอกลยุทธ์การ Hedge - เตือนเมื่อ Risk Metrics เกินขีดจำกัด
import requests
import json

def analyze_greeks_with_ai(portfolio_data: dict, spot_price: float, 
                           model: str = "gpt-4.1