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, ~2,020 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:60-315 | DepthSightAPIClient — HTTP client for backend |
| Socket Wrapper | slack_agent/app.py:387-551 | SlackWebSocketWrapper — mock WebSocket that relays Autopilot events into a Slack thread |
| Chat Handler | slack_agent/app.py:1203-1403 | handle_chat_message() — AI conversation with strategy JSON + trigger phrases |
| Autopilot Bridge | slack_agent/app.py:554-602 | run_autopilot_and_send() — runs run_autopilot_loop() in-process with a Slack-thread WebSocket adapter |
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 | — (status messages in thread) |
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 | Runs a backtest report card for ETHUSDT |
| 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 by exact action_id match |
Button Interactions
Buttons are dispatched by exact action_id match in the Slack interaction handler:
action_id | Handler |
|---|---|
action_analyze_btc | Runs market analysis for BTCUSDT (app.py:904-912) |
action_backtest_eth | Runs a backtest report for ETHUSDT (app.py:915-925) |
action_portfolio | Renders the portfolio card (app.py:928-938) |
button_trigger_generate | Generates the strategy from the confirmed prompt (app.py:1407) |
button_open_editor / button_run_backtest / button_deploy_live | Editor link / backtest modal / live deploy (app.py:1446 / 1452 / 1783) |
Chat Message Flow
handle_chat_message() (slack_agent/app.py:1203-1403) handles all AI conversation messages:
- Sends user input to
POST /ai/chatviaDepthSightAPIClient - Checks the response for strategy JSON — if present, saves the config and posts Open-in-Editor / Run-Backtest / Deploy-Live buttons
- Detects the advisor's strategy-offer phrase (EN/RU) to post a Generate button, and keyword cues (
analyze/price/chart,portfolio/dashboard/pnl,backtest/simulation) to append the matching visual card - Tracks active threads to maintain conversation context across replies
SlackWebSocketWrapper
Sources:The wrapper only formats and forwards Autopilot status events into the Slack thread — status messages get an icon (⏳/⚙️/🔍/📊/⚠️) and are posted with chat_postMessage (lines 408–431); iteration results, completion events, and the final report card follow in the same send_json() method (lines 434–551). Connection lifecycle (Socket Mode connect/reconnect) is handled by Bolt's AsyncSocketModeHandler in main() (app.py:2009-2015).
Autopilot Bridge
The run_autopilot_and_send() function (slack_agent/app.py:554-602) bridges the autopilot loop into Slack:
- Imports and runs
run_autopilot_loop()in-process (lines 557, 589–595), adapting the WebSocket interface to the Slack thread viaSlackWebSocketWrapper - Posts an opening banner and relays the loop's status messages into the thread as they stream in
- On
success/partial_success, the wrapper saves the strategy, posts Open-in-Editor / Deploy-Live buttons, and renders the final report card viapoll_and_render_backtest()(lines 460–547) - Reports fatal errors as a thread message (lines 596–602) — the bridge itself performs no polling
MCP Query Integration
Memory lookups are triggered by the /depthsight memory slash subcommand:
- The
/depthsight memory <symbol|tags>subcommand parses its argument (app.py:818-832) run_mcp_query_and_send()→query_mcp_strategy_memories()opens a direct TCP connection to the MCP Memory Server viaMCPClient(app.py:327-371)- The formatted memory summary is posted as a Slack message in the channel (
app.py:870-893)
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
Backtests run through run_backtest_and_send() (slack_agent/app.py:1802), which first tries the real backtest report from the API (get_latest_backtest, lines 1812–1828) and only falls back to the mock walk when no report exists:
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:
The client's methods are delete_chat_history (line 94), send_chat_message (113), get_strategy_config (145), save_strategy (159), trigger_backtest (193), poll_backtest_report (243), get_latest_backtest (257), get_backtest_details (273), get_portfolio_status (286), get_user_profile (300), and close (313).
| 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 |
WebSocket (port 8765) | — | run_autopilot_loop trigger (api/websocket_server.py:358) |
/api/v1/optimizations | POST | Start optimization process (api/routes/tasks.py:202) |
/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?mode=live | GET | Fetch portfolio stats (route: api/routes/portfolio.py:133; note: get_portfolio_status currently requests the stale path /portfolio/portfolio — app.py:289) |
Authentication
| Method | When Used |
|---|---|
| JWT Bearer | Both DEPTHSIGHT_JWT_TOKEN and SLACK_ALLOW_JWT_OVERRIDE=true are set (global identity override, disabled by default) |
| 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 — run_backtest_and_send fallback: WR 53-66%, DD 8-15%, PF 1.6-2.3, Sharpe 1.2-2.0 (app.py:1841-1845); poll_and_render_backtest fallback: WR 53-65%, DD 7-14%, PF 1.7-2.2, Sharpe 1.3-1.9 (app.py:1751-1755) |
| 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 (requires SLACK_ALLOW_JWT_OVERRIDE=true) |
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 for the Autopilot and Co-Pilot LLM agents — 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.