This commit is contained in:
reizha
2025-07-11 19:14:55 +07:00
parent e1bff1cac2
commit 831085d8b3
37 changed files with 20947 additions and 0 deletions

41
bbca-patchtst/.gitignore vendored Normal file
View File

@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

79
bbca-patchtst/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,79 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/next/dist/bin/next",
"args": ["dev"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"],
"env": {
"NODE_OPTIONS": "--inspect"
}
},
{
"name": "Next.js: debug client-side",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/next/dist/bin/next",
"args": ["dev"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"],
"serverReadyAction": {
"pattern": "started server on .+, url: (https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
}
},
{
"name": "Next.js: debug full stack",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/node_modules/next/dist/bin/next",
"args": ["dev"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**"],
"serverReadyAction": {
"pattern": "started server on .+, url: (https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
},
"env": {
"NODE_OPTIONS": "--inspect"
}
},
{
"name": "Next.js: attach to running dev server",
"type": "node",
"request": "attach",
"port": 9229,
"skipFiles": ["<node_internals>/**"]
},
{
"name": "Chrome: Launch",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}",
"sourceMapPathOverrides": {
"webpack://_N_E/*": "${webRoot}/*",
"webpack:///./*": "${webRoot}/*",
"webpack:///./~/*": "${webRoot}/node_modules/*"
}
}
],
"compounds": [
{
"name": "Next.js: debug server + client",
"configurations": [
"Next.js: debug server-side",
"Chrome: Launch"
]
}
]
}

36
bbca-patchtst/README.md Normal file
View File

@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

View File

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6909
bbca-patchtst/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
{
"name": "bbca-patchtst",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-slot": "^1.2.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lightweight-charts": "^5.0.7",
"lucide-react": "^0.511.0",
"next": "15.3.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^3.3.0",
"yahoo-finance2": "^2.13.3"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.3.2",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.0",
"typescript": "^5"
}
}

View File

@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@ -0,0 +1,141 @@
// app/api/candles/route.ts
import { NextResponse } from 'next/server';
import yahooFinance from 'yahoo-finance2';
// Valid intervals for yahoo-finance2
const VALID_INTERVALS = ['1m', '2m', '5m', '15m', '30m', '60m', '90m', '1h', '1d', '5d', '1wk', '1mo', '3mo'] as const;
type ValidInterval = typeof VALID_INTERVALS[number];
function isValidInterval(interval: string): interval is ValidInterval {
return VALID_INTERVALS.includes(interval as ValidInterval);
}
function getMillisecondsForInterval(interval: ValidInterval, count: number): number {
const intervalToMs: Record<ValidInterval, number> = {
'1m': 60 * 1000,
'2m': 2 * 60 * 1000,
'5m': 5 * 60 * 1000,
'15m': 15 * 60 * 1000,
'30m': 30 * 60 * 1000,
'60m': 60 * 60 * 1000,
'90m': 90 * 60 * 1000,
'1h': 60 * 60 * 1000,
'1d': 24 * 60 * 60 * 1000,
'5d': 5 * 24 * 60 * 60 * 1000,
'1wk': 7 * 24 * 60 * 60 * 1000,
'1mo': 30 * 24 * 60 * 60 * 1000,
'3mo': 90 * 24 * 60 * 60 * 1000,
};
return intervalToMs[interval] * count;
}
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const symbol = searchParams.get('symbol') || 'BBCA.JK';
const intervalParam = searchParams.get('interval') || '1d';
const count = Math.min(parseInt(searchParams.get('count') || '100'), 500); // Limit to 500 max
const endParam = searchParams.get('end');
console.log('API Request:', { symbol, interval: intervalParam, count, end: endParam });
// Validate interval
if (!isValidInterval(intervalParam)) {
return NextResponse.json(
{ error: `Invalid interval. Valid intervals: ${VALID_INTERVALS.join(', ')}` },
{ status: 400 }
);
}
const interval = intervalParam as ValidInterval;
// Calculate date range
let endDate: Date;
let startDate: Date;
if (endParam) {
// For pagination (loading more historical data)
endDate = new Date(endParam);
if (isNaN(endDate.getTime())) {
return NextResponse.json({ error: 'Invalid end date format' }, { status: 400 });
}
} else {
// For initial load (current data)
endDate = new Date();
}
// Calculate start date based on interval and count
const timespan = getMillisecondsForInterval(interval, count);
startDate = new Date(endDate.getTime() - timespan);
// Add some buffer for weekends/holidays (especially for daily data)
if (interval === '1d' || interval === '5d' || interval === '1wk') {
startDate = new Date(startDate.getTime() - (7 * 24 * 60 * 60 * 1000)); // Add 7 days buffer
}
// Fetch data from Yahoo Finance
const results = await yahooFinance.historical(symbol, {
period1: startDate,
period2: endDate,
interval: interval,
});
if (!results || results.length === 0) {
return NextResponse.json(
{ error: 'No data found for the specified symbol and time range' },
{ status: 404 }
);
}
// Process and format the data
const candles = results
.filter(d => d.date && d.open && d.high && d.low && d.close) // Filter out incomplete data
.map((d) => ({
time: Math.floor(new Date(d.date).getTime() / 1000), // Unix timestamp in seconds
open: Number(d.open),
high: Number(d.high),
low: Number(d.low),
close: Number(d.close),
volume: d.volume ? Number(d.volume) : 0,
}))
.sort((a, b) => a.time - b.time) // Sort by time ascending
.slice(-count); // Take only the requested number of candles
// Validate that we have reasonable data
if (candles.length === 0) {
return NextResponse.json(
{ error: 'No valid candle data found' },
{ status: 404 }
);
}
return NextResponse.json(candles);
} catch (error) {
console.error('API Error:', error);
// Provide more specific error messages
if (error instanceof Error) {
if (error.message.includes('404')) {
return NextResponse.json(
{ error: `Symbol "${searchParams?.get('symbol')}" not found` },
{ status: 404 }
);
}
if (error.message.includes('timeout')) {
return NextResponse.json(
{ error: 'Request timeout - please try again' },
{ status: 408 }
);
}
}
return NextResponse.json(
{ error: 'Failed to fetch data from Yahoo Finance' },
{ status: 500 }
);
}
}

View File

@ -0,0 +1,53 @@
import { NextRequest } from 'next/server';
export async function POST(req: NextRequest) {
try {
const { searchParams } = new URL(req.url);
const body = await req.json();
const { symbol, clicked_date } = body;
if (!symbol || !clicked_date) {
return new Response(JSON.stringify({ error: 'Missing required parameters: symbol and clicked_date' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
// === 3. POST to Flask backend ===
const predictResponse = await fetch('http://localhost:8000/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
symbol,
clicked_date
}),
});
if (!predictResponse.ok) {
const errorData = await predictResponse.json();
return new Response(JSON.stringify({ error: errorData.error || 'Failed to get predictions' }), {
status: predictResponse.status,
headers: { 'Content-Type': 'application/json' },
});
}
const predictionData = await predictResponse.json();
console.log('Prediction Data:', predictionData);
return new Response(JSON.stringify(predictionData), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
} catch (err: any) {
console.error('Server Error:', err);
return new Response(JSON.stringify({ error: err.message || 'Internal server error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}

View File

@ -0,0 +1,103 @@
import Image from "next/image";
export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold">
src/app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
</div>
);
}

View File

@ -0,0 +1,857 @@
'use client';
import { useEffect, useRef, useCallback, useState } from 'react';
import {
createChart,
ColorType,
CandlestickSeries,
HistogramSeries,
type IChartApi,
type ISeriesApi,
type CandlestickData,
type MouseEventParams,
} from 'lightweight-charts';
// ============================================================================
// INTERFACES & TYPES (Interface Segregation Principle)
// ============================================================================
interface CandlestickWithVolume extends CandlestickData {
volume?: number;
}
interface VolumeData {
time: string | number;
value: number;
color: string;
}
interface ChartTheme {
background: string;
textColor: string;
gridColor: string;
borderColor: string;
}
interface StockChartProps {
symbol?: string;
interval?: string;
count?: number;
onCandleClick?: (clickedCandle: CandlestickData, historical60: CandlestickData[], symbol: string, interval: string, count: number) => void;
onDataLoaded?: (data: CandlestickData[]) => void;
width?: number;
height?: number;
theme?: 'dark' | 'light';
}
interface PredictionResult {
action_code: number;
action_label: string;
clicked_date: string;
close_price: number;
symbol: string;
confidence?: number;
predicted_price?: number;
horizon_days?: number;
forecasted_prices?: {
day: number;
date: string;
predicted_price: number;
change_percent: number;
}[];
}
interface ChartState {
isLoading: boolean;
isLoadingMore: boolean;
selectedCandle: number | null;
chartData: CandlestickData[];
earliestDate: Date | null;
predictionResult: PredictionResult | null;
isPredicting: boolean;
}
// ============================================================================
// DATA ACCESS LAYER (Single Responsibility Principle)
// ============================================================================
class StockDataService {
private static instance: StockDataService;
static getInstance(): StockDataService {
if (!StockDataService.instance) {
StockDataService.instance = new StockDataService();
}
return StockDataService.instance;
}
async fetchStockData(
symbol: string,
interval: string,
count: number,
endDate?: Date
): Promise<{ candleData: CandlestickData[]; volumeData: VolumeData[] }> {
try {
const endParam = endDate ? `&end=${endDate.toISOString()}` : '';
const url = `/api/candles?symbol=${symbol}&interval=${interval}&count=${count}${endParam}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
const candleData: CandlestickData[] = await response.json();
if (!Array.isArray(candleData) || candleData.length === 0) {
throw new Error('Invalid data format received from API');
}
const formattedCandleData = this.formatCandleData(candleData);
const volumeData = this.generateVolumeData(formattedCandleData);
return { candleData: formattedCandleData, volumeData };
} catch (error) {
console.error('Error fetching stock data:', error);
console.log('Falling back to generated data...');
return this.generateFallbackData(count);
}
}
private formatCandleData(candleData: CandlestickData[]): CandlestickData[] {
return candleData.map(candle => ({
...candle,
time: typeof candle.time === 'number' ? candle.time : candle.time
}));
}
private generateVolumeData(candleData: CandlestickData[]): VolumeData[] {
return candleData.map(candle => ({
time: candle.time,
value: Math.round(Math.random() * 50000000 + 10000000),
color: candle.close > candle.open ? '#26a69a40' : '#ef535040'
}));
}
generateFallbackData(count: number): { candleData: CandlestickData[]; volumeData: VolumeData[] } {
console.log('Generating fallback data...');
const candleData: CandlestickData[] = [];
const volumeData: VolumeData[] = [];
let basePrice = 9675;
for (let i = 0; i < count; i++) {
const date = new Date('2024-01-01');
date.setDate(date.getDate() + i);
const timeString = date.toISOString().split('T')[0];
const change = (Math.random() - 0.5) * basePrice * 0.02;
const open = Math.round(basePrice);
const close = Math.round(basePrice + change);
const high = Math.round(Math.max(open, close) + Math.random() * 100);
const low = Math.round(Math.min(open, close) - Math.random() * 100);
const volume = Math.round(Math.random() * 50000000 + 10000000);
candleData.push({ time: timeString, open, high, low, close });
volumeData.push({
time: timeString,
value: volume,
color: close > open ? '#26a69a40' : '#ef535040'
});
basePrice = close;
}
return { candleData, volumeData };
}
getEarliestDate(candleData: CandlestickData[]): Date | null {
if (candleData.length === 0) return null;
const firstCandle = candleData[0];
return typeof firstCandle.time === 'number'
? new Date(firstCandle.time * 1000)
: new Date(firstCandle.time);
}
}
// ============================================================================
// CHART CONFIGURATION (Single Responsibility Principle)
// ============================================================================
class ChartConfigurationService {
private themes: Record<'dark' | 'light', ChartTheme> = {
dark: {
background: '#0f1419',
textColor: '#d1d4dc',
gridColor: '#2a2e39',
borderColor: '#4a5568'
},
light: {
background: '#ffffff',
textColor: '#333333',
gridColor: '#e1e3e6',
borderColor: '#e1e3e6'
}
};
getChartOptions(theme: 'dark' | 'light', width: number, height: number) {
const themeConfig = this.themes[theme];
return {
layout: {
background: { type: ColorType.Solid, color: themeConfig.background },
textColor: themeConfig.textColor,
},
width,
height,
grid: {
vertLines: { color: themeConfig.gridColor },
horzLines: { color: themeConfig.gridColor },
},
timeScale: {
timeVisible: true,
borderColor: themeConfig.borderColor,
},
rightPriceScale: {
borderColor: themeConfig.borderColor,
scaleMargins: { top: 0.1, bottom: 0.2 },
},
};
}
getCandlestickSeriesOptions() {
return {
upColor: '#26a69a',
downColor: '#ef5350',
borderVisible: false,
wickUpColor: '#26a69a',
wickDownColor: '#ef5350',
};
}
getVolumeSeriesOptions() {
return {
color: '#26a69a',
priceFormat: { type: 'volume' as const },
priceScaleId: 'volume',
};
}
}
// ============================================================================
// CHART INTERACTION HANDLER (Single Responsibility Principle)
// ============================================================================
class ChartInteractionHandler {
constructor(
private onCandleClick?: (clickedCandle: CandlestickData, historical60: CandlestickData[], symbol: string, interval: string, count: number) => void
) { }
handleCandleClick = async (
param: MouseEventParams,
chartData: CandlestickData[],
setSelectedCandle: (index: number | null) => void,
setPredictionResult: (result: PredictionResult | null) => void,
setIsPredicting: (isPredicting: boolean) => void,
symbol: string = 'BBCA.JK',
interval: string = '1d',
count: number = 60
) => {
const clickedTime = param.time;
const clickedIndex = chartData.findIndex(candle => candle.time === clickedTime);
if (clickedIndex === -1) return;
setSelectedCandle(clickedIndex);
setIsPredicting(true);
setPredictionResult(null);
const clickedCandle = chartData[clickedIndex];
const clickedCandleDate = typeof clickedCandle.time === 'number'
? new Date(clickedCandle.time * 1000)
: new Date(clickedCandle.time);
try {
const url = `/api/predict`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
symbol,
clicked_date: clickedCandleDate.toISOString().split('T')[0]
})
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const data: PredictionResult = await response.json();
setPredictionResult(data);
console.log('Prediction result:', data);
} catch (error) {
console.error('Error fetching prediction:', error);
// Show error state or fallback
setPredictionResult({
action_code: -1,
action_label: 'ERROR',
clicked_date: clickedCandleDate.toISOString().split('T')[0],
close_price: clickedCandle.close,
symbol,
horizon_days: 6,
forecasted_prices: []
});
} finally {
setIsPredicting(false);
}
};
}
// ============================================================================
// INFINITE SCROLL HANDLER (Single Responsibility Principle)
// ============================================================================
class InfiniteScrollHandler {
constructor(
private dataService: StockDataService,
private symbol: string,
private interval: string,
private count: number
) { }
async loadMoreHistoricalData(
earliestDate: Date | null,
chartData: CandlestickData[],
candlestickSeries: ISeriesApi<'Candlestick'>,
volumeSeries: ISeriesApi<'Histogram'>,
setChartData: (data: CandlestickData[]) => void,
setEarliestDate: (date: Date | null) => void
): Promise<void> {
if (!earliestDate) return;
try {
const endDate = new Date(earliestDate.getTime() - 24 * 60 * 60 * 1000);
const { candleData, volumeData } = await this.dataService.fetchStockData(
this.symbol,
this.interval,
this.count,
endDate
);
if (candleData.length > 0) {
const mergedCandleData = [...candleData, ...chartData];
const mergedVolumeData = [...volumeData, ...this.generateExistingVolumeData(chartData)];
candlestickSeries.setData(mergedCandleData);
volumeSeries.setData(mergedVolumeData);
setChartData(mergedCandleData);
const newEarliestDate = this.dataService.getEarliestDate(candleData);
setEarliestDate(newEarliestDate);
console.log('Loaded', candleData.length, 'more historical candles');
}
} catch (error) {
console.error('Error loading more data:', error);
}
}
private generateExistingVolumeData(chartData: CandlestickData[]): VolumeData[] {
return chartData.map(candle => ({
time: candle.time,
value: Math.round(Math.random() * 50000000 + 10000000),
color: candle.close > candle.open ? '#26a69a40' : '#ef535040'
}));
}
handleVisibleLogicalRangeChange = (
logicalRange: any,
isLoadingMore: boolean,
loadMoreCallback: () => Promise<void>
) => {
if (!logicalRange || isLoadingMore) return;
if (logicalRange.from <= 5) {
console.log('User scrolled to beginning, loading more data...');
loadMoreCallback();
}
};
}
// ============================================================================
// PRICE CALCULATOR (Single Responsibility Principle)
// ============================================================================
class PriceCalculatorService {
calculatePriceMetrics(chartData: CandlestickData[]) {
const currentPrice = chartData.length > 0 ? chartData[chartData.length - 1].close : 0;
const priceChange = chartData.length > 1 ?
chartData[chartData.length - 1].close - chartData[chartData.length - 2].close : 0;
const percentChange = chartData.length > 1 ?
(priceChange / chartData[chartData.length - 2].close) * 100 : 0;
return { currentPrice, priceChange, percentChange };
}
}
// ============================================================================
// MAIN COMPONENT (Open/Closed Principle - Open for extension, Closed for modification)
// ============================================================================
export default function BBCAStockChart({
symbol = 'BBCA.JK',
interval = '1d',
count = 100,
onCandleClick,
onDataLoaded,
width,
height = 500,
theme = 'light'
}: StockChartProps) {
// Services (Dependency Injection)
const dataService = StockDataService.getInstance();
const configService = new ChartConfigurationService();
const interactionHandler = new ChartInteractionHandler(onCandleClick);
const scrollHandler = new InfiniteScrollHandler(dataService, symbol, interval, count);
const priceCalculator = new PriceCalculatorService();
// Refs
const chartContainerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
const candlestickSeriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
const volumeSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
// State
const [state, setState] = useState<ChartState>({
isLoading: true,
isLoadingMore: false,
selectedCandle: null,
chartData: [],
earliestDate: null,
predictionResult: null,
isPredicting: false,
});
// State updaters
const setIsLoading = (isLoading: boolean) =>
setState(prev => ({ ...prev, isLoading }));
const setIsLoadingMore = (isLoadingMore: boolean) =>
setState(prev => ({ ...prev, isLoadingMore }));
const setSelectedCandle = (selectedCandle: number | null) =>
setState(prev => ({ ...prev, selectedCandle }));
const setChartData = (chartData: CandlestickData[]) =>
setState(prev => ({ ...prev, chartData }));
const setEarliestDate = (earliestDate: Date | null) =>
setState(prev => ({ ...prev, earliestDate }));
const setPredictionResult = (predictionResult: PredictionResult | null) =>
setState(prev => ({ ...prev, predictionResult }));
const setIsPredicting = (isPredicting: boolean) =>
setState(prev => ({ ...prev, isPredicting }));
// Load more data handler
const loadMoreHistoricalData = useCallback(async () => {
if (!candlestickSeriesRef.current || !volumeSeriesRef.current || state.isLoadingMore) return;
setIsLoadingMore(true);
await scrollHandler.loadMoreHistoricalData(
state.earliestDate,
state.chartData,
candlestickSeriesRef.current,
volumeSeriesRef.current,
setChartData,
setEarliestDate
);
setIsLoadingMore(false);
}, [state.earliestDate, state.chartData, state.isLoadingMore, scrollHandler]);
// Handle candle click with current state
const handleCandleClick = useCallback((param: MouseEventParams) => {
interactionHandler.handleCandleClick(
param,
state.chartData,
setSelectedCandle,
setPredictionResult,
setIsPredicting,
symbol,
interval,
count
);
}, [state.chartData, interactionHandler, symbol, interval, count]);
// Handle scroll with current state
const handleVisibleLogicalRangeChange = useCallback((logicalRange: any) => {
scrollHandler.handleVisibleLogicalRangeChange(
logicalRange,
state.isLoadingMore,
loadMoreHistoricalData
);
}, [state.isLoadingMore, loadMoreHistoricalData, scrollHandler]);
// Chart initialization
useEffect(() => {
if (!chartContainerRef.current) return;
console.log('Initializing chart...');
setIsLoading(true);
const chartWidth = width || chartContainerRef.current.clientWidth;
const chartOptions = configService.getChartOptions(theme, chartWidth, height);
const chart = createChart(chartContainerRef.current, chartOptions);
const candlestickSeries = chart.addSeries(CandlestickSeries, configService.getCandlestickSeriesOptions());
const volumeSeries = chart.addSeries(HistogramSeries, configService.getVolumeSeriesOptions());
chartRef.current = chart;
candlestickSeriesRef.current = candlestickSeries;
volumeSeriesRef.current = volumeSeries;
// Load initial data
const loadInitialData = async () => {
try {
const { candleData, volumeData } = await dataService.fetchStockData(symbol, interval, count);
candlestickSeries.setData(candleData);
volumeSeries.setData(volumeData);
setChartData(candleData);
setEarliestDate(dataService.getEarliestDate(candleData));
onDataLoaded?.(candleData);
setTimeout(() => {
chart.timeScale().fitContent();
setIsLoading(false);
}, 100);
} catch (error) {
console.error('Error loading initial data:', error);
setIsLoading(false);
}
};
// Handle resize
const handleResize = () => {
if (chartContainerRef.current) {
chart.applyOptions({ width: chartContainerRef.current.clientWidth });
}
};
window.addEventListener('resize', handleResize);
loadInitialData();
// Cleanup
return () => {
console.log('Cleaning up chart');
chart.remove();
window.removeEventListener('resize', handleResize);
};
}, [symbol, interval, count, theme, height, width]);
// Subscribe to events with current handlers (separate effect)
useEffect(() => {
if (!chartRef.current) return;
const chart = chartRef.current;
// Subscribe to click events
chart.subscribeClick(handleCandleClick);
// Subscribe to visible logical range changes
chart.timeScale().subscribeVisibleLogicalRangeChange(handleVisibleLogicalRangeChange);
// Cleanup subscriptions
return () => {
chart.unsubscribeClick(handleCandleClick);
chart.timeScale().unsubscribeVisibleLogicalRangeChange(handleVisibleLogicalRangeChange);
};
}, [handleCandleClick, handleVisibleLogicalRangeChange]);
// Calculate price metrics
const { currentPrice, priceChange, percentChange } = priceCalculator.calculatePriceMetrics(state.chartData);
return (
<div className="p-6 bg-gray-50 min-h-screen">
{/* Header */}
<div className="mb-6 bg-white rounded-lg shadow-sm p-6">
<div className="flex items-center justify-between mb-4">
<h1 className="text-3xl font-bold text-gray-900">BBCA Trading Analysis</h1>
<div className="flex items-center space-x-2">
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
<span className="text-sm text-gray-600">Live Data</span>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{/* Current Price */}
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-lg">
<p className="text-sm text-gray-600 mb-1">Current Price</p>
<p className="text-2xl font-bold text-gray-900">
Rp {currentPrice.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
</p>
</div>
{/* Price Change */}
<div className={`p-4 rounded-lg ${priceChange >= 0 ? 'bg-gradient-to-r from-green-50 to-emerald-50' : 'bg-gradient-to-r from-red-50 to-pink-50'}`}>
<p className="text-sm text-gray-600 mb-1">24h Change</p>
<div className="flex items-center space-x-2">
<span className={`text-2xl ${priceChange >= 0 ? 'text-green-600' : 'text-red-600'}`}>
{priceChange >= 0 ? '↗' : '↘'}
</span>
<span className={`text-xl font-bold ${priceChange >= 0 ? 'text-green-600' : 'text-red-600'}`}>
{priceChange >= 0 ? '+' : ''}{percentChange.toFixed(2)}%
</span>
</div>
</div>
{/* Data Points */}
<div className="bg-gradient-to-r from-purple-50 to-violet-50 p-4 rounded-lg">
<p className="text-sm text-gray-600 mb-1">Data Points</p>
<p className="text-2xl font-bold text-gray-900">{state.chartData.length}</p>
</div>
</div>
{/* Instructions */}
<div className="mt-4 bg-blue-50 border border-blue-200 rounded-lg p-4">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-blue-600 font-bold">💡</span>
</div>
<div>
<p className="text-sm font-medium text-blue-900">
Interactive Analysis
</p>
<p className="text-xs text-blue-700">
Click any candle to get AI-powered PatchTST analysis and trading recommendations
</p>
</div>
</div>
</div>
</div>
{/* Chart Container */}
<div className="bg-white rounded-lg shadow-sm p-6 mb-6">
<div className="relative">
<div
ref={chartContainerRef}
className="w-full border border-gray-200 rounded-lg bg-white"
style={{ height: height }}
/>
{/* Loading overlay */}
{state.isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-90 rounded-lg">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-lg font-medium text-gray-700">Loading {symbol}</p>
<p className="text-sm text-gray-500">Fetching market data...</p>
</div>
</div>
)}
{/* Loading more indicator */}
{state.isLoadingMore && (
<div className="absolute top-4 left-4 bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg">
<div className="flex items-center space-x-2">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
<span className="text-sm font-medium">Loading historical data...</span>
</div>
</div>
)}
{/* Chart Info */}
<div className="absolute bottom-4 right-4 bg-gray-900 bg-opacity-80 text-white px-4 py-2 rounded-lg">
<p className="text-sm font-medium">{symbol}</p>
<p className="text-xs opacity-75">{state.chartData.length} candles</p>
</div>
</div>
</div>
{/* Prediction Result Card */}
{(state.predictionResult || state.isPredicting) && (
<div className="fixed top-4 right-4 bg-white border border-gray-200 rounded-xl shadow-xl p-6 w-[28rem] max-h-[80vh] overflow-y-auto z-50">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-800">
{state.isPredicting ? 'Analyzing...' : 'AI Prediction'}
</h3>
<button
onClick={() => {
setPredictionResult(null);
setIsPredicting(false);
setSelectedCandle(null);
}}
className="text-gray-400 hover:text-gray-600 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{state.isPredicting ? (
<div className="text-center py-8">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600 font-medium">Running PatchTST analysis...</p>
<p className="text-sm text-gray-500 mt-2">Generating 6-day forecast...</p>
</div>
) : state.predictionResult && (
<div>
{/* Action Badge */}
<div className={`inline-flex items-center px-4 py-3 rounded-lg border-2 mb-4 ${
state.predictionResult.action_code === 0 ? 'bg-red-50 border-red-200 text-red-800' :
state.predictionResult.action_code === 1 ? 'bg-green-50 border-green-200 text-green-800' :
'bg-blue-50 border-blue-200 text-blue-800'
}`}>
<span className="text-2xl mr-3">
{state.predictionResult.action_code === 0 ? '📉' :
state.predictionResult.action_code === 1 ? '📈' : '⚖️'}
</span>
<div>
<span className="font-bold text-xl block">{state.predictionResult.action_label}</span>
{state.predictionResult.horizon_days && (
<span className="text-sm opacity-75">{state.predictionResult.horizon_days}-day horizon</span>
)}
</div>
</div>
{/* Stock Info */}
<div className="bg-gray-50 rounded-lg p-4 mb-4">
<div className="grid grid-cols-2 gap-3">
<div>
<p className="text-xs text-gray-500 uppercase tracking-wide">Symbol</p>
<p className="font-mono font-semibold text-gray-800">{state.predictionResult.symbol}</p>
</div>
<div>
<p className="text-xs text-gray-500 uppercase tracking-wide">Date</p>
<p className="font-mono font-semibold text-gray-800">{state.predictionResult.clicked_date}</p>
</div>
</div>
<div className="mt-3 pt-3 border-t border-gray-200">
<p className="text-xs text-gray-500 uppercase tracking-wide">Current Price</p>
<p className="font-mono font-bold text-lg text-gray-800">
Rp {state.predictionResult.close_price.toLocaleString('id-ID', { maximumFractionDigits: 2 })}
</p>
</div>
</div>
{/* 6-Day Forecast */}
{state.predictionResult.forecasted_prices && state.predictionResult.forecasted_prices.length > 0 && (
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-4 mb-4">
<h4 className="font-semibold text-gray-800 mb-3 flex items-center">
<span className="text-blue-600 mr-2">📊</span>
6-Day Price Forecast
</h4>
<div className="space-y-2">
{state.predictionResult.forecasted_prices.map((forecast, index) => (
<div key={index} className="flex justify-between items-center bg-white rounded-lg p-3 shadow-sm">
<div className="flex items-center space-x-3">
<div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
<span className="text-blue-600 font-semibold text-sm">D{forecast.day}</span>
</div>
<div>
<p className="font-mono text-sm text-gray-600">{forecast.date}</p>
</div>
</div>
<div className="text-right">
<p className="font-mono font-semibold text-gray-800">
Rp {forecast.predicted_price.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
</p>
<p className={`text-sm font-medium ${
forecast.change_percent >= 0 ? 'text-green-600' : 'text-red-600'
}`}>
{forecast.change_percent >= 0 ? '+' : ''}{forecast.change_percent.toFixed(2)}%
</p>
</div>
</div>
))}
</div>
{/* Summary */}
<div className="mt-4 pt-3 border-t border-blue-200">
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<p className="text-gray-600">Avg Change</p>
<p className={`font-semibold ${
state.predictionResult.forecasted_prices.reduce((sum, f) => sum + f.change_percent, 0) / state.predictionResult.forecasted_prices.length >= 0
? 'text-green-600'
: 'text-red-600'
}`}>
{((state.predictionResult.forecasted_prices.reduce((sum, f) => sum + f.change_percent, 0) / state.predictionResult.forecasted_prices.length)).toFixed(2)}%
</p>
</div>
<div>
<p className="text-gray-600">Expected by Day 6</p>
<p className="font-semibold text-gray-800">
Rp {state.predictionResult.forecasted_prices[state.predictionResult.forecasted_prices.length - 1]?.predicted_price.toLocaleString('id-ID', { maximumFractionDigits: 0 })}
</p>
</div>
</div>
</div>
</div>
)}
{/* Description */}
<div className="bg-blue-50 rounded-lg p-4 mb-4">
<p className="text-sm text-blue-800 leading-relaxed">
{state.predictionResult.action_code === 0 ?
'Our PatchTST AI model suggests selling this stock based on technical patterns and forecasts a potential decline over the next 6 days.' :
state.predictionResult.action_code === 1 ?
'Our PatchTST AI model suggests buying this stock based on technical patterns and forecasts potential growth over the next 6 days.' :
'Our PatchTST AI model suggests holding this stock based on technical patterns and forecasts mixed signals over the next 6 days.'
}
</p>
</div>
{/* Confidence & Accuracy */}
{state.predictionResult.confidence && (
<div className="bg-green-50 rounded-lg p-4 mb-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-green-800">Model Confidence</span>
<span className="text-lg font-bold text-green-800">{(state.predictionResult.confidence * 100).toFixed(1)}%</span>
</div>
<div className="w-full bg-green-200 rounded-full h-2 mt-2">
<div
className="bg-green-600 h-2 rounded-full transition-all duration-300"
style={{ width: `${(state.predictionResult.confidence || 0) * 100}%` }}
></div>
</div>
</div>
)}
{/* Disclaimer */}
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
<p className="text-xs text-yellow-800">
This is an AI-generated prediction using PatchTST for educational purposes only.
Market conditions can change rapidly. Always do your own research and consider consulting with financial advisors before making investment decisions.
</p>
</div>
</div>
)}
</div>
)}
{/* Selected Candle Info */}
{state.selectedCandle !== null && (
<div className="fixed bottom-4 left-4 bg-white border border-gray-200 rounded-lg shadow-lg p-4 w-64">
<h4 className="font-semibold text-gray-800 mb-2">Selected Candle</h4>
<div className="text-sm text-gray-600">
<p>Position: #{state.selectedCandle + 1}</p>
<p>Date: {String(state.chartData[state.selectedCandle]?.time)}</p>
<p>Close: Rp {state.chartData[state.selectedCandle]?.close.toLocaleString('id-ID')}</p>
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@ -0,0 +1,185 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}