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

@JPLaclau @Lehigr2

Howdy folks!

Ran into same issue here, but I figured it out!

Long story short because it’s ES Module, you’ll have to import it:

// global.fetch = require('node-fetch')
import fetch from 'node-fetch'

if (!globalThis.fetch) {
  globalThis.fetch = fetch
}

Then in package.json you’ll need to add type:

{
  "dependencies": {
    "cryptocompare": "^1.0.0",
    "dotenv": "^10.0.0",
    "gemini-api": "^2.0.4",
    "node-fetch": "^3.0.0"
  },
  "type": "module"
}

Now, if you run it like that you’ll have an issue with require for GeminiAPI (assuming you used that). For that, we need to add two more lines of code, basically importing the require (weird but it works);

import { createRequire } from 'module'
const require = createRequire(import.meta.url)

After that, you should be able to execute the cryptocompare functions. Hope that helps… it worked for me

we don’t have Gemini in my country, i have been following your gemini installation for BitMax, below is the screenshot for what i have got, i am right? kindly need some help if not.Screenshot 2021-09-21 at 08.50.35

i don’t see BitMax-Api in what i have installed.

This was very helpful thanks.

If bitmax does not have a module for their api, you might have to build it yourself, we use gemini because they have their own module that make our life easier for programming a bot with it.

Carlos Z

Hi, I have messed up my code and I cant fix the syntax error. I forgot the lines that I have changed.

Can i just delete the whole thing and start all over again starting from downloading the powershell?

Hello

I am having issues. Im supposedly able to save the atom file to my computer.
Although when I try to copy the file to my powershell it says the file doesnt exist.
Am I missing something?

Hi Ivan,

I need a bit of help. I am trying to add “yarn add gemini-api” and I keep getting the below message.
Can you send the actual link as well (for yarn gemini-api) and suggestion to the error message?
I used from https://yarnpkg.com/package/gemini-api.

PS C:\Users\zsolt\Desktop\Ivan on Tech Academy\Programing Trading Bot> yarn add gemini-api
yarn : File C:\Users\zsolt\AppData\Roaming\npm\yarn.ps1 cannot be loaded because running scripts is disabled on this
system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • yarn add gemini-api
  •   + CategoryInfo          : SecurityError: (:) [], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess
    
    
    

thank you!

Zsolt

1 Like

Hey @Zsolt, hope you are well.

Try to use windows command prompt (CMD) instead of powershell, yours have the scripts blocked (you can google about how to run scripts on powershell if you want to use it).

Carlos Z

1 Like

Hi Everyone! Can anyone tell me why do we use a recursive call in the strategy, after the TimeOut()?
Won’t this result in ever growing memory requirement (and eventual crash)? As the app needs to be up and running continuously, this would be an issue.

Basically to create a loop on the function execution, one way or another, you need to iterate many times in the same code to track the price and take an action on it (based on the logic you put into).

The TimeOut() is the common example for it, but it could be something else if you want to.

Carlos Z

Hi Carlos!
Thanks for the answer! The point I wanted to ask wasn’t that I don’t get the use of the TimeOut() (we need to wait), but Ivan created a loop by having the function call itself again after the TimeOut. I though this would be a recursion and - correct me if I’m wrong - the computer keeps track of all variables on all scopes until the function exits (and it never does). So this would lead to a ballooning use of memory by the function (I am probably wrong if this is the common way to do it). I would have expected a while loop to encapsulate the cycle.

1 Like

having issues linking my gemini to Atom and Powershell.

const GeminiAPI = require (“gemini-api”).default;
const secret = “2NZvfm5gbZ2aZVrd659a19hquFGf”
const key = “rltjWkLoRlqWrXOQUhub”
const restClient = new GeminiAPI ({key,secret,sandbox:true});

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

Powershell:
Keeps coming up as error… No green indicators

Downloaded sandbox and everything and still doesnt work. Plus the order doesnt show up on Gemini. Did I miss something?

Hi There,

How do I run Node.JS on MAC?

Thank you

Hey @kr81, hope you are well.

Sorry for the delayed answer.

Take a look into this reply which is related to the issue your facing :nerd_face:

Carlos Z

You might wanna check: https://www.webucator.com/article/how-to-run-a-nodejs-application-on-a-mac/

Carlos Z

Thank you man. It really helps:
“when creating api choose primary not the master”.

For those who are still struggling, I filled secret as key and vice versa, for the first time. Different sequence for secret and key in atom(Ivan’s code) and on Gemini.

Also for me it works only in CMD and not in Workshell.

1 Like

Thanks for help. It is the case also. I have to admit that this course is hard to follow according to those “catches”.

2 Likes

Hello,

I having trouble with my BOT, when I run node index.js , it executes only buy, but not HOLD, its stalls and returns to command, also the trades are not being recorded on website gemini sandbox, if anyone knows about this issue please advise, thanks.

Strategy does not loop HOLD, code stops abruptly ,


C:\Users\jflor\Documents\AlgorithmicTrading>node index.js

=======================
Executing Strategy
MA:  62135
Price:  60756.00
BUY!

C:\Users\jflor\Documents\AlgorithmicTrading>

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 no position)

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

console.log("Executing Strategy");
  // If BTC > MA ==> sell (if we have a position)
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.marketSellBitcoin()
      .then(res=>{
        console.log("Sell successful");
        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 = "3iLGT133vQnkFePqaGoYHU7nGtcY";
const key = "account-XCa2X8uBDIBwfjWNDOBT";
const restClient = new GeminiAPI({key,secret, sandbox:true});

module.exports = {

  marketBuyBitcoin:function(){
    return restClient.newOrder({amount: 1,
                      price:60000,
                      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.js

const CCAPIKey = "9372ee7b2e6bd4fa91f0822336bc293d5d580bffcf11c7c958568627c6ce8baf";
const CryptoCompareAPI = require("cryptocompare");
CryptoCompareAPI.setApiKey(CCAPIKey);


module.exports = {



  hourlyMovingAverage:function(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 movingAverage = Math.floor(sum / hours);
      callback(movingAverage);

    })
    .catch(console.error)

  }



}

Now when I run on PowerShell I get this;

PS C:\Users\jflor\Documents\AlgorithmicTrading> node index.js

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62026
Price:  62079.21
HOLD!

=======================
Executing Strategy
MA:  62025
Price:  62017.13
BUY!
PS C:\Users\jflor\Documents\AlgorithmicTrading>

I am getting this error while installing

yarn add gemini-api

SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions…js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/home/jigmet/.nvm/versions/node/v5.1.1/lib/node_modules/yarn/bin/yarn.js:24:13)
at Module._compile (module.js:425:26)
at Object.Module._extensions…js (module.js:432:10)