PQAP User Guide
Table of Contents
- Getting Started
- Understanding the Dashboard
- Viewing Positions and P&L
- Understanding Strategies
- Telegram Alerts
- Monitoring and Maintenance
Getting Started
Prerequisites
- Python 3.11+
- Polymarket API credentials (optional for monitoring mode)
- Telegram bot token and chat ID (for alerts)
Installation
-
Clone and setup environment
bash cd /path/to/polymarket python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt -
Configure environment variables
Create a .env file in the project root:
```bash
# Polymarket credentials (optional - leave empty for monitoring mode)
POLYMARKET_API_KEY=your_api_key
POLYMARKET_API_SECRET=your_api_secret
POLYMARKET_PRIVATE_KEY=your_private_key
# Telegram alerts (required) TELEGRAM_BOT_TOKEN=your_bot_token TELEGRAM_CHAT_ID=your_chat_id ```
-
Choose a configuration
-
Development:
configs/dev.yaml- Small capital, conservative settings - Production:
configs/prod.yaml- Real capital, optimized settings
Running PQAP
Local Development
python -m src.main configs/dev.yaml
Background Process (Linux/Mac)
nohup python -m src.main configs/dev.yaml > pqap.log 2>&1 &
Using systemd (Linux)
sudo systemctl start pqap
sudo systemctl status pqap
Accessing the Dashboard
Once PQAP is running, the web dashboard is available at:
- Local: http://localhost:8080
- EC2: http://54.85.161.228:8080 (or https://pqap.tailwindtech.ai)
Key Pages: - Dashboard: http://localhost:8080/dashboard - Strategies: http://localhost:8080/strategies - Trades: http://localhost:8080/trades - Markets: http://localhost:8080/markets - Signals: http://localhost:8080/signals - Observability: http://localhost:8080/observability - Docs: http://localhost:8080/docs
Understanding the Dashboard
Homepage (Dashboard)
The main dashboard provides a real-time overview of the trading system.
Strategy Controls
- Strategy List: All registered strategies with enable/disable toggles
- Status Indicators:
- Green = Active and trading
- Yellow = Enabled but no recent signals
- Red = Disabled
- Performance Metrics: Win rate, total trades, P&L per strategy
Quick Actions
- Enable/Disable Strategies: Click toggle switches
- View Details: Click strategy name for configuration details
- Force Refresh: Reload button updates all metrics
Markets Page
View all tracked markets and arbitrage opportunities.
Market Information
- Question: The prediction market question
- Prices: Current YES and NO prices
- Sum Price: YES + NO (values < 1.0 indicate arbitrage opportunities)
- Volume: 24-hour trading volume
- Status: Active, closed, or resolved
Features
- Auto-refresh: Updates every 10 seconds
- Sort by Sum Price: Arbitrage opportunities appear at top
- Filter by Volume: Focus on liquid markets
Signals Page
Historical view of all trading signals generated by strategies.
Signal Details
- Strategy: Which strategy generated the signal
- Market: What market was targeted
- Type: BUY, SELL, HOLD, or CLOSE
- Confidence: Strategy confidence (0-1.0)
- Expected Profit: Estimated profit from the trade
- Status: Executed, rejected, or expired
Risk Rejections
Signals marked "rejected" were blocked by the risk engine. Common reasons: - Capital limit exceeded - Daily loss limit hit - Position size too large - Market already at max exposure
Paper Trading Page
Real-time view of simulated trading performance (no real money).
Portfolio Summary
- Total Capital: Current portfolio value
- Available Capital: Cash available for new trades
- Unrealized P&L: Profit/loss on open positions
- Realized P&L: Profit/loss from closed trades
- Return %: Total return percentage
Open Positions
- Market: What you're betting on
- Side: YES or NO
- Shares: Number of shares held
- Entry Price: Average purchase price
- Current Price: Current market price
- P&L: Current profit or loss
- Age: How long you've held the position
Trade History
Recent trades with timestamps, prices, and P&L.
P&L Chart
Visual representation of portfolio value over time.
Orderbook Page
Real-time orderbook data for active markets.
Orderbook Metrics
- Best Bid/Ask: Top prices for buying and selling
- Spread: Difference between bid and ask
- Imbalance: Ratio of buy vs sell pressure
- Depth: Total volume at best prices
Use Cases
- Identify tight spreads for market making
- Detect orderbook imbalances
- Monitor liquidity before trading
P&L Page
Performance attribution report by strategy.
Summary Metrics
- Total P&L: Combined profit/loss across all strategies
- Realized P&L: Locked-in profits from closed positions
- Unrealized P&L: Current profit/loss on open positions
By Strategy
- Allocated Capital: How much capital assigned to each strategy
- Total Trades: Number of trades executed
- Win Rate: Percentage of profitable trades
- Average P&L: Average profit per trade
- Sharpe Ratio: Risk-adjusted return metric
Viewing Positions and P&L
Paper Trading Portfolio
PQAP runs in paper trading mode by default, simulating trades without real money.
Real-time Monitoring
- Navigate to Dashboard page (http://localhost:8080/dashboard)
- Check Portfolio Summary at the top
- Review Open Positions to see current holdings
- Scroll to Trade History for recent activity
Understanding P&L Metrics
Unrealized P&L (Mark-to-Market) - Profit/loss on positions you still hold - Changes as market prices move - Not locked in until you close the position
Realized P&L - Actual profit/loss from completed trades - Locked in and won't change - The "real" measure of performance
Total P&L - Unrealized + Realized - Your total performance if you closed everything now
Position Aging
Positions show how long you've held them: - Green = Recently opened (< 1 hour) - Yellow = Medium-term (1-24 hours) - Red = Long-term (> 24 hours)
Long-term positions may indicate: - Strong conviction trades - Strategies without exit logic - Markets that haven't moved
Live Trading (Real Money)
If you've configured a private key, PQAP executes real trades.
Important Notes
- Paper Trading ALWAYS Runs: Even with live trading enabled, paper trades execute for tracking
- Check Logs: Real trade execution appears in logs with
[LIVE]prefix - Monitor Capital: Real capital depletes with each trade
- Risk Limits Apply: Daily loss limits and position size caps protect you
Live Trading Indicators
- Startup message shows "Mode: TRADING" (vs "MONITORING")
- Logs show both
[PAPER]and[LIVE]execution - Telegram alerts include live trade notifications
Understanding Strategies
PQAP uses pluggable strategies that generate trading signals.
Active Strategies
1. Dual Arbitrage (dual_arb_v1)
What it does: Exploits temporary mispricing where YES + NO prices sum to less than $1.00
How it works: - Monitors all binary markets for YES + NO < 1.0 (after fees) - Atomically buys both sides when opportunity detected - Locks in risk-free profit at market resolution
Configuration:
dual_arb_v1:
min_profit_threshold: "0.01" # Minimum 1% profit
fee_rate: "0.02" # 2% exchange fees
Edge: Highly competitive, opportunities decay in seconds
2. Mean Reversion (mean_reversion_v1)
What it does: Bets that prices will return to their historical average
How it works: - Tracks rolling mean and standard deviation for each market - BUYs when price drops significantly below mean (negative z-score) - SELLs when price rises significantly above mean (positive z-score) - Exits when price returns to mean or hits stop-loss
Configuration:
mean_reversion_v1:
entry_zscore: "1.5" # Enter when |z-score| > 1.5
exit_zscore: "0.5" # Exit when |z-score| < 0.5
max_hold_periods: 30 # Force exit after 30 periods
Best for: Volatile markets with clear price swings
3. Market Maker (market_maker_v1)
What it does: Provides liquidity by posting bid/ask quotes, earning the spread
How it works: - Posts buy orders slightly below market price - Posts sell orders slightly above market price - Earns spread when both sides fill - Manages inventory to stay balanced
Configuration:
market_maker_v1:
min_spread_pct: "0.04" # Minimum 4% spread
max_inventory_pct: "0.08" # Max 8% inventory imbalance
Risk: Inventory risk if market moves against you
Strategy Lifecycle
1. Signal Generation
Strategy analyzes market data and returns a Signal object: - BUY or SELL direction - Confidence level (0-1.0) - Suggested position size - Price limits
2. Risk Check
Risk engine validates the signal: - Capital limits - Daily loss limits - Position size caps - Kill switch status
3. Execution
If risk check passes: - Paper trade executes immediately (simulation) - Live trade submits to exchange (if enabled)
4. Tracking
Trade results feed back to strategy: - Updates internal state - Adjusts position tracking - Calculates P&L
Enabling/Disabling Strategies
Via Dashboard
- Navigate to main dashboard
- Find strategy in list
- Click toggle switch
- Confirm the action
Via Configuration File
Edit configs/dev.yaml:
enabled_strategies:
- dual_arb_v1 # Enabled
- mean_reversion_v1 # Enabled
# - momentum_v1 # Disabled (commented out)
Restart PQAP for changes to take effect.
Auto-Disable
Strategies automatically disable if: - Daily loss limit exceeded - Excessive failed trades (> 50% failure rate) - Configuration validation fails - Kill switch triggered
You'll receive a Telegram alert when this happens.
Telegram Alerts
Alert Types
1. System Status
When: Startup, shutdown, hourly updates Example:
🚀 PQAP Started
Mode: MONITORING
Environment: DEV
Capital: $100
Strategies: 3 enabled
Hourly updates: ON
2. Hourly Updates
When: Every hour while running Contains: - Portfolio P&L and return % - Number of open positions - Total trades executed - Data collection stats (markets tracked, snapshots) - Error count since last update
Example:
⏰ PQAP Hourly Update
Time: 2024-12-24 15:00 UTC
📈 Portfolio:
P&L: +$2.45 (+2.45%)
Capital: $98.55
Positions: 3
Trades: 12
📊 Data Collection:
Markets: 50
Snapshots: 1,234
Anomalies: 5
⚠️ Errors: 0
3. Trade Execution
When: Trade completes Contains: Strategy, P&L, cumulative P&L
4. Risk Alerts
When: Risk limit breached or kill switch triggered Contains: Reason for alert, affected strategy
5. Error Alerts
When: Critical error occurs Contains: Error message, context (strategy, market)
Setting Up Telegram Alerts
1. Create a Telegram Bot
- Open Telegram and search for @BotFather
- Send
/newbotcommand - Follow prompts to name your bot
- Save the bot token (looks like
1234567890:ABCdefGHIjklMNOpqrsTUVwxyz)
2. Get Your Chat ID
- Start a chat with your new bot
- Send any message
- Visit
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates - Find your chat ID in the response (looks like
123456789)
3. Configure PQAP
Add to .env file:
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
TELEGRAM_CHAT_ID=123456789
4. Test the Connection
Run PQAP - you should receive a startup message immediately.
Alert Configuration
Adjusting Alert Frequency
Edit src/alerts/telegram.py:
- rate_limit_seconds: Minimum time between messages (default: 1.0)
Hourly update interval is set in src/main.py (_hourly_status_loop function).
Disabling Alerts
Leave TELEGRAM_BOT_TOKEN empty in .env:
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
PQAP will run without sending alerts (logs only).
Monitoring and Maintenance
Health Checks
HTTP Health Endpoint
curl http://localhost:8080/health
Response:
{
"status": "ok",
"uptime_seconds": 3600,
"active_strategies": 3,
"markets_tracked": 50
}
API Status
curl http://localhost:8080/api/status
Detailed status including: - Environment (dev/prod) - Capital allocation - Strategy states - Recent errors
Log Files
Local Development
Logs print to console in real-time.
Background Process
tail -f pqap.log
Systemd (Linux)
journalctl -u pqap -f
Common Issues
No Signals Generated
Possible causes: 1. Markets don't meet strategy criteria (volume too low, etc.) 2. Strategies disabled 3. Risk limits preventing signal generation
Solution: - Check strategy parameters in config - Lower thresholds for testing (min_volume, min_edge, etc.) - Review risk limits
Paper Trading Not Updating
Possible causes: 1. No signals being generated 2. Market data not refreshing 3. Orderbook data missing
Solution: - Verify market data is flowing (check Markets page) - Restart PQAP - Check API rate limits
Capital Exhausted
Possible causes: 1. Too many open positions 2. Position sizes too large 3. Strategies without exit logic
Solution:
- Reduce order_size_pct in strategy configs
- Enable only strategies with exit logic
- Set max_hold_periods to force exits
- Reset paper trading: see Resetting Paper Trading
Telegram Alerts Not Sending
Possible causes: 1. Invalid bot token or chat ID 2. Bot not started (no message sent to bot) 3. Network connectivity issues
Solution:
- Verify credentials in .env
- Send a message to your bot in Telegram
- Check PQAP logs for Telegram errors
Resetting Paper Trading
Via Admin API (Coming Soon)
The admin interface will include a reset button.
Manual Reset
Delete the paper trading state file:
rm data/paper_trading_state.json
Restart PQAP - paper trading will reinitialize with configured capital.
Database Maintenance
Backup Databases
cp data/market_history.db data/market_history.db.backup
cp data/pqap_dev.db data/pqap_dev.db.backup
Clean Old Data
# Remove old market snapshots (> 90 days)
sqlite3 data/market_history.db "DELETE FROM market_snapshots WHERE timestamp < datetime('now', '-90 days')"
Reset Everything
rm data/*.db
rm data/paper_trading_state.json
PQAP will create fresh databases on next startup.
Performance Optimization
Reduce Market Polling Frequency
Edit src/main.py, _poll_markets_loop():
await asyncio.sleep(10) # Change to 30 for less frequent updates
Limit Markets Tracked
Edit src/main.py, _discover_markets():
self._discovered_markets = markets_sorted[:50] # Change to 20 for fewer markets
Disable Data Collection
Comment out data collection in src/main.py, run():
# data_task = asyncio.create_task(self._collect_data_loop())
Advanced Usage
Custom Strategy Parameters
Edit configs/dev.yaml to tune strategy behavior:
strategies:
mean_reversion_v1:
parameters:
entry_zscore: "2.0" # More conservative entry
exit_zscore: "0.3" # Earlier exits
min_volume_24h: "5000" # Higher liquidity requirement
order_size_pct: "0.01" # Smaller positions
Restart PQAP to apply changes.
Multiple Environments
Run dev and prod configurations separately:
# Terminal 1: Development
python -m src.main configs/dev.yaml
# Terminal 2: Production
python -m src.main configs/prod.yaml
Use different databases and ports to avoid conflicts.
Exporting Data
Export Signals to CSV
sqlite3 data/pqap_dev.db <<EOF
.headers on
.mode csv
.output signals.csv
SELECT * FROM signals WHERE timestamp > datetime('now', '-7 days');
.quit
EOF
Export Trades to CSV
sqlite3 data/pqap_dev.db <<EOF
.headers on
.mode csv
.output trades.csv
SELECT * FROM trades WHERE timestamp > datetime('now', '-7 days');
.quit
EOF
Support and Troubleshooting
Getting Help
- Check logs for error messages
- Review this user guide
- Consult
/docs/STRATEGY_GUIDE.mdfor strategy development - Consult
/docs/DEPLOYMENT_GUIDE.mdfor deployment issues
Reporting Issues
When reporting an issue, include:
- PQAP version (check git log or release tag)
- Configuration file used
- Relevant log snippets
- Steps to reproduce
Best Practices
- Start with Paper Trading: Never risk real money until paper trading proves profitable
- Monitor Daily: Check Telegram alerts and dashboard at least once per day
- Backup Regularly: Copy databases before making major changes
- Test Configuration Changes: Always test in dev environment first
- Track Performance: Review P&L reports weekly to identify winning strategies
- Respect Risk Limits: Don't increase limits just to trade more - increase them when strategy proves edge