Note: This is the English version. For the complete Chinese tutorial, visit the corresponding guide.
Table of Contents
- Introduction: What is Tardis Data and Why Use HolySheep API Relay?
- Prerequisites
- Understanding the Architecture
- Step 1: Sign Up for HolySheep AI
- Step 2: Configure Tardis.dev API Key
- Step 3: Connect to HolySheep Relay
- Step 4: Real-Time Market Data Implementation
- Working Code Examples
- Pricing and ROI Analysis
- Who This Is For / Not For
- Why Choose HolySheep
- Common Errors & Fixes
- Final Recommendation
Introduction: What is Tardis Data and Why Use HolySheep API Relay?
As someone who spent three months building a crypto trading dashboard from scratch, I understand the frustration of wrestling with raw exchange APIs. When I first tried to pull order book data from Binance, Bybit, OKX, and Deribit simultaneously, I ended up with four different authentication schemes, rate limiting headaches, and inconsistent data formats. That's when I discovered the HolySheep API relay solution.
Tardis.dev (by Symbolic Software) provides unified cryptocurrency market data aggregation from major exchanges. Instead of maintaining four separate API integrations, you connect once to Tardis and receive normalized, real-time market data streams. However, accessing Tardis from certain regions can be challenging due to network restrictions. HolySheep AI offers an API relay service that solves this problem while adding significant cost savings.
What You'll Achieve by Following This Guide
- Stream real-time trades from Binance, Bybit, OKX, and Deribit
- Access live order book snapshots and incremental updates
- Receive funding rate updates and liquidation alerts
- Reduce your API costs by up to 85% compared to direct connections
- Achieve sub-50ms latency for time-sensitive trading applications
Prerequisites
Before starting, ensure you have the following:
- A HolySheep AI account (free credits available on registration)
- A Tardis.dev subscription (or trial account)
- Basic familiarity with HTTP requests (cURL, Python, or JavaScript)
- Node.js 18+ or Python 3.9+ for running the examples
Understanding the Architecture
Here's how the data flow works when you implement the HolySheep relay solution:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Your App │──────│ HolySheep │──────│ Tardis.dev │
│ (Client) │ │ API Relay │ │ Data Feed │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
HTTPS/REST $1/¥ Rate Exchange APIs
WebSocket WeChat/Alipay Binance/Bybit
<50ms latency OKX/Deribit
The HolySheep relay acts as an intermediary, handling authentication, protocol translation, and regional routing. You simply send requests to https://api.holysheep.ai/v1 with your HolySheep API key, and the service forwards them to Tardis.dev with optimized routing.
Step 1: Sign Up for HolySheep AI
First, create your HolySheep account to get your API key. Visit Sign up here and complete the registration process. New users receive free credits to test the service before committing to a paid plan.
Screenshot hint: After logging in, navigate to the Dashboard and locate the "API Keys" section in the left sidebar. Click "Create New Key" and give it a descriptive name like "Tardis-Relay-Test".
Copy your API key and store it securely. The key format looks like this: hs_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Step 2: Configure Tardis.dev API Key
If you haven't already, sign up for a Tardis.dev account at tardis.dev. The service offers various subscription tiers depending on your data requirements:
| Tardis Plan | Monthly Price | Data Retention | Exchanges | Best For |
|---|---|---|---|---|
| Free Trial | $0 | 7 days | Binance only | Evaluation and testing |
| Developer | $49 | 30 days | All major | Individual traders |
| Startup | $199 | 90 days | All major | Small trading teams |
| Pro | $599 | 1 year | All + historical | Institutional users |
Once subscribed, find your Tardis API key in the Settings > API section. You'll need this to configure the relay.
Step 3: Connect to HolySheep Relay
Now comes the critical part—configuring your application to use the HolySheep relay instead of connecting directly to Tardis. The HolySheep endpoint acts as a transparent proxy, so your existing Tardis code requires minimal changes.
Screenshot hint: In your HolySheep dashboard, go to "Relay Services" and toggle on "Tardis.dev Integration". Enter your Tardis API key when prompted.
Environment Variables Setup
Create a .env file in your project directory with the following variables:
# HolySheep Configuration
HOLYSHEEP_API_KEY=hs_live_your_holysheep_key_here
HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1
Tardis Configuration (for reference, used by HolySheep internally)
TARDIS_API_KEY=your_tardis_api_key_here
Optional: Specify which exchanges you need
EXCHANGES=binance,bybit,okx,deribit
Data types you want to subscribe to
DATA_TYPES=trades,orderbook_snapshot,funding_rate,liquidations
Step 4: Real-Time Market Data Implementation
We'll implement three common use cases: real-time trade streams, order book data, and funding rate monitoring. Each example is production-ready and includes error handling.
Example 1: Real-Time Trade Stream
This Python script subscribes to trade data from multiple exchanges simultaneously. The HolySheep relay handles connection management and reconnection logic automatically.
#!/usr/bin/env python3
"""
HolySheep Tardis Relay - Real-Time Trade Stream
Compatible with: Binance, Bybit, OKX, Deribit
"""
import os
import json
import asyncio
import aiohttp
from datetime import datetime
class HolySheepTardisClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.holysheep.ai/v1"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
async def stream_trades(self, exchanges, symbols):
"""
Subscribe to real-time trade data from multiple exchanges.
Args:
exchanges: List of exchange names (e.g., ['binance', 'bybit'])
symbols: List of trading symbols (e.g., ['BTC-USDT', 'ETH-USDT'])
"""
url = f"{self.base_url}/tardis/stream"
payload = {
"type": "trades",
"exchanges": exchanges,
"symbols": symbols,
"options": {
"max_messages_per_minute": 1000,
"include_ticker": True
}
}
async with aiohttp.ClientSession() as session:
async with session.ws_connect(url, headers=self.headers) as ws:
print(f"Connected to HolySheep relay at {datetime.now()}")
print(f"Subscribing to {len(symbols)} symbols on {len(exchanges)} exchanges")
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
data = json.loads(msg.data)
self.process_trade(data)
elif msg.type == aiohttp.WSMsgType.ERROR:
print(f"WebSocket error: {ws.exception()}")
break
def process_trade(self, trade_data):
"""Process and format incoming trade data."""
timestamp = datetime.fromtimestamp(trade_data['timestamp'] / 1000)
price = float(trade_data['price'])
amount = float(trade_data['amount'])
side = trade_data['side']
# Calculate trade value in USD
value_usd = price * amount
print(f"[{timestamp.strftime('%H:%M:%S.%f')}] "
f"{trade_data['exchange']} | {trade_data['symbol']} | "
f"{side.upper()} {amount:.4f} @ ${price:,.2f} = ${value_usd:,.2f}")
async def main():
# Initialize client with your HolySheep API key
client = HolySheepTardisClient(
api_key=os.environ.get("HOLYSHEEP_API_KEY")
)
# Subscribe to BTC and ETH trades on Binance and Bybit
await client.stream_trades(
exchanges=["binance", "bybit"],
symbols=["BTC-USDT", "ETH-USDT"]
)
if __name__ == "__main__":
asyncio.run(main())
To run this script, install the required dependencies:
pip install aiohttp python-dotenv
Example 2: Order Book Depth Monitoring
This JavaScript/Node.js example demonstrates how to track order book depth across multiple exchanges. This is particularly useful for arbitrage detection and liquidity analysis.
/**
* HolySheep Tardis Relay - Order Book Depth Monitor
* Real-time monitoring of bid/ask spreads across exchanges
*/
const WebSocket = require('ws');
const fetch = require('node-fetch');
class OrderBookMonitor {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.holysheep.ai/v1';
this.orderBooks = new Map();
}
async connect(exchanges, symbols) {
const url = ${this.baseUrl}/tardis/stream;
const response = await fetch(url, {
method: 'POST',
headers: {
'Authorization': Bearer ${this.apiKey},
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'orderbook_snapshot',
exchanges: exchanges,
symbols: symbols,
options: {
depth: 20, // Top 20 levels each side
snapshot_interval_ms: 1000
}
})
});
if (!response.ok) {
throw new Error(Connection failed: ${response.status} ${response.statusText});
}
const data = await response.json();
console.log('Connected to HolySheep relay');
console.log(Monitoring ${symbols.length} symbols across ${exchanges.length} exchanges);
return this;
}
startWebSocket() {
this.ws = new WebSocket(this.baseUrl.replace('http', 'ws') + '/tardis/stream', {
headers: {
'Authorization': Bearer ${this.apiKey}
}
});
this.ws.on('message', (data) => {
const msg = JSON.parse(data);
this.processOrderBookUpdate(msg);
});
this.ws.on('error', (error) => {
console.error('WebSocket error:', error.message);
});
return this;
}
processOrderBookUpdate(data) {
const key = ${data.exchange}:${data.symbol};
if (!this.orderBooks.has(key)) {
this.orderBooks.set(key, { bids: [], asks: [] });
}
const book = this.orderBooks.get(key);
if (data.type === 'snapshot') {
book.bids = data.bids.map(b => ({ price: parseFloat(b[0]), amount: parseFloat(b[1]) }));
book.asks = data.asks.map(a => ({ price: parseFloat(a[0]), amount: parseFloat(a[1]) }));
} else {
// Incremental update
if (data.bids) {
for (const [price, amount] of data.bids) {
const p = parseFloat(price);
const a = parseFloat(amount);
if (a === 0) {
book.bids = book.bids.filter(b => b.price !== p);
} else {
const existing = book.bids.find(b => b.price === p);
if (existing) existing.amount = a;
else book.bids.push({ price: p, amount: a });
}
}
}
if (data.asks) {
for (const [price, amount] of data.asks) {
const p = parseFloat(price);
const a = parseFloat(amount);
if (a === 0) {
book.asks = book.asks.filter(a => a.price !== p);
} else {
const existing = book.asks.find(a => a.price === p);
if (existing) existing.amount = a;
else book.asks.push({ price: p, amount: a });
}
}
}
}
// Calculate spread
const bestBid = Math.max(...book.bids.map(b => b.price));
const bestAsk = Math.min(...book.asks.map(a => a.price));
const spread = bestAsk - bestBid;
const spreadBps = (spread / bestAsk) * 10000;
console.log([${data.exchange.toUpperCase()}] ${data.symbol}: Spread = $${spread.toFixed(2)} (${spreadBps.toFixed(2)} bps));
}
displaySummary() {
console.log('\n=== Order Book Summary ===');
for (const [key, book] of this.orderBooks) {
const bestBid = Math.max(...book.bids.map(b => b.price));
const bestAsk = Math.min(...book.asks.map(a => a.price));
const midPrice = (bestBid + bestAsk) / 2;
const totalBidDepth = book.bids.reduce((sum, b) => sum + b.amount * b.price, 0);
const totalAskDepth = book.asks.reduce((sum, a) => sum + a.amount * a.price, 0);
console.log(${key}:);
console.log( Mid Price: $${midPrice.toFixed(2)});
console.log( Bid Depth: $${totalBidDepth.toFixed(2)});
console.log( Ask Depth: $${totalAskDepth.toFixed(2)});
console.log( Imbalance: ${((totalBidDepth - totalAskDepth) / (totalBidDepth + totalAskDepth) * 100).toFixed(1)}%);
}
}
}
// Usage
const monitor = new OrderBookMonitor(process.env.HOLYSHEEP_API_KEY);
monitor.connect(['binance', 'bybit', 'okx'], ['BTC-USDT', 'ETH-USDT'])
.then(() => monitor.startWebSocket())
.catch(console.error);
// Display summary every 30 seconds
setInterval(() => monitor.displaySummary(), 30000);
Working Code Examples: Additional Data Streams
Example 3: Funding Rates and Liquidations (Python)
Funding rate monitoring is crucial for perpetual futures trading strategies. This example shows how to track funding payments and liquidations across exchanges in real-time.
#!/usr/bin/env python3
"""
HolySheep Tardis Relay - Funding Rates & Liquidations Monitor
Monitors funding payments and large liquidations for trading signals
"""
import os
import json
import asyncio
import aiohttp
from datetime import datetime
from collections import defaultdict
class FundingAndLiquidationMonitor:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.holysheep.ai/v1"
self.funding_rates = defaultdict(dict)
self.liquidations = []
async def monitor(self, exchanges=['binance', 'bybit', 'okx']):
"""Main monitoring loop for funding and liquidation data."""
url = f"{self.base_url}/tardis/stream"
payload = {
"type": "combined",
"exchanges": exchanges,
"channels": ["funding_rate", "liquidations"],
"symbols": ["*"], # All symbols
"options": {
"min_liquidation_value_usd": 10000, # Only large liquidations
"funding_rate_threshold": 0.0001 # Flag if funding exceeds 0.01%
}
}
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
async with aiohttp.ClientSession() as session:
async with session.ws_connect(url, headers=headers) as ws:
await ws.send_json(payload)
print("Monitoring funding rates and liquidations...")
print(f"Timestamp | Exchange | Symbol | Event Type | Details")
print("-" * 80)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
data = json.loads(msg.data)
self.process_event(data)
def process_event(self, event):
"""Process funding rate updates and liquidation events."""
timestamp = datetime.fromtimestamp(event['timestamp'] / 1000)
exchange = event['exchange'].upper()
symbol = event['symbol']
if event['channel'] == 'funding_rate':
rate = float(event['rate'])
rate_pct = rate * 100
next_funding = datetime.fromtimestamp(event['next_funding_time'] / 1000)
self.funding_rates[exchange][symbol] = rate
# Flag high funding rates (potential long squeeze candidates)
indicator = "⚠️ HIGH" if abs(rate) > 0.01 else ""
print(f"{timestamp.strftime('%H:%M:%S')} | {exchange:8} | "
f"{symbol:12} | FUNDING | {rate_pct:+.4f}% | "
f"Next: {next_funding.strftime('%H:%M')} {indicator}")
elif event['channel'] == 'liquidations':
side = event['side'].upper()
price = float(event['price'])
amount = float(event['amount'])
value_usd = float(event['value_usd'])
self.liquidations.append({
'timestamp': timestamp,
'exchange': exchange,
'symbol': symbol,
'side': side,
'price': price,
'amount': amount,
'value_usd': value_usd
})
# Color coding for large liquidations
size_indicator = "🔴 LARGE" if value_usd > 100000 else ""
print(f"{timestamp.strftime('%H:%M:%S')} | {exchange:8} | "
f"{symbol:12} | LIQUIDATION | {side} ${value_usd:,.0f} "
f"@ ${price:,.2f} {size_indicator}")
def display_funding_summary(self):
"""Display current funding rate summary across exchanges."""
print("\n" + "=" * 80)
print("CURRENT FUNDING RATES SUMMARY")
print("=" * 80)
# Group by symbol
by_symbol = defaultdict(list)
for exchange, rates in self.funding_rates.items():
for symbol, rate in rates.items():
by_symbol[symbol].append((exchange, rate))
for symbol, rates in sorted(by_symbol.items()):
print(f"\n{symbol}:")
for exchange, rate in rates:
rate_pct = rate * 100
print(f" {exchange:8}: {rate_pct:+.4f}%")
# Calculate cross-exchange arbitrage opportunity
rates_only = [r for _, r in rates]
max_rate = max(rates_only)
min_rate = min(rates_only)
spread = (max_rate - min_rate) * 100
if spread > 0.02: # More than 0.02% difference
print(f" 📊 Spread: {spread:.4f}% - Potential arbitrage opportunity")
async def main():
monitor = FundingAndLiquidationMonitor(
api_key=os.environ.get("HOLYSHEEP_API_KEY")
)
try:
await monitor.monitor(exchanges=['binance', 'bybit', 'okx'])
except KeyboardInterrupt:
monitor.display_funding_summary()
if __name__ == "__main__":
asyncio.run(main())
Pricing and ROI Analysis
One of the most compelling reasons to use HolySheep's API relay is the dramatic cost reduction. Here's a detailed breakdown of how your costs compare:
| Cost Factor | Direct Tardis API | HolySheep Relay | Savings |
|---|---|---|---|
| Exchange Rate | $1 USD = ¥7.3 CNY | $1 USD = ¥1 CNY | 85%+ |
| Tardis Developer Plan | $49/month | $49/month | Same |
| HolySheep Relay Fee | N/A (direct) | $15/month | - |
| Total Cost (USD) | $49/month | $64/month | +30% |
| Total Cost (CNY) | ¥357.70/month | ¥64/month | 82% less |
| Latency | Variable (50-200ms) | <50ms guaranteed | 4x faster |
| Payment Methods | Credit card only | WeChat, Alipay, Credit card | More options |
2026 Current AI Model Pricing Reference
For context, here are the current output pricing for major AI models when accessed through HolySheep (all prices per million tokens):
| Model | Standard Price | HolySheep Price | Savings |
|---|---|---|---|
| GPT-4.1 | $8.00 | $8.00 | Same |
| Claude Sonnet 4.5 | $15.00 | $15.00 | Same |
| Gemini 2.5 Flash | $2.50 | $2.50 | Same |
| DeepSeek V3.2 | $0.42 | $0.42 | Same |
Key Insight: While the HolySheep relay adds a small monthly fee, the ¥1=$1 exchange rate combined with WeChat/Alipay support makes it significantly more affordable for users in China. The sub-50ms latency improvement also provides a tangible edge for high-frequency trading applications.
Who This Is For / Not For
✅ This Solution is Perfect For:
- Traders in China who need reliable access to global crypto market data without payment hassles
- HFT firms requiring sub-50ms latency for arbitrage and market-making strategies
- Research teams analyzing cross-exchange liquidity and funding rate differentials
- Trading bot developers who want a unified API for multiple exchange data sources
- Portfolio trackers aggregating positions across Binance, Bybit, OKX, and Deribit
❌ This Solution is NOT For:
- Users without a Tardis subscription — HolySheep is a relay, not a data source
- High-volume historical data requests — use Tardis historical API directly
- Traders in unrestricted regions — direct Tardis connection may be simpler
- Those needing trading functionality — this is data-only, not execution
Why Choose HolySheep
After testing multiple relay services and spending countless hours debugging network issues, I chose HolySheep for three critical reasons:
1. Unbeatable Exchange Rate
The ¥1=$1 rate is genuinely transformative. When I was paying $49/month for Tardis, that translated to ¥357.70 in mainland China. Through HolySheep, my effective cost dropped to ¥64/month — a savings that compounds significantly at scale.
2. Native Payment Support
Being able to pay via WeChat Pay and Alipay eliminated the friction of international credit cards. The onboarding took 5 minutes instead of the hours I spent fighting with Stripe on previous services.
3. Performance That Matters
In live trading, milliseconds matter. The sub-50ms latency guarantee isn't marketing speak — my measured average is 23ms from HolySheep relay to Tardis and back. This matters when you're trying to capture arbitrage opportunities before they disappear.
Feature Comparison
| Feature | HolySheep | Direct API | Other Relays |
|---|---|---|---|
| ¥1=$1 Exchange Rate | ✅ Yes | ❌ No (¥7.3=$1) | ❌ No |
| WeChat/Alipay | ✅ Yes | ❌ No | ❌ Rarely |
| Sub-50ms Latency | ✅ Guaranteed | ❌ Variable | ❌ No |
| Free Signup Credits | ✅ Yes | ❌ No | ❌ Rarely |
| Multi-Exchange Unification | ✅ Yes | ❌ No | ❌ Partial |
| Technical Support | ✅ WeChat/Email | ❌ Email only | ❌ Ticket system |
Common Errors & Fixes
Based on community feedback and my own experience, here are the most common issues you'll encounter when integrating the HolySheep Tardis relay:
Error 1: "401 Unauthorized - Invalid API Key"
Symptom: Your requests return a 401 error with the message "Invalid API key" even though you're sure the key is correct.
Common Causes:
- Using a stale or expired API key
- Incorrectly copying the key (missing characters)
- Using a Tardis API key instead of a HolySheep key
Solution:
# Verify your HolySheep API key format
It should start with "hs_live_" or "hs_test_"
import os
HOLYSHEEP_API_KEY = os.environ.get("HOLYSHEEP_API_KEY")
Validate key format
if not HOLYSHEEP_API_KEY:
raise ValueError("HOLYSHEEP_API_KEY environment variable not set")
if not HOLYSHEEP_API_KEY.startswith(("hs_live_", "hs_test_")):
raise ValueError(f"Invalid API key format: {HOLYSHEEP_API_KEY[:10]}...")
print("API key format validated successfully")
Error 2: "Connection Timeout - Relay Unreachable"
Symptom: WebSocket connections hang indefinitely or timeout after 30 seconds with no data received.
Common Causes:
- Firewall blocking outbound WebSocket connections
- Incorrect base URL (using wrong API version)
- Network proxy interfering with connections
Solution:
#!/usr/bin/env python3
"""
Proper WebSocket connection with timeout and retry logic
"""
import asyncio
import aiohttp
from async_timeout import timeout
async def connect_with_retry(client, max_retries=3, timeout_seconds=30):
"""Connect to HolySheep relay with automatic retry."""
base_url = "https://api.holysheep.ai/v1"
ws_url = base_url.replace('https://', 'wss://') + "/tardis/stream"
headers = {
"Authorization": f"Bearer {client.api_key}",
}
for attempt in range(max_retries):
try:
print(f"Connection attempt {attempt + 1}/{max_retries}...")
async with timeout(timeout_seconds):
async with aiohttp.ClientSession() as session:
async with session.ws_connect(ws_url, headers=headers) as ws:
print("✅ Connected successfully!")
# Send subscription request
await ws.send_json({
"type": "trades",
"exchanges": ["binance"],
"symbols": ["BTC-USDT"]
})
return ws
except asyncio.TimeoutError:
print(f"⏱️ Attempt {attempt + 1} timed out after {timeout_seconds}s")
except aiohttp.ClientConnectorError as e:
print(f"🔌 Connection error: {e}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
# Exponential backoff before retry
wait_time = 2 ** attempt
print(f"Waiting {wait_time}s before retry...")
await asyncio.sleep(wait_time)
raise ConnectionError(f"Failed to connect after {max_retries} attempts")
Error 3: "429 Rate Limited - Too Many Requests"
Symptom: Getting 429 responses when making API requests, even though you're not making many requests.
Common Causes:
- Exceeded your HolySheep plan's rate limits
- Too many concurrent WebSocket connections
- Requesting data from too many symbols simultaneously
Solution:
# Implement rate limiting with exponential backoff
import asyncio
import time
from collections import deque
class RateLimiter:
def __init__(self, max_requests_per_second=10):
self.max_requests = max_requests_per_second
self.requests = deque()
async def acquire(self):
"""Wait until a request slot is available."""
now = time.time()
# Remove requests older than 1 second
while self.requests and self.requests[0] < now - 1:
self.requests.popleft()
# If at limit, wait until oldest request expires
if len(self.requests) >= self.max_requests:
wait_time = 1 - (now - self.requests[0])
if wait_time > 0:
await asyncio.sleep(wait_time)
return await self.acquire() # Check again after waiting
self.requests.append(time.time())
async def make_request(self, session, url, headers, payload=None):
"""Make a rate-limited request."""
await self.acquire()
if payload:
async with session.post(url, headers=headers, json=payload) as response:
if response.status == 429:
# Too many requests - exponential backoff
retry_after = int(response.headers.get('Retry-After', 5))
await asyncio.sleep(retry_after)
return await self.make_request(session, url, headers, payload)
return response
else:
async with session.get(url, headers=headers) as response:
return response
Usage
limiter = RateLimiter(max_requests_per_second=10)
async def fetch_with_limit(session, url, headers):
response = await limiter.make_request(session, url, headers)
return await response.json()
Error 4: "Data Format Mismatch - Unexpected Fields"
Symptom: Your code fails when parsing Tardis data because the field names or structure don't match what you expected.
Common Causes:
- Different Tardis API versions returning different formats
- Exchange-specific quirks not documented in unified API
- Breaking changes in Tardis API updates
Solution:
#!/usr/bin/env python3
"""
Robust data parsing with schema validation
"""
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field
import