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

I was able to figure this out. I needed to uninstall node-fetch and install an earlier version.

1 Like

I had a few troubles getting Gemini API but managed to figure it out.

  1. I opened PowerShell as an administrator.
  2. Directed to folder. cd and paste path
  3. Installed yarn, npm install yarn --global
  4. yarn add gemini-api (fails, script disabled)
  5. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7 to bypass policy enter Set-ExecutionPolicy -ExecutionPolicy RemoteSigned and hit yes.
  6. Use the up arrow to run the 4th step (yarn add gemini-api) and enter to install.

    This is what I’ve done just in case anyone has trouble. If there are any mistakes please let me know, thank you!

You might need to reinstall yarn, your version is out of date, and probably one of the dependencies needs the latest version to work properly.

https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable

Carlos Z

1 Like

I’m very new to all this but i found a walk through on setting up and navigating through PowerShell.
https://youtu.be/MY0yIUPDe50

Got It! scrolled through various messages in the forum that were helpful. First made sure the console was up to date and updated dependencies. When making an API Key don’t use the Master key, use primary. Had some missing brackets and added them to the code. I also added

.catch(console.error);

Please need help! I’ve been stuck looking at this code for hours.

index.js

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 a position)
 // If BTC > MA ==> sell (If we have a postion)

 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 successfull");
         hasPosition = true;

         setTimeout(strategy,1000);
       })
       .catch(error => console.error)

     }

    else if(price > ma && hasPosition){

       console.log("Sell!");
       exchange.marketBuyBitcoin()
       .then(res =>{
         console.log("Sell successfull");
         hasPosition = false;

         setTimeout(strategy,1000);
         })
       .catch(error=> console.error)

     }

     else{

       console.log("Hold!");
       setTimeout(strategy,1000);
     }


   })


 });

}

strategy();

exchange.js

const GeminiAPI = require("gemini-api").default;
const secret = "**********";
const key = "account-**********";
const restClient = new GeminiAPI({key, secret, sandbox:true});


module.exports = {

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

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

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

  }

}

indicators.js

onst CCAPIKey = "************"
const CryptoCompareAPI = require("cryptocompare");
CryptoCompareAPI.setApiKey(CCAPIKey);

module.exports = {

  hourlyMovingAverage:function(cryptoAsset, fiatCurrency, hours, callback){

    if(hours>169){
      console.error("Only up tp 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 movingAverage = Math.floor (sum/hours);
    callback(movingAverage);

    })
    .catch(console.error)

  }
}

Does the console shows any error when you run the code?

Carlos Z

Is it that the first order isn’t successful so the console doesn’t print hold every second?

Could you please share your code in the following way?

Carlos Z

Problem solved I think it was the spacing at the very top function.

var strategy = function(){

IT WORKS!

1 Like

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

ERROR

node-fetch changed to ES modules by default:

SOLUTION:

  1. Uninstall the current version of node-fetch with npm uninstall node-fetch
  2. Install the second version: npm install node-fetch@2
    It has worked for me!
2 Likes

Heyy there. I am having problems with the gemini web page, I don’t know what to do. Can someone, help me pls?

what is your issue?
https://exchange.sandbox.gemini.com/balances check this website you should be able to have an account;
make sure you validate your account by clicking on the email from gemini or an sms sent to your phone. otherwise the API settings wont work.
then go to settings and set your API; avoid the master key to use ; create a primary API and save it.
example:

const GeminiAPI = require("gemini-api").default;
const secret = "< secret key";
const key = "account-secret account key";
const restClient = new GeminiAPI({key, secret, sandbox:true});

1 Like

all right i finish the course
and the forum was great to fix some of the updates/ on the node-fetch upgrade … i got stuck but the forum saved me time :hammer:
the only change I made on the code is to set the MA value to added into my sell or buy bitcon at the MA price; so i will buy or sell something instead of a fix number; i increased timer to 10 sec… so i can catch with my slow :eyes: the results

in indicator.js file
module.exports = {

     marketBuyBitcoin:function(ticker){

    return restClient.newOrder({
          amount:1,
          price:ticker,
          side:"buy",
          symbol:"btcusd",
          options:["immediate-or-cancel"]})
in index.js
exchange.bitcoinPrice(ma)
        .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("bought successfull");
                    hasPosition = true;
                    setTimeout(strategy,10000);

                })
                .catch(error => console.error)```
Image with results

Thanks Aldrin, let me look into that. If I cannot move on, Could I request your help?

1 Like

Hi,
I came across a failure when running following:

baichen@MacProM1:~/GeminiApi$ node index.js 
node:internal/modules/cjs/loader:1125
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/baichen/GeminiApi/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /Users/baichen/GeminiApi/node_modules/node-fetch/src/index.js from /Users/baichen/GeminiApi/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /Users/baichen/GeminiApi/node_modules/node-fetch/src/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/baichen/GeminiApi/node_modules/node-fetch/package.json.

    at new NodeError (node:internal/errors:363:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1125:13)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:828:14)
    at Module.require (node:internal/modules/cjs/loader:1012:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at Object.<anonymous> (/Users/baichen/GeminiApi/index.js:1:16)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:988:32) {
  code: 'ERR_REQUIRE_ESM'
}

Code:

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

const GeminiAPI = require("gemini-api").default;

const key = "xxxx";

const secret = "xxxx";

const CCAPIKey = "xxx";

const restClient = new GeminiAPI({key,secret,sandbox:true});

const CryptoCompareAPI = require("cryptocompare");

CryptoCompareAPI.setApiKey(CCAPIKey);

you have to either upgrade or downgrade your node-fetch ; I believe i had the same error and i did this and then it worked out.

const GeminiAPI = require("gemini-api").default;
const secret = "xxxxxxxxxxxxx";
const key = "xxxxxxxxxxxxxx";
const restClient = new GeminiAPI({key, secret, sandbox: true});

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

Hi everyone, I am running into the following problem in powershell:

{
result: ‘error’,
reason: ‘InvalidNonce’,
message: “Nonce ‘1660911401386’ is not within 30 seconds of server time ‘1660911402’’”
}

Does anyone know what this means?

You might need to sync the time of your OS system.

Carlos Z