AI Agent Macro Trading: Event-Driven Strategies for Crypto Markets
Macro trading is the art of reading the global economic environment and positioning a portfolio accordingly. For AI agents operating in crypto markets, macro signals have become the highest-leverage information layer available — a Fed rate surprise moves BTC more in an hour than most technical patterns do in a week.
This guide covers everything an agent needs: how to parse the macro event calendar, which data releases matter most, how crypto assets correlate with DXY and global liquidity, and complete code examples for building an event-driven macro trading system on Purple Flea Trading.
Why Macro Matters for Crypto Agents
Crypto has evolved from a speculative niche into a macro asset class. Institutional participation means BTC and ETH now respond to the same forces that move gold, tech equities, and emerging market currencies — sometimes more violently, because the crypto market never closes and leverage is always accessible.
For a trading agent, this creates both risk and opportunity. An agent running a pure technical momentum strategy will get crushed by a surprise CPI print that moves the entire market 6% in 15 minutes. But an agent that monitors macro data feeds and adjusts exposure before high-impact events can avoid the worst drawdowns — and position for outsized moves when actual data diverges from consensus.
The Macro–Crypto Transmission Mechanism
Understanding how macro affects crypto is essential before building strategies. The primary channels are:
- Risk appetite: In risk-on environments, capital flows into high-beta assets including crypto. In risk-off, capital flees to USD, Treasuries, and gold. BTC behaves like a high-beta tech stock in most macro regimes.
- Liquidity: Central bank balance sheet expansion (QE) inflates all asset prices. Quantitative tightening deflates them. Global M2 money supply has a documented 6–12 month leading relationship with BTC price.
- Dollar strength: Since commodities and crypto are priced in USD, a stronger dollar reduces purchasing power for non-USD investors. DXY correlation with BTC typically runs -0.6 to -0.9 during trend episodes.
- Interest rates: Higher rates increase the opportunity cost of holding non-yielding assets and stress over-leveraged structures. The 2022 rate cycle correlated with ~73% BTC drawdown.
- Geopolitical risk: Ambiguous — sometimes BTC acts as "digital gold" (Ukraine 2022 early spike), sometimes it correlates with equities selloffs (March 2020 COVID crash).
Macro regimes are sticky. Once the Fed pivots or a risk-off regime begins, the directional bias persists for weeks or months. Agents that correctly identify regime changes early outperform by a wide margin.
The Macro Event Calendar
Every trading agent needs to maintain a live calendar of high-impact macro events. The following events drive the largest crypto market moves:
Building a Machine-Readable Event Calendar
Agents need structured access to event schedules. The best free API sources are tradingeconomics.com (paid), investing.com (scrape), and fred.stlouisfed.org for historical data. For production agents, use a dedicated economic calendar service:
// economic-calendar.js — Fetch upcoming high-impact events
const CALENDAR_API = 'https://api.tradingeconomics.com/calendar';
const API_KEY = process.env.TE_API_KEY;
async function getUpcomingEvents(daysAhead = 7, minImpact = 'high') {
const today = new Date().toISOString().split('T')[0];
const future = new Date(Date.now() + daysAhead * 86400000)
.toISOString().split('T')[0];
const res = await fetch(
`${CALENDAR_API}?c=${API_KEY}&d1=${today}&d2=${future}&importance=3`
);
const events = await res.json();
// Normalize to standard format
return events
.filter(e => ['United States', 'Euro Area'].includes(e.Country))
.map(e => ({
date: e.Date,
country: e.Country,
event: e.Event,
consensus: e.Forecast,
previous: e.Previous,
impact: e.Importance === 3 ? 'high' : e.Importance === 2 ? 'medium' : 'low',
hoursUntil: (new Date(e.Date) - Date.now()) / 3600000
}))
.sort((a, b) => new Date(a.date) - new Date(b.date));
}
// Example output:
// { date: '2026-03-19', event: 'FOMC Rate Decision', consensus: 4.25,
// previous: 4.5, impact: 'high', hoursUntil: 312 }
Fed Meeting Impact Analysis
No single institution moves crypto markets more than the Federal Reserve. Understanding FOMC dynamics is non-negotiable for any macro agent.
The Fed Reaction Function
The Fed primarily targets:
- Inflation (PCE target: 2%) — above target = hawkish pressure
- Maximum employment — below 4% unemployment = less urgency to cut
- Financial stability — credit events can force dovish pivots even with hot inflation
For crypto agents, the key signal is Fed Funds Futures pricing. The CME FedWatch tool shows market-implied probability of rate changes. When actual decisions diverge from what futures priced in, large moves happen:
// fed-futures.js — Parse CME FedWatch implied probabilities
async function getFedFuturesImplied() {
// FRED API: Fed Funds Futures 30-day contract
const res = await fetch(
'https://api.stlouisfed.org/fred/series/observations' +
'?series_id=FF&api_key=' + process.env.FRED_KEY +
'&sort_order=desc&limit=1&file_type=json'
);
const data = await res.json();
const currentRate = parseFloat(data.observations[0].value);
// Cross-reference with upcoming FOMC date
const nextFOMC = await getNextFOMCDate();
const marketImplied = 100 - currentRate; // approximate from futures price
return {
currentRate,
marketImplied,
nextFOMC,
// Surprise potential: high if market very confident in no change
surprisePotential: Math.abs(marketImplied - Math.round(marketImplied * 4) / 4)
};
}
// Agent trading logic around FOMC
async function fomcPositionManager(currentPositions) {
const { hoursUntil } = await getNextFOMCDate();
const surprise = await getFedFuturesImplied();
if (hoursUntil < 6) {
// Within 6 hours: reduce all directional exposure by 50%
console.log('FOMC imminent — reducing exposure');
return scalePositions(currentPositions, 0.5);
}
if (hoursUntil < 24 && surprise.surprisePotential > 0.1) {
// High surprise potential: reduce by 30%
return scalePositions(currentPositions, 0.7);
}
return currentPositions; // no change
}
Post-FOMC Trading Patterns
A well-documented pattern in crypto: the first 30-minute reaction to FOMC statements is often a fake-out in the wrong direction, followed by a sustained reversal over the next 2–4 hours. This happens because:
- Algorithms react to headlines before humans process nuance
- Press conference adds context that changes interpretation
- Options market makers delta-hedge, creating artificial moves
Avoid entering positions in the first 30 minutes post-release. Wait for the press conference to begin (30 min after statement) and trade the confirmed direction. The 30-min fake-out is real and consistent.
CPI, NFP, and Economic Data Releases
CPI: The Inflation Trigger
Consumer Price Index is released monthly by the BLS (Bureau of Labor Statistics). The crypto market's reaction follows a predictable logic:
| CPI Outcome | Fed Implication | BTC Expected Move | Agent Action |
|---|---|---|---|
| Hot (above consensus) | More hikes / hold higher longer | -3% to -8% | Short before release if trend hot |
| In-line | No surprise | ±1-2% | Stay neutral, watch for drift |
| Cool (below consensus) | Rate cut expectations rise | +3% to +10% | Long into release if trend cooling |
| Disinflation confirmed | Pivot narrative builds | +5% to +20% over weeks | Increase long exposure post-release |
// cpi-monitor.js — Parse FRED CPI data and generate trading signal
const FRED_BASE = 'https://api.stlouisfed.org/fred/series/observations';
async function getCPISignal() {
// CPIAUCSL = CPI All Urban Consumers
const res = await fetch(
`${FRED_BASE}?series_id=CPIAUCSL&api_key=${process.env.FRED_KEY}` +
'&sort_order=desc&limit=13&file_type=json'
);
const { observations } = await res.json();
const values = observations
.filter(o => o.value !== '.')
.map(o => ({ date: o.date, value: parseFloat(o.value) }))
.reverse();
// Calculate YoY inflation rate
const latest = values[values.length - 1];
const yearAgo = values[values.length - 13];
const yoy = ((latest.value - yearAgo.value) / yearAgo.value) * 100;
// 3-month trend
const threeMonthAgo = values[values.length - 4];
const recentTrend = ((latest.value - threeMonthAgo.value) / threeMonthAgo.value) * 100 * 4; // annualized
return {
yoy: yoy.toFixed(2),
recentTrend: recentTrend.toFixed(2),
signal: recentTrend < yoy - 0.5 ? 'DISINFLATION' :
recentTrend > yoy + 0.5 ? 'REACCELERATION' : 'STABLE',
tradingBias: recentTrend < 2.5 ? 'BULLISH' :
recentTrend > 3.5 ? 'BEARISH' : 'NEUTRAL'
};
}
// Example output:
// { yoy: '2.8', recentTrend: '2.1', signal: 'DISINFLATION', tradingBias: 'BULLISH' }
NFP: Jobs Data and Crypto
Non-Farm Payrolls is released the first Friday of each month at 08:30 ET. The relationship with crypto is more nuanced than CPI:
- Very strong NFP (+300k+): Mixed for crypto — good economy but hawkish Fed risk
- Weak NFP (-50k): Clear bearish signal — recession risk triggers risk-off
- Goldilocks NFP (+150–200k): Best for crypto — strong economy, no Fed urgency
- Unemployment rate spike (more important than raw payrolls): If unemployment rises to 4.5%+, crypto can rally on rate cut expectations
Bitcoin as a Macro Asset
Bitcoin's macro correlations have strengthened significantly since institutional adoption accelerated in 2020–2021. The chart patterns tell a clear story:
BTC and Global M2 Money Supply
The most reliable long-term macro relationship for BTC is with global M2 (money supply of major economies). The mechanism is straightforward: when central banks print money, some flows into risk assets including crypto. The relationship has a 6–12 week lead time — M2 expansion precedes BTC rally by approximately that window.
// m2-tracker.js — Monitor global M2 expansion for macro bias
async function getGlobalM2Signal() {
// US M2 from FRED
const usM2Res = await fetch(
`https://api.stlouisfed.org/fred/series/observations` +
`?series_id=M2SL&api_key=${process.env.FRED_KEY}` +
`&sort_order=desc&limit=6&file_type=json`
);
const { observations } = await usM2Res.json();
const m2Values = observations
.filter(o => o.value !== '.')
.map(o => parseFloat(o.value))
.reverse();
const m2_3mChange = (m2Values[m2Values.length - 1] - m2Values[0]) /
m2Values[0] * 100;
// M2 YoY from FRED (series M2YER or calculate manually)
const m2Trend = m2_3mChange > 0.5 ? 'EXPANDING' :
m2_3mChange < -0.5 ? 'CONTRACTING' : 'FLAT';
return {
m2_3mChange: m2_3mChange.toFixed(2) + '%',
m2Trend,
// Crypto forward bias based on historical M2 → BTC lag
btcBiasIn8Weeks: m2Trend === 'EXPANDING' ? 'BULLISH' :
m2Trend === 'CONTRACTING' ? 'BEARISH' : 'NEUTRAL'
};
}
DXY Correlation and Currency Risk
The US Dollar Index (DXY) measures USD strength against a basket of major currencies (EUR 57.6%, JPY 13.6%, GBP 11.9%, CAD 9.1%, SEK 4.2%, CHF 3.6%). Since BTC is priced in USD, a rising dollar creates direct headwind.
DXY Trading Signals
| DXY Signal | Meaning | Crypto Implication |
|---|---|---|
| DXY above 50-day MA | Dollar trend up | Headwind for BTC/ETH |
| DXY below 50-day MA | Dollar weakening | Tailwind for crypto |
| DXY at 2-year high | Dollar peak possible | Watch for reversal = crypto opportunity |
| DXY RSI > 70 | Dollar overbought | Potential dollar reversal, crypto rebound |
| DXY rapid spike (+2%) | Risk-off episode | Immediate crypto sell pressure |
// dxy-signal.js — Use forex rates to proxy DXY signal
// DXY not on crypto APIs; proxy via EUR/USD (largest component)
async function getDXYSignal() {
// Binance or Kraken for EUR/USD proxy — use EURUSD spot
const res = await fetch('https://api.coinbase.com/v2/prices/EUR-USD/spot');
const { data } = await res.json();
const eurusd = parseFloat(data.amount);
// EUR/USD inverse = approximate DXY proxy (57.6% of DXY is EUR)
// Normalized: EURUSD 1.10 = DXY ~100, EURUSD 1.05 = DXY ~107
const dxyProxy = (1 / eurusd) * 110; // rough normalization
// 20-day simple MA would need historical data; simplified signal:
const dxyStrong = dxyProxy > 105;
const dxyWeak = dxyProxy < 100;
return {
eurusd: eurusd.toFixed(4),
dxyProxy: dxyProxy.toFixed(1),
signal: dxyStrong ? 'STRONG_DOLLAR_HEADWIND' :
dxyWeak ? 'WEAK_DOLLAR_TAILWIND' : 'NEUTRAL',
cryptoBias: dxyStrong ? 'BEARISH' : dxyWeak ? 'BULLISH' : 'NEUTRAL'
};
}
Global Liquidity Cycles
Michael Howell's work on global liquidity has become foundational for macro crypto traders. The framework: global liquidity = central bank reserves + private credit expansion. When both expand simultaneously, risk assets including crypto inflate dramatically. When one or both contract, they deflate.
Liquidity Cycle Phases
- Phase 1 — Tightening: Fed hikes, QT begins, credit conditions tighten. Crypto enters bear market. Agent should be short or flat, low leverage.
- Phase 2 — Pivot anticipation: Hikes pause, futures price in cuts. Crypto bottoms. First buying opportunity. Accumulate long exposure slowly.
- Phase 3 — Early easing: First cuts announced. Risk-on resumes. Aggressive long positioning.
- Phase 4 — Full easing / QE: Balance sheet expands. Blow-off top conditions. Scale out into strength, reduce leverage.
// liquidity-regime.js — Classify current global liquidity regime
async function getLiquidityRegime() {
// Key indicators from FRED
const indicators = await Promise.all([
// Fed balance sheet (WALCL)
fetchFRED('WALCL', 4),
// Bank credit growth (TOTBKCR)
fetchFRED('TOTBKCR', 4),
// 10Y Treasury yield (DGS10) — proxy for financial conditions
fetchFRED('DGS10', 4),
// Financial Conditions Index (NFCI)
fetchFRED('NFCI', 4)
]);
const [fedBalance, bankCredit, treasury10y, fci] = indicators;
const fedExpanding = fedBalance.trend > 0;
const creditExpanding = bankCredit.trend > 0;
const yieldsRising = treasury10y.trend > 0.05;
const conditionsTight = fci.latest > 0.5; // positive NFCI = tighter
let regime, cryptoBias, leverage;
if (fedExpanding && creditExpanding && !yieldsRising) {
regime = 'FULL_EASING';
cryptoBias = 'STRONG_BULLISH';
leverage = 'HIGH'; // up to max available
} else if (!fedExpanding && !creditExpanding && yieldsRising) {
regime = 'FULL_TIGHTENING';
cryptoBias = 'STRONG_BEARISH';
leverage = 'LOW'; // minimal, defensive
} else if (!fedExpanding && creditExpanding) {
regime = 'TRANSITIONAL_IMPROVING';
cryptoBias = 'MILDLY_BULLISH';
leverage = 'MEDIUM';
} else {
regime = 'MIXED';
cryptoBias = 'NEUTRAL';
leverage = 'MEDIUM_LOW';
}
return { regime, cryptoBias, leverage, indicators };
}
async function fetchFRED(seriesId, periods) {
const res = await fetch(
`https://api.stlouisfed.org/fred/series/observations` +
`?series_id=${seriesId}&api_key=${process.env.FRED_KEY}` +
`&sort_order=desc&limit=${periods}&file_type=json`
);
const { observations } = await res.json();
const vals = observations.filter(o => o.value !== '.').map(o => parseFloat(o.value));
return {
latest: vals[0],
trend: vals[0] - vals[vals.length - 1],
series: vals.reverse()
};
}
Risk-On vs Risk-Off Positioning
Experienced macro traders classify market environments as risk-on or risk-off. Crypto is a high-beta risk-on asset by nature. Building a real-time risk regime detector is one of the highest-value things a macro agent can do.
Risk Regime Indicators
- VIX (Volatility Index): VIX > 25 = fear, reduce crypto exposure. VIX < 15 = complacency, good for long carry.
- Credit spreads (HY-IG spread): Widening spreads = credit stress, risk-off signal.
- Gold vs. Bitcoin ratio: Gold outperforming BTC = traditional safe haven demand, risk-off. BTC outperforming = risk appetite.
- Crypto market dominance shift: BTC dominance rising while total market cap falls = BTC serving as relative safe haven within crypto.
// risk-regime.js — Multi-signal risk regime detector
async function detectRiskRegime() {
// VIX approximation via FRED or options data
const vixRes = await fetch(
'https://api.stlouisfed.org/fred/series/observations' +
'?series_id=VIXCLS&api_key=' + process.env.FRED_KEY +
'&sort_order=desc&limit=5&file_type=json'
);
const vixData = await vixRes.json();
const vix = parseFloat(vixData.observations[0].value);
// Crypto-specific fear gauge: funding rates across perps
const fundingRes = await fetch('https://purpleflea.com/api/v1/market/funding-rates');
const funding = await fundingRes.json();
const avgFunding = funding.markets
.map(m => m.fundingRate)
.reduce((a, b) => a + b, 0) / funding.markets.length;
// BTC/ETH relative to 50-day MA (proxy from recent price data)
const btcRes = await fetch('https://purpleflea.com/api/v1/market/candles?symbol=BTC-PERP&interval=1d&limit=50');
const btcCandles = await btcRes.json();
const btcMA50 = btcCandles.candles
.map(c => c.close)
.reduce((a, b) => a + b, 0) / 50;
const btcLast = btcCandles.candles[btcCandles.candles.length - 1].close;
const btcAboveMA = btcLast > btcMA50;
// Score the regime: 0-10 (0=risk off, 10=risk on)
let score = 5;
if (vix < 15) score += 2;
else if (vix > 25) score -= 2;
else if (vix > 35) score -= 4;
if (avgFunding > 0.01) score += 1; // positive funding = bullish sentiment
else if (avgFunding < -0.005) score -= 2; // negative = fear
if (btcAboveMA) score += 2;
else score -= 1;
score = Math.max(0, Math.min(10, score));
return {
vix, avgFunding: (avgFunding * 100).toFixed(4) + '%', btcAboveMA, score,
regime: score >= 7 ? 'RISK_ON' : score <= 3 ? 'RISK_OFF' : 'NEUTRAL',
maxLeverage: score >= 7 ? 5 : score >= 5 ? 3 : score >= 3 ? 1 : 0
};
}
Geopolitical Risk Management
Geopolitical events are harder to systematize than scheduled data releases, but they represent some of the sharpest short-term moves in crypto markets. Key patterns:
Geopolitical Event Taxonomy
- Military conflicts: Initial risk-off spike (BTC -5 to -15%), followed by BTC as hedge recovery if conflict prolongs.
- Sanctions announcements: Mixed — can boost BTC if large economy is cut off from SWIFT (Russia 2022).
- Crypto regulation news: Direct impact. SEC enforcement actions, ETF approvals, exchange shutdowns.
- Major exchange failures: FTX-style — catastrophic short-term, but creates long-term buying opportunities.
// geo-risk-monitor.js — Parse news for geopolitical risk signals
// Uses a news API + simple keyword scoring
const RISK_KEYWORDS = {
critical: ['nuclear', 'exchange collapse', 'exchange hack', 'SEC ban', 'government seizure'],
high: ['war declaration', 'sanctions', 'central bank digital', 'crypto banned', 'exchange insolvent'],
medium: ['trade tariffs', 'election uncertainty', 'debt ceiling', 'government shutdown'],
low: ['GDP miss', 'trade deficit', 'protest', 'political uncertainty']
};
const RISK_WEIGHTS = { critical: 10, high: 5, medium: 2, low: 1 };
async function getGeoRiskScore() {
const res = await fetch(
'https://newsapi.org/v2/everything' +
'?q=crypto+bitcoin+market+global&sortBy=publishedAt' +
'&pageSize=20&apiKey=' + process.env.NEWS_API_KEY
);
const { articles } = await res.json();
let totalRisk = 0;
const triggeredEvents = [];
for (const article of articles) {
const text = (article.title + ' ' + article.description).toLowerCase();
for (const [level, keywords] of Object.entries(RISK_KEYWORDS)) {
for (const kw of keywords) {
if (text.includes(kw)) {
totalRisk += RISK_WEIGHTS[level];
triggeredEvents.push({ level, keyword: kw, headline: article.title });
}
}
}
}
const riskLevel = totalRisk > 20 ? 'EXTREME' :
totalRisk > 10 ? 'HIGH' :
totalRisk > 5 ? 'ELEVATED' : 'NORMAL';
return {
score: totalRisk,
riskLevel,
triggeredEvents: triggeredEvents.slice(0, 5),
// Action: reduce position size if risk is elevated
positionSizeMultiplier: riskLevel === 'EXTREME' ? 0.2 :
riskLevel === 'HIGH' ? 0.5 :
riskLevel === 'ELEVATED' ? 0.75 : 1.0
};
}
Macro Hedge Strategies
A macro-aware agent doesn't just react to events — it pre-positions hedges before high-risk events. On Purple Flea Trading's 275+ perp markets, several instruments serve as effective macro hedges:
Available Hedging Instruments
- BTCUSD inverse perp: Short BTC as primary macro hedge during risk-off
- ETHUSD short: Higher beta than BTC, amplifies hedge in sell-offs
- Gold correlates (PAXG-PERP): Long gold/short BTC as risk-off pair trade
- Stable coin yield: Park capital in Purple Flea Wallet USDC earning yield during macro uncertainty
- Reduced leverage: Simply reducing leverage IS a hedge — less exposure to margin calls during volatile events
// macro-hedge.js — Automated macro hedging before high-impact events
import { getUpcomingEvents } from './economic-calendar.js';
import { getRiskRegime } from './risk-regime.js';
const PF_API = 'https://purpleflea.com/api/v1';
async function manageMacroHedge(portfolio, apiKey) {
const events = await getUpcomingEvents(3); // next 3 days
const regime = await detectRiskRegime();
const highImpactSoon = events.filter(
e => e.impact === 'high' && e.hoursUntil < 48
);
// Base hedge ratio from regime
let hedgeRatio = regime.regime === 'RISK_OFF' ? 0.5 :
regime.regime === 'NEUTRAL' ? 0.2 : 0.05;
// Increase hedge as events approach
if (highImpactSoon.length > 0) {
const closestEvent = highImpactSoon[0];
if (closestEvent.hoursUntil < 6) hedgeRatio = Math.max(hedgeRatio, 0.8);
else if (closestEvent.hoursUntil < 24) hedgeRatio = Math.max(hedgeRatio, 0.5);
else hedgeRatio = Math.max(hedgeRatio, 0.3);
}
// Calculate hedge size
const totalLongExposure = portfolio.positions
.filter(p => p.side === 'long')
.reduce((sum, p) => sum + p.notional, 0);
const targetHedgeSize = totalLongExposure * hedgeRatio;
const currentHedge = portfolio.positions
.filter(p => p.side === 'short')
.reduce((sum, p) => sum + p.notional, 0);
const hedgeAdjustment = targetHedgeSize - currentHedge;
if (Math.abs(hedgeAdjustment) > 100) { // $100 minimum
console.log(`Adjusting hedge by $${hedgeAdjustment.toFixed(2)}`);
console.log(`Reason: ${highImpactSoon[0]?.event || 'regime'}`);
// Place hedge order via Purple Flea API
await fetch(`${PF_API}/orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
symbol: 'BTC-PERP',
side: hedgeAdjustment > 0 ? 'sell' : 'buy',
size: Math.abs(hedgeAdjustment),
orderType: 'market',
reduceOnly: hedgeAdjustment < 0
})
});
}
return {
hedgeRatio,
targetHedgeSize,
adjustment: hedgeAdjustment,
reason: highImpactSoon[0]?.event || regime.regime
};
}
Agent News Parsing for Macro Signals
Modern macro agents don't just monitor economic calendars — they parse unstructured news in real-time to catch macro signals before they hit official data releases. LLM-powered classification transforms raw headlines into structured trading signals.
// macro-news-classifier.js — LLM-powered macro signal extraction
// Uses a fast model (claude-haiku or gpt-4o-mini) for low-latency classification
async function classifyMacroNews(headline, description) {
const prompt = `You are a macro trading signal classifier.
Classify this news headline for crypto market impact.
Headline: "${headline}"
Description: "${description}"
Respond with JSON only:
{
"relevance": 0-10,
"direction": "bullish" | "bearish" | "neutral",
"urgency": "immediate" | "hours" | "days" | "weeks",
"category": "fed" | "inflation" | "employment" | "geopolitical" | "regulation" | "credit" | "other",
"confidence": 0-10,
"action": "reduce_exposure" | "increase_exposure" | "add_hedge" | "hold"
}`;
const res = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'x-api-key': process.env.CLAUDE_KEY,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
body: JSON.stringify({
model: 'claude-haiku-4-5',
max_tokens: 256,
messages: [{ role: 'user', content: prompt }]
})
});
const { content } = await res.json();
return JSON.parse(content[0].text);
}
// News polling loop
async function runMacroNewsAgent(portfolio, apiKey) {
const seenIds = new Set();
while (true) {
const res = await fetch(
'https://newsapi.org/v2/top-headlines?category=business' +
'&pageSize=10&apiKey=' + process.env.NEWS_API_KEY
);
const { articles } = await res.json();
for (const article of articles) {
if (seenIds.has(article.url)) continue;
seenIds.add(article.url);
const signal = await classifyMacroNews(
article.title,
article.description || ''
);
if (signal.relevance >= 7 && signal.confidence >= 7) {
console.log(`High-relevance macro signal: ${article.title}`);
console.log(`Signal: ${JSON.stringify(signal, null, 2)}`);
if (signal.urgency === 'immediate') {
await manageMacroHedge(portfolio, apiKey);
}
}
}
await new Promise(r => setTimeout(r, 60000)); // check every minute
}
}
Complete Macro Trading Agent
Putting it all together: a complete agent that integrates all macro signals and manages exposure on Purple Flea Trading automatically. Get started with free USDC from the Purple Flea Faucet.
// macro-agent.js — Complete macro-aware trading agent
import { getUpcomingEvents } from './economic-calendar.js';
import { getLiquidityRegime } from './liquidity-regime.js';
import { detectRiskRegime } from './risk-regime.js';
import { getDXYSignal } from './dxy-signal.js';
import { getCPISignal } from './cpi-monitor.js';
import { getGeoRiskScore } from './geo-risk-monitor.js';
const PF_API = 'https://purpleflea.com/api/v1';
class MacroTradingAgent {
constructor(apiKey) {
this.apiKey = apiKey;
this.state = { lastSignalTime: 0, currentPositions: [] };
}
async getCompositeSignal() {
const [events, liquidity, risk, dxy, cpi, geo] = await Promise.all([
getUpcomingEvents(2),
getLiquidityRegime(),
detectRiskRegime(),
getDXYSignal(),
getCPISignal(),
getGeoRiskScore()
]);
// Weighted composite score: -100 (bearish) to +100 (bullish)
let score = 0;
// Liquidity regime (highest weight)
const liquidityMap = {
FULL_EASING: 40, TRANSITIONAL_IMPROVING: 20,
MIXED: 0, FULL_TIGHTENING: -40
};
score += liquidityMap[liquidity.regime] || 0;
// Risk regime
const riskMap = { RISK_ON: 25, NEUTRAL: 0, RISK_OFF: -25 };
score += riskMap[risk.regime] || 0;
// DXY signal
const dxyMap = {
WEAK_DOLLAR_TAILWIND: 15,
NEUTRAL: 0,
STRONG_DOLLAR_HEADWIND: -15
};
score += dxyMap[dxy.signal] || 0;
// CPI trend
const cpiMap = {
DISINFLATION: 15, STABLE: 0, REACCELERATION: -15
};
score += cpiMap[cpi.signal] || 0;
// Geopolitical risk (always negative)
score -= geo.score * 0.5;
// Upcoming high-impact events — reduce conviction
const highImpactCount = events.filter(e => e.impact === 'high').length;
const eventDiscount = highImpactCount * 10;
const adjustedScore = score * (1 - eventDiscount / 100);
return {
rawScore: score,
adjustedScore: Math.max(-100, Math.min(100, adjustedScore)),
components: { liquidity: liquidity.regime, risk: risk.regime, dxy: dxy.signal, cpi: cpi.signal, geoRisk: geo.riskLevel },
upcomingEvents: events.filter(e => e.impact === 'high').slice(0, 3),
recommendation: adjustedScore > 50 ? 'LONG_AGGRESSIVE' :
adjustedScore > 20 ? 'LONG_MODERATE' :
adjustedScore > -20 ? 'FLAT' :
adjustedScore > -50 ? 'SHORT_MODERATE' : 'SHORT_AGGRESSIVE'
};
}
async executeStrategy() {
const signal = await this.getCompositeSignal();
console.log('Macro composite signal:', JSON.stringify(signal, null, 2));
const leverageMap = {
LONG_AGGRESSIVE: 4,
LONG_MODERATE: 2,
FLAT: 0,
SHORT_MODERATE: -2,
SHORT_AGGRESSIVE: -4
};
const targetLeverage = leverageMap[signal.recommendation];
if (Math.abs(targetLeverage) > 0) {
// Get account balance
const balRes = await fetch(`${PF_API}/account/balance`, {
headers: { 'Authorization': `Bearer ${this.apiKey}` }
});
const { balance } = await balRes.json();
// Calculate target position size
const targetNotional = balance.usdc * Math.abs(targetLeverage);
await fetch(`${PF_API}/orders`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
symbol: 'BTC-PERP',
side: targetLeverage > 0 ? 'buy' : 'sell',
size: targetNotional,
orderType: 'market',
leverage: Math.abs(targetLeverage)
})
});
}
return signal;
}
}
// Run every 4 hours
const agent = new MacroTradingAgent(process.env.PF_API_KEY);
setInterval(() => agent.executeStrategy(), 4 * 60 * 60 * 1000);
agent.executeStrategy(); // initial run
New agents can claim $1 free USDC from the Purple Flea Faucet to start testing macro strategies with real positions. No deposit required.
Summary and Best Practices
Macro trading is the most intellectually demanding trading style — it requires synthesizing dozens of data sources and maintaining a coherent macro worldview. For agents, the key advantages are tirelessness and discipline: an agent never gets tired of monitoring 4am CPI releases, never panic-sells based on emotion, and always follows the systematic signal framework.
- Always reduce exposure 6–12 hours before scheduled high-impact events
- Wait 30 minutes after FOMC/CPI releases before taking directional positions
- Weight liquidity regime most heavily — it's the dominant long-term driver
- DXY is your best real-time macro dashboard (via EUR/USD proxy)
- News parsing with LLMs catches unscheduled macro shocks before price moves
- Start with paper trading your macro signals for 30 days before going live
Trade 275+ Markets with Macro-Aware Agents
Purple Flea Trading offers the full perp suite your macro agent needs — BTC, ETH, major and exotic pairs, 0.05% maker fees.
Start Trading