# SILICO Python SDK

[![PyPI version](https://badge.fury.io/py/silico.svg)](https://badge.fury.io/py/silico)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Dead simple Python SDK for building trading bots on SILICO.

## Why SILICO?

- 🎯 **Paper trading** - Test strategies with fake money, real prices
- 📊 **Learn from failures** - We collect failure data to improve trading AI
- 🚀 **5 minutes to deploy** - From zero to trading in one command
- 💰 **Completely free** - No hidden costs, no real money at risk

## Installation

```bash
pip install silico
```

## Quick Start

```python
from silico import SilicoBot
import time

# Initialize (API key from https://silico.fun/dashboard)
bot = SilicoBot(api_key="sk_xxx")

# Simple buy-low-sell-high
while True:
    price = bot.get_price("SOL/USDC")

    if price < 100:
        bot.buy("SOL/USDC", amount_usdc=50)
    elif price > 150:
        bot.sell("SOL/USDC", amount_usdc=50)

    time.sleep(10)
```

**That's it.** You're trading.

## Examples

### RSI Strategy

```python
from silico import SilicoBot
from collections import deque

bot = SilicoBot(api_key="sk_xxx")
prices = deque(maxlen=50)

while True:
    price = bot.get_price("SOL/USDC")
    prices.append(price)

    rsi = calculate_rsi(prices)  # Your RSI function

    if rsi < 30:  # Oversold
        bot.buy("SOL/USDC", amount_usdc=100, strategy_tag="RSI")
    elif rsi > 70:  # Overbought
        bot.sell("SOL/USDC", amount_usdc=100, strategy_tag="RSI")

    time.sleep(10)
```

Full examples in [`examples/`](./examples/):
- [`quickstart.py`](./examples/quickstart.py) - Your first bot
- [`rsi_strategy.py`](./examples/rsi_strategy.py) - RSI mean reversion
- [`advanced.py`](./examples/advanced.py) - All features

## Features

### Automatic Environment Detection

```python
# Local development - auto-detects localhost:8000
bot = SilicoBot(api_key="sk_test")

# Production - auto-uses api.silico.fun
bot = SilicoBot(api_key="sk_prod")

# Or explicit
bot = SilicoBot(api_key="sk_xxx", base_url="http://custom:8000")
```

### Error Handling

```python
from silico import SilicoBot, RateLimitError, InsufficientBalanceError

bot = SilicoBot(api_key="sk_xxx")

try:
    bot.buy("SOL/USDC", amount_usdc=1000)
except RateLimitError as e:
    print(f"Rate limited - retry after {e.retry_after}s")
except InsufficientBalanceError as e:
    print(f"Need ${e.required_balance}, have ${e.current_balance}")
```

### Market Data

```python
# Fetch current price
price = bot.get_price("SOL/USDC")

# Prices are cached automatically
cached = bot.market.get_price("SOL/USDC")
```

### Trade Responses

```python
result = bot.buy("SOL/USDC", amount_usdc=100)

if result.success:
    print(f"Trade ID: {result.trade_id}")
    print(f"Price: ${result.executed_price}")
else:
    print(f"Failed: {result.error_message}")
```

## API Reference

### `SilicoBot`

Main client for interacting with SILICO.

**Constructor:**
```python
SilicoBot(
    api_key: str,
    base_url: Optional[str] = None,  # Auto-detected
    timeout: int = 30
)
```

**Methods:**

#### `buy(symbol, amount_usdc, strategy_tag=None, max_slippage_bps=50)`
Execute a BUY trade.

**Parameters:**
- `symbol` (str): Trading pair, e.g. "SOL/USDC"
- `amount_usdc` (float): Amount in USDC to buy
- `strategy_tag` (str, optional): Strategy identifier
- `max_slippage_bps` (int): Max slippage in basis points (default: 50 = 0.5%)

**Returns:** `TradeResponse`

#### `sell(symbol, amount_usdc, strategy_tag=None, max_slippage_bps=50)`
Execute a SELL trade. Same parameters as `buy()`.

#### `get_price(symbol)`
Get current market price.

**Parameters:**
- `symbol` (str): Trading pair, e.g. "SOL/USDC"

**Returns:** `float` - Current price

### Exceptions

All exceptions inherit from `SilicoError`:

- `AuthenticationError` - Invalid API key
- `RateLimitError` - Too many requests (has `.retry_after`)
- `InsufficientBalanceError` - Not enough balance (has `.current_balance`, `.required_balance`)
- `InvalidSymbolError` - Invalid trading pair
- `NetworkError` - Connection failed

## Development

### Setup

```bash
git clone https://github.com/silico/python-sdk
cd python-sdk
pip install -e ".[dev]"
```

### Testing

```bash
# Unit tests
pytest

# With coverage
pytest --cov=silico

# Integration tests (requires API key)
export SILICO_API_KEY="sk_xxx"
pytest tests/test_integration.py
```

### Code Quality

```bash
# Format
black silico/ tests/

# Lint
flake8 silico/ tests/
```

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md)

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)

## License

MIT - See [LICENSE](./LICENSE)

## Support

- 📖 **Docs**: [docs.silico.fun](https://docs.silico.fun)
- 💬 **Discord**: [discord.gg/silico](https://discord.gg/silico)
- 🐛 **Issues**: [GitHub Issues](https://github.com/silico/python-sdk/issues)
- 🌐 **Website**: [silico.fun](https://silico.fun)

---

Made with ❤️ by the SILICO team
