> ## Documentation Index
> Fetch the complete documentation index at: https://docs.meter.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# E-commerce Price Monitoring

> Monitor product prices and availability with Meter

# E-commerce Price Monitoring

Complete example showing how to monitor e-commerce products for price changes and stock availability.

## Use case

Track competitor prices, product availability, and detect when products go on sale.

## What you'll build

* Strategy for extracting product data
* Hourly monitoring schedule
* Price drop alerts
* Inventory tracking

## Prerequisites

* Meter API key
* **TODO**: Your alerting system (email, Slack, etc.)
* **TODO**: Your target e-commerce site

## Step 1: Generate strategy

**TODO**: Replace with your actual e-commerce site and data

```python theme={null}
from meter_sdk import MeterClient
import os

client = MeterClient(api_key=os.getenv("METER_API_KEY"))

# Generate strategy
strategy = client.generate_strategy(
    url="https://example-shop.com/products",  # TODO: Your URL
    description="Extract product name, price, image URL, and stock availability",
    name="E-commerce Product Monitor"
)

strategy_id = strategy["strategy_id"]
print(f"Strategy ID: {strategy_id}")

# Check preview
print("\nPreview data:")
for item in strategy['preview_data'][:3]:
    print(f"  {item}")
```

## Step 2: Set up monitoring

```python theme={null}
# Monitor every hour
schedule = client.create_schedule(
    strategy_id=strategy_id,
    url="https://example-shop.com/products",  # TODO: Your URL
    interval_seconds=3600  # Every hour
)

print(f"Schedule ID: {schedule['schedule_id']}")
```

## Step 3: Process price changes

**TODO**: Implement your price tracking logic

```python theme={null}
def process_price_changes(schedule_id, price_threshold=50.0):
    """Check for price changes and alert on drops"""
    changes = client.get_schedule_changes(schedule_id, mark_seen=True)

    if changes['count'] == 0:
        print("No changes detected")
        return

    print(f"Processing {changes['count']} changes")

    for change in changes['changes']:
        for product in change['results']:
            # TODO: Parse price (format depends on your site)
            # price = float(product['price'].replace('$', ''))

            # TODO: Implement price tracking
            # old_price = get_last_known_price(product['name'])

            # if price < old_price * 0.9:  # 10% drop
            #     send_price_drop_alert(product['name'], old_price, price)

            # TODO: Store current price
            # store_price(product['name'], price)

            pass

# Run periodically
import time

while True:
    process_price_changes(schedule['schedule_id'])
    time.sleep(3600)
```

## Step 4: Track inventory

**TODO**: Implement stock tracking

```python theme={null}
def track_inventory(schedule_id):
    """Alert when out-of-stock items come back"""
    changes = client.get_schedule_changes(schedule_id, mark_seen=True)

    for change in changes['changes']:
        for product in change['results']:
            # TODO: Check stock status
            # in_stock = product.get('stock_availability') == 'In Stock'
            # was_out_of_stock = check_previous_stock_status(product['name'])

            # if in_stock and was_out_of_stock:
            #     send_back_in_stock_alert(product['name'])

            # TODO: Update stock status
            # update_stock_status(product['name'], in_stock)

            pass
```

## Complete example

**TODO**: Full working implementation

```python theme={null}
# full_example.py

from meter_sdk import MeterClient
import os
import time
import json
from datetime import datetime

client = MeterClient(api_key=os.getenv("METER_API_KEY"))

# TODO: Add your configuration
CONFIG = {
    "url": "https://example-shop.com/products",
    "price_threshold": 50.0,  # Alert on prices below this
    "check_interval": 3600,   # Check every hour
    "price_drop_percent": 10  # Alert on 10%+ price drops
}

# TODO: Implement price tracking storage
PRICE_HISTORY_FILE = "price_history.json"

def load_price_history():
    """Load price history from file"""
    try:
        with open(PRICE_HISTORY_FILE, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}

def save_price_history(history):
    """Save price history to file"""
    with open(PRICE_HISTORY_FILE, 'w') as f:
        json.dump(history, f, indent=2)

def send_alert(message):
    """Send alert (TODO: implement your alerting)"""
    print(f"ALERT: {message}")
    # TODO: Send email, Slack notification, etc.

def main():
    """Main monitoring loop"""
    # Generate or load strategy
    # TODO: Store strategy_id in config file
    strategy_id = "your-strategy-id"  # Replace with actual

    # Create or load schedule
    # TODO: Store schedule_id in config file
    schedule_id = "your-schedule-id"  # Replace with actual

    price_history = load_price_history()

    while True:
        print(f"\n[{datetime.now()}] Checking for changes...")

        changes = client.get_schedule_changes(schedule_id, mark_seen=True)

        if changes['count'] > 0:
            print(f"Processing {changes['count']} changes")

            for change in changes['changes']:
                for product in change['results']:
                    # TODO: Implement your processing logic
                    product_name = product.get('name')

                    # Example: Track prices
                    # current_price = parse_price(product.get('price'))
                    # old_price = price_history.get(product_name)

                    # if old_price and current_price < old_price * (1 - CONFIG['price_drop_percent'] / 100):
                    #     send_alert(f"{product_name} price dropped: ${old_price} -> ${current_price}")

                    # price_history[product_name] = current_price

            save_price_history(price_history)

        else:
            print("No changes detected")

        print(f"Waiting {CONFIG['check_interval']} seconds...")
        time.sleep(CONFIG['check_interval'])

if __name__ == "__main__":
    main()
```

## Deployment

### Option 1: Run as service

**TODO**: Set up as systemd service or similar

```bash theme={null}
# Run continuously
python ecommerce_monitor.py
```

### Option 2: Cron job

**TODO**: Configure cron

```bash theme={null}
# Add to crontab (check every hour)
0 * * * * cd /path/to/project && python ecommerce_monitor.py
```

### Option 3: Cloud function

**TODO**: Deploy to AWS Lambda, Google Cloud Functions, etc.

## Next steps

* Add database for price history tracking
* Implement email/Slack alerts
* Build price trends visualization
* Add multi-page monitoring

## See also

* [Schedules Concept](/concepts/schedules) - Understanding monitoring
* [Pull-Based Monitoring](/guides/pull-based-monitoring) - Polling patterns
* [Webhooks Guide](/guides/webhooks) - Real-time alerts

## Need help?

Email me at [mckinnon@meter.sh](mailto:mckinnon@meter.sh)
