# Kuru Market Maker SDK (Python)

A Python SDK for building market maker bots on the Kuru protocol.

## Features

- **Unified Order Types** - Single `Order` class supporting limit, market, and cancel operations
- **Type Safety** - Full validation of Solidity uint bounds (uint32, uint40, uint96, uint256)
- **Order Lifecycle Tracking** - Track orders from creation to fill or cancellation
- **Batch Operations** - Support for batch order updates
- **Web3 Integration** - Direct interaction with Kuru orderbook smart contracts
- **Real-time Orderbook Feed** - WebSocket client for live market data with auto-reconnection

## Installation

This project uses [uv](https://github.com/astral-sh/uv) for dependency management.

```bash
# Install dependencies
uv sync

# Run tests
uv run pytest tests/ -v

# Run examples
PYTHONPATH=. uv run python examples/order_usage.py
```

## Quick Start

### Real-time Orderbook Feed

```python
from src.feed.orderbook_ws import OrderbookWebsocket

async def handle_snapshot(snapshot):
    print(f"Received snapshot for {snapshot.market_address}")
    print(f"Best bid: {snapshot.bids[0]}")
    print(f"Best ask: {snapshot.asks[0]}")

async def handle_update(update):
    print(f"Update: {update.event_type.value}")
    print(f"Order ID: {update.order_id}")

ws = OrderbookWebsocket(
    ws_url="wss://ws.kuru.io/",
    market_address="0x122C0D8683Cab344163fB73E28E741754257e3Fa",
    on_snapshot=handle_snapshot,
    on_update=handle_update,
)

await ws.connect()
```

### Creating Orders

```python
from src.manager.order import create_limit_order, create_market_order, OrderSide

# Create a limit buy order
limit_order = create_limit_order(
    cloid="my-order-001",
    side=OrderSide.BUY,
    price=50000,
    size=1000000,
    post_only=True
)

# Create a market sell order
market_order = create_market_order(
    cloid="my-order-002",
    side=OrderSide.SELL,
    size=500000,
    min_amount_out=24000000,
    is_margin=False,
    is_fill_or_kill=False
)
```

### Order Lifecycle

```python
from src.manager.order import OrderStatus

# Track order status
order.update_status(OrderStatus.ORDER_SENT)
order.update_status(OrderStatus.ORDER_PLACED)
order.set_kuru_order_id(12345)
order.update_status(OrderStatus.ORDER_FULLY_FILLED)

# Create unique ID from transaction hash
tx_hash = "0x1234567890abcdef..."
unique_id = order.create_unique_id(tx_hash)
```

## Documentation

- **[Order Types Documentation](docs/ORDER_TYPES.md)** - Complete guide to order types and usage
- **[Orderbook WebSocket Documentation](docs/ORDERBOOK_WEBSOCKET.md)** - Real-time market data feed
- **[Examples](examples/order_usage.py)** - Usage examples for all order types
- **[Orderbook WebSocket Examples](examples/orderbook_ws_usage.py)** - WebSocket feed examples

## Order Types

The SDK provides a unified `Order` class that supports:

### Limit Orders
Place orders at specific prices in the orderbook:
```python
create_limit_order(cloid, side, price, size, post_only)
```

### Market Orders
Execute immediately against the best available price:
```python
create_market_order(cloid, side, size, min_amount_out, is_margin, is_fill_or_kill)
```

### Cancel Orders
Cancel multiple orders in batch:
```python
create_cancel_order(cloid, order_ids_to_cancel)
```

### Batch Updates
Pass a list of orders to batch update the orderbook:
```python
batch_orders = [
    create_limit_order("batch-1", OrderSide.BUY, 49500, 100000, True),
    create_limit_order("batch-2", OrderSide.SELL, 51500, 120000, True),
]
# Execute via manager/executor
```

## Order Status Tracking

Orders go through the following lifecycle:
- `ORDER_CREATED` - Created locally
- `ORDER_SENT` - Transaction sent to blockchain
- `ORDER_PLACED` - Confirmed on orderbook
- `ORDER_PARTIALLY_FILLED` - Partially filled
- `ORDER_FULLY_FILLED` - Completely filled
- `ORDER_CANCELLED` - Cancelled
- `ORDER_TIMEOUT` - Timed out

## Project Structure

```
kuru-mm-py/
├── src/
│   ├── manager/
│   │   ├── order.py         # Order types and validation
│   │   └── order_manager.py # Order management
│   ├── executor/
│   │   └── orders_executor.py # Transaction execution
│   ├── feed/
│   │   ├── rpc_ws.py        # Blockchain WebSocket feeds
│   │   └── orderbook_ws.py  # Orderbook WebSocket client
│   ├── abis/                # Contract ABIs
│   ├── client.py            # Main client
│   ├── configs.py           # Configuration
│   └── utils.py             # Utilities
├── tests/
│   ├── test_order.py        # Order type tests
│   ├── test_configs.py      # Config tests
│   └── test_orderbook_ws.py # Orderbook WebSocket tests
├── examples/
│   ├── order_usage.py       # Order usage examples
│   └── orderbook_ws_usage.py # Orderbook WebSocket examples
└── docs/
    ├── ORDER_TYPES.md       # Order types documentation
    └── ORDERBOOK_WEBSOCKET.md # Orderbook WebSocket documentation
```

## Testing

Run the test suite:

```bash
# Run all tests
uv run pytest tests/ -v

# Run specific test file
uv run pytest tests/test_order.py -v

# Run with coverage
uv run pytest tests/ --cov=src
```

## Requirements

- Python >= 3.14
- Dependencies managed via uv (see `pyproject.toml`)

## License

[Add license information]

## Contributing

[Add contribution guidelines]

## Support

[Add support information]
