This commit is contained in:
discountry
2025-10-03 15:28:16 +08:00
parent d5c4b04746
commit fcb83bd16b
925 changed files with 165721 additions and 4 deletions
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
@@ -0,0 +1,43 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Description
This app demonstrates the use of ccxt with a nextjs project. It showcases the use of both ccxt as a server side package and also to be running in the client:
- **/tickers**: uses the **clients Window websockets** to connect to the exchange and stream ticker values
- **/balance**: uses a **server side call** to protect exposing any api keys and fetches and shows the user balance.
## Getting Started
1. install the dependencies:
```bash
npm run install
```
2. Set the keys in pages/balance.tsx
3. Run the app:
```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.
## Screenshots
##### Index
![menu](https://github.com/ccxt/ccxt/assets/12142844/645b5fe8-fd13-44f8-bded-20733843ccea)
##### Client side websocket example
![websocket](https://github.com/ccxt/ccxt/assets/12142844/7c28f8c9-aefd-4db3-8aff-6ff06b93a8bc)
##### Server side private endpoint fetch balance
![balance](https://github.com/ccxt/ccxt/assets/12142844/bd253903-43ea-4225-a7ca-193aaa29f42a)
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
{
"name": "nextjs-page-router",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"ccxt": "^4.1.56",
"next": "15.4.7",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.0.3",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"typescript": "^5"
}
}
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -0,0 +1,6 @@
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
@@ -0,0 +1,13 @@
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
@@ -0,0 +1,46 @@
import ccxt, { Balances } from 'ccxt'
// This is for showcase purposes in prod move this to environment variable like process.env.BINANCEUSDM_API_KEY
const apiKey = ""
const secret = ""
export async function getServerSideProps () {
const exchange = new ccxt.kraken({ apiKey, secret })
const balances = await exchange.fetchBalance()
// remove undefined values to prevent serializing error
Object.keys(balances).forEach(key => balances[key] === undefined && delete balances[key])
return {
props: {
balances,
},
}
}
export default function Balance({balances}: {balances: Balances}) {
return (
<main className={`flex min-h-screen flex-col items-center justify-between p-24`}>
<table>
<thead>
<tr>
<th>Currency</th>
<th>Free</th>
<th>Used</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{Object.keys(balances).map((currency: string) => (
balances[currency].free !== undefined && (
<tr key={currency}>
<td>{currency}</td>
<td>{balances[currency].free}</td>
<td>{balances[currency].used}</td>
<td>{balances[currency].total}</td>
</tr>
)
))}
</tbody>
</table>
</main>
)
}
@@ -0,0 +1,8 @@
export default function Home() {
return (
<main className={`flex min-h-screen flex-col items-center space-y-10`}>
<a className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 w-120 m-4" href="/balance">Balance - Using Server Side calls</a>
<a className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 w-120 m-4" href="/tickers">Tickers - Using Client Side websockets</a>
</main>
)
}
@@ -0,0 +1,61 @@
import ccxt, { Exchange, Ticker } from 'ccxt'
import { useEffect, useState } from 'react';
const exchangeIds = ['binance', 'bitget', 'bybit', 'cryptocom']
export default function Home() {
const [exchanges, setExchanges] = useState<Record<string, Exchange>>({});
const [tickers, setTickers] = useState<Record<string, Ticker>>({});
const [error, setError] = useState<string>();
useEffect(() => {
console.log('starting exchanges...');
const newExchanges: Record<string, Exchange> = exchangeIds.reduce((acc: any, exchangeId) => {
acc[exchangeId] = new (ccxt.pro as any)[exchangeId];
return acc;
}, {});
setExchanges(newExchanges);
}, []);
useEffect(() => {
const fetchTickers = async () => {
for (const exchangeId in exchanges) {
try {
const newTicker = await exchanges[exchangeId].watchTicker('BTC/USDT');
setTickers(tickers => ({ ...tickers, [exchangeId]: newTicker }));
} catch (e) {
setError(exchangeId + ': ' + JSON.stringify(e) + '\n')
}
};
};
fetchTickers();
}, [tickers, exchanges, error]);
return (
<main
className={`flex min-h-screen flex-col items-center justify-between p-24`}
>
<div className="z-10 max-w-5xl w-full font-mono text-sm lg:flex justify-between">
{exchangeIds.map((exchangeId) => (
<div key={exchangeId} className="flex-1">
<h3>{exchangeId}</h3>
<ul>
<li>{`last: ${tickers[exchangeId]?.last}`}</li>
<li>{`high: ${tickers[exchangeId]?.high}`}</li>
<li>{`low: ${tickers[exchangeId]?.low}`}</li>
<li>{`bid: ${tickers[exchangeId]?.bid}`}</li>
<li>{`ask: ${tickers[exchangeId]?.ask}`}</li>
<li>{`ask volume: ${tickers[exchangeId]?.askVolume}`}</li>
<li>{`bid volume: ${tickers[exchangeId]?.bidVolume}`}</li>
<li>{`close: ${tickers[exchangeId]?.close}`}</li>
</ul>
</div>
))}
</div>
<div>
<h3>Last error:</h3>
<p>{error ? error : "None"}</p>
</div>
</main>
)
}
@@ -0,0 +1,27 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}
@@ -0,0 +1,20 @@
import type { Config } from 'tailwindcss'
const config: Config = {
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
backgroundImage: {
'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
'gradient-conic':
'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
},
},
},
plugins: [],
}
export default config
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "es5",
"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,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}