Skip to content

Instantly share code, notes, and snippets.

@kyawswarthwin
Created March 25, 2024 06:43
Show Gist options
  • Save kyawswarthwin/5e7029d2c4f675cc000b8457c1fb4698 to your computer and use it in GitHub Desktop.
Save kyawswarthwin/5e7029d2c4f675cc000b8457c1fb4698 to your computer and use it in GitHub Desktop.
import fetch from 'node-fetch';
import { handleResponse, median } from './helper.util.js';
function getRateDetails(currency, tradeType) {
let params = {
asset: 'USDT',
fiat: currency,
tradeType
};
if (currency === 'USD') {
params = {
...params,
...{
publisherType: 'merchant',
merchantCheck: true
}
};
}
return getPriceDetails(params);
}
function getExchangeRates(currencies) {
return Promise.all(
currencies.split('|').map((currency) =>
getExchangeRate(currency).then((price) => ({
currency,
price
}))
)
);
}
function getExchangeRate(currency) {
return new Promise(async (resolve, reject) => {
try {
const [buyRate, sellRate] = await Promise.all([
getRate(currency, 'BUY'),
getRate(currency, 'SELL')
]);
resolve({
buy: buyRate,
sell: sellRate
});
} catch (error) {
reject(error);
}
});
}
function getRate(currency, tradeType) {
let params = {
asset: 'USDT',
fiat: currency,
tradeType
};
if (currency === 'USD') {
params = {
...params,
...{
publisherType: 'merchant',
merchantCheck: true
}
};
}
return getPrice(params);
}
function getPriceDetails(params) {
return new Promise(async (resolve, reject) => {
try {
const { tradeType } = params;
const prices = [];
const ads = await getAds(params);
ads.map((ad) => {
prices.push(parseFloat(ad.adv.price));
});
const min = tradeType === 'SELL' ? prices.length - 1 : 0;
const max = tradeType === 'SELL' ? 0 : prices.length - 1;
resolve({
min: prices[min],
med: median(prices),
max: prices[max]
});
} catch (error) {
reject(error);
}
});
}
function getPrice(params) {
return getAd({
...params,
...{
page: 1,
rows: 1
}
}).then(({ data }) => parseFloat(data[0].adv.price));
}
function getAds(params) {
return new Promise(async (resolve, reject) => {
try {
const ads = [];
const rowsPerPage = 20; //Max limit of rows per page is 20.
let currentPage = 1;
let totalPages;
do {
const { data, total } = await getAd({
...params,
...{
page: currentPage,
rows: rowsPerPage
}
});
ads.push(...data);
totalPages = totalPages ?? Math.ceil(total / rowsPerPage);
currentPage++;
} while (currentPage <= totalPages);
resolve(ads);
} catch (error) {
reject(error);
}
});
}
function getAd(params) {
return fetch('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(handleResponse)
.then(({ data }) => data);
}
export { getExchangeRates, getRateDetails };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment