this a repo that acts as a template for creating servelerless agents with cloudflare kv. It has scheduled jobs but also interacts with incoming webhooks. It has actions, which provide context for the llm. A user may message the llm on telegram and ask for financial data using /finan and the llm will respoond with a message geenrated using the data. scheduled jobs can also run actions. finan example action: /**
Financial Analysis Action
This action analyzes trending cryptocurrency pools on the Base network using the GeckoTerminal API.
It provides financial metrics and technical analysis including:
Market stats (FDV, Volume, Price Change)
Technical indicators (RSI, MACD, Momentum)
Volume trends
Trigger: Messages containing "/finan" or can set schedule in ./src/jobs/
*/
import { Action } from './base';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
// Get technical analysis for top performer
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
Assistant
User
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// Format the data for the LLM
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
/**
Fetches trending pools from GeckoTerminal API
Returns array of pool data or empty array if fetch fails
*/
private async fetchTrendingPools() {
try {
const response = await fetch(${this.GECKOTERMINAL_BASE_URL}/networks/base/trending_pools?page=1&duration=24h);
const data = await response.json();
return data.data || [];
} catch (error) {
Logger.error('Error fetching trending pools:', error);
return [];
}
}
/**
Finds the top performing pool based on 24h price change
*/
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
/**
Fetches and calculates technical indicators for a given pool
// Only calculate metrics if we have enough data
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
} catch (error) {
Logger.error('Error calculating technicals:', error);
return {} as TechnicalAnalysis;
}
}
/**
Calculates RSI using 14-period lookback
*/
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
code
let gains = 0;
code
let losses = 0;
// Calculate initial average gain and loss
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
// Calculate RSI using smoothed averages
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
[task]
Look through the codebase and understand the intent. embodying the persona and knowledge of a cf worker and TS expert, suggest a way to make the codebase more elegant and fit for purpose. remember users will fork this codebase to use as a template for their own agents, with its own actions etc. We want to keep it as modular as possible with all functionality in core. only things user should have to change is index.ts, adding their own actions, and character.json. If you think this could be done more elegantly without losing its capability, suggest the new codebase design with code changes and directory structure. make it elegant, simple, and lean, minimise duplicate code but not at the cost of capability (responding to webhooks, running scheduled jobs, hooking in actions if needed)
your changes must be easy to read and follow, so i can implement them, explain how it is more elegant, with less code and still maintains a good template.
Okay, I've thoroughly reviewed the provided code for the serverless agent template. As a Cloudflare worker and TypeScript expert, I see a good foundation here, but also areas where we can significantly enhance its elegance, modularity, and ease of use for users looking to fork and customize it.
Current Architecture and its Shortcomings
The existing structure has a good separation of concerns with actions, a core directory for types, logging etc. However, there's a bit of coupling and potential for repetition, especially when it comes to fetching, error handling, and structuring responses, that could be made more uniform.
Proposed Enhanced Architecture
The core principle behind these improvements is to move all shared functionalities into the core directory, making actions simpler to write, and keeping the main worker file (index.ts) cleaner. This makes it much easier for users to understand where to modify things.
src/jobs/scheduled_job.ts: Example of a scheduled job running an action, more generic with message.
typescript
// src/jobs/scheduled_job.ts
import { Logger } from '../core/logger';
import { FinancialAnalysisAction } from '../actions/finan';
export async function scheduledJob() {
Logger.info('Running scheduled job');
const financialAnalysisAction = new FinancialAnalysisAction();
const analysis = await financialAnalysisAction.getMarketAnalysis();
if(analysis){
Logger.info('Market analysis: ', analysis);
//TODO: Send somewhere?
}else{
Logger.warn('No trending pool to analyze.');
}
}
src/index.ts: Main worker entrypoint, simplified action handling and scheduled job triggering.
typescript
// src/index.ts
import { Logger } from './core/logger';
import { Message, ActionResult } from './core/types';
import { FinancialAnalysisAction } from './actions/finan';
import { scheduledJob } from './jobs/scheduled_job';
// Define your character
const character = require('../character.json')
// Initialize actions
const actions = [
new FinancialAnalysisAction(),
// Add other actions here
];
async function handleWebhook(request: Request): Promise<Response> {
try {
if(request.method !== "POST"){
return new Response("Method not allowed",{status:405});
}
const body = await request.json() as any;
const message:Message = {
text:body.message?.text,
//Add other properties here
};
const action = actions.find(a => a.shouldExecute(message));
if (action) {
Logger.info(`Executing action: ${action.name}`);
const result = await action.execute(message);
return handleActionResult(result);
} else {
return new Response("No matching action found.", { status: 404 });
}
} catch (error) {
Logger.error('Error handling webhook:', error);
return new Response("Internal Server Error",{status:500});
}
}
function handleActionResult(result: ActionResult): Response {
if(result.shouldSendMessage){
const responseMessage = buildResponse(result.text, result.context || null);
return new Response(JSON.stringify(responseMessage), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}else{
return new Response('ok',{status:200})
}
}
function buildResponse(message:string, context:string|null){
return {
message,
character: {
name:character.name,
description:character.description,
context
},
}
}
async function handleScheduled(event: ScheduledController) {
Logger.info(`Scheduled event at: ${new Date().toISOString()}`);
await scheduledJob();
}
export default {
async fetch(request: Request): Promise<Response> {
if(request.method === "POST"){
return handleWebhook(request);
}
return new Response('ok')
},
scheduled: handleScheduled,
};
Key Improvements:
Modularity: All shared logic is in the core directory. Actions are now lean and focused on their specific task.
DRY (Don't Repeat Yourself): API interaction, error handling, and data formatting is now centralized reducing boilerplate code in the actions.
Readability: The codebase is easier to navigate and understand, making it more approachable for new users.
Extensibility: Adding a new action just requires creating a file inside actions folder, and adding it to the actions array in index.ts.
Testability: By moving shared logic to core, it becomes easier to write unit tests.
Simplicity: The structure is now more intuitive for those new to the project.
How to Use:
Fork and Clone: Fork the repository and clone it to your local machine.
Install dependencies: Run npm install
Create Actions: Add new action files to the src/actions/ directory extending the base Action class, then add this to the actions array in index.ts.
Modify character.json: Modify the namedescription and the context that the llm will use.
Modify index.ts: If your worker will be doing something else, you can modify the index.ts file.
Deploy to Cloudflare Workers: Use Wrangler or another method to deploy your worker.
Why This is More Elegant
This refactored architecture is more elegant because it adheres to the principles of good software design:
Single Responsibility Principle: Each module or class has one specific job.
Open/Closed Principle: The core is open for extension but closed for modification, you can add actions without changing core files.
Separation of Concerns: Each part of the application has its own distinct task.
This approach creates a leaner, cleaner codebase, which is easier to maintain, extend, and understand, making it an ideal template for users wanting to quickly create serverless agents on Cloudflare.
I apprecite you want to centralise api calls, but this will not work, as some data comes form api, but needs headers, cookies, or scrapes a webpage. check these example actions i mad ethat show you this:
/**
Financial Analysis Action
This action analyzes trending cryptocurrency pools on the Base network using the GeckoTerminal API.
It provides financial metrics and technical analysis including:
Market stats (FDV, Volume, Price Change)
Technical indicators (RSI, MACD, Momentum)
Volume trends
Trigger: Messages containing "/finan" or can set schedule in ./src/jobs/
*/
import { Action } from './base';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
// Get technical analysis for top performer
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
// Format the data for the LLM
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
/**
Fetches trending pools from GeckoTerminal API
Returns array of pool data or empty array if fetch fails
*/
private async fetchTrendingPools() {
try {
const response = await fetch(${this.GECKOTERMINAL_BASE_URL}/networks/base/trending_pools?page=1&duration=24h);
const data = await response.json();
return data.data || [];
} catch (error) {
Logger.error('Error fetching trending pools:', error);
return [];
}
}
/**
Finds the top performing pool based on 24h price change
*/
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
/**
Fetches and calculates technical indicators for a given pool
// Only calculate metrics if we have enough data
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
} catch (error) {
Logger.error('Error calculating technicals:', error);
return {} as TechnicalAnalysis;
}
}
/**
Calculates RSI using 14-period lookback
*/
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
code
let gains = 0;
code
let losses = 0;
// Calculate initial average gain and loss
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
// Calculate RSI using smoothed averages
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
if (!flowsData) {
return {
text: "Could not fetch ETF flows data.",
shouldSendMessage: true,
context: "Error fetching ETF data."
};
}
return {
text: flowsData,
shouldSendMessage: true,
context: `You are a cryptocurrency market analyst. Create a concise and brief analysis of the ETF flows data for both BTC and ETH ETFs. Focus on significant inflows/outflows and their potential market impact. Keep the response under 300 characters. No emojis. Use a professional tone. Include total flows for both BTC and ETH.`
};
} catch (error) {
Logger.error('Failed to analyze ETF flows:', error);
return {
text: "Sorry, I encountered an error while analyzing ETF flows.",
shouldSendMessage: true,
context: "Error occurred during ETF analysis."
};
}
}
/**
Fetches and analyzes ETF flows data
Can be called directly by scheduled jobs
*/
async getETFFlowsAnalysis(): Promise<string | null> {
try {
const [btcData, ethData] = await Promise.all([
this.fetchETFData('btc'),
this.fetchETFData('eth')
]);
const response = await fetch(urls[type]);
const text = await response.text();
// Split into lines
const lines = text.split('\n');
// Find the ticker line first (contains IBIT/FBTC for BTC or EETH/BRRR for ETH)
const tickerLine = type === 'btc'
? lines.find(line => line.includes('IBIT') || line.includes('FBTC'))
: lines.find(line => line.includes('ETHA') || line.includes('FETH'));
if (!tickerLine) {
Logger.error(`No ticker line found for ${type}`);
return null;
}
// Extract tickers
const tickers = tickerLine.split('|')
.map(t => t.trim())
.filter(Boolean);
// Find the first data line after the ticker line
let dataStartIndex = lines.indexOf(tickerLine);
let latestDataLine = '';
// Look for the first line with a date after the ticker line
for (let i = dataStartIndex; i < lines.length; i++) {
const line = lines[i];
if (line.includes('|')) {
const cells = line.split('|').map(cell => cell.trim());
// Check if this is a data line (has a date)
if (cells[1]?.match(/\d{2}\s+Dec\s+2024/)) {
latestDataLine = line;
break;
}
}
}
if (!latestDataLine) {
Logger.error(`No data line found for ${type}`);
return null;
}
// Parse the data line
const cells = latestDataLine.split('|').map(cell => cell.trim()).filter(Boolean);
const date = cells[0];
const flows: { [key: string]: number } = {};
let total = 0;
// Process each flow value
for (let i = 1; i < cells.length - 1; i++) {
let value = cells[i];
if (value === '-') continue;
// Remove commas and handle parentheses for negative numbers
value = value.replace(/,/g, '');
const flow = value.startsWith('(')
? -parseFloat(value.slice(1, -1))
: parseFloat(value);
if (!isNaN(flow)) {
// Map the column index to the correct ticker
const tickerIndex = i - 1;
if (tickerIndex < tickers.length) {
flows[tickers[tickerIndex]] = flow;
total += flow;
}
}
}
// Use the last cell as total if it's a valid number
const lastCell = cells[cells.length - 1];
if (lastCell && lastCell !== '-') {
const parsedTotal = parseFloat(lastCell.replace(/,/g, ''));
if (!isNaN(parsedTotal)) {
total = parsedTotal;
}
}
return { date, flows, total };
} catch (error) {
Logger.error(`Error fetching ${type} ETF data:`, error);
return null;
}
}
import { Logger } from '../core/logger';
import type { Env } from '../core/types';
export class SaraDataAction {
private env: Env;
code
setEnv(env: Env) {
this.env = env;
}
// Placeholder for future data gathering methods
async getMarketData(): Promise<string | null> {
// TODO: Implement real data gathering
Logger.info('SARA market data gathering not yet implemented');
return null;
}
async getEconomicData(): Promise<string | null> {
// TODO: Implement real data gathering
Logger.info('SARA economic data gathering not yet implemented');
return null;
}
}
[task]
rethink your approach. think from an elegant but simple and easy to read perspective. this prioritises suers who want to use the template, their ability to understand how to use it, and its elegant directory and code design. Dont sacrifice any current capability. make the scheduler and jobs elegant to define a new job in the jobs dir, but without the need for the other file. same for actions base and index. most logic should be in core.
Okay, you're absolutely right to call out the limitations of my previous approach regarding API calls, headers, cookies, and web scraping. I got carried away with centralization and didn't account for the varied needs of different actions. Thank you for providing those example actions; they're very helpful in understanding the real-world complexities.
Let's rethink this, prioritizing a more flexible and user-friendly approach while keeping elegance, simplicity, and ease of use as our guiding principles.
Revised Architecture
The core idea here is to make core provide powerful tools, but not to enforce a specific way to use them. We will move away from a central Api class to providing helper functions and utilities in the core directory, this allows users to use standard fetch with any headers, cookies, or other configurations, but also keeps some helper functions centralised, we also make actions easier to create, and more flexible, and move the scheduler to core.
7. src/actions/finan.ts: Refactored financial analysis action.
```typescript
// src/actions/finan.ts
import { Action } from '../core/action';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
import { http } from '../core/http';
import { formatUSD } from '../core/utils';
code
8. src/actions/etf.ts: ETF flows analysis action.
```typescript
import { Action } from '../core/action';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
import { http } from '../core/http';
code
9. src/actions/macro.ts: Macro economic analysis action.
```typescript
import { Action } from '../core/action';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
import { http } from '../core/http';
code
10. src/jobs/scheduled_job.ts: Example of a scheduled job running an action, more generic with message.
```typescript
// src/jobs/scheduled_job.ts
import { Logger } from '../core/logger';
import { FinancialAnalysisAction } from '../actions/finan';
import { scheduler } from '../core/scheduler';
11. src/index.ts: Main worker entrypoint, simplified action handling and scheduled job triggering.
```typescript
// src/index.ts
import { Logger } from './core/logger';
import { Message, ActionResult, Env } from './core/types';
import { FinancialAnalysisAction } from './actions/finan';
import { ETFFlowsAction } from './actions/etf';
import { MacroAction } from './actions/macro';
import { scheduler } from './core/scheduler';
code
// Define your character
const character = require('../character.json')
// Initialize actions
const actions = [
new FinancialAnalysisAction(),
new ETFFlowsAction(),
new MacroAction(),
// Add other actions here
];
async function handleWebhook(request: Request, env:Env): Promise<Response> {
try {
if(request.method !== "POST"){
return new Response("Method not allowed",{status:405});
}
const body = await request.json() as any;
const message:Message = {
text:body.message?.text,
//Add other properties here
};
const action = actions.find(a => a.shouldExecute(message));
if (action) {
Logger.info(`Executing action: ${action.name}`);
const result = await action.execute(message, env);
return handleActionResult(result);
} else {
return new Response("No matching action found.", { status: 404 });
}
} catch (error) {
Logger.error('Error handling webhook:', error);
return new Response("Internal Server Error",{status:500});
}
}
function handleActionResult(result: ActionResult): Response {
if(result.shouldSendMessage){
const responseMessage = buildResponse(result.text, result.context || null);
return new Response(JSON.stringify(responseMessage), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}else{
return new Response('ok',{status:200})
}
}
function buildResponse(message:string, context:string|null){
return {
message,
character: {
name:character.name,
description:character.description,
context
},
}
}
export default {
async fetch(request: Request, env:Env): Promise<Response> {
if(request.method === "POST"){
return handleWebhook(request, env);
}
return new Response('ok')
},
scheduled: (event: ScheduledController) => scheduler.handleScheduled(event),
};
```
Key Changes and Explanations:
http.ts: provides helper get function that does basic error checking. This is imported by actions as needed, giving full flexibility for headers, cookies, and other configurations.
Action Flexibility: Each action is now completely independent in how it fetches its data, while still using a common base and core functionality, allowing them to handle more complex scenarios.
scheduler.ts: The scheduler is now in core, to add a job, you can now just import the scheduler, and run scheduler.addJob('jobname', async() => { ...job });
Simplified Action Creation: To add a new action, just create a new file in src/actions/, extend Action, and add it to the actions array in index.ts.
No More Central API Class: No more central API class, but a helpful HTTP function, giving actions full control over their data fetching.
Environmental Variables: Actions can now accept an optional env parameter in execute to gain access to secrets if needed.
Why This is Better:
Flexibility: No limitations are imposed on how actions fetch data, so they can handle different APIs, web scraping, and authentication needs.
Simplicity: Actions are still easy to create, but now have more power without being limited to a central api class.
Elegance:
// src/actions/finan.ts
import { Action } from '../core/action';
import type { Message, ActionResult } from '../core/types';
import { Logger } from '../core/logger';
import { Api } from '../core/api';
import { formatUSD } from '../core/utils';
interface TechnicalAnalysis {
rsi: number;
macd: {
macd: number;
signal: number;
histogram: number;
};
momentum: number;
volumeTrend: number;
}
interface OHLCVData {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
export class FinancialAnalysisAction extends Action {
private readonly GECKOTERMINAL_BASE_URL = 'https://api.geckoterminal.com/api/v2';
private api = new Api(this.GECKOTERMINAL_BASE_URL);
constructor() {
super('financial', 'Analyzes financial data for crypto pools');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/finan') ?? false;
}
async execute(message: Message): Promise<ActionResult> {
try {
Logger.info('Starting financial analysis');
const trendingPools = await this.fetchTrendingPools();
const topPerformer = this.findTopPerformer(trendingPools);
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: `You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name`
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
private async fetchTrendingPools() {
const data = await this.api.get<{ data: any[] }>(
'networks/base/trending_pools',
{ page: '1', duration: '24h' }
);
return data?.data || [];
}
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
private async analyzeTechnicals(poolAddress: string): Promise<TechnicalAnalysis> {
const data = await this.api.get<{data:{attributes:{ohlcv_list:number[][]}}}>(
`networks/base/pools/${poolAddress}/ohlcv/hour`,
{ limit: '168' }
);
if(!data?.data?.attributes?.ohlcv_list){
return {} as TechnicalAnalysis
}
const ohlcv: OHLCVData[] = data.data.attributes.ohlcv_list.map((item: number[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5]
}));
const result: Partial<TechnicalAnalysis> = {};
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
}
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
let gains = 0;
let losses = 0;
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
}
private calculateMACD(data: OHLCVData[]): { macd: number; signal: number; histogram: number } {
const closePrices = data.map(d => d.close);
const ema12 = this.calculateEMA(closePrices, 12);
const ema26 = this.calculateEMA(closePrices, 26);
const macdLine = ema12 - ema26;
const signalLine = this.calculateEMA([macdLine], 9);
return {
macd: macdLine,
signal: signalLine,
histogram: macdLine - signalLine
};
}
private calculateEMA(data: number[], period: number): number {
const multiplier = 2 / (period + 1);
let ema = data[0];
for (let i = 1; i < data.length; i++) {
ema = (data[i] - ema) * multiplier + ema;
}
return ema;
}
private calculateMomentum(data: OHLCVData[]): number {
if (data.length < 2) return 0;
const currentPrice = data[data.length - 1].close;
const previousPrice = data[0].close;
return ((currentPrice - previousPrice) / previousPrice) * 100;
}
private calculateVolumeTrend(data: OHLCVData[]): number {
if (data.length < 24) return 0;
const recentVolume = data.slice(-12).reduce((sum, d) => sum + d.volume, 0) / 12;
const previousVolume = data.slice(-24, -12).reduce((sum, d) => sum + d.volume, 0) / 12;
return ((recentVolume - previousVolume) / previousVolume) * 100;
}
private formatAnalysis(pool: any, analysis: TechnicalAnalysis): string {
let output = `Financial Analysis for ${pool.attributes.name}\n\n` +
`Market Stats:\n` +
`• FDV: ${formatUSD(pool.attributes.fdv_usd)}\n` +
`• 24h Volume: ${formatUSD(pool.attributes.volume_usd.h24)}\n` +
`• 24h Change: ${pool.attributes.price_change_percentage.h24}%\n`;
const indicators: string[] = [];
if ('rsi' in analysis) {
const rsiInterpretation = analysis.rsi > 70 ? 'Overbought' : analysis.rsi < 30 ? 'Oversold' : 'Neutral';
indicators.push(`• RSI (14): ${analysis.rsi.toFixed(2)} (${rsiInterpretation})`);
}
if ('macd' in analysis) {
const macdSignal = analysis.macd.histogram > 0 ? 'Bullish' : 'Bearish';
indicators.push(`• MACD Signal: ${macdSignal}`);
}
if ('momentum' in analysis) {
indicators.push(`• Price Momentum: ${analysis.momentum.toFixed(2)}%`);
}
if ('volumeTrend' in analysis) {
indicators.push(`• Volume Trend: ${analysis.volumeTrend > 0 ? 'up' : 'down'} ${Math.abs(analysis.volumeTrend).toFixed(2)}%`);
}
if (indicators.length > 0) {
output += '\nTechnical Indicators:\n' + indicators.join('\n');
}
output += `\n\nContract: ${pool.attributes.address}`;
return output;
}
async getMarketAnalysis(): Promise<string | null> {
try {
const pool = await this.getTrendingPool();
if (!pool) {
return null;
}
const analysis = await this.performTechnicalAnalysis(pool);
return this.formatAnalysis(pool, analysis);
} catch (error) {
Logger.error('Error getting market analysis:', error);
return null;
}
}
private async getTrendingPool() {
const trendingPools = await this.fetchTrendingPools();
return this.findTopPerformer(trendingPools);
}
private async performTechnicalAnalysis(pool: any) {
return await this.analyzeTechnicals(pool.attributes.address);
}
}
index.ts is now the single point of entry, handling both webhooks and scheduled events. It uses the actions array to handle any action and then builds a standard response.
constructor() {
super('macro', 'Analyzes global macro economic data');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/macro') ?? false;
}
private cleanTable(rawTable: string): EconomicData[] {
const lines = rawTable.split('\n');
const data: EconomicData[] = [];
// Find the start of the data table
const tableStartIndex = lines.findIndex(line => line.includes('| Country |'));
if (tableStartIndex === -1) return [];
// Skip the header and separator rows
let currentLine = tableStartIndex + 2;
// Process data rows
while (currentLine < lines.length) {
const line = lines[currentLine];
if (!line.includes('|') || line.includes('Trading Economics provides')) break;
const columns = line.split('|').map(col => col.trim());
if (columns.length < 10) {
currentLine++;
continue;
}
// Remove URLs and brackets from country name
const countryMatch = columns[1].match(/\[(.*?)\]/);
if (!countryMatch) {
currentLine++;
continue;
}
const country = countryMatch[1];
// Convert string values to numbers, removing brackets and URLs
const cleanNumber = (str: string) => {
const match = str.match(/\[(.*?)\]/);
if (!match) return NaN;
return parseFloat(match[1]);
};
data.push({
country,
gdp: cleanNumber(columns[2]),
gdpGrowth: cleanNumber(columns[3]),
interestRate: cleanNumber(columns[4]),
inflationRate: cleanNumber(columns[5]),
joblessRate: cleanNumber(columns[6]),
govBudget: cleanNumber(columns[7]),
debtToGdp: cleanNumber(columns[8]),
currentAccount: cleanNumber(columns[9]),
population: cleanNumber(columns[10])
});
currentLine++;
}
return data;
}
private formatMacroData(data: EconomicData[]): string {
return data.map(country =>
`${country.country}:\n` +
`• GDP: $${country.gdp}B\n` +
`• GDP Growth: ${country.gdpGrowth}%\n` +
`• Interest Rate: ${country.interestRate}%\n` +
`• Inflation: ${country.inflationRate}%\n` +
`• Unemployment: ${country.joblessRate}%\n` +
`• Debt/GDP: ${country.debtToGdp}%\n` +
(country.currentAccount ? `• Current Account: ${country.currentAccount}%\n` : '') +
`• Population: ${country.population}M`
).join('\n\n');
}
async getMacroAnalysis(): Promise<string | null> {
try {
const response = await fetch(this.MACRO_URL);
if (!response.ok) {
throw new Error(`Failed to fetch macro data: ${response.statusText}`);
}
const rawText = await response.text();
const economicData = this.cleanTable(rawText);
if (economicData.length === 0) {
return null;
}
return this.formatMacroData(economicData);
} catch (error) {
Logger.error('Error getting macro analysis:', error);
return null;
}
}
async getRawMacroData(): Promise<string | null> {
return await this.getMacroAnalysis();
}
async execute(message: Message): Promise<ActionResult> {
try {
Logger.info('Starting macro economic analysis');
const macroData = await this.getMacroAnalysis();
if (!macroData) {
return {
text: "Could not fetch macro economic data.",
shouldSendMessage: true,
context: "Error fetching macro data."
};
}
// Ensure data fits within Telegram's limit (4096 chars)
const truncatedData = macroData.length > 2000 ? macroData.slice(0, 1997) + '...' : macroData;
return {
shouldSendMessage: true,
context: `You are a macro economic analyst. Analyze this global economic data and provide insights:
Please provide:
1. Overview of global economic conditions
2. Notable trends in GDP growth and inflation
3. Concerns or risks in specific regions
4. Comparison between major economies
5. Recommendations for economic outlook
Focus on key insights that would be relevant for investment and policy decisions.
Keep the response concise and under 2000 characters.
Data:
${truncatedData}`,
text: "Analyzing global economic data..."
};
} catch (error) {
Logger.error('Failed to analyze macro economic data:', error);
return {
text: "Sorry, I encountered an error while analyzing the economic data.",
shouldSendMessage: true,
context: "Error occurred during macro analysis."
};
}
}
interface TechnicalAnalysis {
rsi: number;
macd: {
macd: number;
signal: number;
histogram: number;
};
momentum: number;
volumeTrend: number;
}
interface OHLCVData {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
export class FinancialAnalysisAction extends Action {
private readonly GECKOTERMINAL_BASE_URL = 'https://api.geckoterminal.com/api/v2';
constructor() {
super('financial', 'Analyzes financial data for crypto pools');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/finan') ?? false;
}
async execute(message: Message, env?:any): Promise<ActionResult> {
try {
Logger.info('Starting financial analysis');
const trendingPools = await this.fetchTrendingPools();
const topPerformer = this.findTopPerformer(trendingPools);
if (!topPerformer) {
return {
text: "Could not find any trending pools to analyze.",
shouldSendMessage: true,
context: "No trending pools found to analyze."
};
}
const analysis = await this.analyzeTechnicals(topPerformer.attributes.address);
const formattedData = this.formatAnalysis(topPerformer, analysis);
return {
text: formattedData,
shouldSendMessage: true,
context: `You are a cryptocurrency market analyst you reply with short and concise responses with the pool name. Analyze the following market data and provide insights in a clear, informative way that is short. Focus on key metrics, trends, and what they might indicate. Explain what the technical indicators suggest about future price movements include the token name. Short messages max 300 characters. Do not use emojis. The post must start with the pool name`
};
} catch (error) {
Logger.error('Failed to perform financial analysis:', error);
return {
text: "Sorry, I encountered an error while analyzing the market data.",
shouldSendMessage: true,
context: "Error occurred during financial analysis."
};
}
}
private async fetchTrendingPools() {
const response = await http.get(
`${this.GECKOTERMINAL_BASE_URL}/networks/base/trending_pools?page=1&duration=24h`
)
if(!response) return [];
const data = await response.json() as { data: any[] };
return data?.data || [];
}
private findTopPerformer(pools: any[]) {
return pools.reduce((top: any, current: any) => {
const currentChange = parseFloat(current.attributes.price_change_percentage.h24 || '0');
const topChange = top ? parseFloat(top.attributes.price_change_percentage.h24 || '0') : -Infinity;
return currentChange > topChange ? current : top;
}, null);
}
private async analyzeTechnicals(poolAddress: string): Promise<TechnicalAnalysis> {
const response = await http.get(
`${this.GECKOTERMINAL_BASE_URL}/networks/base/pools/${poolAddress}/ohlcv/hour?limit=168`
)
if(!response) return {} as TechnicalAnalysis
const data = await response.json() as { data: { attributes: { ohlcv_list: number[][] } } };
if(!data?.data?.attributes?.ohlcv_list){
return {} as TechnicalAnalysis
}
const ohlcv: OHLCVData[] = data.data.attributes.ohlcv_list.map((item: number[]) => ({
timestamp: item[0],
open: item[1],
high: item[2],
low: item[3],
close: item[4],
volume: item[5]
}));
const result: Partial<TechnicalAnalysis> = {};
if (ohlcv.length >= 14) {
result.rsi = this.calculateRSI(ohlcv);
}
if (ohlcv.length >= 26) {
result.macd = this.calculateMACD(ohlcv);
}
if (ohlcv.length >= 2) {
result.momentum = this.calculateMomentum(ohlcv);
}
if (ohlcv.length >= 24) {
result.volumeTrend = this.calculateVolumeTrend(ohlcv);
}
return result as TechnicalAnalysis;
}
private calculateRSI(data: OHLCVData[]): number {
const period = 14;
if (data.length < period + 1) return 0;
let gains = 0;
let losses = 0;
for (let i = 1; i <= period; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) gains += change;
else losses -= change;
}
let avgGain = gains / period;
let avgLoss = losses / period;
for (let i = period + 1; i < data.length; i++) {
const change = data[i].close - data[i - 1].close;
if (change >= 0) {
avgGain = (avgGain * 13 + change) / period;
avgLoss = (avgLoss * 13) / period;
} else {
avgGain = (avgGain * 13) / period;
avgLoss = (avgLoss * 13 - change) / period;
}
}
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
}
private calculateMACD(data: OHLCVData[]): { macd: number; signal: number; histogram: number } {
const closePrices = data.map(d => d.close);
const ema12 = this.calculateEMA(closePrices, 12);
const ema26 = this.calculateEMA(closePrices, 26);
const macdLine = ema12 - ema26;
const signalLine = this.calculateEMA([macdLine], 9);
return {
macd: macdLine,
signal: signalLine,
histogram: macdLine - signalLine
};
}
private calculateEMA(data: number[], period: number): number {
const multiplier = 2 / (period + 1);
let ema = data[0];
for (let i = 1; i < data.length; i++) {
ema = (data[i] - ema) * multiplier + ema;
}
return ema;
}
private calculateMomentum(data: OHLCVData[]): number {
if (data.length < 2) return 0;
const currentPrice = data[data.length - 1].close;
const previousPrice = data[0].close;
return ((currentPrice - previousPrice) / previousPrice) * 100;
}
private calculateVolumeTrend(data: OHLCVData[]): number {
if (data.length < 24) return 0;
const recentVolume = data.slice(-12).reduce((sum, d) => sum + d.volume, 0) / 12;
const previousVolume = data.slice(-24, -12).reduce((sum, d) => sum + d.volume, 0) / 12;
return ((recentVolume - previousVolume) / previousVolume) * 100;
}
private formatAnalysis(pool: any, analysis: TechnicalAnalysis): string {
let output = `Financial Analysis for ${pool.attributes.name}\n\n` +
`Market Stats:\n` +
`• FDV: ${formatUSD(pool.attributes.fdv_usd)}\n` +
`• 24h Volume: ${formatUSD(pool.attributes.volume_usd.h24)}\n` +
`• 24h Change: ${pool.attributes.price_change_percentage.h24}%\n`;
const indicators: string[] = [];
if ('rsi' in analysis) {
const rsiInterpretation = analysis.rsi > 70 ? 'Overbought' : analysis.rsi < 30 ? 'Oversold' : 'Neutral';
indicators.push(`• RSI (14): ${analysis.rsi.toFixed(2)} (${rsiInterpretation})`);
}
if ('macd' in analysis) {
const macdSignal = analysis.macd.histogram > 0 ? 'Bullish' : 'Bearish';
indicators.push(`• MACD Signal: ${macdSignal}`);
}
if ('momentum' in analysis) {
indicators.push(`• Price Momentum: ${analysis.momentum.toFixed(2)}%`);
}
if ('volumeTrend' in analysis) {
indicators.push(`• Volume Trend: ${analysis.volumeTrend > 0 ? 'up' : 'down'} ${Math.abs(analysis.volumeTrend).toFixed(2)}%`);
}
if (indicators.length > 0) {
output += '\nTechnical Indicators:\n' + indicators.join('\n');
}
output += `\n\nContract: ${pool.attributes.address}`;
return output;
}
async getMarketAnalysis(): Promise<string | null> {
try {
const pool = await this.getTrendingPool();
if (!pool) {
return null;
}
const analysis = await this.performTechnicalAnalysis(pool);
return this.formatAnalysis(pool, analysis);
} catch (error) {
Logger.error('Error getting market analysis:', error);
return null;
}
}
private async getTrendingPool() {
const trendingPools = await this.fetchTrendingPools();
return this.findTopPerformer(trendingPools);
}
private async performTechnicalAnalysis(pool: any) {
return await this.analyzeTechnicals(pool.attributes.address);
}
}
```
interface ETFData {
date: string;
flows: {
[fund: string]: number;
};
total: number;
}
export class ETFFlowsAction extends Action {
constructor() {
super('etf_flows', 'Analyzes BTC and ETH ETF flows');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/etf') ?? false;
}
async execute(message: Message, env?:any): Promise<ActionResult> {
try {
Logger.info('Starting ETF flows analysis');
const flowsData = await this.getETFFlowsAnalysis();
if (!flowsData) {
return {
text: "Could not fetch ETF flows data.",
shouldSendMessage: true,
context: "Error fetching ETF data."
};
}
return {
text: flowsData,
shouldSendMessage: true,
context: `You are a cryptocurrency market analyst. Create a concise and brief analysis of the ETF flows data for both BTC and ETH ETFs. Focus on significant inflows/outflows and their potential market impact. Keep the response under 300 characters. No emojis. Use a professional tone. Include total flows for both BTC and ETH.`
};
} catch (error) {
Logger.error('Failed to analyze ETF flows:', error);
return {
text: "Sorry, I encountered an error while analyzing ETF flows.",
shouldSendMessage: true,
context: "Error occurred during ETF analysis."
};
}
}
async getETFFlowsAnalysis(): Promise<string | null> {
try {
const [btcData, ethData] = await Promise.all([
this.fetchETFData('btc'),
this.fetchETFData('eth')
]);
if (!btcData || !ethData) {
return null;
}
return this.formatFlowsData(btcData, ethData);
} catch (error) {
Logger.error('Error getting ETF flows analysis:', error);
return null;
}
}
private async fetchETFData(type: 'btc' | 'eth'): Promise<ETFData | null> {
try {
const urls = {
btc: 'https://r.jina.ai/https://farside.co.uk/btc/',
eth: 'https://r.jina.ai/https://farside.co.uk/eth/'
};
const response = await http.get(urls[type]);
if(!response) return null;
const text = await response.text();
const lines = text.split('\n');
const tickerLine = type === 'btc'
? lines.find(line => line.includes('IBIT') || line.includes('FBTC'))
: lines.find(line => line.includes('ETHA') || line.includes('FETH'));
if (!tickerLine) {
Logger.error(`No ticker line found for ${type}`);
return null;
}
const tickers = tickerLine.split('|')
.map(t => t.trim())
.filter(Boolean);
let dataStartIndex = lines.indexOf(tickerLine);
let latestDataLine = '';
for (let i = dataStartIndex; i < lines.length; i++) {
const line = lines[i];
if (line.includes('|')) {
const cells = line.split('|').map(cell => cell.trim());
if (cells[1]?.match(/\d{2}\s+Dec\s+2024/)) {
latestDataLine = line;
break;
}
}
}
if (!latestDataLine) {
Logger.error(`No data line found for ${type}`);
return null;
}
const cells = latestDataLine.split('|').map(cell => cell.trim()).filter(Boolean);
const date = cells[0];
const flows: { [key: string]: number } = {};
let total = 0;
for (let i = 1; i < cells.length - 1; i++) {
let value = cells[i];
if (value === '-') continue;
value = value.replace(/,/g, '');
const flow = value.startsWith('(')
? -parseFloat(value.slice(1, -1))
: parseFloat(value);
if (!isNaN(flow)) {
const tickerIndex = i - 1;
if (tickerIndex < tickers.length) {
flows[tickers[tickerIndex]] = flow;
total += flow;
}
}
}
const lastCell = cells[cells.length - 1];
if (lastCell && lastCell !== '-') {
const parsedTotal = parseFloat(lastCell.replace(/,/g, ''));
if (!isNaN(parsedTotal)) {
total = parsedTotal;
}
}
return { date, flows, total };
} catch (error) {
Logger.error(`Error fetching ${type} ETF data:`, error);
return null;
}
}
private formatFlowsData(btcData: ETFData, ethData: ETFData): string {
const formatFlow = (num: number) =>
num >= 0 ? `+${num.toFixed(2)}` : num.toFixed(2);
return `ETF Flows Analysis\n\n` +
`BTC ETFs (${btcData.date}):\n` +
Object.entries(btcData.flows)
.map(([fund, flow]) => `• ${fund}: ${formatFlow(flow)}`)
.join('\n') +
`\nTotal BTC Flow: ${formatFlow(btcData.total)}\n\n` +
`ETH ETFs (${ethData.date}):\n` +
Object.entries(ethData.flows)
.map(([fund, flow]) => `• ${fund}: ${formatFlow(flow)}`)
.join('\n') +
`\nTotal ETH Flow: ${formatFlow(ethData.total)}`;
}
}
```
interface EconomicData {
country: string;
gdp: number;
gdpGrowth: number;
interestRate: number;
inflationRate: number;
joblessRate: number;
govBudget: number;
debtToGdp: number;
currentAccount: number;
population: number;
}
export class MacroAction extends Action {
private readonly MACRO_URL = 'https://r.jina.ai/https://tradingeconomics.com/matrix?g=top';
constructor() {
super('macro', 'Analyzes global macro economic data');
}
shouldExecute(message: Message): boolean {
return message.text?.toLowerCase().includes('/macro') ?? false;
}
private cleanTable(rawTable: string): EconomicData[] {
const lines = rawTable.split('\n');
const data: EconomicData[] = [];
const tableStartIndex = lines.findIndex(line => line.includes('| Country |'));
if (tableStartIndex === -1) return [];
let currentLine = tableStartIndex + 2;
while (currentLine < lines.length) {
const line = lines[currentLine];
if (!line.includes('|') || line.includes('Trading Economics provides')) break;
const columns = line.split('|').map(col => col.trim());
if (columns.length < 10) {
currentLine++;
continue;
}
const countryMatch = columns[1].match(/\[(.*?)\]/);
if (!countryMatch) {
currentLine++;
continue;
}
const country = countryMatch[1];
const cleanNumber = (str: string) => {
const match = str.match(/\[(.*?)\]/);
if (!match) return NaN;
return parseFloat(match[1]);
};
data.push({
country,
gdp: cleanNumber(columns[2]),
gdpGrowth: cleanNumber(columns[3]),
interestRate: cleanNumber(columns[4]),
inflationRate: cleanNumber(columns[5]),
joblessRate: cleanNumber(columns[6]),
govBudget: cleanNumber(columns[7]),
debtToGdp: cleanNumber(columns[8]),
currentAccount: cleanNumber(columns[9]),
population: cleanNumber(columns[10])
});
currentLine++;
}
return data;
}
private formatMacroData(data: EconomicData[]): string {
return data.map(country =>
`${country.country}:\n` +
`• GDP: $${country.gdp}B\n` +
`• GDP Growth: ${country.gdpGrowth}%\n` +
`• Interest Rate: ${country.interestRate}%\n` +
`• Inflation: ${country.inflationRate}%\n` +
`• Unemployment: ${country.joblessRate}%\n` +
`• Debt/GDP: ${country.debtToGdp}%\n` +
(country.currentAccount ? `• Current Account: ${country.currentAccount}%\n` : '') +
`• Population: ${country.population}M`
).join('\n\n');
}
async getMacroAnalysis(): Promise<string | null> {
try {
const response = await http.get(this.MACRO_URL);
if (!response) {
throw new Error(`Failed to fetch macro data: ${response}`);
}
const rawText = await response.text();
const economicData = this.cleanTable(rawText);
if (economicData.length === 0) {
return null;
}
return this.formatMacroData(economicData);
} catch (error) {
Logger.error('Error getting macro analysis:', error);
return null;
}
}
async getRawMacroData(): Promise<string | null> {
return await this.getMacroAnalysis();
}
async execute(message: Message, env?:any): Promise<ActionResult> {
try {
Logger.info('Starting macro economic analysis');
const macroData = await this.getMacroAnalysis();
if (!macroData) {
return {
text: "Could not fetch macro economic data.",
shouldSendMessage: true,
context: "Error fetching macro data."
};
}
const truncatedData = macroData.length > 2000 ? macroData.slice(0, 1997) + '...' : macroData;
return {
shouldSendMessage: true,
context: `You are a macro economic analyst. Analyze this global economic data and provide insights:
Please provide:
1. Overview of global economic conditions
2. Notable trends in GDP growth and inflation
3. Concerns or risks in specific regions
4. Comparison between major economies
5. Recommendations for economic outlook
Focus on key insights that would be relevant for investment and policy decisions.
Keep the response concise and under 2000 characters.
Data:
${truncatedData}`,
text: "Analyzing global economic data..."
};
} catch (error) {
Logger.error('Failed to analyze macro economic data:', error);
return {
text: "Sorry, I encountered an error while analyzing the economic data.",
shouldSendMessage: true,
context: "Error occurred during macro analysis."
};
}
}
}
```