-
Notifications
You must be signed in to change notification settings - Fork 158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: added chart Indicator tool #212
Open
narasimha-1511
wants to merge
4
commits into
NeurProjects:main
Choose a base branch
from
narasimha-1511:feat/chart-indicators
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
import { checkIndicatorsAction } from "@/server/actions/indicator"; | ||
import { z } from 'zod'; | ||
|
||
// Define the schema for the tool's parameters | ||
const indicatorToolParameters = z.object({ | ||
indicator: z.enum(['rsi', 'sma', 'bb', 'macd']).describe('The indicator to check'), | ||
parameters: z.object({ | ||
period: z.number().optional().describe('The period for the indicator'), | ||
fast: z.number().optional(), | ||
slow: z.number().optional(), | ||
signal: z.number().optional(), | ||
}), | ||
contractAddress: z.string().describe('The contract address of the token to check'), | ||
fromTimestamp: z.number().optional().describe('The timestamp to start checking from'), | ||
}); | ||
|
||
// Define the tool | ||
export const indicatorTools = { | ||
checkIndicators: { | ||
displayName: '📈 Indicator Tool', | ||
description: 'Check financial indicators like RSI, SMA, BB, and MACD for a given contract address.', | ||
parameters: indicatorToolParameters, | ||
execute: async (input: z.infer<typeof indicatorToolParameters>) => { | ||
try { | ||
// Call the existing checkIndicatorsAction function | ||
const result = await checkIndicatorsAction(input); | ||
|
||
if(!result?.data) { | ||
return { | ||
success: false, | ||
error: 'Unable to fetch indicator data.', | ||
}; | ||
} | ||
|
||
if (result?.data?.success) { | ||
return { | ||
success: true, | ||
data: result.data.data, | ||
suppressFollowUp: true, | ||
}; | ||
} else { | ||
return { | ||
success: false, | ||
error: result.data.error, | ||
}; | ||
} | ||
} catch (error) { | ||
return { | ||
success: false, | ||
error: 'Unexpected error during indicator check', | ||
}; | ||
} | ||
}, | ||
render: (result: unknown) => { | ||
const typedResult = result as { | ||
success: boolean; | ||
data?: number; | ||
error?: string; | ||
}; | ||
|
||
if (!typedResult.success) { | ||
return ( | ||
<div className="relative overflow-hidden rounded-2xl bg-muted p-4"> | ||
<div className="flex items-center gap-3"> | ||
<p className="text-md text-center"> | ||
{typedResult.error || 'Unable to fetch indicator data.'} | ||
</p> | ||
</div> | ||
</div> | ||
); | ||
} | ||
|
||
return ( | ||
<div className="space-y-4"> | ||
<div className="rounded-lg bg-muted p-4"> | ||
<p className="text-sm text-muted-foreground">Indicator Result</p> | ||
|
||
<p className="font-medium">{typedResult.data}</p> | ||
</div> | ||
</div> | ||
); | ||
}, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import { actionClient, ActionResponse } from "@/lib/safe-action"; | ||
import { z } from 'zod'; | ||
import { getDexOhlcv, getTokenPools } from '@/server/actions/chart'; | ||
import { rsi, sma, bb , macd } from 'indicatorts'; | ||
import { TIMEFRAME } from "@/types/chart"; | ||
|
||
const DEFAULT_PERIOD = 14; | ||
const DEFAULT_MACD_FAST = 12; | ||
const DEFAULT_MACD_SLOW = 26; | ||
const DEFAULT_MACD_SIGNAL = 9; | ||
|
||
interface IndicatorParameters { | ||
period?: number; | ||
fast?: number; | ||
slow?: number; | ||
signal?: number; | ||
} | ||
|
||
interface IndicatorInput { | ||
indicator: 'rsi' | 'sma' | 'bb' | 'macd'; | ||
parameters: IndicatorParameters; | ||
contractAddress: string; | ||
fromTimestamp?: number; | ||
} | ||
|
||
const indicatorSchema = z.object({ | ||
indicator: z.enum(['rsi', 'sma', 'bb', 'macd']), | ||
parameters: z.object({ | ||
period: z.number().optional(), | ||
fast: z.number().optional(), | ||
slow: z.number().optional(), | ||
signal: z.number().optional(), | ||
}), | ||
contractAddress: z.string(), | ||
fromTimestamp: z.number().optional(), | ||
}); | ||
|
||
function getClosingValues(olhcvList: number[][], fromTimestamp?: number): number[] { | ||
// [timestamp, open, high, low, close , volume] // this is the format of the olhcvList | ||
return fromTimestamp | ||
? olhcvList.filter(([timestamp]) => timestamp >= fromTimestamp).map(([, , , , close]) => close) | ||
: olhcvList.map(([, , , , close]) => close); | ||
} | ||
|
||
function calculateIndicator(indicator: string, closingValues: number[], parameters: IndicatorParameters): number { | ||
switch (indicator) { | ||
case 'rsi': | ||
const rsiResult = rsi(closingValues, { period: parameters.period || DEFAULT_PERIOD }); | ||
const rsiValue = rsiResult[rsiResult.length - 1]; | ||
if(typeof rsiValue !== 'number') { | ||
throw new Error('Failed to calculate RSI'); | ||
} | ||
return rsiValue; | ||
case 'sma': | ||
const smaResult = sma(closingValues, { period: parameters.period || DEFAULT_PERIOD }); | ||
const smaValue = smaResult[smaResult.length - 1]; | ||
if(typeof smaValue !== 'number') { | ||
throw new Error('Failed to calculate SMA'); | ||
} | ||
return smaValue; | ||
case 'bb': | ||
const bbResult = bb(closingValues, { period: parameters.period || DEFAULT_PERIOD }); | ||
const bbValue = bbResult.upper[bbResult.upper.length - 1]; | ||
if(typeof bbValue !== 'number') { | ||
throw new Error('Failed to calculate BB'); | ||
} | ||
return bbValue; | ||
case 'macd': | ||
const macdResult = macd(closingValues, { | ||
fast: parameters.fast || DEFAULT_MACD_FAST, | ||
slow: parameters.slow || DEFAULT_MACD_SLOW, | ||
signal: parameters.signal || DEFAULT_MACD_SIGNAL, | ||
}); | ||
const macdValue = macdResult.macdLine[macdResult.macdLine.length - 1]; | ||
if(typeof macdValue !== 'number') { | ||
throw new Error('Failed to calculate MACD'); | ||
} | ||
return macdValue; | ||
default: | ||
throw new Error('Unsupported indicator'); | ||
} | ||
} | ||
|
||
export const checkIndicatorsAction = actionClient | ||
.schema(indicatorSchema) | ||
.action(async (input): Promise<ActionResponse<number>> => { | ||
try { | ||
const { indicator, parameters, contractAddress, fromTimestamp } = input.parsedInput; | ||
|
||
const topPoolId = await getTokenPools(contractAddress, 'solana'); | ||
const olhcvList = await getDexOhlcv(topPoolId, 'solana', TIMEFRAME.MINUTES, '1'); | ||
const closingValues = getClosingValues(olhcvList, fromTimestamp); | ||
|
||
if (closingValues.length === 0) { | ||
return { success: false, error: 'No closing values found' }; | ||
} | ||
|
||
const result = calculateIndicator(indicator, closingValues, parameters); | ||
return { success: true, data: result }; | ||
} catch (error) { | ||
return { success: false, error: error instanceof Error ? error.message : 'Unexpected error' }; | ||
} | ||
}); | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix switch case scoping and add data validation.
📝 Committable suggestion
🧰 Tools
🪛 Biome (1.9.4)
[error] 48-48: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 49-49: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 55-55: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 56-56: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 62-62: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 63-63: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 69-73: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 74-74: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think there are no minimum values here !
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
@narasimha-1511 Actually, each technical indicator does require a minimum number of data points to produce valid calculations:
Without these minimum points, the calculations would be mathematically invalid or produce unreliable results. The validation I suggested would prevent potential errors or misleading indicator values.
Would you like me to modify the minimum points in the validation to match your specific requirements?
Citations:
🌐 Web query:
💡 Result:
The minimum number of data points required varies by indicator due to differences in calculation methods and recommended precision standards:
RSI (Relative Strength Index)
SMA (Simple Moving Average)
Bollinger Bands
MACD (Moving Average Convergence Divergence)
†EMA = Exponential Moving Average.
For practical use cases like trading strategies or academic analysis, exceeding these minima improves accuracy[1][4][10].
Citations:
@narasimha-1511 I apologize for my previous response - you were right to question it. After thorough research, the actual minimum data points required are much more conservative:
Would you like me to update the validation logic with these more accurate minimum requirements? We could also add a warning when data points are below the recommended minimum but above the mathematical minimum, instead of throwing an error.
Citations:
✏️ Learnings added