AI and ML Integration

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.

⏱️ 8 min read📊 Level: Intermediate

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

Rendering diagram...

Key Components

ComponentFilePurpose
Bot Entry Pointslack_agent/app.pySlack Bolt SDK, slash commands, event handlers, button/modals
Card Rendererslack_agent/card_renderer.pyHTML → PNG rendering via Playwright
Templatesslack_agent/templates/*.htmlFour dark-theme card templates
API Clientslack_agent/app.py:52-288DepthSightAPIClient — HTTP client for backend
Socket Wrapperslack_agent/app.py:289-412SlackWebSocketWrapper — manages Socket Mode lifecycle + reconnection
Chat Handlerslack_agent/app.py:413-530handle_chat_message() — AI conversation with strategy JSON + trigger phrases
Autopilot Bridgeslack_agent/app.py:1812-1960run_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

SubcommandDescriptionCard
help (or empty)Show interactive help menu—
analyze <symbol>Market analysis (default BTCUSDT)Market Analysis
backtest <symbol>Run backtest simulation (default BTCUSDT)Backtest Report
portfolioPortfolio dashboardPortfolio
memoryView agent memory summary—
optimize <symbol>Trigger autopilot loop for strategy optimizationBacktest Report
clear / resetClear AI chat session history—
(anything else)Passed to AI chat—

Interactive Buttons

ButtonAction
Analyze BTCInstant market analysis for BTCUSDT
Backtest ETHOpens backtest configuration modal
View PortfolioRenders portfolio dashboard
Generate StrategyTriggers AI strategy generation
Run BacktestOpens modal with date, timeframe, capital inputs
Deploy LiveDeploys strategy as live trading bot

Events

EventBehavior
@DepthSight mentionStarts AI conversation in thread
Direct MessageAI conversation; replies in thread stay active
Modal submissionCaptures backtest config params
Button clickRoutes 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:

PrefixHandler
analyze_*handle_analyze_button() — runs market analysis for the symbol
backtest_*Opens backtest config modal
run_autopilot_*Opens autopilot config modal
view_portfoliohandle_portfolio() — renders portfolio card
generate_strategyOpens strategy generation modal

Chat Message Flow

handle_chat_message() (slack_agent/app.py:413-530) handles all AI conversation messages:

  1. Sends user input to POST /ai/chat via DepthSightAPIClient
  2. Checks response for strategy JSON — if present, renders a backtest card
  3. Listens for trigger phrases (run backtest, optimize, etc.) for card rendering cues
  4. 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:

  1. Calls POST /ai/autopilot with symbol + params
  2. Polls for completion (120 retries × 5s, matching the backtest poll pattern)
  3. On completion, renders the result as a backtest card
  4. 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:

  1. handle_chat_message() detects query keywords
  2. Calls GET /ai/memories via DepthSightAPIClient
  3. Injects memory context into the AI prompt before sending to chat endpoint
  4. Returns augmented response with memory-backed insights

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:

Rendering diagram...

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.pro footer branding
  • Placeholder substitution via {{ KEY }} syntax

Template Structure

CardFileDimensionsSections
Backtesttemplates/backtest_card.html800×480Strategy name + subtitle, equity chart (SVG), 2×3 KPI grid
Market Analysistemplates/market_analysis_card.html800×420Symbol + price header, sparkline chart, 4 indicator panels, AI insight
Portfoliotemplates/portfolio_card.html800×420Hero PnL, 4 stat cards, 7-day bar chart, active bot pills
Trade Alerttemplates/trade_alert_card.html800×420Signal 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:

Sources:
API EndpointMethodPurpose
/api/v1/ai/chatPOSTAI conversation (advisor / generator modes)
/api/v1/ai/chat/history/{id}DELETEClear session context
/api/v1/ai/memoriesGETFetch agent memories
/api/v1/ai/autopilotPOSTStart autopilot loop
/api/v1/ai/optimizePOSTStart optimization process
/api/v1/strategies/configPOSTSave generated strategy
/api/v1/strategies/configGETList saved strategies
/api/v1/strategies/config/{id}GETFetch saved strategy
/api/v1/strategies/config/{id}DELETEDelete saved strategy
/api/v1/backtestsPOSTQueue backtest task
/api/v1/backtests/{task_id}GETPoll backtest results
/api/v1/portfolio/portfolio?mode=liveGETFetch portfolio stats

Authentication

MethodWhen Used
JWT BearerDEPTHSIGHT_JWT_TOKEN env var set (testing against production)
Trusted Slack BypassDefault — sends X-Slack-Secret, X-User-Email, Authorization: Bearer slack_bot_trusted_bypass

Binance Public API

EndpointFunctionPurpose
api.binance.com/api/v3/ticker/24hrfetch_binance_ticker()24h price + volume data
api.binance.com/api/v3/klinesfetch_binance_history()24 hourly candles for sparkline

Mock Data Fallback

When the backend API is unreachable, the bot falls back to realistic mock data:

CardMock Strategy
BacktestRandom 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)
Portfolio3 default bots ("BTC Momentum v2", "ETH Breakout Pro", "SOL DCA Grid"), 7-day PnL with daily variance
Market AnalysisRSI 45-68, trend/volatility inferred from price change, generated AI insight text

Deployment

Environment Variables

VariableDefaultDescription
SLACK_BOT_TOKEN—Slack Bot User OAuth Token (xoxb-...)
SLACK_APP_TOKEN—Slack App-Level Token (xapp-...)
DEPTHSIGHT_API_URLhttp://localhost:8000/api/v1Backend API base URL
API_KEY_SECRET—Shared secret for trusted Slack auth
DEPTHSIGHT_JWT_TOKEN—Optional JWT for production testing
MCP_MEMORY_HOST127.0.0.1MCP memory server host
MCP_MEMORY_PORT8100MCP 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

FeatureWhat We Show
Rich Visual CardsHTML/CSS → Playwright → PNG — not plain Slack Block Kit
Multi-Card GalleryBacktest, Market Analysis, Portfolio, Trade Alert — four distinct card types
Real-Time AlertsTrade signals with animated pulsing dots, confidence bars, unrealized PnL
AI IntegrationFull AI assistant chat via @mentions and DMs
Self-HealingMock data fallback when backend is unreachable
Socket ModeNo public endpoint needed, works behind NAT
Thread ContextActive thread tracking keeps multi-turn conversations coherent