Javascript bot programming using Gemini API, NodeJS and CryptoCompare - DISCUSSION

hey can someone help me please? i’m having trouble with the Daily Moving Average Indicator
Everything works except the Daily MA indicator i’m still getting this error on the power shell:

TypeError: Cannot read property ‘close’ of undefined
at D:_WORKING_TEMP__Ivan on Tech_Academy_\Algorithmic Trading_code\indicators.js:64:22
at processTicksAndRejections (node:internal/process/task_queues:94:5)

//  DAILY MA (MOVING AVERAGE) BLOCK-START // THIS IS LINE 51
    DailyMA:function(cryptoAsset, fiatCurrency, days, callback){
      if(days>365){
        console.error("Error: Only up to 365 days allowed!")
        return
      }
      // fetching data from CryptoCompare API
      CryptoCompareAPI.histoDay(cryptoAsset, fiatCurrency)
      .then(data => {
        // calculate MA from past hours
        data = data.reverse()
        var sum = 0;
        for(var i = 0; i<days; i++){
        sum+=data[i].close;
        }
        var Days_movingAverage = sum/days;
        callback(Days_movingAverage)
      })
      .catch(console.error); // listen for any errors
 },    // DAILY MA (MOVING AVERAGE) BLOCK-END //THIS WOULD BE LINE 70

so exactly, the error is sending me to this line (after reversing de data)
specifically, its refering to “.close”
so what to do with this?? I have no clue

sum+=data[i].close;

my best guess is that i need to tell the DailyMA function to fetch the last unix timestamp avaliable (meaning everything exluiding today) ?? but i have no idea on how to exactly do that… plz helps?

  • toTs (Number) Last unix timestamp to return data for.
  • limit (Number | 'none' ) Limit the number of days to lookup. Default is 30. If you set it to the string 'none' , you will get all available data.

removing the DailyMA indicator makes everything work fine (I’m starting video 25 “scripting gemini buy bitcoin shortcut” so basically everything works fine, just this indicator has been giving me trouble)

1 Like

Hey @Alex_Chaz, hope you are ok.

Could you please provide the entire code so i can test it? But i think it could be a bad declaration for the callback, in my code, i made the functions async because it is more efficient to manage async functions, here is my example function:

/*
// @dev Calculate Daily Moving Average
// @var _asset, string
// @var _pair, string
// @var _days, integer
*/
async function dailyMovingAverage(_asset, _pair, _days, callback){
  if(_days>31){console.log("Only up to 31 days allowed."); return}
  let _data = await cCompare.histoDay(_asset, _pair, function(_res){
    _res.reverse()
    let _sum = 0
    for(let _i = 0; _i < _days; _i++){
      _sum += _res[_i].close
    }
    let _movingAverage = Math.floor(_sum/_days)
    callback(_movingAverage)
  })
}

Carlos Z

1 Like

thank you! im gonna try it this way hoping i dont need to come back asking more questions haha

1 Like

Hi Guys,

I am stuck with Powershell when i try to send the order to Gemini it tell gives me error message about unhandled promise rejection. I have follow allong all why Ivan was saying.
I don’t know how to fix this, can someone hepl, please?

1 Like

Hi all! I am trying to sign up with GEMINI. Unfortunately i am stuck at the next step.The link is forwarding me to https://exchange.sandbox.gemini.com/register/confirm-phone but in reality all i see is a blank page. Developer tools telling me there is an an issue with

Request URL: https://static.sandbox.gemini.com/js/xxxxxxxxxxxxx.js
Request Method: GET
Status Code: 404 
Remote Address: 13.32.14.55:443
Referrer Policy: strict-origin-when-cross-origin

My question: Is anybody in the same situation ? And yes i got the email from GEMINI to approve my device… but the next step failed. Any other ideas ?
Cheers CH

1 Like

Hey @Leo1, hope you are ok.

Please provide an screenshot of the error that is being showed to you or you can copy/paste the code by following this guideline: FAQ - How to post code in the forum

Carlos Z

hey @mchoeti, hope you are ok.

You could have an issue with the GEMINI platform, maybe an adblock or something that blocks your signup. Any case i advice you to contact GEMINI support to see what options do they offer.

Carlos Z

Dear Carlos! Thanks for your reply. I did that and i will wait a little bid. As an alternative i can use a different email. I mean it is only sandbox. But unfortunately ma shields have been down. So i was really open for an Kilrathi attack. @Does someone know the famous pc game Wing Commander ? Anyway. Thanks for your reply i will keep you up to date. Cheers Ch

Dear @Grant38 try this one… Please replace this values with your secret and your key

/*jshint esversion: 6 */
console.log("Welcome my API Key");

// Basic SETUP
const GeminiAPI = require("gemini-api").default;
const secret = "yourAPISecret";
const key = "yourAPIKey";
const restClient = new GeminiAPI({ key, secret, sandbox: true });

restClient.newOrder({
        amount: 1,
        price: 100,
        side: "buy",
        symbol: "btcusd"
    })
    .then(_res => {
        console.log(_res);
    })
    .catch(console.error);

Yes you do not need the console. But for me this is always a good starting point .
Safe trades :slight_smile:

And if you want it a little bid simpler. Try to use this one. Replace restClient.newOrder and the rest with the following code.

restClient.getAllSymbols()
    .then(response => {
        console.log(response)
    });

Then safe it and give it a try

Thank you have sorted it out

Had the same issue and this worked. Thank You!!!

well i thought it worked, not this comes up.
image
image

@thecil
sorry im basically blowing up this page but i think it worked now. there was a space between gemini and -api when its suppose to be “one word”.
image

however now i have a new issue
please help, what am i doing wrong?
image
image

1 Like

when you write getALLSymbols, ALL, is supposed to be —>All, so like this: getAllSymbols (don’t forget restclient)

1 Like

Hey @VincentC, hope you are ok.

As @cryptoforyou has mention, your declaration if incorrect.
You have getALLSymbols() where it should be getAllSymbols.

Carlos Z

1 Like

whoops, those ()s atrnt part of the code

2 Likes

image
im having trouble getting the “Hold” portion of the loop coming back. It always ends after confirming the buy. what have i done now??

//Index

global.fetch = require("node-fetch");

const indicators = require("./indicators.js");
const exchange = require("./exchange.js");

var hasPosition = false;
var strategy = function(){


//IF BTC < MA ==> BUY (If we have no position)
//IF BTC > ma ==> SELL (if we have a position)

console.log("     ");
console.log("=================");
console.log("Executing strategy");

indicators.hourlyMovingAverage("BTC", "USD", 100, function(ma){
  exchange.bitcoinPrice()
  .then(res => {
    var price = res.last;
  console.log("MA:", ma);
console.log("price:", price);

if(price < ma && !hasPosition){

  console.log("buy!");
  exchange.marketBuyBitcoin()
  .then(res=>{
    console.log("buy successful");
      hasPosition = true;
      setTimeout(strategy,1000);

  })
.catch(error => console.error)
}

else if(price > ma && hasPosition){
  console.log("sell!");
  exchange.marketBuyBitcoin()
  .then(res=>{
    console.log("Sell successful");
      hasPosition = false;

      setTimeout(strategy,1000);

  })
.catch(error => console.error)
}

else{
  console.log("hold");
  setTimeout(strategy,1000);


}


  })
});

}

strategy();
//exchange
module.exports = {

  marketBuyBitcoin:function(){
  return restClient.newOrder({amount:1, price:100000, side:"buy", symbol:"btcusd", options:["immediate-or-cancel"]})

},
  marketSellBitcoin:function(){
    return restClient.newOrder({amount:1, price:1, side:"sell", symbol:"btcusd", options:["immediate-or-cancel"]})
  },

  bitcoinPrice:function(){
    return restClient.getTicker("btcusd");
  }


}
//Indicators
module.exports = {

  hourlyMovingAverage:function hMovingAverage(cryptoAsset, fiatCurrency, hours, callback){
if(hours>169){
  console.error("only up to 169 hours allowed!")
  return
}
CryptoCompareAPI.histoHour(cryptoAsset, fiatCurrency)
.then(data => {
  data = data.reverse();
  var sum = 0;
  for(var i = 0;i<hours;i++){
    sum+=data[i].close;
}
var hMovingAverage = Math.floor(sum/hours);

callback(hMovingAverage);
})
.catch(console.error);}

,
dailyMovingAverage:function dMovingAverage(cryptoAsset,fiatCurrency,days,callback){
if(days>300){
console.error("only up to 300 days allowed!")
return
}
CryptoCompareAPI.histoDay(cryptoAsset, fiatCurrency, {limit:"none"})
.then(data => {
data = data.reverse();
var sum = 0;
for(var i = 0;i<days;i++){
  sum+=data[i].close;
}
var dMovingAverage = sum/days;

callback(dMovingAverage);
})
.catch(console.error);}
,

minutelyMovingAverage:function mMovingAverage(cryptoAsset,fiatCurrency,minutes,callback){
if(minutes>1400){
  console.error("only up to 1440 minutes allowed!")
  return
}

CryptoCompareAPI.histoMinute(cryptoAsset, fiatCurrency)
.then(data => {
  data = data.reverse();
  var sum = 0;
  for(var i = 0;i<minutes;i++){
    sum+=data[i].close;
}
var mMovingAverage = sum/minutes;

callback(mMovingAverage);
})
.catch(console.error);}
};

Please can someone help me. I’m on lecture 14 of the bot programming section and everytime I enter node index.js it keeps showing me this warning:

(node:10140) UnhandledPromiseRejectionWarning: #
(Use node --trace-warnings ... to show where the warning was created)
(node:10140) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:10140) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

If anyone can assist I would really appreciate it! Thanks

1 Like

can you copy your code or screen shot plz? hope all is well!

I need help.

Error: Cannot find module ‘gemini-api’
Require stack:

  • C:\Users\thedo\Documents\AnonymoBot1\index.js
    ←[90m at Function.Module._resolveFilename (node:internal/modules/cjs/loader:924:15)←[39m
    ←[90m at Function.Module._load (node:internal/modules/cjs/loader:769:27)←[39m
    ←[90m at Module.require (node:internal/modules/cjs/loader:996:19)←[39m
    ←[90m at require (node:internal/modules/cjs/helpers:92:18)←[39m
    at Object. (C:\Users\thedo\Documents\AnonymoBot1\index.js:1:19)
    ←[90m at Module._compile (node:internal/modules/cjs/loader:1092:14)←[39m
    ←[90m at Object.Module._extensions…js (node:internal/modules/cjs/loader:1121:10)←[39m
    ←[90m at Module.load (node:internal/modules/cjs/loader:972:32)←[39m
    ←[90m at Function.Module._load (node:internal/modules/cjs/loader:813:14)←[39m
    ←[90m at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)←[39m {
    code: ←[32m’MODULE_NOT_FOUND’←[39m,
    requireStack: [ ←[32m’C:\Users\thedo\Documents\AnonymoBot1\index.js’←[39m ]

i keep getting this error code. what am I doing wrong?