Enterprise-Grade AI-Powered Indonesian Stock Market Analytics Platform
Real-time market intelligence, advanced price alerts with anti-spam batch notifications, bandarmologi analysis, and institutional trading insights delivered via Telegram.
IHSG Analytics Bot is a production-ready, enterprise-grade Telegram bot that delivers comprehensive Indonesian stock market analytics powered by artificial intelligence. Built with TypeScript 6.x and Node.js 24.x, the platform integrates real-time market data from GoAPI, leverages AI Aggregator (primary) and Google Gemini (fallback) for intelligent natural language processing, and provides persistent cloud storage through Supabase PostgreSQL.
- π Advanced Alert Engine - Anti-spam batch notification system with HTML formatting and exponential backoff retry mechanism
- π€ Dual AI Architecture - Primary AI Aggregator with automatic Google Gemini fallback for 99.9% uptime
- π Institutional Analytics - Bandarmologi tracking, foreign flow analysis, and liquidity sentiment indicators
- β‘ Production-Hardened - Exponential backoff with Β±20% jitter, graceful error handling, and configurable worker intervals
- π¨ Premium UX - Beautiful HTML notifications with monospace data alignment and strategic emoji indicators
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β IHSG Analytics Bot β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Telegram ββββββΆβ Telegraf ββββββΆβ Hermes β β
β β User βββββββ Bot Handler βββββββ AI Agent β β
β ββββββββββββββββ ββββββββββββββββ ββββββββ¬ββββββββ β
β β β
β Tool Calling β
β β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Tool Registry (19 Tools) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β β’ Market Data (10) β’ Watchlist (3) β’ Portfolio (3) β β
β β β’ Price Alerts (3) β’ Technical Analysis & Bandarmologi β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β GoAPI β β Supabase β β Alert β β
β β IDX Data β β PostgreSQL β β Worker β β
β β + Retry Logicβ β (Cloud) β β (Background)β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β AI Providers (Dual Architecture) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β Primary: AI Aggregator (gpt-4o) + Fallback: Gemini 2.0 β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Runtime | Node.js | 24.x | Server-side JavaScript execution |
| Language | TypeScript | 6.0 | Type-safe development with latest features |
| Bot Framework | Telegraf | 4.x | Telegram Bot API wrapper with middleware |
| AI Orchestration | Vercel AI SDK | 6.x | LLM tool calling & streaming responses |
| Database | Supabase | 2.x | Cloud PostgreSQL with Row Level Security |
| HTTP Server | Express | 5.x | Webhook mode routing & health checks |
| HTTP Client | Axios | 1.x | External API requests with retry logic |
| Validation | Zod | 4.x | Runtime schema validation & type inference |
| Chart Rendering | QuickChart.io | API | Serverless chart generation (no dependencies) |
- GoAPI - Real-time Indonesian stock market data provider (IDX)
- AI Aggregator - Primary LLM provider (OpenAI-compatible endpoint)
- Google Gemini - Fallback LLM provider (automatic failover)
- Supabase - Managed PostgreSQL database with real-time subscriptions
- QuickChart.io - Chart rendering service (30-day historical data)
Production-Grade Alert System with Zero-Spam Guarantee
Multiple alerts triggered for the same user are automatically consolidated into a single beautiful HTML message:
Before Optimization:
User has 3 alerts triggered
β Sends 3 separate messages (notification spam)
After Optimization:
User has 3 alerts triggered
β
Sends 1 consolidated message (batch notification)
Benefits:
- π 60-80% reduction in Telegram messages
- π¨ Premium HTML formatting with monospace alignment
- π Summary statistics (total count, average price)
- π Better user experience (no spam)
Example Batch Notification:
π BATCH ALERT TRIGGERED
Anda memiliki 3 alert yang terpicu!
βββββββββββββββββββββββββ
1. π’ BBCA
π° Rp 5.600 π’ +0.90%
π― Target di atas Rp 5.500
2. π’ BBRI π
π° Rp 5.250 π’ +5.00%
π +5% dari Rp 5.000
3. π΄ TLKM π‘οΈ
π° Rp 3.990 π΄ -4.80%
π‘οΈ Drop 5% dari high Rp 4.200
βββββββββββββββββββββββββ
π RINGKASAN
Total Alert : 3
Rata-rata : Rp 4.947
Status : Semua dinonaktifkan
β
Semua alert telah dinonaktifkan
Resilient API calls to GoAPI with intelligent retry logic:
- 3 retry attempts with exponential backoff (1s β 2s β 4s)
- Β±20% jitter to prevent thundering herd problem
- Comprehensive logging with attempt tracking
- Graceful degradation (worker continues despite failures)
Retry Flow:
Attempt 1: Immediate execution
β (fails)
Attempt 2: Wait ~1s with jitter (800ms - 1200ms)
β (fails)
Attempt 3: Wait ~2s with jitter (1600ms - 2400ms)
β (fails)
Attempt 4: Wait ~4s with jitter (3200ms - 4800ms)
β (still fails)
Skip symbol, continue with next
Handled Scenarios:
- β Network timeouts
- β API rate limits (HTTP 429)
- β Transient failures
- β Invalid responses
- β Missing data
Customize alert checking frequency via environment variable:
# Alert check interval in milliseconds
# Default: 120000ms (2 minutes)
# Recommended range: 60000-300000ms (1-5 minutes)
ALERT_CHECK_INTERVAL_MS=120000Tradeoffs:
| Interval | Responsiveness | API Usage | Server Load |
|---|---|---|---|
| 1 min (60000ms) | β‘ High | π High | π₯ High |
| 2 min (120000ms) | βοΈ Balanced | π Moderate | π Low |
| 5 min (300000ms) | π’ Slower | π Low | π Minimal |
1. STATIC Alert - Fixed price targets
π― PRICE ALERT
βββββββββββββββββββββββββ
π BBCA
π° Rp 5.600 π’ +0.90%
π’ Kondisi: Harga naik di atas
π― Target: Rp 5.500
π DATA PASAR
Open : Rp 5.550
High : Rp 5.650
Low : Rp 5.500
Perubahan: +50 (0.90%)
Volume : 124.12M
2. PERCENTAGE Alert - Relative movement triggers
π PERCENTAGE ALERT
βββββββββββββββββββββββββ
π BBRI
π° Rp 5.250 π’ +5.00%
π’ Kondisi: Naik 5%
π Harga Base: Rp 5.000
π― Target: Rp 5.400
π Perubahan: 5.00%
3. TRAILING STOP Alert - Dynamic protection
π‘οΈ TRAILING STOP
βββββββββββββββββββββββββ
π TLKM
π° Rp 3.990 π΄ -4.80%
π΄ Kondisi: Turun 5% dari high
ποΈ Day High: Rp 4.200
π― Threshold: Rp 3.990
π Drop: 5.00%
Cloud-Synchronized Personal Stock Tracking
- β Add/remove stocks with natural language
- β View real-time prices for all tracked stocks
- β Persistent storage in Supabase
- β
Per-user isolation with
chat_idindexing
Example Commands:
"Tambahkan BBCA ke watchlist"
"Tampilkan watchlist saya"
"Hapus TLKM dari watchlist"
- β Record average purchase price per stock
- β Track total lots owned
- β Calculate profit/loss automatically
- β View portfolio summary with current valuations
Example Commands:
"Tambah BBRI ke portfolio, harga rata-rata 5000, total 10 lot"
"Tampilkan portfolio saya"
"Hapus ASII dari portfolio"
Comprehensive Indonesian Stock Exchange (IDX) Data
Real-Time Prices:
"Berapa harga BBCA sekarang?"
"Cek harga TLKM"
Market Summary:
"Bagaimana kondisi pasar hari ini?"
"Gimana IHSG hari ini?"
Top Movers:
"Saham apa yang naik tertinggi?"
"Top losers hari ini?"
Stock Comparison:
"Bandingkan BBRI dan BBNI"
"Compare ASII vs UNTR"
Historical Data:
"Data historis TLKM 30 hari terakhir"
"Grafik harga BBCA"
Fundamentals:
"Fundamental ASII"
"Analisa fundamental BBRI"
Supported Indicators:
- RSI (14-period) - Overbought/oversold momentum
- MACD (12/26/9) - Trend-following momentum
- Moving Averages - SMA 20, EMA 20, SMA 50
- Support/Resistance - Dynamic levels from 30-day data
Example:
"RSI TLKM berapa sekarang?"
"MACD BBRI gimana?"
"Analisa teknikal BBCA"
Track Smart Money and Institutional Trading Patterns
- Top 3 broker accumulation/distribution classification
- Daily trading volume by broker house
- Net buy/sell positioning
Example:
"Bandarmologi BBCA"
"Broker summary TLKM"
- Net foreign investor positioning
- 1-day, 5-day, and 20-day flow tracking
- Foreign ownership percentage trends
Example:
"Foreign flow TLKM"
"Asing masuk BBRI?"
- Combined institutional sentiment analysis
- Sentiment scale: VERY_BULLISH β VERY_BEARISH
- Smart money tracking algorithms
Example:
"Liquidity flow UNTR"
"Bandar akumulasi ASII?"
Professional 30-Day Historical Charts
- Serverless rendering via QuickChart.io API
- No native dependencies required
- Automatic caching (60 seconds)
- Support for all IDX stocks
Example:
"Tampilkan chart BBCA"
"Grafik harga TLKM"
Create a .env file in the project root:
# ============================================
# TELEGRAM CONFIGURATION
# ============================================
# Your Telegram bot token from @BotFather
TELEGRAM_BOT_TOKEN=your-telegram-bot-token
# ============================================
# MARKET DATA API
# ============================================
# GoAPI key for Indonesian stock market data
GOAPI_KEY=your-goapi-key
# ============================================
# AI PROVIDERS
# ============================================
# AI Aggregator (Primary)
AGGREGATOR_API_KEY=your-aggregator-api-key
AGGREGATOR_BASE_URL=https://lite.koboillm.com/v1
AGGREGATOR_MODEL=openai/gpt-4o
# Google Gemini (Fallback - activated on primary rate limit)
GOOGLE_GENERATIVE_AI_API_KEY=your-google-ai-api-key
# ============================================
# DATABASE (SUPABASE)
# ============================================
# Supabase project URL (Dashboard β Settings β API)
SUPABASE_URL=https://your-project.supabase.co
# Supabase service role key (Dashboard β Settings β API)
# β οΈ WARNING: Keep this secret! Never expose to client-side code.
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
# ============================================
# SERVER CONFIGURATION
# ============================================
# Application mode: development (polling) | production (webhook)
NODE_ENV=development
# Server port (used in production webhook mode)
PORT=3000
# ============================================
# ALERT WORKER CONFIGURATION
# ============================================
# Alert check interval in milliseconds (how often to check active price alerts)
# Default: 120000ms (2 minutes)
# Recommended range: 60000-300000ms (1-5 minutes)
#
# Lower values:
# β
More responsive alerts (faster notifications)
# β Higher GoAPI usage (more frequent price checks)
# β Increased server load
#
# Higher values:
# β
Reduced API calls (lower costs)
# β
Lower server resource usage
# β Slower alert responses (delayed notifications)
#
# Production recommendation: 120000ms (2 minutes) - balanced approach
ALERT_CHECK_INTERVAL_MS=120000| Variable | Required | Default | Description |
|---|---|---|---|
TELEGRAM_BOT_TOKEN |
β | - | Bot authentication token from @BotFather |
GOAPI_KEY |
β | - | API key for GoAPI stock market data |
AGGREGATOR_API_KEY |
β | - | AI Aggregator API key (primary LLM provider) |
AGGREGATOR_BASE_URL |
β | https://lite.koboillm.com/v1 |
AI Aggregator endpoint URL |
AGGREGATOR_MODEL |
β | openai/gpt-4o |
Model identifier for AI Aggregator |
GOOGLE_GENERATIVE_AI_API_KEY |
β | - | Google Gemini API key (fallback provider) |
SUPABASE_URL |
β | - | Your Supabase project URL |
SUPABASE_SERVICE_ROLE_KEY |
β | - | Supabase service role key (backend only) |
NODE_ENV |
β | development |
Application environment mode |
PORT |
β | 3000 |
HTTP server port (production webhook only) |
ALERT_CHECK_INTERVAL_MS |
β | 120000 |
Alert worker check interval in milliseconds |
- Node.js β₯ 24.x (Download)
- npm or pnpm package manager
- Active accounts and API keys for:
1. Clone the Repository
git clone https://github.com/prstyaDev/ihsg-analytics-bot.git
cd ihsg-analytics-bot2. Install Dependencies
npm install3. Configure Environment
cp .env.example .envEdit .env with your actual credentials.
4. Database Setup
The bot uses Supabase PostgreSQL with automatic schema migrations. Tables are created automatically when you connect the repository to your Supabase project via GitHub Integration.
Required Tables:
watchlist- Personal stock tracking listsalerts- Price alert configurationsportfolio- User portfolio holdings
5. Run Development Server
npm run devThe bot will start in polling mode (no webhook required for local development).
6. Production Build
npm run build
npm start1. Polling Mode (Development)
- No public domain required
- Uses Telegram long polling
- Ideal for local testing
2. Webhook Mode (Production)
- Requires public domain with SSL
- More efficient for high traffic
- Recommended for production
Environment:
NODE_ENV=production
PORT=3000
ALERT_CHECK_INTERVAL_MS=120000Webhook Setup:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-d "url=https://yourdomain.com/telegram-webhook"βοΈ Railway
- Zero-config deployment
- Automatic HTTPS
- Free tier available
- One-click deploy
βοΈ Heroku
- Hobby tier with worker dynos
- Add-ons for PostgreSQL
- Easy scaling
βοΈ Fly.io
- Global edge deployment
- Automatic SSL certificates
- Docker-based deployment
βοΈ VPS (DigitalOcean, Linode, AWS EC2)
- Full control
- Nginx reverse proxy
- PM2 process manager
- Manual SSL with Certbot
- β
Set
NODE_ENV=production - β Configure webhook URL
- β Set up reverse proxy (Nginx)
- β Enable HTTPS/SSL
- β Configure firewall rules
- β Set up monitoring (PM2, Datadog)
- β Configure log rotation
- β Set up database backups
- β Test alert worker startup
- β Verify batch notifications
ihsg-bot/
βββ src/
β βββ index.ts # Application entry point
β βββ agent/
β β βββ hermes.ts # AI agent orchestration
β βββ bot/
β β βββ index.ts # Telegram bot handlers
β βββ config/
β β βββ env.ts # Environment validation (Zod)
β βββ db/
β β βββ index.ts # Supabase client & queries
β βββ tools/
β β βββ registry.ts # Tool definitions (19 tools)
β βββ utils/
β β βββ chart.ts # Chart generation utility
β β βββ retry.ts # Exponential backoff retry
β β βββ technical.ts # Technical indicators (RSI, MACD, MA)
β β βββ bandar.ts # Bandarmologi & foreign flow
β β βββ tradingHours.ts # IDX trading hours logic
β βββ workers/
β βββ alertWorker.ts # Background alert worker
βββ .env # Environment variables (gitignored)
βββ .env.example # Environment template
βββ .gitignore
βββ package.json
βββ tsconfig.json
βββ README.md
The bot implements comprehensive error handling at multiple layers:
// 120-second timeout for AI queries
if (queryErr.message === 'TIMEOUT_ERROR') {
await ctx.reply("β± Maaf, pengambilan data market sedang padat, coba lagi sebentar lagi.");
}// Automatic fallback to Google Gemini
if (errStr.includes('RESOURCE_EXHAUSTED') || errStr.includes('rate_limit')) {
console.log('[System] Menggunakan Fallback Google Gemini...');
// Gemini handles the request
}// Exponential backoff with 3 retries
await retryWithBackoff(
async () => await api.get('/stock/idx/prices'),
{ maxRetries: 3, baseDelay: 1000, operationName: 'GoAPI price fetch' }
);// Graceful degradation if database fails
if (!result.success) {
console.warn('[System] Database connection failed - watchlist features may be unavailable');
// Bot continues with limited functionality
}Alert Worker:
# Test with 2-minute interval
ALERT_CHECK_INTERVAL_MS=120000 npm run dev
# Test with aggressive 30-second interval
ALERT_CHECK_INTERVAL_MS=30000 npm run devBatch Notifications:
- Create 3 alerts for same user with different symbols
- Trigger all alerts in same cycle
- Verify single consolidated message received
Exponential Backoff:
- Use invalid GoAPI key
- Observe retry attempts in logs
- Verify worker continues with next symbol
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Standards:
- TypeScript strict mode
- ESLint compliance
- Comprehensive error handling
- JSDoc documentation for public APIs
This project is licensed under the MIT License. See LICENSE file for details.
- Issues: GitHub Issues
- Documentation: Wiki
- Telegram: @prstyaDev
- GoAPI - Indonesian stock market data provider
- Telegraf - Excellent Telegram Bot API framework
- Supabase - Managed PostgreSQL with real-time features
- Vercel AI SDK - Powerful LLM orchestration toolkit
- QuickChart.io - Serverless chart rendering
Built with β€οΈ by prstyaDev