Skip to content

Instantly share code, notes, and snippets.

@grsLammy
Created November 3, 2023 10:05
Show Gist options
  • Save grsLammy/c1c2ac68f09b8b110a18dab3036bf8b6 to your computer and use it in GitHub Desktop.
Save grsLammy/c1c2ac68f09b8b110a18dab3036bf8b6 to your computer and use it in GitHub Desktop.
Code snippet for single order
export const placeSingleOrderController = async (
req: ClientWithRequestQueryBody<{ projectId: string }, { qty: number; price: number }>,
res: Response,
) => {
try {
const { projectId } = req.query;
const { qty, price } = req.body;
const order = {
category: 'spot',
symbol: 'BTCUSDT',
side: 'Buy',
orderType: 'Limit',
qty,
price,
timeInForce: 'GTC',
};
const { bybitApiKey } = await bybitKeys(projectId);
const recWindow = constants.bybitRecWindow;
const timeStamp = Date.now().toString();
const data = JSON.stringify(order);
const paramStr = `${timeStamp}${bybitApiKey}${recWindow}${data}`;
const sign = await getSignature(projectId, paramStr);
const placedOrder = (await (
await axios({
method: 'POST',
url: 'https://api-testnet.bybit.com/v5/order/create',
headers: {
'X-BAPI-SIGN-TYPE': constants.bybitXBapiSignType,
'X-BAPI-SIGN': sign,
'X-BAPI-API-KEY': bybitApiKey,
'X-BAPI-TIMESTAMP': timeStamp as unknown as string,
'X-BAPI-RECV-WINDOW': recWindow.toString(),
'Content-Type': 'application/json; charset=utf-8',
},
data,
})
).data) as BybitOrder;
if (!placedOrder || placedOrder.retCode !== 0)
return res.status(500).json(prepareResponse(true, 'Error placing order', placedOrder));
if (placedOrder) {
return res.status(200).json(prepareResponse(false, 'New orders place on bybit', placedOrder));
}
} catch (error) {
// Handle errors and return an error response.
const errorMsg = (error as Error)?.message || textContent.CONTRLRS_BYBITPLACEORDER_CONTRLR_ERROR;
console.error(textContent.CONTRLRS_BYBITPLACEORDER_CONTRLR_ERROR, error);
return res.status(500).json(prepareResponse(true, errorMsg, error));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment