Copy // setup.ts
import 'dotenv/config'
interface RequestHeaders {
[key: string]: string
}
interface CreateLeverageOrderRequest {
price: number
leverage_type: 'cross' | 'isolated'
quantity: number
direction: 'buy' | 'sell'
order_type: 'MarketOpen' | 'LimitOpen'
expiration_time_in_min?: number
base_asset_id: string
initial_margin_asset_id: string
initial_margin: number
leverage: number
take_profit_price?: number
take_profit_amount?: number
stop_loss_price?: number
stop_loss_amount?: number
is_mobile?: boolean
}
function getBaseUrl() {
const baseUrl = process.env.VDEX_BASE_URL || '<https://api.vdex.com>'
return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl
}
function createHeaders({ apiKey }: { apiKey: string }): RequestHeaders {
if (!apiKey || !apiKey.startsWith('vdex_')) throw new Error('Missing or invalid VDEX_API_KEY')
return {
'X-API-Key': apiKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
async function httpJson<T>({ url, method, headers, body }: {
url: string
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
headers: RequestHeaders
body?: unknown
}): Promise<T> {
const res = await fetch(url, {
method,
headers,
body: body ? JSON.stringify(body) : undefined
})
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`HTTP ${res.status} ${res.statusText}${text ? `: ${text}` : ''}`)
}
return res.json() as Promise<T>
}
// GET /v2/users/balances
export async function getBalances(): Promise<unknown> {
const baseUrl = getBaseUrl()
const headers = createHeaders({ apiKey: process.env.VDEX_API_KEY as string })
return httpJson({ url: `${baseUrl}/v2/users/balances`, method: 'GET', headers })
}
// POST /v2/orders
export async function placeOrder(order: CreateLeverageOrderRequest): Promise<unknown> {
const baseUrl = getBaseUrl()
const headers = createHeaders({ apiKey: process.env.VDEX_API_KEY as string })
return httpJson({ url: `${baseUrl}/v2/orders`, method: 'POST', headers, body: order })
}
// Example usage
async function main() {
const balances = await getBalances()
console.log('balances', balances)
const order: CreateLeverageOrderRequest = {
price: 65000,
leverage_type: 'cross',
quantity: 0.01,
direction: 'buy',
order_type: 'LimitOpen',
expiration_time_in_min: 60,
base_asset_id: 'BTCUSD',
initial_margin_asset_id: 'USDT',
initial_margin: 100,
leverage: 10,
take_profit_price: 70000,
stop_loss_price: 62000
}
const placed = await placeOrder(order)
console.log('order', placed)
}
main().catch(err => {
console.error(err)
process.exit(1)
})