Real-time portfolio monitoring is a foundational practice for any active participant in Web3. Unlike traditional finance, where brokerages provide consolidated views, managing assets across multiple blockchains, wallets, and protocols is inherently fragmented. A monitoring system solves this by aggregating data from disparate sources—wallet addresses, smart contract positions, and DeFi protocols—into a single, actionable dashboard. This allows you to track your total net worth, exposure to specific assets, and the performance of individual investments without manually checking a dozen different interfaces.
Setting Up Real-Time Portfolio Monitoring and Alerting
Setting Up Real-Time Portfolio Monitoring and Alerting
A guide to building automated systems that track your on-chain assets and notify you of critical events.
The core of any monitoring setup is a reliable data source. For developers, this typically means using specialized APIs from providers like Chainscore, Alchemy, or The Graph. These services index raw blockchain data and provide structured endpoints for querying wallet balances, token holdings, NFT collections, and DeFi positions. For example, you can fetch all ERC-20 token balances for an Ethereum address using the alchemy_getTokenBalances RPC method or query a subgraph for a wallet's liquidity provider positions on Uniswap V3. Setting up automated scripts to poll these APIs at regular intervals is the first technical step.
Once you have a data pipeline, the next step is establishing alerting logic. Effective alerts move beyond simple balance checks. You should monitor for specific on-chain events that impact your portfolio's health or security. Key triggers include: significant price movements for held assets, the expiration of a critical limit order on a DEX like dYdX, a change in governance parameters for a staking pool you're invested in, or suspicious outflows from a wallet. These conditions are defined in your monitoring code, often using price oracles like Chainlink for asset values and event listeners for on-chain transactions.
Implementing the alerting system requires choosing a notification channel. For personal use, simple integrations with messaging platforms are common. You can use webhooks to send alerts to a Discord server via a bot, push notifications to a phone using services like Pushover or Telegram's Bot API, or even trigger emails for less time-sensitive reports. The code to handle this typically involves a serverless function (e.g., on Vercel or AWS Lambda) that runs your monitoring logic on a schedule and calls the notification service's API when an alert condition is met.
Finally, consider security and cost. Your monitoring script will need access to API keys and potentially private notification webhooks. These secrets must be stored securely using environment variables or a secrets manager. Additionally, be mindful of API rate limits and compute costs, especially if you are polling data frequently for multiple addresses. Starting with a simple cron job that runs every 5-10 minutes is a cost-effective approach. As your needs grow, you can explore more sophisticated architectures using message queues for event-driven alerts, which reduce unnecessary polling and provide faster notification times.
Prerequisites and System Architecture
Before building a real-time portfolio monitor, you need the right tools and a clear architectural plan. This section covers the essential software, APIs, and system design patterns.
The foundation of a robust monitoring system is a reliable data source. For on-chain data, you'll need access to an RPC provider like Alchemy, Infura, or QuickNode for the relevant blockchains (e.g., Ethereum, Polygon, Arbitrum). For aggregated portfolio data, you can use specialized APIs such as the Chainscore Portfolio API or Zapper's API. You'll also need a backend runtime; Node.js with TypeScript is a common choice for its extensive Web3 library support (ethers.js, viem) and async capabilities.
A scalable architecture separates concerns into distinct services. The core is a data ingestion layer that polls APIs or subscribes to WebSocket streams for real-time updates. This data is processed by a portfolio aggregation service, which normalizes asset values (often to USD via price oracles like Chainlink) and calculates metrics like total net worth, profit/loss, and asset allocation. This processed state is then stored in a low-latency database like Redis for quick access by the frontend or alerting engine.
The alerting engine is a critical component that evaluates predefined rules against the live portfolio state. Rules can be simple (e.g., "ETH balance drops below 1.0") or complex (e.g., "portfolio value decreases by 15% in 1 hour"). This service needs to integrate with notification channels. Common integrations include sending emails via SendGrid, SMS with Twilio, or push notifications to a mobile app using Firebase Cloud Messaging. For developers, logging alerts to a channel like Discord or Slack via webhooks is also practical.
Here's a basic code snippet for a Node.js service that fetches an Ethereum balance and checks an alert condition using ethers.js:
javascriptimport { ethers } from 'ethers'; const provider = new ethers.JsonRpcProvider('YOUR_RPC_URL'); const walletAddress = '0x...'; async function checkBalance() { const balanceWei = await provider.getBalance(walletAddress); const balanceEth = ethers.formatEther(balanceWei); console.log(`Balance: ${balanceEth} ETH`); if (parseFloat(balanceEth) < 1.0) { // Trigger alert logic console.log('ALERT: Balance below 1 ETH!'); } } // Poll every 30 seconds setInterval(checkBalance, 30000);
For production systems, consider reliability and cost. Implement retry logic with exponential backoff for API calls to handle rate limits or temporary outages. Cache frequent, non-critical requests to reduce API costs. Use a message queue (like RabbitMQ or AWS SQS) to decouple the data ingestion from the alert processing, ensuring the system remains responsive during high load. Finally, always secure your API keys and RPC endpoints using environment variables or a secrets management service.
Step 1: Ingesting Data with Blockchain Indexers
Learn how to build the foundational data layer for real-time portfolio monitoring by connecting to and querying blockchain indexers.
A blockchain indexer is a specialized service that processes raw, on-chain data into a structured, queryable format. Instead of manually parsing transaction logs or scanning entire block histories, you query an indexed database for specific events, token balances, or contract states. For portfolio monitoring, this means you can efficiently track wallet holdings, token transfers, and DeFi positions across multiple chains without running your own nodes. Popular indexers include The Graph for its subgraph protocol, Covalent for its unified API, and Alchemy's Enhanced APIs for real-time event streaming.
To ingest data, you first identify the specific data points needed for your portfolio tracker. Common requirements include: ERC-20 and ERC-721 token balances, Swap, Deposit, and Withdraw events from DEXs and lending protocols, and current prices from oracles. You then use the indexer's query language (like GraphQL for The Graph) or REST API endpoints to fetch this data. For example, a query to get a wallet's USDC balance on Ethereum might filter for the Transfer event where the to address matches your target wallet.
Setting up a real-time feed requires subscribing to updates rather than polling. Services like The Graph's GraphQL Subscriptions or Alchemy's WebSockets (alchemy.com/docs/apis/websockets) push new data to your application as blocks are finalized. This is critical for instant alerting. Your code must listen for these streams and parse the incoming data, typically in JSON format, to update your internal portfolio state. Handling chain reorganizations (reorgs) is also essential; a robust indexer will provide data with confirmation depths or stream block and removed flags.
Here's a conceptual code snippet for subscribing to token transfers for a specific wallet using a GraphQL subscription:
graphqlsubscription { transfers(where: {or: [{from: "$walletAddress"}, {to: "$walletAddress"}]}) { id from to value token { symbol decimals } transaction { blockNumber } } }
This subscription would fire every time the specified wallet sends or receives a tracked token, providing the core event data for your monitoring system.
When building your pipeline, consider multi-chain support from the start. Your portfolio tracker is likely monitoring assets on Ethereum, Polygon, Arbitrum, and others. Using a unified API like Covalent or a multi-chain indexer setup with The Graph simplifies this by providing a consistent data schema across networks. You'll need to manage separate connections or API keys for each chain, aggregate the results, and normalize values (like converting token amounts using decimals) before they can be summed or analyzed for your portfolio's total value.
Finally, implement initial data backfilling. Before the real-time stream begins, you need the current state of all tracked wallets. This is done by running historical queries to fetch all past balances and transactions. Once this baseline is established, the real-time subscription takes over to apply incremental updates. This two-phase approach—historical backfill followed by live subscription—ensures your monitoring system is accurate and immediately responsive to new on-chain activity.
Aggregating Real-Time Market Prices
Build a resilient data pipeline to fetch, normalize, and store live price feeds from multiple decentralized and centralized exchanges.
A robust portfolio monitor requires a reliable stream of live market data. Relying on a single source is a critical vulnerability; exchanges can experience downtime, API rate limits, or temporary price anomalies. Your system should aggregate prices from multiple liquidity sources such as Uniswap V3 pools, Curve Finance gauges, and centralized exchange APIs like CoinGecko or Binance. This approach, known as price oracle aggregation, mitigates the risk of bad data by cross-referencing feeds and calculating a volume-weighted or median price.
Implementing this involves setting up asynchronous data fetchers for each source. For on-chain DEX data, use a provider like Alchemy or QuickNode to subscribe to new block events and query pool reserves. For CEX APIs, schedule periodic HTTP requests. A common pattern is to structure your aggregator with a PriceFetcher interface, allowing you to plug in different implementations. Critical considerations include handling rate limits (using exponential backoff), managing WebSocket reconnections, and parsing the varied response formats from each exchange into a unified internal model.
Once you have raw prices, you must normalize them. Different sources quote token pairs differently (e.g., ETH/USDC vs. USDC/ETH) and use varying decimal precisions. Convert all prices to a common quote currency (like USD) and a standard decimal format (typically 18 decimals for internal math). For tokens without direct USD pairs, you may need to calculate a price through a common base asset like ETH or USDC, constructing a price path (e.g., MKR -> WETH -> USDC).
The final step is deriving a single consensus price. A simple method is to discard outliers beyond a standard deviation threshold and take the median of the remaining values. For more sophisticated DeFi applications, consider a time-weighted average price (TWAP) from on-chain oracles like Chainlink, or a liquidity-weighted average from DEX pools. Store this aggregated price with a timestamp in your database. This cleansed data layer becomes the foundation for calculating portfolio values in the next step and triggering accurate alerts.
Here is a simplified code snippet demonstrating the core aggregation logic in Node.js, using the axios library for API calls and the ethers library for on-chain queries:
javascriptasync function fetchAggregatedPrice(tokenAddress, sources) { const pricePromises = sources.map(source => source.fetchPrice(tokenAddress)); const results = await Promise.allSettled(pricePromises); const validPrices = results .filter(r => r.status === 'fulfilled' && r.value > 0) .map(r => r.value); // Basic outlier removal: discard prices outside 2 standard deviations const avg = validPrices.reduce((a, b) => a + b) / validPrices.length; const stdDev = Math.sqrt(validPrices.map(p => Math.pow(p - avg, 2)).reduce((a, b) => a + b) / validPrices.length); const filteredPrices = validPrices.filter(p => Math.abs(p - avg) <= 2 * stdDev); // Return the median price filteredPrices.sort((a, b) => a - b); const mid = Math.floor(filteredPrices.length / 2); return filteredPrices.length % 2 !== 0 ? filteredPrices[mid] : (filteredPrices[mid - 1] + filteredPrices[mid]) / 2; }
Continuously monitor the health of your price feeds. Implement logging for fetch failures and latency, and set up internal alerts if a data source consistently deviates from the consensus or goes offline. This proactive monitoring ensures your portfolio valuations remain accurate and your downstream alerting system functions on trustworthy data. The next step uses this aggregated price stream to compute real-time portfolio balances and equity.
Blockchain Indexer and Data Provider Comparison
Key metrics and capabilities for popular services used to power real-time portfolio monitoring.
| Feature / Metric | The Graph | Covalent | Alchemy | Moralis |
|---|---|---|---|---|
Data Latency | < 1 sec | ~5 sec | < 1 sec | ~3 sec |
Historical Data Depth | Full chain | Full chain | Full chain | 2000 blocks |
Real-time WebSocket API | ||||
Free Tier Queries/Day | 100,000 | 100,000 | 300M CU | 1,000,000 |
Multi-chain Support | ||||
Custom Subgraph/Indexing | ||||
NFT API Support | ||||
Enterprise SLA |
Step 3: Building a Configurable Alert Engine
This guide details how to implement a real-time alerting system for portfolio monitoring using Chainscore's WebSocket API and a serverless backend.
A configurable alert engine requires a backend service that listens for on-chain events and dispatches notifications. The core architecture involves three components: a WebSocket client to subscribe to real-time data feeds from Chainscore, a rules engine to evaluate incoming data against user-defined conditions, and a notification dispatcher to send alerts via email, SMS, or webhook. For this tutorial, we'll build a Node.js service using the @chainscore/chainscore SDK and deploy it on a serverless platform like Vercel or AWS Lambda for scalability and cost-efficiency.
First, establish a connection to the Chainscore WebSocket stream. You'll need your project's API key to authenticate. The following code snippet demonstrates subscribing to wallet activity events for a specific address, such as large token transfers or NFT mints.
javascriptimport { Chainscore } from '@chainscore/chainscore'; const chainscore = new Chainscore({ apiKey: 'YOUR_API_KEY' }); // Subscribe to real-time events for a wallet const subscription = await chainscore.wallets.subscribe({ address: '0x742d35Cc6634C0532925a3b844Bc9e...', eventTypes: ['token_transfer', 'nft_transfer'] }); subscription.on('data', (event) => { console.log('New event:', event); // Pass event to the rules engine evaluateAlertRules(event); });
The rules engine is where you define and evaluate alert conditions. Store user configurations in a database (e.g., PostgreSQL or Supabase) with fields for threshold_amount, token_address, condition (e.g., >, <), and notification_channel. When an event is received, the engine checks it against all active rules. For example, a rule might trigger if a wallet receives more than 10 ETH from a new, previously unseen address—a potential sign of a phishing refund or airdrop scam. Implementing this requires parsing the event's value and from fields.
Finally, the notification dispatcher sends alerts based on the triggered rule. Use services like Twilio for SMS, SendGrid for email, or a simple HTTP POST to a Discord webhook. It's critical to implement rate limiting and alert deduplication to prevent spamming users. For production, consider using a message queue (e.g., Redis Bull) to handle notification jobs asynchronously. This ensures your main event loop isn't blocked by slow third-party API calls, maintaining the real-time responsiveness of your alert system.
To make the engine configurable via a frontend, expose a REST API (e.g., using Next.js API routes) that allows users to create, read, update, and delete their alert rules. Protect these endpoints with authentication. The complete flow is: User sets a rule in UI → Rule saved to DB → WebSocket stream emits event → Rules engine evaluates → Notification dispatched. This setup provides a foundation for monitoring wallet security, DeFi position health, and opportunistic trading signals.
Common Alert Types for Institutional Monitoring
Real-time alerts are critical for institutional portfolio management. This guide covers the essential alert types for monitoring wallet activity, market movements, and protocol health.
Large Transfer Alerts
Monitor for significant asset movements that could indicate portfolio rebalancing, withdrawals, or unauthorized access. Set thresholds based on a percentage of total holdings or a fixed USD value.
- Example: Alert on any transfer exceeding 5% of a wallet's ETH balance.
- Use Case: Detect potential security breaches or the execution of a large OTC trade.
Smart Contract Interaction Alerts
Track interactions with DeFi protocols, NFT marketplaces, or custom contracts. This is essential for monitoring staking, liquidity provision, and governance participation.
- Key to monitor: Contract addresses, function calls (e.g.,
deposit,swap,approve), and gas fees. - Example: Get alerted when a wallet interacts with a new, unaudited lending protocol.
Price and Slippage Alerts
Receive notifications when an asset's price moves beyond a defined threshold or when expected trade execution slippage is too high. Crucial for managing limit orders and liquidation risks.
- Price Alert: Notify if ETH drops below $3,000.
- Slippage Alert: Flag any DEX swap where price impact exceeds 2%.
Liquidation Risk Alerts
For leveraged positions on protocols like Aave or Compound, monitor health factors and loan-to-value (LTV) ratios. Proactive alerts prevent forced liquidations.
- Critical Metric: Alert when a position's health factor falls below 1.5.
- Action: Allows time to add collateral or repay debt to secure the position.
Governance and Staking Alerts
Stay informed about delegation changes, proposal votes, and staking rewards. Ensures active participation in DAOs and proof-of-stake networks.
- Monitor for: Votes cast from delegated wallets, changes to validator nodes, or unclaimed reward thresholds.
- Example: Alert when a governance proposal you delegated votes on is nearing its conclusion.
Anomaly and Behavioral Alerts
Use pattern recognition to flag unusual activity, such as transactions to new addresses, sudden spikes in gas spending, or interactions with known scam contracts.
- Behavioral Baseline: Establish normal activity patterns for each wallet.
- Anomaly Detection: Flag a transaction that is 10x the typical gas fee or a transfer to a blacklisted address.
Step 4: Creating Dashboards and APIs for Stakeholders
Transform raw blockchain data into actionable insights through real-time dashboards and programmatic APIs for stakeholders and automated systems.
A real-time monitoring dashboard is the primary interface for stakeholders to track portfolio performance, risk metrics, and on-chain activity. Tools like Grafana, Superset, or custom React/Vue applications connected to your data warehouse (e.g., PostgreSQL, TimescaleDB) are standard. Key visualizations include: total portfolio value (TVL) over time, asset allocation breakdowns, yield earned across protocols, exposure to specific smart contracts or chains, and gas fee expenditure. Setting alert thresholds for metrics like sudden TVL drops, unusual withdrawal patterns, or missed governance votes turns passive monitoring into proactive risk management.
For programmatic access, you need a secure REST API or GraphQL endpoint. This allows other internal systems (like trading bots or risk engines) and trusted external partners to query portfolio data without direct database access. Using a framework like FastAPI (Python) or Express.js (Node.js), you can create endpoints such as /api/v1/portfolio/value that returns current holdings, or /api/v1/transactions?address=0x... for historical activity. Implement authentication using API keys with scoped permissions and rate limiting to control access and prevent abuse.
The core of both dashboards and APIs is a well-structured data model. Your database should have tables for wallet_balances (snapshots), transactions (with labels for DeFi actions), token_prices, and protocol_interactions. Use materialized views or pre-aggregated tables for performance-critical queries, like calculating hourly portfolio returns. For true real-time alerts, complement batch ETL jobs with streaming pipelines using Kafka or Amazon Kinesis to process new blocks and transactions as they are confirmed, triggering instant notifications via Slack, Discord, or PagerDuty.
Effective alerting requires defining clear, actionable triggers. Examples include: a withdrawal exceeding 20% of portfolio TVL, a position's health factor on a lending protocol dropping below 1.5, or a governance proposal being submitted that affects a held asset. Implement these as scheduled queries or streaming rules that, when triggered, execute a webhook call to your notification service. For developers, providing a webhook endpoint allows stakeholders to receive push notifications of these events directly into their own systems, enabling fully automated response workflows.
Finally, consider data accessibility for different stakeholder groups. A fund manager might need a high-level dashboard, while a smart contract auditor requires a detailed API feed of all incoming/outgoing transactions. Use role-based access control (RBAC) in your API and dashboard to serve tailored data views. Document your APIs using OpenAPI/Swagger and provide example queries for common use cases, such as calculating impermanent loss for a specific liquidity pool position over a given date range.
Essential Tools and Documentation
Tools and protocols developers use to build real-time portfolio monitoring and alerting for onchain assets. Each card focuses on production-grade infrastructure with concrete integration paths.
Setting Up Real-Time Portfolio Monitoring and Alerting
Proactive monitoring is essential for managing risk and capital efficiency in DeFi. This guide explains how to set up automated alerts for wallet activity, protocol health, and market conditions.
Real-time portfolio monitoring tracks on-chain activity across your wallets and deployed smart contracts. Core data points include token balances, pending transactions, liquidity pool positions, debt levels in lending protocols, and governance votes. Services like Chainscore, Tenderly, and DefiLlama aggregate this data, providing a unified dashboard. Setting up monitoring begins with connecting your wallet addresses (EOAs) and contract addresses via API. For developers, tools like the Chainscore API or The Graph allow you to build custom queries that fetch real-time state from protocols like Aave, Uniswap, or Compound.
Automated alerting transforms passive data into actionable intelligence. Critical alerts to configure include: large unexpected outflows, failed transactions exceeding a gas threshold, collateralization ratios dropping below a safe level (e.g., below 150% on MakerDAO), and smart contract admin function calls. For operational security, set up multi-channel notifications: use Telegram or Discord for immediate, high-priority alerts and email for daily summary reports. Tools like OpenZeppelin Defender and Forta can monitor for specific contract events and suspicious transaction patterns, providing an early warning system for potential exploits or operational errors.
To implement a basic balance alert using the Chainscore API, you can set up a cron job that polls for changes. For example, a Node.js script can call the GET /v1/address/{address}/balance endpoint periodically. If the USDC balance falls below a defined threshold, the script can trigger a webhook to a service like PagerDuty or send a message via the Telegram Bot API. Always use environment variables for API keys and sensitive thresholds. For smart contracts, monitor event logs for critical functions; an alert should fire if a RoleGranted or OwnershipTransferred event is emitted without prior multi-sig confirmation.
Beyond wallet-level alerts, monitor the health of the protocols you interact with. Subscribe to governance forums for announcements on parameter changes or upcoming upgrades. Use DeFi Safety scores or Chainscore's Protocol Risk Dashboard to track audits and incident history. Set up alerts for drastic changes in Total Value Locked (TVL) or liquidity depth on your primary DEX pairs, as these can signal rising risk or impending volatility. Combining protocol-level and position-level monitoring creates a defense-in-depth strategy for your digital assets.
Finally, establish clear escalation procedures. Define who receives alerts and their response protocols. Test your alerting system regularly by simulating conditions, such as moving a small amount of tokens to trigger a balance alert. Document the setup and ensure backup maintainers have access. In the fast-moving DeFi environment, the few minutes gained from a well-configured alert can be the difference between a managed response and a significant loss.
Frequently Asked Questions
Common questions and troubleshooting for developers implementing real-time portfolio and alerting systems using on-chain data.
Real-time data latency is typically caused by your data source's indexing speed, not the Chainscore API. Chainscore provides data as soon as it's confirmed on-chain. The delay often originates from the underlying RPC provider or indexer you are using to fetch raw blockchain state.
Common causes and fixes:
- RPC Node Latency: Public RPC endpoints can have high latency. Switch to a dedicated, paid RPC provider from services like Alchemy, Infura, or QuickNode for lower latency and higher reliability.
- Indexing Lag: If you rely on The Graph or another indexing protocol, subgraphs can lag behind the chain head during high activity. Check your subgraph's
_metablock height. - Polling Interval: Your application's polling interval for new data might be too long. For true real-time updates, use WebSocket connections to your RPC provider instead of HTTP polling.
Conclusion and Next Steps
You have now configured a system to track wallet balances and receive real-time alerts. This guide covered the core components, but there are several ways to extend and harden your monitoring setup.
To build upon this foundation, consider implementing more sophisticated alert logic. Instead of simple threshold triggers, you can create alerts based on percentage changes, track specific token ratios within your portfolio, or monitor for unusual transaction patterns like large, unexpected outflows. Integrating with on-chain data providers like The Graph for historical analysis or Tenderly for transaction simulation can provide deeper context for your alerts, helping you distinguish between routine DeFi interactions and potential security events.
For production systems, focus on reliability and security. Move your alerting logic and API keys off the client-side and into a secure backend service. Use environment variables for all sensitive data and implement proper error handling and retry logic for RPC calls. Consider setting up a dedicated monitoring wallet that holds minimal funds, using it to test your alerting pipeline without risking your main assets. Regularly audit the smart contracts of the protocols you interact with, as changes to their code can affect balance calculations.
The next step is automation. Use the alerts as triggers for automated actions. For example, a sharp drop in a liquidity pool's TVL could trigger an automated withdrawal via a smart contract wallet (like Safe) or a bot. You can also connect your monitoring system to portfolio management dashboards (e.g., DeBank, Zapper) via their APIs for a consolidated view. Finally, stay updated on new tools; services like Chainscore offer specialized APIs for real-time balance and transaction monitoring, which can simplify and scale the architecture outlined here.