Skip to main content

Overview

ClyptQ Trading System is an execution pipeline that converts strategy signals into actual trades. The same code runs from Backtest to Live, ensuring reproducibility.

TradingDriver

The central orchestrator for all trading systems:
from clyptq.apps.trading import TradingDriver

# Initialize from spec
driver = TradingDriver.from_spec(trading_spec)

# Load data
driver.load_data(
    items=["BTC/USDT:USDT", "ETH/USDT:USDT"],
    start=datetime(2024, 1, 1),
    end=datetime(2024, 12, 31)
)

# Execute
for result in driver.run():
    print(f"{result.timestamp}: PnL={result.pnl}")
TradingDriver Responsibilities:
  • Execute ComputeGraph (calculate strategy signals)
  • Manage TradingState (portfolio state)
  • Execute Orders (Execution Pipeline)
  • Track Performance (Metrics)

Execution Pipeline

Order execution is processed through a 3-stage pipeline:
1. Intention
   └─> Declarative order specification
       "Maintain BTC at 30% of portfolio"

2. Delta Calculation
   └─> Calculate required change from current position
       "Currently 20% → Increase to 30% = +10% buy needed"

3. Order Execution
   └─> Generate and execute actual exchange orders
       "Market buy 0.5 BTC"

Trading Intentions

Declarative order specifications:
from clyptq.apps.trading.spec.intention import TradingIntention

# Weight-based (portfolio weight)
intention = TradingIntention(
    mode="weight",
    values={
        "BTC/USDT:USDT": 0.3,  # 30%
        "ETH/USDT:USDT": 0.2   # 20%
    }
)

# Quantity-based (absolute quantity)
intention = TradingIntention(
    mode="quantity",
    values={
        "BTC/USDT:USDT": 1.5,  # 1.5 BTC
        "ETH/USDT:USDT": 10.0  # 10 ETH
    }
)
Delta Calculation:
# Current state
current_btc_qty = 1.0  # Holding 1 BTC
book_size = 10000.0    # $10,000 portfolio
btc_price = 42000.0

# Target weight = 30%
target_notional = 0.3 * book_size  # $3,000
target_qty = target_notional / btc_price  # 0.071 BTC

# Delta
delta = target_qty - current_btc_qty  # -0.929 BTC (sell)

Execution Modes

Backtest: Simulate with historical data
# INSTANT: Perfect execution
spec = TradingSpec(
    execution=TradingExecutionSpec(
        mode="backtest",
        latency_mode="INSTANT"  # No slippage
    )
)

# LATENT: Realistic simulation
spec = TradingSpec(
    execution=TradingExecutionSpec(
        mode="backtest",
        latency_mode="LATENT",  # Orderbook matching
        fill_model="aggressive"  # "aggressive" or "passive"
    )
)
Paper: Real-time data, simulated trading
spec = TradingSpec(
    execution=TradingExecutionSpec(
        mode="paper",
        venue="binance"
    )
)
Live: Real trading
spec = TradingSpec(
    execution=TradingExecutionSpec(
        mode="live",
        venue="binance",
        api_key=os.getenv("BINANCE_API_KEY"),
        api_secret=os.getenv("BINANCE_API_SECRET")
    )
)

TradingState

Portfolio state tracking:
class TradingState:
    """Current portfolio state"""

    # Spot account
    spot_balances: Dict[str, float]      # {symbol: quantity}
    spot_locked: Dict[str, float]         # Quantity in orders

    # Futures account
    futures_positions: Dict[str, Position]
    futures_balance: float
    futures_margin_used: float

    # Common
    total_equity: float                   # Total assets
    unrealized_pnl: float                 # Unrealized profit/loss
    realized_pnl: float                   # Realized profit/loss
State Updates:
# Auto-update on fill
fill = Fill(
    symbol="BTC/USDT:USDT",
    side="buy",
    quantity=0.5,
    price=42000.0,
    fee=0.001,
    timestamp=datetime.now()
)

state.apply_fill(fill)
# spot_balances["BTC/USDT:USDT"] += 0.5
# spot_balances["USDT"] -= (0.5 * 42000.0 + fee)
Margin Calculation (Futures):
# Position margin requirement
position_margin = abs(position_value) / leverage

# Maintenance margin
maintenance_margin = position_value * maintenance_margin_rate

# Available margin
available_margin = futures_balance - margin_used

# Liquidation check
if futures_balance < maintenance_margin:
    # Liquidation triggered

Order Types

Market Order: Immediate execution
order = MarketOrder(
    symbol="BTC/USDT:USDT",
    side="buy",
    quantity=0.5
)
Limit Order: Limit price order
order = LimitOrder(
    symbol="BTC/USDT:USDT",
    side="buy",
    quantity=0.5,
    price=41000.0,
    time_in_force="GTC"  # Good-Till-Cancel
)
Stop Order: Stop loss/take profit
order = StopOrder(
    symbol="BTC/USDT:USDT",
    side="sell",
    quantity=0.5,
    stop_price=40000.0  # Market sell when this price is reached
)

Risk Management

Position Limits:
spec = TradingSpec(
    execution=TradingExecutionSpec(
        max_position_size={"BTC/USDT:USDT": 10.0},  # Max 10 BTC
        max_position_pct=0.3,  # Max 30% of portfolio
        max_leverage=5.0       # Max 5x leverage
    )
)
Stop Loss & Take Profit:
# Specify directly in intention
intention = TradingIntention(
    mode="weight",
    values={"BTC/USDT:USDT": 0.3},
    stop_loss={"BTC/USDT:USDT": 0.95},   # Close at 5% loss
    take_profit={"BTC/USDT:USDT": 1.10}  # Close at 10% profit
)
Drawdown Limit:
spec = TradingSpec(
    execution=TradingExecutionSpec(
        max_drawdown=0.20  # Stop trading at 20% loss
    )
)

Cost Models

Trading costs are automatically applied per venue:
# Binance Spot
BinanceSpotCostModel(
    maker_fee=0.001,   # 0.1%
    taker_fee=0.001,   # 0.1%
    min_notional=10.0  # Minimum order value
)

# Binance Futures
BinanceFuturesCostModel(
    maker_fee=0.0002,  # 0.02%
    taker_fee=0.0004,  # 0.04%
    funding_rate=0.0001  # Every 8 hours
)
Slippage Models:
# Aggressive: taker order (immediate fill)
slippage = 0.0005  # 0.05% slippage

# Passive: maker order (wait at limit price)
slippage = 0.0  # No slippage, but fill not guaranteed

Environment Safety

Environment-specific restrictions to prevent mistakes:
# Dev: All modes allowed
if CLYPTQ_ENV == "dev":
    allow_modes = ["backtest", "paper", "live"]

# Prod: Live forbidden (Backend only)
if CLYPTQ_ENV == "prod":
    if mode == "live":
        raise EnvironmentError(
            "Live trading not allowed in prod environment. "
            "Use Backend API for live trading."
        )

# Kernel: Backtest only
if CLYPTQ_ENV == "kernel":
    allow_modes = ["backtest"]

Performance Tracking

Real-time Metrics:
# Auto-calculated every tick
result = driver.step()

print(f"Timestamp: {result.timestamp}")
print(f"Equity: {result.total_equity}")
print(f"PnL: {result.realized_pnl + result.unrealized_pnl}")
print(f"Sharpe: {result.sharpe_ratio}")
print(f"Drawdown: {result.max_drawdown}")
Custom Metrics:
# Add Metric Operator to ComputeGraph
sharpe = graph.add_node("sharpe",
    AccumSharpe(Input("returns", lookback=1))
)

win_rate = graph.add_node("win_rate",
    WinRate(Input("trades", lookback=100))
)

Best Practices

1. Test by Mode
# Stage 1: Backtest (INSTANT)
# Stage 2: Backtest (LATENT)
# Stage 3: Paper (real-time)
# Stage 4: Live (small amount)
# Stage 5: Live (full)
2. Risk Management
# Always configure
- max_position_size
- max_drawdown
- stop_loss
3. Consider Costs
# Actual profit = Strategy profit - Costs
- Trading fees
- Slippage
- Funding fees (Futures)
4. State Monitoring
# Check periodically
- Position size
- Margin usage
- Unrealized PnL

Ecosystem Value

For Builders:
  • Backtest = Live (same code)
  • Production infrastructure provided
  • Automated risk management
For Buyers:
  • Transparent execution logic
  • Verifiable performance
  • Built-in safety mechanisms