Thị trường tiền điện tử năm 2024 chứng kiến sự bùng nổ của các chiến lược arbitrage, đặc biệt là kết hợp giữa triangular arbitrage (三角套利) và funding rate arbitrage (资金费率套利). Bài viết này sẽ phân tích chi tiết rủi ro của chiến lược kết hợp này, đồng thời cung cấp giải pháp tối ưu hóa chi phí API cho nhà giao dịch.

Kịch bản lỗi thực tế: "ConnectionError: timeout after 3000ms"

Tôi vẫn nhớ rõ ngày 15/03/2024, khi chiến lược arbitrage của mình đang chạy ngon lành trên 3 cặp BTC/USDT, ETH/USDT, BTC/ETH. Đột nhiên, một lệnh hedge bị miss hoàn toàn do timeout khi gọi API Binance. Kết quả? Thua lỗ $2,340 trong 47 giây vì exposed position không được đóng đúng lúc.

# Screenshot lỗi thực tế
2024-03-15 14:32:17.892 | ERROR | BinanceFuturesAPI
ConnectionError: timeout after 3000ms
Endpoint: /fapi/v2/order
Symbol: BTCUSDT
Side: SELL
Quantity: 0.5

Mất cân bằng position: +0.5 BTC long không hedge

Thua lỗ: $2,340 (BTC giảm $4,680 sau đó)

Nguyên nhân gốc: Rate limit exceeded + network latency cao

Giải pháp: Cần retry logic + fallback exchange

Đây là bài học đắt giá về tầm quan trọng của risk management trong arbitrage strategy. Hãy cùng phân tích chi tiết.

Giới thiệu về Triangular Arbitrage và Funding Rate Arbitrage

1. Triangular Arbitrage (三角套利)

Triangular arbitrage là việc khai thác chênh lệch giá giữa 3 cặp tiền trên cùng một sàn. Ví dụ:

# Ví dụ: Arbitrage trên Binance

Cặp 1: BTC/USDT = 65,000

Cặp 2: ETH/USDT = 3,500

Cặp 3: ETH/BTC = 0.0538

Tính toán arbitrage opportunity:

Bước 1: Mua 1 BTC với giá 65,000 USDT

Bước 2: Bán 1 BTC → nhận ETH theo tỷ giá ETH/BTC

1 BTC / 0.0538 = 18.59 ETH

Bước 3: Bán 18.59 ETH → nhận USDT

18.59 × 3,500 = 65,065 USDT

Lợi nhuận: 65,065 - 65,000 = $65 (0.1%)

Sau phí: ~$40 (0.062%)

Điều kiện thực hiện: Chênh lệch > 0.15% mới có lợi nhuận

vì phí spot trading: 0.1% × 3 = 0.3% (maker+taker)

2. Funding Rate Arbitrage (资金费率套利)

Chiến lược này khai thác chênh lệch funding rate giữa perpetual futures và spot. Nhà giao dịch long futures (nhận funding) đồng thời short spot để hedge rủi ro.

# Ví dụ: Funding Rate Arbitrage trên Bybit

Funding rate BTCUSDT: +0.015% mỗi 8 giờ

Tương đương: +0.135% mỗi ngày

Cấu trúc position:

Long 1 BTC perpetual futures (nhận funding)

Short 1 BTC spot (hedge hoàn toàn)

Thu nhập hàng ngày:

Funding nhận được: 1 × 0.135% = 0.00135 BTC

Phí funding trả: ~0 (thường rất nhỏ)

Phí spot trading: 0.1% × 2 = 0.2% = 0.002 BTC

Phí futures trading: 0.02% × 2 = 0.04% = 0.0004 BTC

Net: Mỗi ngày lỗ ~0.001 BTC

Nhưng khi funding rate > 0.1%/8h: BẮT ĐẦU CÓ LỢI NHUẬN!

Chiến lược chỉ hiệu quả khi:

- Funding rate > 0.05% mỗi 8 giờ

- Spot-futures basis > 0.02%

Chiến lược Kết hợp: Triangular + Funding Rate

Việc kết hợp hai chiến lược này tạo ra cơ hội đa dạng hóa thu nhập, nhưng cũng đi kèm rủi ro nhân lên.

Sơ đồ chiến lược kết hợp

# ARCHITECTURE: Combined Arbitrage Strategy
#

┌─────────────────────────────────────────────────────────────┐

│ ARBITRAGE BOT │

├─────────────────────────────────────────────────────────────┤

│ │

│ ┌───────────────┐ ┌───────────────────────────────┐ │

│ │ TRIANGULAR │ │ FUNDING RATE │ │

│ │ ARBITRAGE │ │ ARBITRAGE │ │

│ ├───────────────┤ ├───────────────────────────────┤ │

│ │ Spot Markets │ │ Futures + Spot Hedge │ │

│ │ - BTC/USDT │ │ - Long BTC/USDT perpetual │ │

│ │ - ETH/USDT │ │ - Short BTC/USDT spot │ │

│ │ - ETH/BTC │ │ - Long ETH/USDT perpetual │ │

│ │ │ │ - Short ETH/USDT spot │ │

│ └───────────────┘ └───────────────────────────────┘ │

│ │ │ │

│ └───────────┬───────────┘ │

│ ▼ │

│ ┌────────────────┐ │

│ │ RISK MANAGER │ │

│ │ - Drawdown │ │

│ │ - Exposure │ │

│ │ - Liquidation │ │

│ └────────────────┘ │

└─────────────────────────────────────────────────────────────┘

Công thức tính lợi nhuận kết hợp:

Total_PnL = Triangular_PnL + Funding_PnL - Trading_Fees - Slippage

Ví dụ thực tế với $100,000 capital:

Triangular: 0.08% × 2 lần/ngày × $50,000 = $80/ngày

Funding: 0.12% × 3 ngày × $50,000 = $180/ngày

Tổng lý thuyết: $260/ngày (0.26%)

Sau phí: ~$180/ngày (0.18%)

Phân tích Rủi ro Chi tiết

Rủi ro 1: Liquidation Risk (清算风险)

Khi hedge position bằng perpetual futures, nếu funding rate đột ngột giảm hoặc thị trường biến động mạnh, position có thể bị liquidation.

# Ví dụ: Liquidation scenario

Capital: $100,000

Margin sử dụng: 10x leverage

Position:

Long BTC/USDT perpetual: +1 BTC @ $65,000

Short BTC spot: -1 BTC @ $65,000

Nếu BTC tăng 10%:

Futures PnL: -$6,500 (vì đang long)

Spot PnL: +$6,500 (vì đang short)

Net: $0 (hedged hoàn hảo)

NHƯNG! Nếu dùng margin:

Required margin: $6,500

Nếu BTC tăng 15% → liquidation khi margin < maintenance margin

Loss: $6,500 (toàn bộ margin)

Rủi ro thực tế:

- Funding rate đột ngột âm → carry trade đảo ngược

- Basis collapse → hedge không còn hiệu quả

- Liquidity giảm → slippage cao khi thoát

Giải pháp:

1. Chỉ dùng leverage tối đa 3x

2. Đặt stop-loss ngay khi basis < 0.01%

3. Monitor liquidation price liên tục

Rủi ro 2: Execution Risk (执行风险)

Triangular arbitrage đòi hỏi đồng thời thực hiện 3 lệnh. Nếu 1 lệnh fail, toàn bộ chiến lược thất bại.

# Execution failure scenario

Setup: Mua BTC → Bán BTC lấy ETH → Bán ETH lấy USDT

THÀNH CÔNG (lý tưởng):

Step 1: BUY 1 BTC @ 65,000 USDT ✓

Step 2: SELL 1 BTC → BUY 18.59 ETH @ 0.0538 BTC ✓

Step 3: SELL 18.59 ETH @ 3,500 USDT = 65,065 USDT ✓

Lợi nhuận: $65

THẤT BẠI (Step 2 fail):

Step 1: BUY 1 BTC @ 65,000 USDT ✓

Step 2: SELL 1 BTC → FAIL (network error/timeout) ✗

Result: HOLDING 1 BTC không hedge!

Rủi ro: Nếu BTC giảm 5% → Thua lỗ $3,250

GIẢI PHÁP: Atomic execution hoặc All-or-None

1. Sử dụng conditional orders

2. Implement retry với exponential backoff

3. Auto-close position nếu partial fill

Rủi ro 3: Counterparty Risk (交易对手风险)

Khi hoạt động trên nhiều sàn, rủi ro sàn bị hack hoặc freeze withdrawal là rất thực.

# Ví dụ: FTX-like scenario

Giả sử đang hold funds trên sàn có vấn đề

Position distribution nguy hiểm:

- Binance: $40,000 (40%)

- FTX: $30,000 (30%) ← SÀN BỊ COLLAPSE

- Bybit: $30,000 (30%)

Kết quả:

- Mất $30,000 (30% capital)

- Chiến lược arbitrage bị phá vỡ

- Drawdown: 30% trong 1 ngày

Best practices:

1. Không giữ quá 20% funds trên 1 sàn

2. Sử dụng cold wallet cho majority capital

3. Diversify across reputable exchanges only

4. Monitor exchange risk metrics liên tục

Rủi ro 4: Model Risk (模型风险)

Tính toán arbitrage opportunity dựa trên assumptions có thể sai.

# Common model risk scenarios

1. Slippage không được tính đúng

Tính toán: Profit = 0.1%

Thực tế: Slippage = 0.05% × 3 = 0.15%

Kết quả: Lỗ 0.05%

2. Fee tiers không chính xác

Giả định: 0.1% maker fee

Thực tế: Volume < $1M → 0.2% maker fee

Kết quả: Lỗ thêm 0.1% mỗi leg

3. Latency assumptions sai

Tính toán: Execution time = 50ms

Thực tế: Peak time = 500ms+

Chênh lệch: Price đã thay đổi → Thua lỗ

4. Funding rate forecast sai

Dự đoán: Funding rate ổn định 0.02%/8h

Thực tế: Funding rate giảm về 0.005%/8h

Kết quả: Chi phí funding > Lợi nhuận carry

Risk Management Framework

# Risk Management System Implementation

class ArbitrageRiskManager:
    def __init__(self, config):
        self.max_position_size = config['max_position']  # max $10,000
        self.max_daily_loss = config['max_daily_loss']    # max 2%
        self.max_leverage = config['max_leverage']        # max 3x
        self.circuit_breaker = config['circuit_breaker']  # pause if DD > 5%
        
    def check_position_risk(self, position):
        """Kiểm tra rủi ro trước khi open position"""
        
        # 1. Check position size limit
        if position.value > self.max_position_size:
            return False, "Position exceeds max size"
            
        # 2. Check daily loss limit
        if self.today_loss > self.max_daily_loss:
            return False, "Daily loss limit reached"
            
        # 3. Check total exposure
        if self.total_exposure > self.max_exposure:
            return False, "Total exposure limit exceeded"
            
        # 4. Check leverage
        if position.leverage > self.max_leverage:
            return False, "Leverage exceeds limit"
            
        # 5. Check liquidation distance
        if position.liquidation_distance < 0.05:  # < 5%
            return False, "Liquidation too close"
            
        return True, "OK"
    
    def calculate_var(self, positions, confidence=0.95):
        """Value at Risk calculation"""
        # 99% confidence, 1-day VaR
        returns = self.get_historical_returns()
        var = np.percentile(returns, (1 - confidence) * 100)
        return var * sum(p.value for p in positions)
    
    def circuit_breaker_check(self):
        """Emergency stop if drawdown too high"""
        current_dd = self.calculate_drawdown()
        if current_dd > self.circuit_breaker:
            self.emergency_close_all()
            self.send_alert(f"Circuit breaker triggered: DD={current_dd:.2%}")
            return False
        return True
    
    def emergency_close_all(self):
        """Close all positions immediately"""
        for position in self.active_positions:
            try:
                self.exchange.close_position(position)
            except Exception as e:
                logger.error(f"Emergency close failed: {e}")
                # Retry với market order
                self.exchange.close_market(position)

HolySheep AI: Giải pháp API tối ưu cho Arbitrage Trading

Trong quá trình xây dựng và vận hành chiến lược arbitrage, việc sử dụng API cho data analysis và signal generation là rất quan trọng. Đăng ký tại đây để trải nghiệm HolySheep AI với chi phí thấp hơn 85% so với OpenAI.

So sánh chi phí API: HolySheep vs OpenAI vs Anthropic

Nhà cung cấp Model Giá/1M Tokens Latency trung bình Tiết kiệm vs OpenAI
HolySheep AI DeepSeek V3.2 $0.42 <50ms 95.75%
Google Gemini 2.5 Flash $2.50 ~120ms 75%
OpenAI GPT-4.1 $8.00 ~200ms Baseline
Anthropic Claude Sonnet 4.5 $15.00 ~180ms +87.5% đắt hơn

Ứng dụng HolySheep AI trong Arbitrage Strategy

# Ví dụ: Sử dụng HolySheep AI cho market analysis
import requests

Cấu hình HolySheep API

BASE_URL = "https://api.holysheep.ai/v1" API_KEY = "YOUR_HOLYSHEEP_API_KEY" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" }

Prompt cho phân tích funding rate

prompt = """ Phân tích cơ hội funding rate arbitrage cho BTC và ETH perpetual futures. Data hiện tại: - BTC funding rate: +0.025% / 8h trên Binance - ETH funding rate: +0.018% / 8h trên Bybit - BTC/ETH basis (futures-spot): +0.03% - ETH basis: +0.015% Tính toán: 1. Net daily return cho mỗi strategy 2. Risk-adjusted return (sharpe ratio estimate) 3. Khuyến nghị: BTC hay ETH arbitrage tốt hơn? 4. Position sizing tối ưu với $50,000 capital """ payload = { "model": "deepseek-v3.2", "messages": [ {"role": "system", "content": "Bạn là chuyên gia phân tích crypto arbitrage."}, {"role": "user", "content": prompt} ], "temperature": 0.3, "max_tokens": 1000 } response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) result = response.json() print(result['choices'][0]['message']['content'])

Chi phí: ~2,000 tokens × $0.42/1M = $0.00084 = 0.084 cent

So với OpenAI GPT-4.1: ~$0.016 = 1.6 cent (TIẾT KIỆM 95%!)

Code hoàn chỉnh: Arbitrage Signal Generator

# Complete Arbitrage Signal Generator với HolySheep AI

import requests
import json
import time
from datetime import datetime
from typing import Dict, List, Optional

class ArbitrageSignalGenerator:
    """Tạo tín hiệu arbitrage từ HolySheep AI"""
    
    def __init__(self, api_key: str):
        self.base_url = "https://api.holysheep.ai/v1"
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        self.cache = {}
        self.cache_ttl = 60  # Cache 60 giây
        
    def get_triangular_opportunity(self, data: Dict) -> Optional[Dict]:
        """Phân tích cơ hội triangular arbitrage"""
        
        # Check cache
        cache_key = f"triangular_{data.get('timestamp', 0)}"
        if cache_key in self.cache:
            if time.time() - self.cache[cache_key]['time'] < self.cache_ttl:
                return self.cache[cache_key]['data']
        
        prompt = f"""
Bạn là chuyên gia triangular arbitrage. Phân tích dữ liệu sau và trả lời JSON format:

Dữ liệu thị trường:
- BTC/USDT: {data['btc_usdt_price']}
- ETH/USDT: {data['eth_usdt_price']}
- ETH/BTC: {data['eth_btc_price']}
- BTC/USDT spread: {data['btc_spread']}
- ETH/USDT spread: {data['eth_spread']}

Tính toán:
1. Theoretical price của ETH/BTC (từ BTC/USDT ÷ ETH/USDT)
2. Chênh lệch với price thực (%)
3. Net profit sau phí (0.1% mỗi leg)
4. Recommendation: BUY/SELL/HOLD
5. Confidence score (0-100%)

Trả lời format JSON:
{{"theoretical_btc_eth": float, "spread_pct": float, "net_profit_pct": float, "recommendation": str, "confidence": int}}
"""
        
        try:
            response = self._call_ai(prompt)
            result = json.loads(response)
            self.cache[cache_key] = {'data': result, 'time': time.time()}
            return result
        except Exception as e:
            print(f"Error getting triangular opportunity: {e}")
            return None
    
    def get_funding_arbitrage_opportunity(self, data: Dict) -> Optional[Dict]:
        """Phân tích cơ hội funding rate arbitrage"""
        
        prompt = f"""
Phân tích funding rate arbitrage opportunity:

Perpetual Futures:
- BTC funding: {data['btc_funding']}% / 8h
- ETH funding: {data['eth_funding']}% / 8h

Spot Markets:
- BTC spot- futures basis: {data['btc_basis']}%
- ETH spot-futures basis: {data['eth_basis']}%

Tính toán:
1. Daily funding income (%)
2. Carry cost (phí trading + borrow rate nếu có)
3. Net daily return cho BTC và ETH
4. Risk assessment (basis collapse, liquidation)
5. Optimal position sizing với ${data['capital']} capital
6. Stop-loss level

Trả lời format JSON:
{{"btc_daily_return": float, "eth_daily_return": float, "recommended_asset": str, "position_size": float, "stop_loss_pct": float}}
"""
        
        try:
            response = self._call_ai(prompt)
            result = json.loads(response)
            return result
        except Exception as e:
            print(f"Error getting funding opportunity: {e}")
            return None
    
    def get_combined_strategy(self, triangular_data: Dict, funding_data: Dict) -> Dict:
        """Tạo chiến lược kết hợp tối ưu"""
        
        prompt = f"""
Tạo chiến lược arbitrage kết hợp từ 2 phân tích:

Triangular Opportunity:
{json.dumps(triangular_data)}

Funding Rate Opportunity:
{json.dumps(funding_data)}

Yêu cầu:
1. Đề xuất allocation giữa triangular và funding (%)
2. Risk score tổng thể (1-10)
3. Expected return hàng ngày (%)
4. Maximum drawdown ước tính (%)
5. Action plan chi tiết

Trả lời format JSON với các trường: allocation_triangular, allocation_funding, risk_score, expected_daily_return, max_drawdown, action_plan
"""
        
        try:
            response = self._call_ai(prompt)
            result = json.loads(response)
            return result
        except Exception as e:
            print(f"Error getting combined strategy: {e}")
            return {"error": str(e)}
    
    def _call_ai(self, prompt: str) -> str:
        """Gọi HolySheep AI API"""
        payload = {
            "model": "deepseek-v3.2",
            "messages": [
                {"role": "system", "content": "Bạn là chuyên gia crypto arbitrage với 10 năm kinh nghiệm."},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.2,
            "max_tokens": 1500
        }
        
        response = requests.post(
            f"{self.base_url}/chat/completions",
            headers=self.headers,
            json=payload,
            timeout=30
        )
        
        if response.status_code != 200:
            raise Exception(f"API Error: {response.status_code}")
        
        return response.json()['choices'][0]['message']['content']

Sử dụng

generator = ArbitrageSignalGenerator("YOUR_HOLYSHEEP_API_KEY")

Lấy dữ liệu thị trường (cần implement real data fetching)

market_data = { 'btc_usdt_price': 65432.50, 'eth_usdt_price': 3512.30, 'eth_btc_price': 0.05365, 'btc_spread': 0.02, 'eth_spread': 0.015, 'btc_funding': 0.025, 'eth_funding': 0.018, 'btc_basis': 0.03, 'eth_basis': 0.015, 'capital': 50000, 'timestamp': int(time.time()) }

Phân tích

triangular = generator.get_triangular_opportunity(market_data) funding = generator.get_funding_arbitrage_opportunity(market_data) combined = generator.get_combined_strategy(triangular, funding) print(f"Khuyến nghị: {combined.get('recommendation', 'HOLD')}") print(f"Risk Score: {combined.get('risk_score', 'N/A')}") print(f"Expected Return: {combined.get('expected_daily_return', 0):.2f}%/ngày")

Chi phí API ước tính: ~5,000 tokens × $0.42/1M = $0.0021 = 0.21 cent

Lỗi thường gặp và cách khắc phục

Lỗi 1: "401 Unauthorized" - Authentication Failed

# Nguyên nhân: API key sai hoặc hết hạn

Mã lỗi:

{"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}}

Khắc phục:

import os

Sai cách (KHÔNG LÀM):

api_key = "sk-xxxx" # Hardcode trong code

Đúng cách:

1. Lưu API key trong environment variable

export HOLYSHEEP_API_KEY="YOUR_KEY"

2. Load từ environment

api_key = os.environ.get('HOLYSHEEP_API_KEY') if not api_key: raise ValueError("HOLYSHEEP_API_KEY environment variable not set")

3. Validate API key format

if not api_key.startswith('hs_'): raise ValueError("Invalid API key format. Must start with 'hs_'")

4. Test connection trước khi sử dụng

def test_connection(api_key): headers = {"Authorization": f"Bearer {api_key}"} response = requests.get( "https://api.holysheep.ai/v1/models", headers=headers, timeout=10 ) if response.status_code == 401: raise AuthenticationError("Invalid API key") elif response.status_code != 200: raise ConnectionError(f"Connection failed: {response.status_code}") return True

5. Retry với exponential backoff

from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10)) def call_api_with_retry(payload): response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) return response

Lỗi 2: "Rate Limit Exceeded" - Quá nhiều requests

# Nguyên nhân: Gọi API quá nhiều lần trong thời gian ngắn

Mã lỗi:

{"error": {"message": "Rate limit exceeded", "type": "rate_limit_error"}}

Khắc phục:

import time from collections import deque from threading import Lock class RateLimiter: """Token bucket rate limiter""" def __init__(self, max_requests: int = 60, time_window: int = 60): self.max_requests = max_requests self.time_window = time_window self.requests = deque() self.lock = Lock() def acquire(self) -> bool: """Chờ đến khi có slot available""" with self.lock: now = time.time() # Remove expired requests while self.requests and self.requests[0] < now - self.time_window: self.requests.popleft() if len(self.requests) < self.max_requests: self.requests.append(now) return True else: # Calculate wait time wait_time = self.requests[0] - (now - self.time_window) if wait_time > 0: time.sleep(wait_time) self.requests.popleft() self.requests.append(time.time()) return True def wait_if_needed(self): """Chờ nếu cần thiết""" while not self.acquire(): time.sleep(0.1)

Sử dụng rate limiter

limiter = RateLimiter(max_requests=30, time_window=60) # 30 requests/phút def call_api_cached(payload, cache_key): """Gọi API với caching và rate limiting""" # Check cache trước cached = cache.get(cache_key) if cached and time.time() - cached['time'] < 60: return cached['data'] # Wait for rate limit limiter.wait_if_needed() # Call API response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) if response.status_code == 429: # Rate limited - wait và retry retry_after = int(response.headers.get('Retry-After', 60)) print(f"Rate limited. Waiting {retry_after}s...") time.sleep(retry_after) return call_api_cached(payload, cache_key) # Cache kết quả cache[cache_key] = { 'data': response.json(), 'time': time.time() } return response.json()

Lỗi 3: "Connection Timeout" - Network Issues

# Nguyên nhân: Network latency cao hoặc server overload

Mã lỗi:

requests.exceptions.ConnectTimeout: Connection timeout

Khắc phục:

import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry import socket

Cấu hình session với retry strategy

def create_resilient_session(): """Tạo session với automatic retry và timeout tối ưu""" session = requests.Session() # Retry strategy retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["HEAD", "GET", "POST"] ) # Adapter với connection pooling adapter = HTTPAdapter( max_retries=retry_strategy, pool_connections=10, pool_maxsize=20 ) session.mount("https://", adapter) session.mount("http://", adapter) return session

Timeout configuration

TIMEOUT_CONFIG = { 'connect': 5, # Connection timeout: 5s 'read': 25 # Read timeout: 25s }

Fallback endpoints

FALLBACK_ENDPOINTS = [ "https://api.holysheep.ai/v1", "https://backup-api.holysheep.ai/v1", ] def call_with_fallback(payload): """Gọi API với fallback endpoints""" last_error = None for endpoint in FALLBACK_ENDPOINTS: try: session = create_resilient_session() response = session.post( f"{endpoint}/chat