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.0 KiB
TypeScript
97 lines
2.0 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)
|
|
|
|
const text = await request.text()
|
|
|
|
console.log('text', text)
|
|
|
|
const body = JSON.parse(text)
|
|
|
|
console.log('text', 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,
|
|
})
|
|
|
|
await client.submitOrder({
|
|
category: 'linear',
|
|
symbol,
|
|
side,
|
|
orderType: 'Market',
|
|
qty,
|
|
takeProfit,
|
|
stopLoss,
|
|
})
|
|
} catch (error) {
|
|
console.log('Error', error)
|
|
} finally {
|
|
return new Response()
|
|
}
|
|
}
|