Live release feed
Sub-second macro releases for FX backtests
Point-in-time history
Official CPI, jobs, GDP, and central-bank events with point-in-time history.
$25/month 14-day free trial
Start Free Trial

Implementation

How-To Guides

FXMacroData と Webhooks でマクロアラート を設定する

FXMacroDataのアンケートと webhook配信を使用して信頼性の高いマクロアラートシステムを構築する.このガイドでは,新しい指標リリースを検出し,PythonでSlack,Discord,または任意のHTTPエンドポイントに即時通知をプッシュする方法を示します.

他言語版 English
Share article X LinkedIn Email

マクロデータリリースは,FX市場の最も信頼できる触媒の一つです.合意値より0.2%高いCPIプリントは,ニュースヘッドラインが読み込まれる前にEUR/USDが60ピップに滑り込むことができます.あなたのアラートシステムが手動カレンダーチェックまたは広範なタイマーベースの投票に依存している場合は,あなたはすでに遅れています.このガイドは,新しいFXMacroDataが登場する瞬間を検出し,Pythonの80行未満でSlack,Discord,または任意のHTTPエンドポイントに通知を送信する正確なWebhook駆動アラートパイプラインを構築する方法を示します.

建設する

  • 投票回路 設定可能な間隔でFXMacroDataの発表エンドポイントをチェックし,新たに公開された値を検出する
  • Webhook ディスパッチャーの 新しいリリースが検出されたときに,Slack,Discord,またはカスタムエンドポイントに HTTP POST を発射する
  • リリースカレンダー前警告 緊急事態が起こる数分前に警告します 数字が印刷される前に準備ができています
  • 状態の持続性 JSON ファイルを使えば,ボットが再起動する度に同じアラートを二度発射しないようにする.

条件

  • Python 3.9+
  • FXMacroData API キーを 登録する / サブスクリプト そしてダッシュボードからあなたの鍵をコピー
  • Webhook の URL Slack の入力ウェブフックを作成します api.slack.com/apps についてダウンロードする サイトをクリック 設定 → 統合 → Webhook
  • Python パッケージありがとうございました requestsほら schedule
pip install requests schedule

すべての認証情報を環境変数として保存する ソースファイルにハードコードキーを決して:

export FXMACRO_API_KEY="YOUR_FXMACRODATA_KEY"
export WEBHOOK_URL="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"
── なぜ投票とネットフック

投票対推し:正しいパターンを選ぶ

純粋なwebhookサブスクリプションには,公開サーバーエンドポイントと,出力通知を送信するデータプロバイダーが必要です.FXMacroDataを含むほとんどのマクロデータAPIは,プルベースのものです.エンドポイントをクエリして最新の値を受信します.したがって,実践的なパターンは, 軽量投票回路 プログラムが表示されるようにします. webhook ディスパッチャーの (新しいものが現れる瞬間,コードが結果を下流に押し出す).

チームが既に使用しているツールへのWebhook配信の即時性 Slack,Discord,PagerDuty,n8n,または任意のHTTPターゲット. ウェブフックは,Webhooksの利用者に対して,WebHocの利用者を対象とするデータと,WebHookの利用者の間で,WebHubの利用者が,WebWebHokのユーザーに対して,


ステップ 1

ステップ 1 最新の発表値を取得する

ほら 発表 終了点 キーフィールドは,任意の指標と通貨の最新リリース値を返します. announcement_datetime この値がいつ公開されたかを正確に示す2次元のUTCタイムスタンプです.このタイムスタンップをデダプリカのキーとして使用します.最後のチェック以来変更された場合は,新しいリリースが印刷されています.

import os
import requests

BASE_URL = "https://fxmacrodata.com/api/v1"
API_KEY  = os.environ["FXMACRO_API_KEY"]


def fetch_latest(currency: str, indicator: str) -> dict | None:
    """Return the most recent announcement record, or None on failure."""
    try:
        resp = requests.get(
            f"{BASE_URL}/announcements/{currency}/{indicator}",
            params={"api_key": API_KEY},
            timeout=10,
        )
        resp.raise_for_status()
        data = resp.json().get("data", [])
        return data[0] if data else None
    except requests.RequestException as exc:
        print(f"[WARN] fetch failed for {currency}/{indicator}: {exc}")
        return None

検体反応はこうなります

{
  "date": "2026-04-02",
  "val": 4.35,
  "prior": 4.10,
  "announcement_datetime": "2026-04-02T02:30:00Z",
  "currency": "aud",
  "indicator": "policy_rate"
}
ステップ2

ステップ2 追跡状態 重複のアラート回避

プロセスを再起動すると,既に表示されているリリースに対するアラートが再起動しないようにします. announcement_datetime 起動時にボットはこのファイルをロードし,新しいアラートごとに更新されたタイムスタンプを書き戻します.

import json
from pathlib import Path

STATE_FILE = Path("alert_state.json")


def load_state() -> dict:
    if STATE_FILE.exists():
        return json.loads(STATE_FILE.read_text())
    return {}


def save_state(state: dict) -> None:
    STATE_FILE.write_text(json.dumps(state, indent=2))


def is_new_release(state: dict, key: str, record: dict) -> bool:
    """Return True if the announcement_datetime is newer than what we last saw."""
    last_seen = state.get(key)
    current   = record.get("announcement_datetime")
    return current is not None and current != last_seen
ステップ3

ステップ3 ウェブフック通知を送信

Slack の受信ウェブフックとディスコードウェブフックは,JSON 便乗のHTTP POST を両方が受け入れます.下記の関数はフォーマットされたメッセージを作成し,送信します.Slack は text フィールド; ディスコードを使用します content補助は,URL前置詞に基づいて自動的に調整されます.

def send_webhook(webhook_url: str, record: dict, currency: str, indicator: str) -> None:
    """POST a formatted macro-alert message to a Slack or Discord webhook."""
    value    = record.get("val")
    prior    = record.get("prior")
    dt       = record.get("announcement_datetime", "")
    ccy      = currency.upper()
    ind      = indicator.replace("_", " ").title()

    lines = [
        f"📣  *{ccy} {ind}* just printed",
        f"  Value : *{value}*   |   Prior: {prior}",
        f"  Released: {dt}",
    ]
    message = "\n".join(lines)

    # Discord uses "content", Slack uses "text"
    if "discord.com" in webhook_url:
        payload = {"content": message.replace("*", "**")}
    else:
        payload = {"text": message}

    try:
        resp = requests.post(webhook_url, json=payload, timeout=10)
        resp.raise_for_status()
        print(f"[OK] alert sent for {ccy} {ind}")
    except requests.RequestException as exc:
        print(f"[ERROR] webhook delivery failed: {exc}")

ヒント: 設定された HTTP ターゲット

同じこと send_webhook この機能は,POST n8n自動化ワークフロー,Make (Integromat) シナリオ,PagerDuty イベント API,またはあなたの独自のFlask/FastAPI受信機を受け入れるすべての HTTPエンドポイントで動作します. 設定するだけです WEBHOOK_URL 目的 URL に移動し,ペイロードの形を調整します.

ステップ4

ステップ4 投票ループで複数の指標を観察する

通貨/指標ペアを定義し,定期的な間隔でチェックを実行します. schedule 簡単に実行できます.

import schedule
import time

WEBHOOK_URL = os.environ["WEBHOOK_URL"]

# Pairs to monitor — add or remove as needed
WATCHLIST = [
    ("usd", "policy_rate"),
    ("usd", "inflation"),
    ("usd", "non_farm_payrolls"),
    ("eur", "policy_rate"),
    ("eur", "inflation"),
    ("aud", "policy_rate"),
    ("gbp", "policy_rate"),
]


def check_all(state: dict) -> None:
    for currency, indicator in WATCHLIST:
        key    = f"{currency}/{indicator}"
        record = fetch_latest(currency, indicator)
        if record and is_new_release(state, key, record):
            send_webhook(WEBHOOK_URL, record, currency, indicator)
            state[key] = record["announcement_datetime"]
            save_state(state)


def main():
    state = load_state()
    # Run immediately on start, then every 5 minutes
    check_all(state)
    schedule.every(5).minutes.do(check_all, state=state)
    while True:
        schedule.run_pending()
        time.sleep(30)


if __name__ == "__main__":
    main()

端末からボットを起動します.

python macro_alert_bot.py

初めての回数で満たされます alert_state.json 未来は本当に新しいものが現れる時のみ火を燃やします.

ステップ5

ステップ 5 リリース前のカウントダウンアラートを追加

解放が起こったことを知ることは有用です. 起ころうとしている 価値あるもの リリースカレンダーエンドポイント 計画されたことを暴露します announcement_datetime プリントの前に設定可能な数分前に予告を発射する. プリングの初期設定は,

from datetime import datetime, timezone, timedelta

LEAD_MINUTES = 10   # fire a pre-alert this many minutes before the release


def fetch_calendar(currency: str) -> list[dict]:
    try:
        resp = requests.get(
            f"{BASE_URL}/calendar/{currency}",
            params={"api_key": API_KEY},
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json().get("data", [])
    except requests.RequestException as exc:
        print(f"[WARN] calendar fetch failed for {currency}: {exc}")
        return []


def check_upcoming(state: dict) -> None:
    now = datetime.now(tz=timezone.utc)
    for currency, _ in WATCHLIST:
        for event in fetch_calendar(currency):
            scheduled = event.get("announcement_datetime")
            if not scheduled:
                continue
            try:
                event_dt = datetime.fromisoformat(scheduled.replace("Z", "+00:00"))
            except ValueError:
                continue
            # Fire pre-alert if the event is within the lead window and not yet fired
            pre_key = f"pre:{currency}/{event.get('indicator')}:{scheduled}"
            delta   = event_dt - now
            if timedelta(0) < delta <= timedelta(minutes=LEAD_MINUTES):
                if pre_key not in state:
                    send_pre_alert(WEBHOOK_URL, event, currency, delta)
                    state[pre_key] = True
                    save_state(state)


def send_pre_alert(webhook_url: str, event: dict, currency: str, delta: timedelta) -> None:
    ccy      = currency.upper()
    ind      = event.get("indicator", "").replace("_", " ").title()
    expected = event.get("expected")
    prior    = event.get("prior")
    mins     = int(delta.total_seconds() / 60)

    lines = [
        f"⏰  *{ccy} {ind}* due in ~{mins} min",
        f"  Expected: {expected}   |   Prior: {prior}",
    ]
    message = "\n".join(lines)
    if "discord.com" in webhook_url:
        payload = {"content": message.replace("*", "**")}
    else:
        payload = {"text": message}
    try:
        resp = requests.post(webhook_url, json=payload, timeout=10)
        resp.raise_for_status()
        print(f"[OK] pre-alert sent for {ccy} {ind}")
    except requests.RequestException as exc:
        print(f"[ERROR] pre-alert delivery failed: {exc}")

追加する check_upcoming 選挙日程に並べて check_allありがとうございました

def main():
    state = load_state()
    check_all(state)
    check_upcoming(state)
    schedule.every(5).minutes.do(check_all,      state=state)
    schedule.every(5).minutes.do(check_upcoming, state=state)
    while True:
        schedule.run_pending()
        time.sleep(30)
ステップ6

ステップ6 長期間のサービスとして導入

生産用では,ボットがターミナルセッションなしで連続して実行することを望みます.下記は最も一般的な2つの展開パターンです.

オプションA システムDユニット (Linuxサーバー/VPS)

# /etc/systemd/system/macro-alert-bot.service
[Unit]
Description=FXMacroData Alert Bot
After=network.target

[Service]
Type=simple
User=youruser
WorkingDirectory=/opt/macro-alert-bot
ExecStart=/opt/macro-alert-bot/.venv/bin/python macro_alert_bot.py
Restart=always
RestartSec=30
Environment="FXMACRO_API_KEY=YOUR_FXMACRODATA_KEY"
Environment="WEBHOOK_URL=https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now macro-alert-bot

選択肢B ドッカーコンテナ

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY macro_alert_bot.py .
CMD ["python", "macro_alert_bot.py"]
docker build -t macro-alert-bot .
docker run -d --name macro-alert-bot --restart unless-stopped \
  -e FXMACRO_API_KEY="YOUR_FXMACRODATA_KEY" \
  -e WEBHOOK_URL="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK" \
  macro-alert-bot

満載だ requirements.txt

requests>=2.31
schedule>=1.2
概要 概説

概要

マクロアラートパイプラインが稼働します

  • ✅FXMacroDataのアンケート 発表 終了点 監視リストの新しいリリースのために5分ごとに
  • ✅ 再起動で重複するアラートを避けるために状態を継続します
  • ✅ フォーマットされた Webhook メッセージを Slack,Discord,または任意の HTTP ターゲットに送信します
  • 燃焼前は, 消去カウントダウンを警告します. リリースカレンダー 設定可能なリードタイム
  • ✅ systemdサービスまたはDockerコンテナとして継続的に実行されます

次のステップ

  • → 監視リストを 追加指標で拡張する API ドキュメント CPI,雇用,貿易バランスなど
  • → 驚愕フィルターを追加: 警告する時のみ val 偏った expected 騒音削減の限界値を超えて
  • → 組み合わせる COT位置情報 市場が既にサプライズに対応しているかどうかを
  • → AIエージェントへの警告を転送する (参照 OpenClaw 統合ガイド) の文脈で解釈できる.

Blogroll

AI Answer-Ready

Key Facts

Page
How To Macro Alerts Webhooks
Section
Articles
Canonical URL
https://fxmacrodata.com/articles/how-to-macro-alerts-webhooks
Source
FXMacroData editorial and official publisher references
Last Updated
2026-06-15 11:06 UTC

Provenance And Trust

Cite the canonical URL and source field above. Where available, this page maps to official publisher releases and timestamped updates.

Quick Q&A

What is this page about? This page explains How To Macro Alerts Webhooks with directly usable context for trading, research, and API workflows.

What source should be cited? Use the canonical URL and the listed source field; cite official publisher references when available.

How fresh is this content? The last updated value above reflects the page metadata or latest available data timestamp.

Can this be used in AI assistants? Yes. This section is intentionally structured for retrieval and citation in chat assistants.

Prompt Packs

Use these in ChatGPT, Claude, Gemini, Mistral, Perplexity, or Grok for consistent source-aware outputs.

Share page X LinkedIn Email