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

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

Is it possible to create a replicating text box in AngularJS that multiplies when entering input

I am experimenting with creating a sequence of text boxes that dynamically generate new empty text boxes as the user enters information into each one. Each text box is required to have an ng-model value associated with it, and they should all be generated ...

Refresh meta tags in a Next.js/React app

In the process of optimizing a website for SEO, I am facing the challenge of updating the meta description's content dynamically without using any third-party libraries. While I have successfully implemented the functionality, it currently requires a ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...

The image loads successfully from an AJAX request in CodePen, but fails to load in the local

I am currently working on integrating a weather API into my basic website and I would like to incorporate the weather icons as well. The API request successfully works in both my local and live environments, however, I encounter an error with the icon spec ...

What is the best way to turn off the annoying pop-up messages that show up for input validation, specifically the one that says "Please complete

Currently using Angular 2, my form has input fields similar to this simplified version: <input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1"> <!--more inputs like this --> Although I have implement ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers: cNames = ["Year","Count"] And another for data: mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143] The goal is to combine them like this: [ { Year: "2005", Count: 5021 ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

I'm feeling a bit lost with this JSON example - specifically with JSON.parse, JSON.stringify, as well as localStorage.setItem

As a beginner in learning JSON, I find that W3schools does not provide clear explanations of what each line of code does. While I can interpret some parts, there are sections that still remain unclear to me. // Data storage process: 1. myObj = {name: "Jo ...

The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']); myApp.controller('DemoController', function($scope, $timeout, $rootElement) { $scope.$rootElement = $rootElement; $scope.$timeout= $timeout; $scope.init = ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

How can I set the background of specific text selected from a textarea to a div element?

Is it possible to apply a background color to specific selected text from a Text area and display it within a div? let elem = document.getElementById("askQuestionDescription"); let start = elem.value.substring(0, elem.selectionStart); let selection = ...

res.cookie function is unable to set cookies in the Chrome web browser

During development, I have a basic login page running locally on my machine (http://127.0.0.1:5500/index.html) and a simple express server running at http://localhost:3003 Despite seeing the server sending my access_token in response headers, Chrome brows ...

Employ variables as a jQuery selector

let myLink = "#portfolio-link-" + data[i].pf_id; I am storing an ID in a variable. $("#pf-container-1").append(portfolio); console.log(myLink); $(myLink).append(function(){ $("<button class='btn btn-inverse' id='portfo ...

Simulating SOAP requests using the Nock library

I have a project in progress involving a node application that interacts with soap services. To handle parsing of JSON into a valid SOAP request and vice versa for the response, I am using the foam module. Everything works smoothly when communicating with ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...