Metadata-Version: 2.4
Name: cymetica-eventtrader
Version: 0.2.1
Summary: Official Python SDK for the EventTrader prediction markets platform (import name: event_trader)
Project-URL: Homepage, https://cymetica.com
Project-URL: Documentation, https://cymetica.com/sdk
Author-email: Event Trader <dev@cymetica.com>
License-Expression: MIT
Keywords: api,cryptocurrency,defi,prediction-markets,sdk,trading,web3
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.25.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: websockets>=12.0
Provides-Extra: all
Requires-Dist: eth-account>=0.10.0; extra == 'all'
Requires-Dist: web3>=6.0.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: isort>=5.12.0; extra == 'dev'
Requires-Dist: mypy>=1.5.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: web3
Requires-Dist: eth-account>=0.10.0; extra == 'web3'
Requires-Dist: web3>=6.0.0; extra == 'web3'
Description-Content-Type: text/markdown

# Event Trader Python SDK

Official Python SDK for the Event Trader prediction markets platform.

## Features

- **Prediction Markets**: Create and trade on perpetual prediction markets
- **Trading**: Place orders, manage positions, stream orderbooks
- **Incentives**: Bot management, rewards, leaderboards, airdrops
- **Games**: Streaks, duels, tournaments, boosts
- **Wallet**: Multi-wallet support, SIWE auth, portfolio tracking
- **DeFi**: DEX aggregation, IL calculation, MEV protection
- **Exchanges**: Unified CEX interface (Binance, Coinbase, Kraken, etc.)
- **CLOB Exchange**: Hybrid orderbook trading (CLOB + AMM), batch orders
- **Sync Client**: `SyncEventTrader` wrapper for non-async codebases
- **HMAC Signing**: Request integrity via HMAC-SHA256 for low-latency trading

## Installation

```bash
pip install cymetica-eventtrader
```

For Web3 functionality:
```bash
pip install cymetica-eventtrader[web3]
```

## Quick Start

```python
import asyncio
from event_trader import EventTrader

async def main():
    # Initialize with API key
    async with EventTrader(api_key="evt_...") as client:
        # List active markets
        markets = await client.markets.list(status="active")
        for market in markets:
            print(f"{market.question} - {market.status}")

        # Get order book
        orderbook = await client.markets.orderbook(markets[0].id, "BTC")
        print(f"Best bid: {orderbook.best_bid}, Best ask: {orderbook.best_ask}")

        # Place an order
        order = await client.trading.place_order(
            market_id=markets[0].id,
            asset="BTC",
            side="buy",
            price=0.65,
            quantity=100,
        )
        print(f"Order placed: {order.id}")

asyncio.run(main())
```

### Synchronous Client

```python
from event_trader import SyncEventTrader

# Synchronous usage — no asyncio needed
client = SyncEventTrader(api_key="evt_...")

# All methods are synchronous
markets = client.markets.list(status="active")
order = client.trading.place_order(market_id="0x...", asset="BTC", side="buy", price=0.65, quantity=100)

# Factory methods
client = SyncEventTrader.production("evt_...")
client = SyncEventTrader.development("evt_...")

# Context manager
with SyncEventTrader(api_key="evt_...") as client:
    markets = client.markets.list()
```

## Authentication

### API Key
```python
client = EventTrader(api_key="evt_...")
```

### Email/Password
```python
client = await EventTrader.from_credentials(
    email="user@example.com",
    password="password",
)
```

### Wallet (SIWE)
```python
async def sign_message(message: str) -> str:
    # Sign with your wallet
    return wallet.sign_message(message)

client = await EventTrader.from_wallet(
    wallet_address="0x...",
    sign_callback=sign_message,
)
```

### HMAC Signing
```python
# For low-latency trading with request integrity
client = EventTrader(
    api_key="evt_...",
    api_secret="your_secret",  # Enables HMAC-SHA256 signing
)
# All requests automatically signed with X-Signature header
```

## Services

### Markets
```python
# List markets
markets = await client.markets.list(status="active", limit=50)

# Get market details
market = await client.markets.get("0x...")

# Get order book
orderbook = await client.markets.orderbook("0x...", "BTC")

# Get featured market
featured = await client.markets.featured()
```

### Trading
```python
# Place order
order = await client.trading.place_order(
    market_id="0x...",
    asset="BTC",
    side="buy",
    price=0.65,
    quantity=100,
)

# Cancel order
await client.trading.cancel_order(order.id)

# Get open orders
orders = await client.trading.open_orders()

# Get trade history
trades = await client.trading.history(market_id="0x...")
```

### Incentives (Bot Management)
```python
# Register a bot
bot = await client.incentives.register_bot(
    name="MyArbitrageBot",
    wallet_address="0x...",
    strategy_type="arbitrage",
)

# Record trading volume
await client.incentives.record_volume(
    bot_id=bot.id,
    market_id="0x...",
    volume_usd=5000,
)

# Check tier status
tier = await client.incentives.tier_status(bot.id)
print(f"Tier: {tier.current_tier}, Reward Multiplier: {tier.reward_multiplier}x")

# Get earnings
earnings = await client.incentives.earnings(bot.id)

# Get leaderboard
leaderboard = await client.incentives.leaderboard(period="weekly")
```

### Games (Gamification)
```python
# Get gamer profile
profile = await client.games.profile(user_id)
print(f"Level: {profile.level}, XP: {profile.xp}")

# Track win streak
streak = await client.games.record_streak(user_id, "win", market_id)

# Create a duel
duel = await client.games.create_duel(
    market_id="0x...",
    stake_amount=100,
)

# Join tournament
entry = await client.games.join_tournament(tournament_id, user_id)

# Activate boost
boost = await client.games.activate_boost(user_id, "xp_boost")
```

### Wallet
```python
# Get portfolio
portfolio = await client.wallet.portfolio(
    "0x742d35Cc6634C0532925a3b844Bc9e7595f3E6",
    chain="polygon",
)

# Get gas recommendations
gas = await client.wallet.gas_recommendations(chain="polygon")

# Get supported chains
chains = await client.wallet.supported_chains()

# SIWE authentication flow
session = await client.wallet.siwe_authenticate(
    address="0x...",
    sign_callback=sign_message,
)
```

### DeFi
```python
# Get swap quote
quote = await client.defi.swap_quote(
    token_in="0xWETH...",
    token_out="0xUSDC...",
    amount_in="1000000000000000000",  # 1 ETH
    chain="ethereum",
)

# Calculate impermanent loss
il = await client.defi.calculate_il(
    pool_address="0x...",
    token_a="WETH",
    token_b="USDC",
    initial_price="2000",
    current_price="2500",
    initial_value_usd="10000",
)

# Get optimal V3 range
range_result = await client.defi.optimal_range(
    current_price="2500",
    volatility="0.8",
)

# Assess MEV risk
mev = await client.defi.assess_mev_risk(
    token_in="0x...",
    token_out="0x...",
    amount_in="10000000000000000000",
    amount_in_usd="25000",
    slippage_bps=100,
)
```

### Aggregator (Cross-Platform)
```python
# Get markets across platforms
markets = await client.aggregator.markets(
    platforms=["polymarket", "kalshi"],
    category="politics",
)

# Find arbitrage opportunities
arbs = await client.aggregator.arbitrage_opportunities(
    min_spread_bps=20,
    min_profit=1.0,
)

# Route order optimally
plan = await client.aggregator.route_order(
    market_id="0x...",
    outcome_id="Yes",
    side="buy",
    size=100,
    strategy="best_price",
)
```

### Exchanges (CEX Integration)
```python
# Get ticker from Binance
ticker = await client.exchanges.ticker("binance", "BTC/USDT")

# Compare prices across exchanges
comparison = await client.exchanges.compare_tickers(
    "BTC/USDT",
    exchanges=["binance", "coinbase", "kraken"],
)

# Place limit order
order = await client.exchanges.place_limit_order(
    "binance",
    symbol="BTC/USDT",
    side="buy",
    amount=0.001,
    price=50000,
)

# Get account balance
balance = await client.exchanges.balance("binance")
```

### CLOB Exchange
```python
# Get hybrid orderbook (CLOB + AMM)
book = await client.clob.orderbook("vaix", depth=30)

# Place a limit order
order = await client.clob.place_order("vaix", side="buy", quantity="1000", price="0.003")

# Batch orders (up to 50)
results = await client.clob.batch_place_orders("vaix", [
    {"side": "buy", "quantity": "500", "price": "0.003"},
    {"side": "sell", "quantity": "500", "price": "0.004"},
])

# Cancel all orders
await client.clob.cancel_all("vaix")

# Get open orders and trade history
orders = await client.clob.open_orders("vaix")
trades = await client.clob.my_trades("vaix", limit=50)

# Get market stats
stats = await client.clob.stats("vaix")
```

### AI Index Baskets (Trend Cards)
Tokenized, ETF-like on-chain index funds. Each AIB is its own mainnet ERC-20
share token (`AIB-<SYM>`, e.g. `AIB-AA208630`); shares mint against on-chain
basket backing at NAV and are withdrawable on-chain.
```python
# Discover live Trend Cards
cards = await client.aib.list_trend_cards()

# Definition, live NAV, issuance quote, real-time iNAV
info  = await client.aib.get("AIB-AA208630")
nav   = await client.aib.nav("AIB-AA208630")
quote = await client.aib.quote("AIB-AA208630")   # ask=mint@NAV+spread, bid=redeem@NAV-fee
inav  = await client.aib.inav("AIB-AA208630")     # + premium/discount vs market price

# Buy shares (pay USDC, mint at NAV+spread) and check your holdings
order = await client.aib.buy("AIB-AA208630", "100")   # spend 100 USDC
mine  = await client.aib.holdings()                    # non-zero AIB share balances

# Sell to in-platform USDC ...
await client.aib.sell("AIB-AA208630", 50)
# ... or redeem for an ON-CHAIN USDC payout to your own address
await client.aib.redeem("AIB-AA208630", 50, destination_address="0xYourAddress")

# Secondary market: trade shares on the CLOB with the AIB-<SYM> symbol
book = await client.clob.orderbook("AIB-AA208630")
```

### Streaming
```python
# Stream order book updates
async for update in client.streaming.orderbook("0x...", "BTC"):
    print(f"Spread: {update.spread}")

# Private WebSocket (user orders and fills)
async for update in client.streaming.private(token="your_jwt"):
    if update.channel == "userOrders":
        print(f"Order update: {update.data}")
    elif update.channel == "userFills":
        print(f"Fill: {update.data}")
```

### CLOB Streaming (Settlement Notifications)
```python
from event_trader.streaming.clob import CLOBStream

stream = CLOBStream(config, channels=["userFills", "balanceUpdate"], token="jwt_token")

# Settlement status notifications — get alerted to delays
def on_settlement(data):
    status = data.get("settlement_status")
    if status == "settled":
        print(f"Settled on-chain: {data['explorer_url']}")
    elif status == "delayed":
        print(f"Settlement delayed ({data['delay_seconds']}s) — ETA: {data['estimated_completion']}")
    elif status == "failed":
        print(f"Settlement failed — funds will be refunded automatically")

stream.on_settlement(on_settlement)
stream.on_fill(lambda data: print(f"Fill: {data}"))
stream.on_balance(lambda data: print(f"Balance changed"))

async for event in stream:
    pass  # Callbacks fire automatically
```

#### Settlement Status Flow
Orders settle in the background after matching. The WebSocket `settlement_update` event
reports progress:

| Status | Meaning | Fields |
|--------|---------|--------|
| `settled` | On-chain swap confirmed | `tx_hash`, `explorer_url`, `chain` |
| `delayed` | Settlement taking longer than expected | `delay_seconds`, `retry_count`, `estimated_completion` |
| `failed` | Settlement failed after retries | `reason` (internal — use generic message for users) |

Typical settlement time: 10-30 seconds. Maximum: 90 seconds per attempt, up to 3 retries.

## Error Handling

```python
from event_trader import (
    EventTraderError,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
    InsufficientFundsError,
    OrderError,
)

try:
    order = await client.trading.place_order(...)
except InsufficientFundsError:
    print("Not enough balance")
except RateLimitError as e:
    print(f"Rate limited, retry after {e.retry_after}s")
except NotFoundError:
    print("Market not found")
except OrderError as e:
    print(f"Order failed: {e}")
except EventTraderError as e:
    print(f"SDK error: {e}")
```

## Configuration

```python
client = EventTrader(
    api_key="evt_...",
    base_url="https://cymetica.com",
    timeout=30.0,
    max_retries=3,
    debug=True,
)
```

## Examples

See the `examples/` directory for complete examples:

- `basic_trading.py` - Basic trading workflow
- `streaming_orderbook.py` - Real-time orderbook streaming
- `market_maker_bot.py` - Simple market maker
- `bot_incentives.py` - Bot registration and rewards
- `gamification.py` - Games and gamification features
- `defi_integration.py` - DeFi/DEX integration
- `exchange_trading.py` - CEX trading
- `clob_trading.py` - CLOB exchange trading

## License

MIT
