In the fast-paced world of cryptocurrency, staying informed about price fluctuations is crucial. Manually monitoring prices across various exchanges can be time-consuming and inefficient. Imagine a system that automatically alerts you when the price of your favorite cryptocurrencies hits specific targets – that’s what we’ll build today! This tutorial will guide you through creating a simple, interactive cryptocurrency price alert system using TypeScript, providing you with a practical project to learn and apply fundamental TypeScript concepts.
Why Build a Cryptocurrency Price Alert System?
Beyond the obvious benefit of timely price updates, building this system offers several advantages:
- Practical Application: You’ll learn how to fetch data from APIs, handle asynchronous operations, and work with user input.
- Real-World Relevance: Cryptocurrency is a dynamic market, making this project immediately useful.
- Skill Enhancement: It’s a great way to practice TypeScript fundamentals, including types, interfaces, and classes.
Prerequisites
Before we begin, ensure you have the following:
- Node.js and npm (or yarn) installed: This provides the runtime environment and package manager.
- A text editor or IDE: Such as VS Code, to write and edit your code.
- Basic understanding of JavaScript: TypeScript is a superset of JavaScript, so familiarity with JavaScript syntax is helpful.
Setting Up Your Project
Let’s start by setting up our project directory and initializing it with npm. Open your terminal and run the following commands:
mkdir crypto-alert-system
cd crypto-alert-system
npm init -y
This creates a new directory, navigates into it, and initializes a new Node.js project. Next, we’ll install TypeScript and the necessary dependencies:
npm install typescript --save-dev
npm install @types/node axios --save
typescript: The TypeScript compiler.@types/node: Type definitions for Node.js, allowing TypeScript to understand Node.js modules.axios: A library for making HTTP requests (we’ll use this to fetch cryptocurrency prices).
Now, let’s configure TypeScript. Create a tsconfig.json file in your project root with the following content:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
This configuration specifies how the TypeScript compiler should behave. Key settings include:
target: The JavaScript version to compile to (ES2016).module: The module system (CommonJS).outDir: The output directory for compiled JavaScript files (dist).rootDir: The root directory of your TypeScript source files (src).strict: Enables strict type checking.esModuleInterop: Enables interoperability between CommonJS and ES modules.skipLibCheck: Skips type checking of declaration files.
Project Structure
Create the following directory structure in your project:
crypto-alert-system/
├── src/
│ ├── index.ts
│ └── types.ts
├── dist/
├── node_modules/
├── package.json
├── package-lock.json
└── tsconfig.json
This structure organizes our code logically. The src directory will hold our TypeScript files, and dist will contain the compiled JavaScript. types.ts will hold our type definitions.
Creating Type Definitions
Open src/types.ts and define the types we’ll use for cryptocurrency data:
export interface Cryptocurrency {
symbol: string;
name: string;
price: number;
lastUpdated: Date;
}
export interface Alert {
symbol: string;
targetPrice: number;
alerted: boolean;
}
Here, we define two interfaces:
Cryptocurrency: Represents the data we’ll receive from the API (symbol, name, price, last updated time).Alert: Represents a price alert (symbol, target price, and a boolean to track if the alert has been triggered).
Fetching Cryptocurrency Data
Now, let’s write the code to fetch cryptocurrency prices. Open src/index.ts and add the following code:
import axios from 'axios';
import { Cryptocurrency, Alert } from './types';
const API_URL = 'https://api.coingecko.com/api/v3/simple/price';
async function fetchPrice(symbols: string[]): Promise {
try {
const params = {
ids: symbols.join(','),
vs_currencies: 'usd',
};
const response = await axios.get(API_URL, { params });
const prices: Cryptocurrency[] = Object.keys(response.data).map(symbol => {
const data = response.data[symbol];
return {
symbol: symbol.toUpperCase(),
name: symbol.toUpperCase(), // Replace with actual name from API if available
price: data.usd,
lastUpdated: new Date(),
};
});
return prices;
} catch (error) {
console.error('Error fetching prices:', error);
return [];
}
}
This code does the following:
- Imports the
axioslibrary and our custom types. - Defines the API endpoint.
- Creates an
fetchPricefunction to retrieve price data. This function takes an array of cryptocurrency symbols as input. - Uses
axios.getto make a GET request to the CoinGecko API. The API call constructs a query string with the cryptocurrency symbols and the desired currency (USD). - Parses the response data and maps it to an array of
Cryptocurrencyobjects. - Handles potential errors by logging them to the console.
Setting Up Alerts
Next, let’s implement the logic for setting and managing price alerts. Add the following code to src/index.ts:
let alerts: Alert[] = [];
function setAlert(symbol: string, targetPrice: number): void {
const existingAlert = alerts.find(alert => alert.symbol === symbol);
if (existingAlert) {
console.log(`Alert already set for ${symbol}.`);
return;
}
alerts.push({ symbol, targetPrice, alerted: false });
console.log(`Alert set for ${symbol} at $${targetPrice}.`);
}
function checkAlerts(prices: Cryptocurrency[]): void {
prices.forEach(priceData => {
const alert = alerts.find(alert => alert.symbol === priceData.symbol && !alert.alerted);
if (alert && priceData.price >= alert.targetPrice) {
console.log(`ALERT: ${priceData.symbol} reached $${priceData.price}!`);
alert.alerted = true;
}
});
}
Here’s what this code does:
- Declares an
alertsarray to store our alert configurations. - Defines the
setAlertfunction, which allows users to set new alerts. It checks if an alert already exists for the symbol and prevents duplicates. - Defines the
checkAlertsfunction, which iterates through the fetched price data and checks if any alert conditions have been met. If a price reaches or surpasses the target price, an alert message is printed to the console, and thealertedflag is set totrueto prevent repeated alerts.
Implementing the Main Application Logic
Now, let’s tie everything together. Add the following code to src/index.ts:
async function main() {
const symbols = ['btc', 'eth', 'ada']; // Cryptocurrency symbols to track
// Set initial alerts
setAlert('btc', 30000);
setAlert('eth', 2000);
setAlert('ada', 0.5);
// Fetch and check prices every 10 seconds
setInterval(async () => {
const prices = await fetchPrice(symbols);
if (prices.length > 0) {
checkAlerts(prices);
}
}, 10000);
}
main();
This code does the following:
- Defines an array of cryptocurrency symbols to track.
- Calls the
setAlertfunction to set initial alerts for BTC, ETH, and ADA. You can customize these values to your liking. - Uses
setIntervalto repeatedly fetch and check prices every 10 seconds (10000 milliseconds). - Calls
fetchPriceto get the latest prices. - If prices are successfully fetched, it calls
checkAlertsto see if any alerts have been triggered. - Finally, it calls the main function to start the application.
Compiling and Running Your Application
To compile your TypeScript code to JavaScript, open your terminal and run:
tsc
This command uses the TypeScript compiler (tsc) to translate your .ts files into .js files in the dist directory. Then, run the program using Node.js:
node dist/index.js
You should see the application running, fetching prices, and checking for alerts. When a price reaches a target, an alert message will be printed to the console.
Adding User Input (Optional – Interactive Mode)
To make the application more interactive, let’s add the ability for the user to set alerts from the command line. First, install the readline-sync package:
npm install readline-sync
Then, modify your src/index.ts file as follows:
import axios from 'axios';
import { Cryptocurrency, Alert } from './types';
import * as readlineSync from 'readline-sync';
const API_URL = 'https://api.coingecko.com/api/v3/simple/price';
// ... (fetchPrice, setAlert, checkAlerts functions remain the same)
async function main() {
const symbols = ['btc', 'eth', 'ada']; // Cryptocurrency symbols to track
// Set initial alerts (optional, or comment out if using interactive mode)
// setAlert('btc', 30000);
// setAlert('eth', 2000);
// setAlert('ada', 0.5);
// Interactive mode: Prompt the user for alerts
while (true) {
const symbol = readlineSync.question('Enter cryptocurrency symbol (e.g., btc, eth): ').toLowerCase();
if (symbol === 'exit') break;
const targetPriceStr = readlineSync.question('Enter target price: ');
const targetPrice = parseFloat(targetPriceStr);
if (isNaN(targetPrice)) {
console.log('Invalid price. Please enter a number.');
continue;
}
setAlert(symbol, targetPrice);
}
// Fetch and check prices every 10 seconds
setInterval(async () => {
const prices = await fetchPrice(symbols);
if (prices.length > 0) {
checkAlerts(prices);
}
}, 10000);
}
main();
Here’s what we added:
- Imported the
readline-syncmodule. - Added a
whileloop to prompt the user for input. - Uses
readlineSync.questionto get user input for the cryptocurrency symbol and target price. - Validates the input to ensure the price is a number.
- Calls
setAlertwith the user-provided values. - Adds an “exit” option to gracefully terminate the interactive input.
Now, when you run node dist/index.js, you’ll be prompted to enter cryptocurrency symbols and target prices. The application will then monitor the prices and alert you when your targets are met.
Common Mistakes and Troubleshooting
Here are some common mistakes and how to fix them:
- Incorrect API URL: Double-check the API URL. Errors in the URL will prevent the application from fetching data.
- Incorrect Symbol Names: Ensure you are using the correct cryptocurrency symbols (e.g., ‘btc’, ‘eth’, ‘ada’).
- Type Errors: TypeScript’s type checking can help prevent errors. Make sure your types are correctly defined and used. If you encounter type errors, carefully review the error messages and fix the type mismatches.
- Network Issues: Ensure you have a stable internet connection. Network problems can prevent the application from fetching data.
- API Rate Limits: Some APIs have rate limits. If you exceed the rate limits, you may receive errors. Consider implementing error handling and potentially adding delays to your requests.
- Incorrect Installation: Make sure you have installed all the necessary packages using npm or yarn.
Key Takeaways
In this tutorial, we’ve built a functional cryptocurrency price alert system using TypeScript. You’ve learned how to:
- Set up a TypeScript project.
- Fetch data from an API using
axios. - Define and use custom types and interfaces.
- Implement logic for setting and checking alerts.
- Use
setIntervalfor periodic data updates. - (Optional) Add user input using
readline-sync.
FAQ
Q: How can I add more cryptocurrencies to track?
A: Simply add the symbol to the symbols array and set alerts for those currencies. If using interactive mode, you can enter the symbol when prompted.
Q: How can I change the alert frequency?
A: Adjust the interval in the setInterval function (e.g., 10000 for 10 seconds, 60000 for 1 minute).
Q: How do I handle API errors?
A: The fetchPrice function includes basic error handling using a try...catch block. You can expand this to handle specific error codes or implement retry mechanisms.
Q: How can I persist alerts across sessions?
A: You would need to store the alerts in a database or a file (e.g., using JSON) and load them when the application starts. This is beyond the scope of this basic tutorial but is a common extension.
Enhancements and Next Steps
This is a solid foundation, and you can extend this project in many ways:
- Add more features: Implement email or SMS notifications when alerts are triggered.
- Improve UI: Create a more user-friendly interface using a framework like React or Angular.
- Data persistence: Save and load alerts from a file or database.
- Error handling: Implement more robust error handling and API rate limit management.
- Advanced alerts: Add support for different alert conditions (e.g., percentage changes, moving averages).
- Use a different API: Experiment with other cryptocurrency APIs to compare data and features.
Building this cryptocurrency price alert system provides a practical and engaging way to learn TypeScript and apply your knowledge to a real-world problem. The principles you’ve learned here can be applied to many other projects, making it a valuable addition to your programming skillset. The ability to monitor dynamic data and react to changes programmatically is a powerful skill, and this project gives you the tools to begin exploring that capability.
