Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error:

/home/simone/gekko/strategies/high.js:10
sma: function(name, price, points)
^^^

SyntaxError: Unexpected identifier

I even attempted to change the first parameter within the function from "this[name]" but without success. I'm new to JavaScript and eager to understand where I am going wrong. Here is the code snippet:

// simple sma function
// params: name-of-array, price (of something), number of points (sma length)
// returns: the moving average price/value
sma: function(name, price, points)
   {
       // create array if not exist + initialize array
       if( !this[name] )
              {
           let a = 0,     b = [];
           for (a; a < points; a++) { b[a] = 0; }
           this[name] = b;
       }

       let arr = this[name],
           len = arr.length;

       arr[len] = price; // add new value to last position in array
       arr.shift(); // remove oldest value from array (maintaining order)
       this[name] = arr; // save changes

       // calculate current average
       let i = 0,
            total = 0;

       for( i; i < len; i++ ) { total += arr[i]; }

       let avg = total / len;
       return avg;
   },

Here is the complete code:

var strat = {

init : function() {

}
//======================================================================================
// simple sma function
// params: name-of-array, price (of something), number of points (sma length)
// returns: the moving average price/value
sma: function(name, price, points)
   {
       // create array if not exist + generate array
       if( !this[name] )
              {
           let a = 0,     b = [];
           for (a; a < points; a++) { b[a] = 0; }
           this[name] = b;
       }

       let arr = this[name],
           len = arr.length;

       arr[len] = price; // add new value to last position in array
       arr.shift(); // remove oldest value from array (maintaining order)
       this[name] = arr; // save changes

       // calculate current average
       let i = 0,
            total = 0;

       for( i; i < len; i++ ) { total += arr[i]; }

       let avg = total / len;
       return avg;
   },
 };
//======================================================================================

strat.check = function(candle) {

let sma_high = this.sma('sma_high', this.candle.high, 10);
let sma_low = this.sma('sma_low', this.candle.low, 10);

// additional logic can go here, for example:
if( sma_high < sma_low ) this.advice('long')
else this.advice('short')
}
//======================================================================================

module.exports = strat;

Answer №1

On runtime, the parser is unfamiliar with the variable sma, leading to the error message you encountered. This occurs because your syntax is incorrect.

There are two possible approaches to resolve this issue:

  1. sma can be an independent function that should be declared in one of the following ways:
function sma(name, price, points){
   // Implement functionality
}

const sma = (name, price, points)=>{
  // Implement functionality
}

// Invoke the function by calling:
sma("Mercedes", 20000, 50);
  1. sma could be a built-in method within a class object:
class Foo {
 sma(name, price, points){
    // Implement functionality
  }
}

// Invoke the function by calling:
Foo.sma("Mercedes", 20000, 100);

Here is your revised code, now functional and corrected:

class Strat {

  init(){
  }

  sma(name, price, points) {
       // Initialize array if not present + generate new array
       if( !this[name] )
              {
           let a = 0,     b = [];
           for (a; a < points; a++) { b[a] = 0; }
           this[name] = b;
       }

       let arr = this[name],
           len = arr.length;

       arr[len] = price; // Add new element at the end of the array
       arr.shift(); // Remove first element (old value) from the array (maintaining order)
       this[name] = arr; // Set/save updated array

       // Calculate current average
       let i = 0,
            total = 0;

       for( i; i < len; i++ ) { total += arr[i]; }

       let avg = total / len;
       return avg;
       }
    }
Strat.check = function(candle) {

let sma_high = this.sma('sma_high', this.candle.high, 10);
let sma_low = this.sma('sma_low', this.candle.low, 10);

// Additional logic implementation, as a simple example:
if( sma_high < sma_low ) this.advice('long')
  else this.advice('short')
}

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

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

Saving Files in Your React Web Application: Tips and Tricks

Currently, I am working on a React web application that requires the temporary storage of Torrent pieces for streaming purposes using a web player. Any recommendations on how to properly store this data temporarily in order to facilitate the streaming pro ...

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

Get the redirectUri using npm's Request package

When using npm Request to generate a response, I am able to retrieve information like "statusCode" by using "response.statusCode". However, I am unable to retrieve other information such as "redirectUri" as it shows undefined. Is there a way to access the ...

Tips for stacking objects vertically in mobile or tablet view using HTML and CSS

I have been diligently working on a project using a fiddle, and everything appears to be running smoothly in desktop view. The functionality is such that upon clicking any two product items (with one remaining selected by default), a detailed description ...

utilizing jQuery to deliver a $.post request to a .aspx file

Recently, I started following a jQuery tutorial on the phpAcademy channel hosted on thenewboston. In this tutorial, they demonstrate how to create an email validation form using ASP.net instead of PHP. However, despite following all the steps in the tutor ...

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

Encountering problem when trying to upload several images at once using a single input in CodeIgniter with

I'm attempting to use CodeIgniter and AJAX to upload multiple images using a single input field. Here's the code I have so far: HTML: <input type="file" name="files[]" id="file" multiple /> AJAX: $("#addItems").on("submit",function(e) { ...

Tips for iterating through the properties of every object within a Knockout observableArray and dynamically generating a table

My observableArray is dynamically populated with SQL data, resulting in varying columns each time. I am trying to present the SQL results in an HTML table but facing issues with the code below. This is the desired output format... var viewModel = func ...

How can I get my view to render in node.js/express using XMLHttpRequest()?

After working on my node/express app for the past three days, I am still facing an issue with making a GET request to a specific route from the client side. Despite using XMLHttpRequest and setting the necessary headers for authorization, the app remains s ...

Wordpress website fails to initiate Automate on Scroll (aos) functionality

I seem to be having trouble tackling any task that requires even the smallest amount of brain power. My current struggle is trying to integrate the AOS library into my Wordpress site. In an attempt to make it work, I inserted the following code into my fu ...

Retrieve the HTML value of an element in Vue.js by clicking on its adjacent element

Hey there, I'm currently working on a simple notes app and I've hit a roadblock with one particular feature. In my project, I have a card element with a delete button as a child. What I need to achieve is to check if the value of the .card-title ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

What steps are necessary to integrate expo-auth-session with Firebase?

I am working on implementing a feature in my code that will allow users to login and authenticate using their Google credentials. Once they successfully log in, I want them to be added to my authentication database in Firebase. My attempt to achieve this ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Utilize jQuery ajax to target a particular recurring input

I am using HTML code along with another jQuery loop. Within this loop, there is an input element that is also being looped. I am trying to manipulate it using jQuery Ajax... but I am facing an issue where only the first input element works properly. The re ...

Image not appearing when sharing on Facebook

I've been trying to create a Facebook share button using the Javascript SDK, and here is the code I have been utilizing: $(function() { $('.facebook-share').click(function(e) { e.preventDefault(); FB.ui({ method: 'feed& ...

Best practices for bulk inserting sequences in Node.js using MySQL

I have a dataset ready to be inserted into a MySQL database using nodejs. Here is the code I've written: con.connect(function (err) { myArray.forEach((el)=>{ con.query(1stQuery,1stValue,(error,result)=>{ //do something with ...