Bitfinex API websocket orderbook - javascript

I am trying to get the order book through the bitfacex bitfex websocks, but I get an error in the console.
Error in the console: Cannot read property '0' of undefined on the line if (bidsKeys [i]) {
var ws = new WebSocket("wss://api-pub.bitfinex.com/ws/2");
ws.onopen = function() {
// ws.send(JSON.stringify({ event: 'conf', flags: 131072 }))
let msg = JSON.stringify({
event: 'subscribe',
channel: 'book',
pair: 'tBTCUSD',
freq: 'F1',
len: '25',
prec: 'P0'
})
ws.send(msg)
ws.onmessage = function(msg) {
const BOOK = {}
BOOK.bids = {}
BOOK.asks = {}
BOOK.psnap = {}
BOOK.mcnt = 0
msg = JSON.parse(msg.data)
// var response = JSON.parse(msg.data);
// console.log(msg.data);
const csdata = []
const bidsKeys = BOOK.psnap['bids']
const asksKeys = BOOK.psnap['asks']
for (let i = 0; i < 25; i++) {
if (bidsKeys[i]) {
const price = bidsKeys[i]
const pp = BOOK.bids[price]
csdata.push(pp.price, pp.amount)
}
if (asksKeys[i]) {
const price = asksKeys[i]
const pp = BOOK.asks[price]
csdata.push(pp.price, -pp.amount)
}
}
const csStr = csdata.join(':')
const csCalc = CRC.str(csStr)
if (csCalc !== checksum) {
console.error('CHECKSUM_FAILED')
}
}

Related

How to send transaction on solana?

So I literally copied from
(https://docs.solana.com/developing/clients/javascript-api)
I need to send a transaction from one wallet to another, easy right? But this doest work here
error
Specifically, the transfer method cannot create an instruction. I've tried everything I can, but it hasn't worked. Please help dear programmers
MY CODE:
async function transfer() {
const provider = await IsConnected();
console.log(provider.publicKey.toString());
const connection = new solanaWeb3.Connection(
"https://api.devnet.solana.com",
"confirmed"
);
var recieverWallet = new solanaWeb3.PublicKey(
"3uePV7kJcT3w5qMLPTHVAdLc72SF2iDRwNcxDE713EMf"
);
// var airdropSignature = await connection.requestAirdrop(
// provider.publicKey,
// solanaWeb3.LAMPORTS_PER_SOL * 0.4
// );
// await connection
// .confirmTransaction(airdropSignature)
// .then(console.log("Airdropped"));
var transaction = new solanaWeb3.Transaction();
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
transaction.add(
await solanaWeb3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: 10000,
})
);
if (transaction) {
console.log("Txn created successfully");
}
let signed = await provider.signTransaction(transaction).serialize();
let signature = await connection.sendRawTransaction(signed);
console.log(signature);
let bConfirmed = await connection.confirmTransaction(signature);
console.log(bConfirmed);
}
CODE WHERE PROBLEM:
static transfer(
params: TransferParams | TransferWithSeedParams,
): TransactionInstruction {
let data;
let keys;
if ('basePubkey' in params) {
const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;
data = encodeData(type, {
lamports: BigInt(params.lamports),
seed: params.seed,
programId: toBuffer(params.programId.toBuffer()),
});
keys = [
{pubkey: params.fromPubkey, isSigner: false, isWritable: true},
{pubkey: params.basePubkey, isSigner: true, isWritable: false},
{pubkey: params.toPubkey, isSigner: false, isWritable: true},
];
} else {
const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;
***THERE ->*** data = encodeData(type, {lamports: BigInt(params.lamports)});
keys = [
{pubkey: params.fromPubkey, isSigner: true, isWritable: true},
{pubkey: params.toPubkey, isSigner: false, isWritable: true},
];
}
return new TransactionInstruction({
keys,
programId: this.programId,
data,
});
}
export function encodeData<TInputData extends IInstructionInputData>(
type: InstructionType<TInputData>,
fields?: any,
): Buffer {
const allocLength =
type.layout.span >= 0 ? type.layout.span : Layout.getAlloc(type, fields);
const data = Buffer.alloc(allocLength);
const layoutFields = Object.assign({instruction: type.index}, fields);
type.layout.encode(layoutFields, data);
return data;
}
encode(src, b, offset = 0) {
const firstOffset = offset;
let lastOffset = 0;
let lastWrote = 0;
for (const fd of this.fields) {
let span = fd.span;
lastWrote = (0 < span) ? span : 0;
if (undefined !== fd.property) {
const fv = src[fd.property];
if (undefined !== fv) {
lastWrote = fd.encode(fv, b, offset);
if (0 > span) {
/* Read the as-encoded span, which is not necessarily the
* same as what we wrote. */
span = fd.getSpan(b, offset);
}
}
}
lastOffset = offset;
offset += span;
}
const bigInt =
(length: number) =>
(property?: string): Layout<bigint> => {
const layout = blob(length, property);
const {encode, decode} = encodeDecode(layout);
const bigIntLayout = layout as Layout<unknown> as Layout<bigint>;
bigIntLayout.decode = (buffer: Buffer, offset: number) => {
const src = decode(buffer, offset);
return toBigIntLE(Buffer.from(src));
};
bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {
const src = toBufferLE(bigInt, length);
return encode(src, buffer, offset);
};
return bigIntLayout;
};
function toBufferLE(num, width) {
{
const hex = num.toString(16);
const buffer = Buffer.from(hex.padStart(width * 2, '0').slice(0, width * 2), 'hex');
buffer.reverse();
return buffer;
}
// Allocation is done here, since it is slower using napi in C
return converter.fromBigInt(num, Buffer.allocUnsafe(width), false);
}
exports.toBufferLE = toBufferLE;

JS API client throws 'Uncaught (in promise) TypeError: e.join is not a function' after 40 requests

Here is my code (it takes a csv file as input, does some API calls, and outputs the results as another csv file):
let allRows = [];
async function fileToLines(file) {
return new Promise((resolve, reject) => {
reader = new FileReader();
reader.onload = function (e) {
parsedLines = e.target.result.split(/\r|\n|\r\n/);
resolve(parsedLines);
};
reader.readAsText(file);
});
}
document
.getElementById('fileInput')
.addEventListener('change', async function (e) {
var file = e.target.files[0];
if (file != undefined) {
fileToLines(file).then(async id => {
console.log(id)
console.log(parsedLines)
console.log(typeof id);
var idInt = id.map(Number);
var idFiltered = id.filter(function (v) { return v !== '' });
console.log(idFiltered)
if (file != undefined) {
allRows = [];
}
for (let id of idFiltered) {
const row = await getRelease(id);
allRows.push(row);
}
download();
});
}
});
function debounce(inner, ms = 0) {
let timer = null;
let resolves = [];
return function (...args) {
// Run the function after a certain amount of time
clearTimeout(timer);
timer = setTimeout(() => {
/* Get the result of the inner function, then apply it to the resolve function of
each promise that has been created since the last time the inner function was run */
let result = inner(...args);
resolves.forEach(r => r(result));
resolves = [];
}, ms);
return new Promise(r => resolves.push(r));
};
}
const throttleFetch = debounce(fetch, 2500);
function getRelease(idFiltered) {
return throttleFetch(`https://api.discogs.com/releases/${idFiltered}`, {
headers: {
'User-Agent': '***/0.1',
'Authorization': 'key=***, secret=***',
},
}).then(response => response.json())
.then(data => {
if (data.message === 'Release not found.') {
return { error: `Release with ID ${idFiltered} does not exist` };
} else {
const id = data.id;
const delimiter = document.getElementById("delimiter").value || "|";
const artists = data.artists ? data.artists.map(artist => artist.name) : [];
const barcode = data.identifiers.filter(id => id.type === 'Barcode')
.map(barcode => barcode.value);
var formattedBarcode = barcode.join(delimiter);
const country = data.country || 'Unknown';
const genres = data.genres || [];
const formattedGenres = genres.join(delimiter);
const labels = data.labels ? data.labels.map(label => label.name) : [];
const formattedLabels = labels.join(delimiter);
const catno = data.labels ? data.labels.map(catno => catno.catno) : [];
const formattedCatNo = catno.join(delimiter);
const styles = data.styles || [];
const formattedStyles = styles.join(delimiter);
const tracklist = data.tracklist ? data.tracklist
.map(track => track.title) : [];
const formattedTracklist = tracklist.join(delimiter);
const year = data.year || 'Unknown';
const format = data.formats ? data.formats.map(format => format.name) : [];
const qty = data.formats ? data.formats.map(format => format.qty) : [];
const descriptions = data.formats ? data.formats
.map(descriptions => descriptions.descriptions) : [];
const preformattedDescriptions = descriptions.toString()
.replace('"', '""').replace(/,/g, ', ');
const formattedDescriptions = '"' + preformattedDescriptions + '"';
console.log(idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
)
return [idFiltered,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
];
}
});
}
function download() {
const ROW_NAMES = [
"release_id",
"artist",
"format",
"qty",
"format descriptions",
"label",
"catno",
"country",
"year",
"genres",
"styles",
"barcode",
"tracklist"
];
var csvContent = "data:text/csv;charset=utf-8,"
+ ROW_NAMES + "\n" + allRows.map(e => e.join(",")).join("\n");
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for Firefox
link.click();
}
The app passes tests for 5, 10, 20, or 30 lines of input, but when I try 40, I get this error:
Uncaught (in promise) TypeError: e.join is not a function
csvContent file:///D:/DOWNLOADS/CODE/***/csv.js:151
download file:///D:/DOWNLOADS/CODE/***/csv.js:151
<anonymous> file:///D:/DOWNLOADS/CODE///***/csv.js:38
async* file:///D:/DOWNLOADS/CODE/***/csv.js:20
I really don't know why that would be. Any ideas please? TIA.
Apparently I need to add more details but IDK what?

Result won't update VAR

I am trying to run a query, inside AXIOS which gets data from a 3rd party URL. Then uses some of that data to search our mongoDB database.
However it seems it won't update var total = 0
While the query below does function correctly, the return result won't allow me to set that it to the query.
Promise.all(arr.forEach( async (id,index) => {
//(CODE REMOVED JUST TO GET THIS FUNCTION TO WORK)
const search = await geoLocation.find({
'location': {
'$geoWithin': {
'$box': [
[-35.2418503, -13.5076852], [112.8656697, 129.0020486]
]
}
}}).toArray();
total = search.length;
}));
See the full code below
var array = [];
var pointarray = []
var total = 0;
areas.forEach((id,index) => {
if(id.type == "Point"){
pointarray[index] = "N"+id.id;
}else{
array[index] = "R"+id.id;
}
});
var arraySearch = "https://nominatim.openstreetmap.org/lookup?osm_ids="+array.toString()+"&polygon_geojson=1&bbox=1&format=json";
var pointSearch = "https://nominatim.openstreetmap.org/lookup?osm_ids="+pointarray.toString()+"&polygon_geojson=1&bbox=0&format=json"
const requestOne = axios.get(arraySearch);
const requestTwo = axios.get(pointSearch);
axios.all([requestOne, requestTwo])
.then(axios.spread((...responses) => {
const responseOne = responses[0]
const responseTwo = responses[1]
/*
process the responses and return in an array accordingly.
*/
return [
responseOne.data,
responseTwo.data,
];
}))
.then(arr => {
Promise.all(arr.forEach( async (id,index) => {
//const middleIndex = id[index].boundingbox.length / 2;
//const firstHalf = id[index].boundingbox.splice(0, middleIndex);
//const secondHalf = id[index].boundingbox.splice(-middleIndex);
//res.send(secondHalf[0]);
const query = [{
$match: {
location: {
$geoWithin: {$box:[[Number(firstHalf[0]),Number(firstHalf[1])],[Number(secondHalf[0]),Number(secondHalf[1])]]
}
}
}
},{
$count: 'id'
}]
const search = await geoLocation.find({
'location': {
'$geoWithin': {
'$box': [
[-35.2418503, -13.5076852], [112.8656697, 129.0020486]
]
}
}}).toArray();
total = search.length;
// total = search.length;
// const search = geoLocation.aggregate(query).toArray.length;
}));
})
.catch(errors => {
console.log("ERRORS", errors);
})
.then(function () {
res.send(total);
});

how to export this value in nodejs

I'm trying to get the amount received from the request by going to a list and then trying to export it to another file, but I'm having trouble doing this because I tried several ways to pass the list as return and it didn't work.
const moment = require("moment");
const sslChecker = require("ssl-checker");
const express = require("express");
//const dominios = require('./server');
var dominios = [
"api-prd.koerich.com.br",
"api-prd.reservapto.com.br",
"c.btg360.com.br",
"compassouol.com",
"gmfy.compasso.com.br",
"webqplus.cbn.com.bo",
"webqplus.cerchile.cl",
"webqplus.cervepar.com.py",
"webqplus.fnc.com.uy",
"webqplus.quilmes.com.ar",
"www.efurukawa.com",
];
var get_domain = dominios;
for (var i = 0; i < get_domain.length; i++) {
sslChecker(get_domain[i])
.then((certdata) => {
var startdate = new Date(certdata.validFrom);
var enddate = new Date(certdata.validTo);
var certstart = moment(startdate);
var certend = moment(enddate);
var ssldata = [
{
domain: get_domain,
issued: certstart.format("LLLL"),
expires: certend.format("LLLL"),
daysleft: certdata.daysRemaining,
},
];
var data = JSON.parse(certdata.daysRemaining);
var nomes = (certdata.validFor[0]);
var lista = [];
lista.push(data);
lista.push(nomes);
console.log(lista); //get this values
})
.catch((err) => {
console.log(err);
});
}
//module.exports = lista; //export here
console.log:
async function getList() {
mondongo = [];
var dominios = [
"api-prd.koerich.com.br",
"api-prd.reservapto.com.br",
"c.btg360.com.br",
"compassouol.com",
"gmfy.compasso.com.br",
"webqplus.cbn.com.bo",
"webqplus.cerchile.cl",
"webqplus.cervepar.com.py",
"webqplus.fnc.com.uy",
"webqplus.quilmes.com.ar",
"www.efurukawa.com",
]
try {
for (var i = 2; i < domains.length; i++) {
mondongo.push(
sslChecker(domains[i])
.then((certdata) => {
var startdate = new Date(certdata.validFrom);
var enddate = new Date(certdata.validTo);
var certstart = moment(startdate);
var certend = moment(enddate);
var ssldata = [
{
domain: domains,
issued: certstart.format("LLLL"),
expires: certend.format("LLLL"),
daysleft: certdata.daysRemaining,
},
];
var data = certdata.daysRemaining;
var nome = certdata.validFor[0];
var lista = [];
lista.push(nome);
lista.push(data);
return lista;
})
.catch((err) => {
//console.log(err);
})
);
}
}
catch (error) {
console.log(error);
}
var arroz = await Promise.all(mondongo);
return arroz;
}
return:
create a function and use the async await methods.

Aws SDK In lambda function

I am working on lambda function and creating a method for AWS-SDK historical metric report using node, js and I am getting the following errors. Have look at a SS of error
here is my code
function getKeyByValue(object, value) {
return Object.keys(object).find(key =>
object[key] === value);
}
exports.handler = async (event) => {
const AWS = require('aws-sdk');
var connect = new AWS.Connect({ apiVersion: '2017-08-08' });
let queueARN = event.queueARN || null;
const connectInstanceId = process.env.instanceID;
let flag =0, nextToken = null;
let queueARNsObject = {}, queueARNsArray=[], queueTypeObject={};
do{
let listQueuesParams = {
InstanceId: connectInstanceId, /* required */
QueueTypes: [
"STANDARD",
],
NextToken: nextToken,
};
let listQueuesPromise = connect.listQueues(listQueuesParams).promise();
listQueuesResult = await listQueuesPromise;
// console.log(listQueuesResult);
listQueuesResult.QueueSummaryList.forEach(queue => {
if(queueARN != null){
if (queue.Arn == queueARN){
queueARNsArray = [queue.Arn];
queueARNsObject[queue.Name]= queue.Arn;
queueTypeObject[queue.QueueType]= queue.Arn;
flag = 1;
return;
}
}else{
queueARNsObject[queue.Name]= queue.Arn;
queueTypeObject[queue.QueueType]= queue.Arn;
queueARNsArray.push(queue.Arn);
nextToken = listQueuesResult.NextToken;
}
});
}while (flag=0 && nextToken != null);
const HistoricalMetricsList = [
{
Name : 'CONTACTS_HANDLED',
Unit : 'COUNT',
Statistic : 'SUM'
},
{
Name : 'CONTACTS_ABANDONED',
Unit : 'COUNT',
Statistic : 'SUM'
},
];
// Metrics params
var getHistoricalMetricsParams = {
InstanceId: connectInstanceId,
StartTime: 1592993700,
EndTime: 1593039900,
Filters: {
Channels: ["VOICE"],
Queues: queueARNsArray
},
HistoricalMetrics: HistoricalMetricsList,
Groupings: ["QUEUE"]
};
// get current metrics by queues
var getHistoricalMetricsPromise = connect
.getMetricData(getHistoricalMetricsParams)
.promise();
var getHistoricalMetricsResult = await getHistoricalMetricsPromise;
// console.log("current |||||||| 1 metrics:", JSON.stringify(getCurrentMetricsResult));
let queueMetricsArray = [];
if(getHistoricalMetricsResult.MetricResults.length){
getHistoricalMetricsResult.MetricResults.forEach(queue => {
let queueMetrics = {
"Queue_Name" : getKeyByValue(queueARNsObject ,queue.Dimensions.Queue.Arn),
"CallsHandled": queue.Collections[0].Value ,
"CallsAbanoded": queue.Collections[1].Value ,
}
queueMetricsArray.push(queueMetrics);
console.log("TYPE||||", getKeyByValue(queueTypeObject ,queue.Dimensions.Queue.Arn))
});
}else{
keys.forEach(key => {
let queueMetrics = {
"Queue_Name" : getKeyByValue(event ,queue.Dimensions.Queue.Arn),
"CONTACTS_HANDLED": 0,
"CONTACTS_ABANDONED": 0
}
queueMetricsArray.push(queueMetrics);
})
}
const response = {
responseCode: 200,
metricResults: queueMetricsArray
};
return response;
};
I don't have any idea what this is an error about. if anyone of you knows please help me to fix it Thanks. i've done the same thing with Real-Time Metric report and that is running perfectly

Categories

Resources