One method to add up the variances of each pair, and then total the results of each pair using nedb

In my nedb database called trades.json, I am simulating stock trades with the following data:

{"buySell":"BUY","currentPrice":431.55,"_id":"GyTaUKVOCa9x5APS"},
{"buySell":"SELL","currentPrice":431.77,"_id":"Re9VhGrW9ZoiOKFe"},
{"buySell":"BUY","currentPrice":431.65,"_id":"TJrn63bIV8sKBFYh"},
{"buySell":"SELL","currentPrice":431.7539,"_id":"qrsz2l3UVKpQEks8"}

My goal is to calculate the difference in currentPrice between each "BUY" and "SELL" pair of trades, and then sum up those results to determine my overall profits.

I have a functional code snippet for this calculation, but I suspect it may be providing me with the total difference instead of individual profit margins for each trade.

const Datastore = require('nedb')
const trades = new Datastore({ filename: 'trades.json' })
trades.loadDatabase(function (err) {
    if(err) return console.error(err)
})

let sum = []
trades.find({}).exec(function (err, docs) {

    if(err) return console.log(err)

    docs.forEach(element => {
        sum.push(element.currentPrice)
    });
    let pandle = diff(sum)
    pandle = pandle.reduce((a, b) => a + b, 0)
    
    console.log(pandle)
    
})

function diff(A) {
    return A.slice(1).map(function(n, i) { return n - A[i]; });
}

I believe that I need to implement a foreach loop that constructs an array of "BUY" and "SELL" pairs, along with another array to store the sum of these pairs, but I'm facing challenges in getting it to function correctly.

Based on the example provided above, I anticipate that the expected result should be: 0.3239.

Your guidance or assistance in solving this issue would be greatly appreciated!

Answer №1

To calculate the profit, you can subtract values labeled 'BUY' from the total and add values labeled 'SELL'.

const
    strategies = { BUY: val => -val, SELL: val => val },
    transactions = [{ buySell: "BUY", currentPrice: 431.55, _id: "GyTaUKVOCa9x5APS" }, { buySell: "SELL", currentPrice: 431.77, _id: "Re9VhGrW9ZoiOKFe" }, { buySell: "BUY", currentPrice: 431.65, _id: "TJrn63bIV8sKBFYh" }, { buySell: "SELL", currentPrice: 431.7539, _id: "qrsz2l3UVKpQEks8" }],
    profit = transactions.reduce((totalProfit, { buySell, currentPrice }) => totalProfit + strategies[buySell](currentPrice), 0);

console.log(profit);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can jQuery be used to style a single selected option with a unique color?

I have a dropdown menu with a default placeholder ("ex. Crawler Excavator") displayed in lightgray. I want only this placeholder to be in lightgray when selected, while all other labels should be black. Currently, I am able to color the selected item light ...

I am experiencing issues with launching chromium while running Puppeteer on Windows 11 using node js v19.4

Upon following the installation instructions in the documentation to install puppeteer with npm install puppeteer, I attempted to run the example for downloading a webpage as a PDF. However, every time I try to execute the code, Node.js returns the followi ...

Exploring the concepts of nested If statements, for loops, and else if ordering within Javascript programming (FreeCodeCamp - lookUpProfile)

Currently tackling Free Code Camp's Javascript tutorials and encountering a roadblock on the "Contact Profile" <a href="https://www.freecodecamp.com/challenges/profile-lookup#?solution=%2F%2FSetup%0Avar%20contacts%20%3D%20%5B%0A%20%20%20%20%7B%0A%2 ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Sending a parameter value from a blade view in Laravel to a controller: tips and tricks

What is the best way to pass the value "{{$ item-> id}}" to a method in a controller? For example, if we have show.blade.php with the value: "{{$ item-> id}}" In MyController.php, how can we utilize this value within the method: public function ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

Creating functions by using arrays in separate files

I am encountering an issue with defining a function in a separate C++ file that takes an array as an argument. Here are the files involved: selectionsort.cpp #include "selectionsort.hpp" int selectionsort(int a[]){ int length{}; le ...

Using Jquery slideToggle is creating additional spacing between inline-block divs

I am struggling with displaying a list of cities in an inline format. <div class="accordion-container"> <a href="#" class="accordion-toggle">London</a> <div class="accordion-content"> <p>Inform ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Select a JSON item at random using PHP

After analyzing a JSON string, it was discovered to contain various items with different formats and content. Here is an example: [{"Format":"I25","Content":"172284201241"}, {"Format":"I25","Content":"40124139"}, {"Format":"I25","Content":"20197086185689 ...

PHP script only inserting the first element of an array into the MySQL database table

When attempting to capture up to 15 entries upon submission, the code provided is only capturing the initial entry in the database. Additionally, an error message is being displayed, stating: An error in the SQL syntax has occurred. Ensure to refer to the ...

Locate the indices of different values within a numpy array

Let's say we have an array X: X = np.array([[4, 2], [9, 3], [8, 5], [3, 3], [5, 6]]) Now, we want to find the index of the row that contains certain values in this array: searched_values ...

Building a collection of class pointers within a hierarchy

In the following hierarchy of classes, how can I create an array of pointers in C++ to store objects from all the classes? B1 B2 \ / C I attempted the following code but it is not working as expected: #include <iostream> using namespac ...

The footer should remain at the bottom of the page without being permanently fixed

Is there a way to keep the bootstrap footer at the bottom without fixing it in place? In the code example below, the footer should always appear at the bottom. The white space after the footer should come before it. Using sticky-bottom achieves this, but ...

The JavaScript Date() string that was inserted into the database is now elegantly displayed

Can you help me figure out how to format a date string that's stored in a database like this: 2016-09-13T18:18:08.518Z, into a more visually appealing format such as: 13 September 2016? Thank you in advance! ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

Error: Unable to access 'amtSavingsInput' variable before it has been initialized

I encountered an issue with form3/chart3 while trying to replicate the success of form1/chart1 and form2/chart2. Despite following the same steps and structure, form3/chart3 seems to be malfunctioning. The error message I'm receiving is "Uncaught Refe ...

Using a foreach loop on an array to recursively sort through both parent and child nodes in PHP with a function

I am working with a data set stored in an array that uses parent-child ids like id, parent_id, and title. The primary level has a parent_id of 0, and there are multiple parent-child relationships within the array. To organize this array, I am using a recu ...

Ways to adjust the height of one panel based on the height of surrounding panels

I have a layout with three panels: two on the left side and one on the right. <div class="row"> <div class="col s6"> <div class="panel"> content1 </div> <div class="panel"> ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...