From e3d5e7da7c547347cd9c3561faa6f9792ad2861c Mon Sep 17 00:00:00 2001 From: TZGyn Date: Tue, 11 Feb 2025 18:50:17 +0800 Subject: [PATCH] update webhook --- src/routes/webhook/tradingview/+server.ts | 81 ++++++++--------------- 1 file changed, 29 insertions(+), 52 deletions(-) diff --git a/src/routes/webhook/tradingview/+server.ts b/src/routes/webhook/tradingview/+server.ts index db5d0e0..34a4ea6 100644 --- a/src/routes/webhook/tradingview/+server.ts +++ b/src/routes/webhook/tradingview/+server.ts @@ -1,69 +1,46 @@ import { db } from '$lib/db/index.js' import { json } from '@sveltejs/kit' import { RestClientV5 } from 'bybit-api' +import { z } from 'zod' export const POST = async ({ locals, request }) => { - console.log('hit') - console.log(await request.text()) - return json({}) const body = await request.json() - const apiKey = 'wrc1w54Zp5JAfXLxY2' - const apiSecret = 'tY7oYPhwSE1gabFS4PmxtmbDOhkYWvPh0khf' - - const client = new RestClientV5({ - key: apiKey, - secret: apiSecret, - demoTrading: true, - }) + const form = z + .object({ + key: z.string(), + secret: z.string(), + symbol: z.string(), + side: z.enum(['Buy', 'Sell']), + qty: z.string(), + takeProfit: z.string(), + stopLoss: z.string(), + }) + .safeParse(body) - const { symbol, id }: { symbol: string; id: string } = body + if (!form.success) return json({}, { status: 400 }) - const bybitWebhook = await db.query.bybitWebhook.findFirst({ - where: (webhook, { and, eq }) => - and(eq(webhook.id, id), eq(webhook.userId, locals.user.id)), - }) + // const apiKey = 'wrc1w54Zp5JAfXLxY2' + // const apiSecret = 'tY7oYPhwSE1gabFS4PmxtmbDOhkYWvPh0khf' - if (!bybitWebhook) return json({}, { status: 404 }) + const { key, secret, side, symbol, qty, stopLoss, takeProfit } = + form.data - const activeOrders = await client.getActiveOrders({ - category: 'spot', - symbol: bybitWebhook.symbol, + const client = new RestClientV5({ + key: key, + secret: secret, + demoTrading: true, }) - const wallet = await client.getWalletBalance({ - accountType: 'SPOT', - coin: bybitWebhook.symbol, + await client.submitOrder({ + category: 'linear', + symbol, + side, + orderType: 'Market', + qty, + takeProfit, + stopLoss, }) - if (wallet.result.list.length <= 0) return json({}) - - const amount = activeOrders.result.list.reduce( - (acc, item) => Number(item.qty) + acc, - 0, - ) - - if (amount > 0) { - client.submitOrder({ - category: 'spot', - symbol: bybitWebhook.symbol, - side: bybitWebhook.direction === 'buy' ? 'Buy' : 'Sell', - orderType: 'Market', - qty: ( - (Number(wallet.result.list[0].totalAvailableBalance) * - bybitWebhook.quantityPercent) / - 100 - ).toString(), - }) - } else { - client.submitOrder({ - category: 'spot', - symbol: bybitWebhook.symbol, - side: bybitWebhook.direction === 'buy' ? 'Buy' : 'Sell', - orderType: 'Market', - qty: amount.toString(), - }) - } - return new Response() }