OilPriceAPI Docs
GitHub
GitHub
  • Use Case Tutorials

    • Use Case Tutorials
    • Dashboard Building
    • Price Alerts
    • Data Analysis
    • Integration Patterns

Price Alerts

Notify your users (or systems) when a commodity crosses a price threshold using OilPriceAPI webhooks and threshold monitoring.

Problem

You need to react when a price moves — for example, alert a trader when Brent crosses $90, or page an ops channel when diesel spikes. Continuously polling the API and diffing values yourself is wasteful and slow to react. You want a push-based alerting pipeline that fires reliably and is easy to manage.

Solution Architecture

Combine OilPriceAPI webhooks (push delivery) with your own threshold monitoring logic and a notification fan-out:

OilPriceAPI ──webhook──> Your endpoint ──> Threshold check ──> Notify
  (price event)            (verify sig)      (rule engine)     (email/Slack/SMS)
  • Webhooks push price events to your endpoint so you do not have to poll.
  • A threshold rule engine decides whether an event should trigger an alert.
  • A notification layer delivers the alert and records that it fired (so you do not spam users).

Code Implementation

Setting up webhooks

Register an endpoint that OilPriceAPI will POST to when prices update. See the Webhooks API for the full payload schema and the webhook verification guide for signature validation.

curl -X POST https://api.oilpriceapi.com/v1/webhooks \
  -H "Authorization: Token YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/hooks/oilpriceapi",
    "events": ["price.updated"]
  }'

Always verify the X-OilPriceAPI-Signature HMAC-SHA256 header before trusting a payload:

import hashlib
import hmac

def verify_signature(secret: str, body: bytes, signature: str) -> bool:
    expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

Threshold monitoring

Evaluate each incoming event against your alert rules. Use hysteresis (a small buffer) so a price hovering near the line does not flap.

ALERT_RULES = [
    {"commodity": "BRENT_CRUDE_USD", "operator": ">", "threshold": 90.0},
    {"commodity": "WTI_USD", "operator": "<", "threshold": 65.0},
]


def evaluate(event):
    """Return rules that the incoming price event trips."""
    triggered = []
    price = event["price"]
    for rule in ALERT_RULES:
        if rule["commodity"] != event["commodity"]:
            continue
        if rule["operator"] == ">" and price > rule["threshold"]:
            triggered.append(rule)
        elif rule["operator"] == "<" and price < rule["threshold"]:
            triggered.append(rule)
    return triggered

Notification strategies

Fan out triggered alerts to the right channel, and debounce so the same threshold crossing only notifies once.

import time

_last_sent = {}
DEBOUNCE_SECONDS = 900  # 15 minutes


def notify(rule, price):
    key = (rule["commodity"], rule["operator"], rule["threshold"])
    now = time.time()
    if now - _last_sent.get(key, 0) < DEBOUNCE_SECONDS:
        return  # already alerted recently
    _last_sent[key] = now
    send_slack(f"{rule['commodity']} crossed {rule['threshold']} (now {price})")

Alert management

Store rules in a database so users can create, edit, pause, and delete alerts without a code deploy. Track each alert's last-fired time and an enabled flag, and expose a simple CRUD UI or API on top.

Best Practices

  • Prefer webhooks over polling for latency and quota efficiency.
  • Always verify signatures and reject requests with stale timestamps to block replay attacks.
  • Respond to the webhook fast (2xx within a couple of seconds); do the alert evaluation asynchronously on a queue.
  • Debounce and deduplicate so a single crossing does not produce a storm of notifications.
  • Make rules data-driven so non-engineers can manage thresholds.

Common Pitfalls

  • Trusting unverified payloads. Anyone can POST to a public URL — verify the HMAC signature every time.
  • Doing heavy work inside the webhook handler. Slow handlers cause delivery timeouts and retries; offload to a background job.
  • Flapping alerts. Without hysteresis/debounce, a price oscillating around the threshold spams users.
  • No idempotency. Webhook delivery is at-least-once; use the event ID to avoid acting on the same event twice.
Last Updated: 6/22/26, 11:46 AM
Prev
Dashboard Building
Next
Data Analysis