Slack Trading Agent
Interactive Slack bot with rich HTML/CSS card rendering — backtest reports, market analysis, portfolio monitoring, live trade alerts, and AI-powered strategy generation via Playwright screenshots.
The Slack Agent (slack_agent/app.py, ~1,960 lines) is an interactive trading bot that brings DepthSight's full capabilities into Slack. It renders rich visual cards as PNG images via Playwright headless Chromium, providing instant access to backtest results, market analysis, portfolio monitoring, and live trade alerts — all without leaving Slack.
Architecture
Key Components
| Component | File | Purpose |
|---|---|---|
| Bot Entry Point | slack_agent/app.py | Slack Bolt SDK, slash commands, event handlers, button/modals |
| Card Renderer | slack_agent/card_renderer.py | HTML → PNG rendering via Playwright |
| Templates | slack_agent/templates/*.html | Four dark-theme card templates |
| API Client | slack_agent/app.py:52-288 | DepthSightAPIClient — HTTP client for backend |
| Socket Wrapper | slack_agent/app.py:289-412 | SlackWebSocketWrapper — manages Socket Mode lifecycle + reconnection |
| Chat Handler | slack_agent/app.py:413-530 | handle_chat_message() — AI conversation with strategy JSON + trigger phrases |
| Autopilot Bridge | slack_agent/app.py:1812-1960 | run_autopilot_and_send() — full autopilot loop with card rendering |
Card Rendering Pipeline
HTML Template ({{ placeholders }})
→ String substitution with real/mock data
→ Playwright headless Chromium (800×420 or 800×480)
→ Google Fonts (Inter, Montserrat) loaded
→ 300ms settle for SVG animations
→ page.screenshot(type="png")
→ files_upload_v2 → Slack channel
Slack Commands & Interactions
Slash Command: /depthsight
| Subcommand | Description | Card |
|---|---|---|
help (or empty) | Show interactive help menu | — |
analyze <symbol> | Market analysis (default BTCUSDT) | Market Analysis |
backtest <symbol> | Run backtest simulation (default BTCUSDT) | Backtest Report |
portfolio | Portfolio dashboard | Portfolio |
memory | View agent memory summary | — |
optimize <symbol> | Trigger autopilot loop for strategy optimization | Backtest Report |
clear / reset | Clear AI chat session history | — |
| (anything else) | Passed to AI chat | — |
Interactive Buttons
| Button | Action |
|---|---|
| Analyze BTC | Instant market analysis for BTCUSDT |
| Backtest ETH | Opens backtest configuration modal |
| View Portfolio | Renders portfolio dashboard |
| Generate Strategy | Triggers AI strategy generation |
| Run Backtest | Opens modal with date, timeframe, capital inputs |
| Deploy Live | Deploys strategy as live trading bot |
Events
| Event | Behavior |
|---|---|
@DepthSight mention | Starts AI conversation in thread |
| Direct Message | AI conversation; replies in thread stay active |
| Modal submission | Captures backtest config params |
| Button click | Routes to handler based on action_id prefix (analyze_, backtest_, run_autopilot_, etc.) |
Button Interactions
Buttons are routed by action_id prefixes in the Slack interaction handler:
| Prefix | Handler |
|---|---|
analyze_* | handle_analyze_button() — runs market analysis for the symbol |
backtest_* | Opens backtest config modal |
run_autopilot_* | Opens autopilot config modal |
view_portfolio | handle_portfolio() — renders portfolio card |
generate_strategy | Opens strategy generation modal |
Chat Message Flow
handle_chat_message() (slack_agent/app.py:413-530) handles all AI conversation messages:
- Sends user input to
POST /ai/chatviaDepthSightAPIClient - Checks response for strategy JSON — if present, renders a backtest card
- Listens for trigger phrases (
run backtest,optimize, etc.) for card rendering cues - Tracks active threads to maintain conversation context across replies
SlackWebSocketWrapper
Sources:The wrapper handles:
- Auto-reconnection — reconnects on WebSocket disconnect with 5s backoff
- Graceful shutdown — cancels all pending tasks on
SIGINT/SIGTERM - Health monitoring — logs connection status at startup and on reconnect
Autopilot Bridge
The run_autopilot_and_send() function (slack_agent/app.py:1812-1960) bridges the autopilot loop into Slack:
- Calls
POST /ai/autopilotwith symbol + params - Polls for completion (120 retries × 5s, matching the backtest poll pattern)
- On completion, renders the result as a backtest card
- Uploads card image to Slack with the strategy name as filename
MCP Query Integration
When a chat message contains market/symbol queries, the Slack agent can trigger MCP memory lookups:
handle_chat_message()detects query keywords- Calls
GET /ai/memoriesviaDepthSightAPIClient - Injects memory context into the AI prompt before sending to chat endpoint
- Returns augmented response with memory-backed insights
Card Gallery
1. Backtest Result Card
A dark-themed card with the strategy name and DepthSight logo at top. Left panel shows the equity curve (SVG polyline with blue gradient fill). Right panel displays six KPIs in a 2×3 grid.
Dimensions: 800×480 px. Pipeline:
Backtest Logic Flow
Sources:2. Market Analysis Card
Dimensions: 800×420 px. Header with symbol + current price + 24h change. Left: sparkline chart. Right: four indicator panels (RSI, Volume, Trend, Volatility). Bottom: AI Insight box with real-time model commentary.
3. Portfolio Dashboard Card
Dimensions: 800×420 px. Hero PnL number at top, 4 stat cards (active bots, today's trades, win rate, today's PnL), 7-day bar chart, active bot pills at bottom.
4. Trade Alert Card
Dimensions: 800×420 px. Signal badge with animated pulsing green dot, symbol + strategy name. Left column: trade details (entry, size, SL, TP). Right panel: confidence score with gradient bar + unrealized PnL.
Card Templates
All templates share:
- Dark theme gradient (
#1c1917 → #111827) - Inter font for body, Montserrat for the DepthSight logo
- Animated reticle logo SVG with rotating crosshair
depthsight.profooter branding- Placeholder substitution via
{{ KEY }}syntax
Template Structure
| Card | File | Dimensions | Sections |
|---|---|---|---|
| Backtest | templates/backtest_card.html | 800×480 | Strategy name + subtitle, equity chart (SVG), 2×3 KPI grid |
| Market Analysis | templates/market_analysis_card.html | 800×420 | Symbol + price header, sparkline chart, 4 indicator panels, AI insight |
| Portfolio | templates/portfolio_card.html | 800×420 | Hero PnL, 4 stat cards, 7-day bar chart, active bot pills |
| Trade Alert | templates/trade_alert_card.html | 800×420 | Signal badge + pulsing dot, trade details, confidence bar, unrealized PnL |
Backend Integration
DepthSight API Endpoints
The Slack agent communicates with the main DepthSight API via DepthSightAPIClient:
| API Endpoint | Method | Purpose |
|---|---|---|
/api/v1/ai/chat | POST | AI conversation (advisor / generator modes) |
/api/v1/ai/chat/history/{id} | DELETE | Clear session context |
/api/v1/ai/memories | GET | Fetch agent memories |
/api/v1/ai/autopilot | POST | Start autopilot loop |
/api/v1/ai/optimize | POST | Start optimization process |
/api/v1/strategies/config | POST | Save generated strategy |
/api/v1/strategies/config | GET | List saved strategies |
/api/v1/strategies/config/{id} | GET | Fetch saved strategy |
/api/v1/strategies/config/{id} | DELETE | Delete saved strategy |
/api/v1/backtests | POST | Queue backtest task |
/api/v1/backtests/{task_id} | GET | Poll backtest results |
/api/v1/portfolio/portfolio?mode=live | GET | Fetch portfolio stats |
Authentication
| Method | When Used |
|---|---|
| JWT Bearer | DEPTHSIGHT_JWT_TOKEN env var set (testing against production) |
| Trusted Slack Bypass | Default — sends X-Slack-Secret, X-User-Email, Authorization: Bearer slack_bot_trusted_bypass |
Binance Public API
| Endpoint | Function | Purpose |
|---|---|---|
api.binance.com/api/v3/ticker/24hr | fetch_binance_ticker() | 24h price + volume data |
api.binance.com/api/v3/klines | fetch_binance_history() | 24 hourly candles for sparkline |
Mock Data Fallback
When the backend API is unreachable, the bot falls back to realistic mock data:
| Card | Mock Strategy |
|---|---|
| Backtest | Random walk equity curve (random.uniform(-0.015, 0.025)), KPIs in realistic ranges (WR 53-65%, DD 7-15%, PF 1.6-2.3, Sharpe 1.2-2.0) |
| Portfolio | 3 default bots ("BTC Momentum v2", "ETH Breakout Pro", "SOL DCA Grid"), 7-day PnL with daily variance |
| Market Analysis | RSI 45-68, trend/volatility inferred from price change, generated AI insight text |
Deployment
Environment Variables
| Variable | Default | Description |
|---|---|---|
SLACK_BOT_TOKEN | — | Slack Bot User OAuth Token (xoxb-...) |
SLACK_APP_TOKEN | — | Slack App-Level Token (xapp-...) |
DEPTHSIGHT_API_URL | http://localhost:8000/api/v1 | Backend API base URL |
API_KEY_SECRET | — | Shared secret for trusted Slack auth |
DEPTHSIGHT_JWT_TOKEN | — | Optional JWT for production testing |
MCP_MEMORY_HOST | 127.0.0.1 | MCP memory server host |
MCP_MEMORY_PORT | 8100 | MCP memory server port |
PLAYWRIGHT_BROWSERS_PATH | — | Chromium path for card rendering |
Running
# Install dependencies
pip install -r requirements.txt
playwright install chromium
# Start the bot
python -m slack_agent.app
The bot connects via Socket Mode (no public HTTP endpoint needed). It uses asyncio throughout, with asyncio.create_task() for background card rendering and polling.
Why This Wins
| Feature | What We Show |
|---|---|
| Rich Visual Cards | HTML/CSS → Playwright → PNG — not plain Slack Block Kit |
| Multi-Card Gallery | Backtest, Market Analysis, Portfolio, Trade Alert — four distinct card types |
| Real-Time Alerts | Trade signals with animated pulsing dots, confidence bars, unrealized PnL |
| AI Integration | Full AI assistant chat via @mentions and DMs |
| Self-Healing | Mock data fallback when backend is unreachable |
| Socket Mode | No public endpoint needed, works behind NAT |
| Thread Context | Active thread tracking keeps multi-turn conversations coherent |
Intelligent Agent Memory System
MCP-based memory server for the genetic optimizer agent — three-tier hierarchy, sub-agent critic review, automatic rule synthesis, confidence-based forgetting, and screenshot-enhanced strategy generation.
React Web Dashboard
Comprehensive technical guide to the DepthSight web dashboard — architecture, component hierarchy, state management, API layer, routing, i18n, knowledge base, and key implementation patterns.