I am in the process of building my own trading terminal with various functions for a school project where speed is important..
I have two functions that I would like to optimize. But don't know how to proceed from here.
function1
const calcPromise = async () => {
const markPriceData = await restClient.getTickers({
symbol: selectedSymbol,
});
let cash = 100;
const lastPrice = markPriceData.result[0].last_price;
const quantity = Math.round((cash / lastPrice * 1.03).toFixed(3));
return { lastPrice, quantity };
};
it makes one request for the the last price, from the given symbol and calculates the quantity if I want to buy for a certain amount.
function2
export default async function placeOrder() {
try {
const orderData = await restClient.placeActiveOrder({
symbol: selectedSymbol,
order_type: 'Limit',
side: 'Buy',
qty: quantity,
price: lastPrice,
time_in_force: 'GoodTillCancel',
reduce_only: false,
close_on_trigger: false,
position_idx: LinearPositionIdx.OneWayMode
});
const endTime2 = performance.now();
const executionTime2 = endTime2 - startTime2;
console.log(`Buy order ${executionTime2}ms`);
console.log(orderData);
} catch (err) {
console.log(err);
}
}
Function2 takes the value from function 1, lastPrice & quantity and makes another request and executes a buy order.
This process is taking to long. Im clocking this at averege 2-5 seconds. As it is now, function2 must sit and wait for the first request, which will then do the calculations before it can be executed. The idea I have is to get function1 to run in the background somehow. That the price is already available, so that function2 does not need to wait for function1 to be ready.
I've tried implementing async. But it resulted in errors, because function2 always runs faster than function1 if they are run at the same time.
Is there a smart way I can solve this?