DEV Community

Cover image for Monitor Any Stock Price in Your App with 7 Lines of JavaScript
Alexander Schneider
Alexander Schneider

Posted on

Monitor Any Stock Price in Your App with 7 Lines of JavaScript

Ever wanted to add stock price monitoring to your app? Maybe you're building a dashboard, a portfolio tracker, or just want to get notified when Tesla does something crazy again?

Here's how to add real-time stock monitoring to ANY JavaScript application using the StockAlert.pro API.

Installation

npm install @stockalert/sdk
# or
yarn add @stockalert/sdk
Enter fullscreen mode Exit fullscreen mode

The 7-Line Version (I Wasn't Kidding)

import { StockAlertClient } from '@stockalert/sdk';

const client = new StockAlertClient({ apiKey: 'your-free-api-key' });

// Get notified when Apple hits $150
await client.alerts.create({
  symbol: 'AAPL',
  condition: 'price_above',
  threshold: 150
});
Enter fullscreen mode Exit fullscreen mode

That's it. You'll get an email when Apple hits $150. But let's build something more useful...

Real-World Example: Portfolio Dashboard

Let's build a portfolio monitoring system that tracks multiple stocks and sends you notifications when it's time to take profits or cut losses.

import { StockAlertClient } from '@stockalert/sdk';

const client = new StockAlertClient({ apiKey: process.env.STOCKALERT_API_KEY });

// Your portfolio
const portfolio = [
  { symbol: 'AAPL', shares: 100, buyPrice: 145 },
  { symbol: 'GOOGL', shares: 50, buyPrice: 2800 },
  { symbol: 'MSFT', shares: 75, buyPrice: 380 }
];

// Set up price alerts for your portfolio
async function monitorPortfolio() {
  for (const position of portfolio) {
    // Alert when profit hits 10%
    await client.alerts.create({
      symbol: position.symbol,
      condition: 'price_change_up',
      threshold: 10  // 10% gain
    });

    // Alert when loss hits 5% (stop loss)
    await client.alerts.create({
      symbol: position.symbol,
      condition: 'price_change_down',
      threshold: 5  // 5% loss
    });

    console.log(`πŸ“Š Monitoring ${position.symbol}:`);
    console.log(`   Alert when up 10% from current price`);
    console.log(`   Alert when down 5% from current price`);
  }

  console.log('\nβœ… All alerts created! You\'ll get emails when targets are hit.');
}

// Start monitoring
monitorPortfolio();
Enter fullscreen mode Exit fullscreen mode

Working with Webhooks

Want to receive events in your app? Here's how to properly set up webhooks:

Pro tip: You can view and test all your webhooks at https://stockalert.pro/dashboard/settings

import crypto from 'crypto';

// Step 1: Register your webhook endpoint
const webhook = await client.webhooks.create({
  url: 'https://your-app.com/stockalert-webhook',
  events: ['alert.triggered']
});

console.log('Webhook secret:', webhook.secret); // Save this for verification!

// Step 2: Create alerts (they'll send emails/SMS by default)
const alert = await client.alerts.create({
  symbol: 'AAPL',
  condition: 'price_above',
  threshold: 150
});

// Step 3: Handle webhook events when alerts trigger
app.post('/stockalert-webhook', (req, res) => {
  const { event, timestamp, data } = req.body;

  // Verify webhook signature (recommended)
  const signature = req.headers['x-stockalert-signature'];
  const expectedSignature = crypto
    .createHmac('sha256', webhook.secret)
    .update(JSON.stringify(req.body))
    .digest('hex');

  if (signature !== expectedSignature) {
    return res.status(401).send('Invalid signature');
  }

  if (event === 'alert.triggered') {
    console.log(`🚨 Alert triggered at ${timestamp}`);
    console.log(`Symbol: ${data.symbol}`);
    console.log(`Condition: ${data.condition} (threshold: ${data.threshold})`);
    console.log(`Current value: $${data.current_value}`);

    // Your custom logic here: update database, send Slack message, etc.
  }

  res.json({ received: true });
});
Enter fullscreen mode Exit fullscreen mode

Building a Price Monitoring Slack Bot

Here's a Slack bot that lets your team monitor stocks:

import { StockAlertClient } from '@stockalert/sdk';
import { WebClient } from '@slack/web-api';

const stockAlert = new StockAlertClient({ apiKey: process.env.STOCKALERT_API_KEY });
const slack = new WebClient(process.env.SLACK_TOKEN);

// Slack slash command: /watch AAPL above 150
app.post('/slack/commands', async (req, res) => {
  const { text, user_id, channel_id } = req.body;
  const [symbol, condition, value] = text.split(' ');

  // Create the alert
  const alert = await stockAlert.alerts.create({
    symbol: symbol.toUpperCase(),
    condition: `price_${condition}`,
    threshold: parseFloat(value)
  });

  // Store metadata in your database for webhook handling
  await saveAlertMetadata(alert.id, { channel_id, user_id });

  res.json({
    response_type: 'in_channel',
    text: `βœ… Watching ${symbol.toUpperCase()} to go ${condition} $${value}`
  });
});

// Handle the alert
app.post('/slack-webhook', async (req, res) => {
  const { symbol, price, condition, metadata } = req.body;

  await slack.chat.postMessage({
    channel: metadata.channel_id,
    text: `🚨 Alert: ${symbol} is now at $${price}!`,
    blocks: [{
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: `*${symbol}* hit your target price!\nCurrent: *$${price}*\nAlert by: <@${metadata.user_id}>`
      }
    }]
  });

  res.json({ received: true });
});
Enter fullscreen mode Exit fullscreen mode

Email Digest for Your Users

Building a fintech app? Here's how to use daily reminders to keep users informed:

import { StockAlertClient } from '@stockalert/sdk';

const client = new StockAlertClient({ apiKey: process.env.STOCKALERT_API_KEY });

// Set up daily reminders for user's watchlist
async function setupDailyDigest(userEmail, watchlist) {
  for (const symbol of watchlist) {
    await client.alerts.create({
      symbol: symbol,
      condition: 'daily_reminder'
      // Sends every market day at open with current price
    });
  }
}

// Example: Set up for a user watching tech stocks
await setupDailyDigest('user@example.com', ['AAPL', 'GOOGL', 'MSFT']);
Enter fullscreen mode Exit fullscreen mode

What the user receives every market day:

Subject: Daily Reminder for AAPL: +1.24%

Stock Alert: Daily Reminder for AAPL

Daily Reminder: Apple Inc.
Your daily market open summary for Apple Inc. (AAPL). Current price is $175.23.

Alert Details
Here is your daily update for Apple Inc. (AAPL), as of U.S. market open:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Current Price           β”‚ $175.23      β”‚
β”‚ Previous Day's Close    β”‚ $173.08      β”‚
β”‚ Change                  β”‚ +1.24%       β”‚
β”‚ 52-Week High           β”‚ $199.62      β”‚
β”‚ 52-Week Low            β”‚ $164.08      β”‚
β”‚ Volume                  β”‚ 52,341,200   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

---
Sent by StockAlert.pro
Enter fullscreen mode Exit fullscreen mode

Each stock gets its own email with:

  • Current price at market open
  • Previous day's closing price
  • Percentage change (color-coded: green/red)
  • 52-week high and low
  • Trading volume
  • Proper currency formatting based on user location

Pro tip: For a consolidated digest, use webhooks to collect all alerts and send one combined email:

// Collect daily alerts via webhook
const dailyAlerts = new Map();

app.post('/webhook', async (req, res) => {
  const { event, data } = req.body;

  if (event === 'alert.triggered' && data.condition === 'daily_reminder') {
    // Group by user (you'd need to track this in your DB)
    const userId = await getUserIdByAlertId(data.alert_id);

    if (!dailyAlerts.has(userId)) {
      dailyAlerts.set(userId, []);
    }

    dailyAlerts.get(userId).push({
      symbol: data.symbol,
      price: data.current_value,
      timestamp: data.triggered_at
    });

    // Send digest after collecting all morning alerts
    setTimeout(() => sendConsolidatedDigest(userId), 30000);
  }

  res.json({ received: true });
});
Enter fullscreen mode Exit fullscreen mode

Advanced: Technical Indicators

Monitor RSI, Moving Averages, and more:

// Get notified when a stock becomes oversold
await client.alerts.create({
  symbol: 'TSLA',
  condition: 'rsi_limit',
  threshold: 30,  // RSI below 30 = oversold
  parameters: {
    direction: 'below'  // 'below' or 'above'
  }
});

// Golden Cross alert (50-day MA crosses above 200-day MA)
await client.alerts.create({
  symbol: 'SPY',
  condition: 'ma_crossover_golden'
});

// Price touches moving average
await client.alerts.create({
  symbol: 'AAPL',
  condition: 'ma_touch_above',
  parameters: {
    period: 50  // 50-day or 200-day moving average
  }
});
Enter fullscreen mode Exit fullscreen mode

Error Handling & Best Practices

class StockMonitor {
  constructor(apiKey) {
    this.client = new StockAlertClient({ apiKey });
    this.alerts = new Map();
  }

  async createAlert(config) {
    try {
      const alert = await this.client.alerts.create(config);
      this.alerts.set(alert.id, alert);
      console.log(`βœ… Alert created: ${alert.id}`);
      return alert;
    } catch (error) {
      if (error.code === 'RATE_LIMIT') {
        console.error('Rate limit hit, retrying in 60s...');
        await sleep(60000);
        return this.createAlert(config);
      }

      if (error.code === 'INVALID_SYMBOL') {
        console.error(`Invalid symbol: ${config.symbol}`);
        return null;
      }

      throw error;
    }
  }

  async cleanup() {
    // Delete all alerts on shutdown
    for (const [id, alert] of this.alerts) {
      try {
        await this.client.alerts.delete(id);
      } catch (error) {
        console.error(`Failed to delete alert ${id}:`, error);
      }
    }
  }
}

// Graceful shutdown
process.on('SIGTERM', async () => {
  await monitor.cleanup();
  process.exit(0);
});
Enter fullscreen mode Exit fullscreen mode

Testing Your Integration

// Mock webhook endpoint for testing
if (process.env.NODE_ENV === 'development') {
  app.post('/test-webhook', (req, res) => {
    console.log('Webhook received:', JSON.stringify(req.body, null, 2));
    res.json({ received: true });
  });

  // Create a test alert
  await client.alerts.create({
    symbol: 'AAPL',
    condition: 'price_above',
    threshold: 1 // Will trigger immediately
  });

  // For webhook testing, first create a webhook endpoint:
  // const webhook = await client.webhooks.create({
  //   url: 'http://localhost:3000/test-webhook',
  //   events: ['alert.triggered']
  // });
}
Enter fullscreen mode Exit fullscreen mode

Pricing

Free Plan includes:

  • Monitor up to 50 stocks parallel
  • Unlimited email alerts
  • All 21 alert types
  • 1 API key per user
  • 100 API requests/hour

Premium Plan ($14.99/month or $149.99/year):

  • Unlimited stocks
  • 50 SMS/WhatsApp messages per month
  • 10,000 API requests/hour
  • Unlimited API keys
  • Unlimited alerts via API
  • Priority support

Perfect for testing with the free plan, then scale up when you need more power!

What Will You Build?

I've seen developers use this API to build:

  • Portfolio tracking apps
  • Discord/Slack bots
  • Personal dashboards
  • Trading journals
  • News aggregators that react to price movements
  • Chrome extensions for price monitoring

What are you planning to build? Drop a comment below!

Resources


Get your free API key at stockalert.pro - No credit card required

Top comments (0)