Skip to content

StreetLevelTech1/StrideBot

Repository files navigation

StrideBot 🤖📊

AI-powered financial intelligence for Telegram — real-time crypto, forex, stocks, and macro analysis with long-polling on Render.

Python 3.11.15 pytest Code style: ruff


Overview

StrideBot is a Telegram-native bot that delivers financial intelligence across multiple asset classes:

  • Crypto — real-time price feeds (Binance → CoinGecko → Kraken), whale activity, and market signals
  • Macro — global economic trends and regime analysis
  • Forex — currency pair tracking and analysis
  • Stocks — equity market intelligence and research

The bot leverages Groq AI for low-latency analysis, EventBus for reactive scheduling, and a multi-tier system for premium features, all orchestrated by a robust Python backend running on Render.


Quick Start

Prerequisites

  • Python 3.11.15 (via uv or direct installation)
  • UV package manager (curl -LsSf https://astral.sh/uv/install.sh | sh)
  • .env file with required secrets (see Environment Variables)

Run the Bot

# Install dependencies (if not done)
uv sync

# Start the bot
python bot/bot.py

The bot will:

  1. Load environment variables and initialize Sentry
  2. Clear any lingering webhooks
  3. Set up database and Groq client
  4. Register commands and event handlers
  5. Start the health dashboard (HTTP server)
  6. Begin polling for Telegram updates

Run Tests

# Quick test run
uv run pytest bot/tests/ -v

# With coverage (matches CI pipeline)
uv run pytest bot/tests/ --cov=bot --cov-report=xml --cov-report=term-missing -v

Lint & Format

# Check code style
uv run ruff check .
uv run ruff format --check .

# Apply formatting
uv run ruff format .

Environment Variables

Required in .env:

TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
ADMIN_USER_ID=your_admin_user_id
LOG_LEVEL=INFO
DAILY_AI_CAP=100
# Additional optional variables (Groq, Sentry, etc.) as needed

Architecture

Entrypoint: bot/bot.py

The single entry point orchestrates:

  • Environment loading and Sentry initialization
  • SIGTERM trap for graceful shutdown on Render deploys
  • Webhook cleanup to avoid polling/webhook conflicts
  • Database initialization
  • Telegram ApplicationBuilder setup
  • Command and handler registration
  • Scheduler job wiring
  • Health server startup
  • Polling retry loop with exponential backoff

Core Modules

bot/ai/ — AI & LLM Layer

  • client.py — Groq API wrapper
  • context.py — Conversation context management
  • pipeline.py — Request/response pipeline
  • search.py — Web search integration (Tavily)
  • tiers.py — Token budgeting per user tier
  • background.py — Async insight generation

bot/database/ — Persistence Layer

Domain modules for:

  • users — user accounts and tier management
  • history — conversation history
  • premium — subscription tracking
  • alerts — price alerts and conditions
  • watchlist — asset tracking
  • predictions — forecast storage
  • memory — user preferences and context
  • analytics — usage statistics
  • security — rate limiting and auth
  • And more domain-specific modules

bot/data/ — Real-Time Market Data

  • prices.py — Binance → CoinGecko → Kraken chain with 60s TTL cache
  • news.py — Financial news aggregation
  • forex.py — Currency pair feeds
  • stocks.py — Equity data
  • market.py — Market-wide aggregation
  • circuit_breaker.py — Fault tolerance

bot/handlers/ — Telegram Command Handlers (15 files)

  • core.py — Core command utilities, HTML sanitization, cooldowns
  • market.py — Market data commands
  • alerts.py — Alert management
  • premium.py — Premium feature handlers
  • admin.py — Admin-only commands
  • guest.py — Guest user handlers
  • secretary.py — Daily briefing commands
  • Plus utilities, mini-apps, rate limiting, streaming support

bot/scheduler/ — Recurring Intelligence

  • core.py — Scheduling utilities (deduplication, safe sends, cooldowns)
  • posts.py — All post generators (market updates, briefs, etc.)
  • intelligence.py — Breaking news, market signals, trending assets, regime changes
  • alerts.py — Alert checking and triggering
  • images.py — Image generation with Pillow

bot/intelligence/ — Advanced Analytics

  • congress.py — Congressional trading analysis
  • whale.py — Large transaction tracking
  • polymarket.py — Prediction market data
  • trends.py — Trend identification and scoring
  • market_regime.py — Market regime classification
  • news_sources.py — News source credibility
  • research.py — Research paper aggregation

bot/events/ — Reactive Event System

  • bus.py — Central EventBus for pub/sub
  • types.py — Event types (AlertTriggered, BreakingNewsDetected, etc.)

bot/prompts/ — LLM Prompts

System prompts, analysis templates, scheduler prompts, organized by function.

bot/memory/ — Context Retrieval

Salience-trimmed memory for multi-turn conversations.

bot/health/ — Monitoring

  • server.py — HTTP health check endpoint and dashboard
  • Re-exported at top level for easy access

Testing

Test Structure

  • 27 test files in bot/tests/
  • Fixtures in bot/tests/conftest.py:
    • mock_db — patches database module
    • mock_ai — patches ai module
    • mock_crypto — patches data module
    • mock_tavily — patches search
  • Uses stdlib monkeypatch, not unittest.mock
  • No pytest.ini needed; config in pyproject.toml [tool.coverage.*] sections

Example Test Run

uv run pytest bot/tests/test_handlers.py -v -k "test_market_command"

CI/CD Pipeline

.github/workflows/ci.yml runs on PRs to main/master/dev:

  1. Lintruff check + ruff format --check
  2. Syntaxast.parse on all changed .py files
  3. Test — Full pytest suite with coverage
  4. Test Baseline — Non-blocking baseline on base branch
  5. Coverage Gate — Regression check, requires ≥80% diff coverage

Single required status check: ci-required (aggregator job)


Deployment

Render Setup

StrideBot deploys on Render with long-polling:

  • Start Command: python bot/bot.py
  • Environment: Python 3.11.15
  • Health Endpoint: HTTP dashboard at configured port
  • Graceful Shutdown: SIGTERM/SIGINT trap calls os._exit(0) for immediate stop

Deploy Quirks

  • clear_webhook() called at module load time to avoid polling/webhook conflicts
  • SIGTERM handler ensures immediate shutdown on Render restarts
  • Webhook setup is disabled; polling is the transport layer

Important: Module Structure

bot/__init__.py Must NOT Exist

This is intentional and critical. The absence of bot/__init__.py allows:

  • Pytest's prepend-mode to add bot/ to sys.path only once
  • Tests to use bare imports (import database, import handlers, etc.)
  • bot/bot.py to use bare imports when executed directly

Creating bot/__init__.py will break the test suite. See docs/specs/ci-pipeline-spec.md for full details.


Key Features

Real-Time Market Data — Multi-source price feeds with intelligent fallback
AI Analysis — Groq-powered insights with token budgeting
Event-Driven — Reactive scheduler via EventBus
Premium Tiers — Multi-tier feature access control
Whale Tracking — Large transaction alerts
News Intelligence — Breaking news detection and delivery
Rate Limiting — Per-user and global cooldowns
Memory Management — Salience-trimmed context windows
Health Monitoring — Dedicated health dashboard
Graceful Shutdown — Clean Render deploys


Project Stats

  • Language: Python 97.2%, HTML 2.7%
  • Python Version: 3.11.15
  • Test Coverage: Enforced ≥80% on new lines
  • Test Files: 27
  • Linter: Ruff
  • Package Manager: UV

Contributing

  1. Create a feature branch
  2. Write tests for new code (required for CI)
  3. Run uv run pytest bot/tests/ -v locally
  4. Ensure ruff check . and ruff format . pass
  5. Submit a PR to main/dev
  6. CI pipeline must pass (lint, syntax, test, coverage)

License

See LICENSE file (if present) for details.


Support

For issues, questions, or feature requests, please open a GitHub issue in this repository.


Happy trading! 📈🚀

About

AI-powered financial intelligence for Telegram — real-time crypto, forex, stocks, and macro analysis

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages