<p align="center">
  <img src="frontend/public/LuckySt_cropped4.png" alt="LuckySt" height="180" />
</p>

<h3 align="center">The Agentic Market Making Syndicate</h3>

<p align="center">
  <em>Autonomous agents making markets on prediction exchanges.</em><br/>
  <em>Built on Base. Powered by Claude. Governed by the Syndicate.</em>
</p>

<p align="center">
  <img src="https://img.shields.io/badge/chain-Base-0052FF?style=flat-square&logo=coinbase" />
  <img src="https://img.shields.io/badge/markets-Kalshi_%7C_Polymarket_%7C_Turbine-gold?style=flat-square" />
  <img src="https://img.shields.io/badge/agents-Luckbots-black?style=flat-square" />
</p>

---

## What is LuckySt?

LuckySt is an **agentic market making system** for prediction markets. Autonomous AI agents (Luckbots) operate a trading terminal to provide liquidity, tighten spreads, and capture edge on exchanges like **Kalshi**, **Polymarket**, **Turbine**, and **Limitless** (coming soon).

The system replaces the human trader at the keyboard. Luckbots read orderbooks, place and manage orders, and execute market making strategies — all through a real-time trading terminal controlled via Redis commands.

---

## Architecture

```
┌─────────────────────────────────────────────────────┐
│                    Frontend (React)                  │
│              Vite + Shadcn/ui + WebSocket            │
├─────────────────────────────────────────────────────┤
│                  Backend (FastAPI)                    │
│          REST API + WebSocket + Alembic ORM          │
├──────────┬──────────┬──────────┬────────────────────┤
│  Redis   │ Celery   │ Postgres │  Kalshi/Poly/Turbine │
│  Commands│ Workers  │ State    │   Exchange APIs      │
└──────────┴──────────┴──────────┴────────────────────┘
```

| Layer | Tech |
|-------|------|
| **Frontend** | React, Vite, Tailwind CSS, Shadcn/ui |
| **Backend** | FastAPI, Uvicorn, SQLAlchemy, Alembic |
| **Task Queue** | Celery + Redis |
| **Database** | PostgreSQL |
| **Cache & Commands** | Redis |
| **Exchanges** | Kalshi, Polymarket (Polygon), Turbine (Polygon), Limitless (Base — coming soon) |
| **Chain** | Base (Ethereum L2) |
| **Price Data** | Pyth Oracles, CCXT |

---

## Trading Strategies

### JOIN & JUMP
**JOIN** is the core mode — the agent places resting limit orders on both YES and NO sides of a binary market at the current best bid, profiting the spread when both fill. **JUMP** is a tactical action: the agent pennies ahead by 1 cent on a specific market (hotkey 1 or 2) when it determines queue position is unfavorable and the spread supports it. Agents run in JOIN continuously and decide autonomously when to JUMP based on user-defined logic configured at deployment.

### Midpoint Rolling Average
A fair value signal layer built on a rolling window of orderbook midpoints. Samples the YES/NO midpoint every tick, maintains a configurable rolling average, and uses the result to detect mispricing and inform trading decisions — when to hold queue position, when to jump, and when to pause. Prevents chasing prices in volatile or event-driven markets.

### Cumulative Distribution Function
Probability modeling for price-based prediction markets using external data feeds. Fetches spot prices from Pyth oracles and historical data from CCXT, forecasts next-second volatility via an EWMA of recent realized volatility, and computes a log-normal CDF to derive a fair price. The agent then quotes a configurable spread (1-5c+) around that fair price. Volatility window, spread width, and all parameters are set by the user's startup prompt to the Luckbot.

---

## Products

### Automated Market Making
Configure and deploy automated market making instances. Set policies on spread, price feed, position sizing, and strategy — then let it run. Supports single market (YES/NO) and two-market same-side modes.

### Trader & Market Scanner
Deploy automated scanners that track traders and monitor markets in real-time. Receive alerts via Telegram when new opportunities appear or tracked wallets make moves.

### Trade Scheduler
Schedule trading instances to deploy automatically at a set time. Configure your strategy, pick a start and stop time, and the system handles the rest.

### Telegram Mini App
Monitor and control your live trading instances from your phone via a Telegram mini app — pause, jump, stop, and view orderbook data on the go.

### Exchange Compatibility

| Exchange | Status |
|----------|--------|
| **Kalshi** | Active |
| **Polymarket** | Active |
| **Turbine** | Active |
| **Limitless** | In testing, coming soon |

---

## The Syndicate

LuckySt agents are governed by the **Syndicate** — a decentralized collective of autonomous Luckbots. Each agent:

- Trades independently with its own wallet and risk parameters
- Proposes and votes on strategy upgrades via YAML proposals
- Signs an onchain pledge on Base to join
- Maintains USDC on Base for trading capital

**Governance:** Any Luckbot can submit a proposal. Merging requires 3 approvals from other agents. No agent can approve their own proposal.

Read the full lore in [`LORE.md`](LORE.md).

---

## Getting Started (Base Sepolia)

LuckySt runs on **Base**. For development and testing, use **Base Sepolia**.

### 1. Network Configuration

| | Base Mainnet | Base Sepolia |
|---|---|---|
| **Chain ID** | `8453` | `84532` |
| **RPC URL** | `https://mainnet.base.org` | `https://sepolia.base.org` |
| **USDC Token** | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` |
| **Block Explorer** | [basescan.org](https://basescan.org) | [sepolia.basescan.org](https://sepolia.basescan.org) |

To run on testnet, set the environment variable before starting:

```bash
export LUCKYST_NETWORK=testnet
```

This single variable switches everything:
- **Pledge system** — Base Sepolia chain ID, RPC, and USDC token
- **Kalshi API** — [Demo environment](https://demo-api.kalshi.co) (sandbox with mock funds)
- **Docker services** — Automatically passed to all containers

Omit the variable or set `LUCKYST_NETWORK=mainnet` for production.

### 2. Get Testnet Tokens

**Testnet ETH** (for gas):
- [Coinbase Faucet](https://portal.cdp.coinbase.com/products/faucet) — Official Base Sepolia faucet
- [Chainlink Faucet](https://faucets.chain.link/base-sepolia) — GitHub/email verification

**Testnet USDC** (for trading & pledge):
- [Circle Faucet](https://faucet.circle.com/) — Select Base Sepolia

### 3. Add Base Sepolia to Your Wallet

In MetaMask or your wallet of choice, add a custom network:

```
Network Name:   Base Sepolia
RPC URL:        https://sepolia.base.org
Chain ID:       84532
Currency:       ETH
Explorer:       https://sepolia.basescan.org
```

### 4. Sign the Pledge

Once your wallet holds testnet USDC (minimum 1 USDC on testnet, 10 USDC on mainnet):

```bash
export LUCKYST_NETWORK=testnet
python -m agentic.syndicate.pledge
```

---

## Deploy a Luckbot

### Prerequisites

- [Docker](https://docs.docker.com/get-docker/) & Docker Compose
- [Node.js](https://nodejs.org/) 18+
- [Claude Code](https://claude.com/claude-code) CLI
- A [Kalshi](https://kalshi.com) account with API key + RSA key (use demo account for testnet), and/or a MetaMask wallet for Polymarket/Turbine

### 1. Clone & Configure

```bash
git clone https://github.com/npastrami/LuckySt2.git
cd LuckySt2/backend
cp .env.example .env
```

Edit `.env` with your credentials. For testnet, set `LUCKYST_NETWORK=testnet`.

### 2. Start Infrastructure

```bash
cd backend
docker compose --profile dev up -d
```

This boots PostgreSQL, Redis, RabbitMQ, Celery worker, FastAPI, pgAdmin, Redis Commander, and Flower.

### 3. Initialize Database

```bash
docker exec -it trading_app_dev alembic upgrade head
docker exec -it trading_app_dev python create_superuser.py
```

### 4. Start Frontend

```bash
cd frontend
npm install
npm run dev
```

The terminal UI is now live at `http://localhost:5173`.

### 5. Deploy a Trading Instance

1. Open the terminal UI and log in
2. Select your platform (Kalshi, Polymarket, or Turbine)
3. Enter credentials — Kalshi API key + RSA key, or connect MetaMask for Polymarket/Turbine
4. Configure market(s), spread, position settings, and strategy
5. Hit **Deploy**

The instance will appear in the Running section with a live orderbook and CLI.

### 6. Activate Your Luckbot

```bash
cd LuckySt2
claude
```

Claude reads `CLAUDE.md`, loads the skill files, and becomes a Luckbot. It can control running instances via the API — jumping markets, toggling fair value, pausing, and firing — all autonomously based on the strategies in `skills/`.

### Services

| Service | URL | Profile |
|---|---|---|
| **FastAPI** | `http://localhost:8000` | dev/prod |
| **Frontend** | `http://localhost:5173` | — |
| **pgAdmin** | `http://localhost:5050` | dev |
| **Redis Commander** | `http://localhost:8081` | dev |
| **RabbitMQ Management** | `http://localhost:15672` | dev/prod |
| **Flower** (Celery monitor) | `http://localhost:5555` | dev |

---

## Project Structure

```
luckyst2/
├── backend/
│   ├── app/
│   │   ├── core/               # Auth, security, WebSocket, logging
│   │   ├── modules/
│   │   │   ├── terminal/
│   │   │   │   ├── auto/       # Trading engine
│   │   │   │   │   ├── auto1.py    # Single-market instance
│   │   │   │   │   ├── auto2.py    # Multi-market instance
│   │   │   │   │   ├── mm_core.py  # Market making logic
│   │   │   │   │   ├── kalshi_api.py
│   │   │   │   │   └── service.py
│   │   │   │   ├── scanner/    # Trader & market scanners
│   │   │   │   ├── scheduler/  # Trade scheduling
│   │   │   │   └── webapp/     # Telegram mini app
│   │   │   └── user/           # Auth, accounts, Stripe, Telegram
│   │   ├── services/           # Redis, Kalshi service layer
│   │   └── tasks/              # Celery trading & notification tasks
│   ├── alembic/                # Database migrations
│   └── docker-compose.yml
├── frontend/
│   ├── src/
│   │   ├── pages/              # Terminal, Home, Login, Tech, etc.
│   │   └── components/         # Navbar, UI primitives
│   └── vite.config.js
├── agentic/
│   ├── syndicate/              # Pledge, registry, reports, scheduler
│   └── proposals/              # Proposal templates & submissions
├── skills/                     # Agent skill documentation
│   ├── strategies/             # JOIN, JUMP, CDF, midpoint, market info
│   ├── exchanges/              # Kalshi, Polymarket, Turbine, Limitless
│   ├── data/                   # Pyth oracles, CCXT
│   └── infra/                  # Terminal, hotkeys, syndicate ops
├── CLAUDE.md                   # Agent operating instructions
└── LORE.md                     # Syndicate lore & pledge
```

---

## License

MIT License. See [LICENSE](LICENSE) for details.

---

<p align="center">
  <strong>Syndicate eternal. Spreads temporary. Edge ours.</strong>
</p>
