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, ~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

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:60-315DepthSightAPIClient — HTTP client for backend
Socket Wrapperslack_agent/app.py:387-551SlackWebSocketWrapper — mock WebSocket that relays Autopilot events into a Slack thread
Chat Handlerslack_agent/app.py:1203-1403handle_chat_message() — AI conversation with strategy JSON + trigger phrases
Autopilot Bridgeslack_agent/app.py:554-602run_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

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 optimization— (status messages in thread)
clear / resetClear AI chat session history—
(anything else)Passed to AI chat—

Interactive Buttons

ButtonAction
Analyze BTCInstant market analysis for BTCUSDT
Backtest ETHRuns a backtest report card for ETHUSDT
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 by exact action_id match

Button Interactions

Buttons are dispatched by exact action_id match in the Slack interaction handler:

action_idHandler
action_analyze_btcRuns market analysis for BTCUSDT (app.py:904-912)
action_backtest_ethRuns a backtest report for ETHUSDT (app.py:915-925)
action_portfolioRenders the portfolio card (app.py:928-938)
button_trigger_generateGenerates the strategy from the confirmed prompt (app.py:1407)
button_open_editor / button_run_backtest / button_deploy_liveEditor 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:

  1. Sends user input to POST /ai/chat via DepthSightAPIClient
  2. Checks the response for strategy JSON — if present, saves the config and posts Open-in-Editor / Run-Backtest / Deploy-Live buttons
  3. 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
  4. 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:

  1. Imports and runs run_autopilot_loop() in-process (lines 557, 589–595), adapting the WebSocket interface to the Slack thread via SlackWebSocketWrapper
  2. Posts an opening banner and relays the loop's status messages into the thread as they stream in
  3. On success / partial_success, the wrapper saves the strategy, posts Open-in-Editor / Deploy-Live buttons, and renders the final report card via poll_and_render_backtest() (lines 460–547)
  4. 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:

  1. The /depthsight memory <symbol|tags> subcommand parses its argument (app.py:818-832)
  2. run_mcp_query_and_send() → query_mcp_strategy_memories() opens a direct TCP connection to the MCP Memory Server via MCPClient (app.py:327-371)
  3. The formatted memory summary is posted as a Slack message in the channel (app.py:870-893)

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

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:

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:

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 EndpointMethodPurpose
/api/v1/ai/chatPOSTAI conversation (advisor / generator modes)
/api/v1/ai/chat/history/{id}DELETEClear session context
/api/v1/ai/memoriesGETFetch agent memories
WebSocket (port 8765)—run_autopilot_loop trigger (api/websocket_server.py:358)
/api/v1/optimizationsPOSTStart optimization process (api/routes/tasks.py:202)
/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?mode=liveGETFetch portfolio stats (route: api/routes/portfolio.py:133; note: get_portfolio_status currently requests the stale path /portfolio/portfolio — app.py:289)

Authentication

MethodWhen Used
JWT BearerBoth DEPTHSIGHT_JWT_TOKEN and SLACK_ALLOW_JWT_OVERRIDE=true are set (global identity override, disabled by default)
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 — 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)
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 (requires SLACK_ALLOW_JWT_OVERRIDE=true)
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