You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.1 KiB
TypeScript

import { json } from '@sveltejs/kit'
import { RestClientV5 } from 'bybit-api'
import { z } from 'zod'
export const POST = async ({ locals, request }) => {
const type = request.headers.get('Content-Type')
console.log('Type:', type)
if (type !== 'application/json; charset=utf-8') {
return new Response()
}
const body = await request.json()
console.log('Body:', body)
const flatSchema = z.object({
type: z.literal('Flat'),
key: z.string(),
secret: z.string(),
symbol: z.string(),
side: z.enum(['Buy', 'Sell']),
qty: z.string(),
takeProfit: z.string().optional(),
stopLoss: z.string().optional(),
})
const percentSchema = z.object({
type: z.literal('Percent'),
key: z.string(),
secret: z.string(),
symbol: z.string(),
side: z.enum(['Buy', 'Sell']),
entryPrice: z.string(),
qtyPercent: z.string(),
takeProfitPercent: z.string().optional(),
stopLossPercent: z.string().optional(),
})
const form = z.union([flatSchema, percentSchema]).safeParse(body)
if (!form.success) {
console.log(form.error)
return json({}, { status: 400 })
}
// const apiKey = 'wrc1w54Zp5JAfXLxY2'
// const apiSecret = 'tY7oYPhwSE1gabFS4PmxtmbDOhkYWvPh0khf'
const { key, secret, side, symbol } = form.data
try {
let qty
let takeProfit
let stopLoss
if (form.data.type === 'Flat') {
qty = form.data.qty
takeProfit = form.data.takeProfit
stopLoss = form.data.stopLoss
} else {
qty = (
(Number(form.data.entryPrice) *
Number(form.data.qtyPercent)) /
100
).toString()
takeProfit = (
Number(form.data.entryPrice) *
(1 + Number(form.data.takeProfitPercent) / 100)
).toString()
stopLoss = (
Number(form.data.entryPrice) *
(1 - Number(form.data.stopLossPercent) / 100)
).toString()
}
const client = new RestClientV5({
key: key,
secret: secret,
demoTrading: true,
})
console.log({ qty, takeProfit, stopLoss })
await client.submitOrder({
category: 'linear',
symbol,
side,
orderType: 'Market',
qty,
takeProfit,
stopLoss,
})
} catch (error) {
console.log('Error', error)
} finally {
return new Response()
}
}