Automated crypto trading bot implementation 6 (with.Upbit Open API)
This post is about āImplementing an automated cryptocurrency trading bot 6 (series)ā.
Nowadays, the value of cryptocurrencies is steadily increasing.
In a bull market, it is necessary to trade according to your own trading technique.
In this series, we will create a trading bot that automatically trades according to the logic written in the code without me having to look at it.
In the previous article, I provided a step-by-step guide to the code that was written.
In this article, weāll go all the way to querying the market and exporting the resulting values to a JSON file to trade more cryptocurrencies.
(See: https://github.com/yeonuk44/Trading-Bot)
Get market code
const request = require("request");
const options = {
method: "GET",
url: "https://api.upbit.com/v1/market/all?isDetails=false",
headers: { accept: "application/json" },
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Thatās all it takes to get it to load.
However, I want to use modularity so that itās only used when needed, so Iām going to create a new market.js and make that function exportable.
Get my market.js code
// market.js
const request = require("request");
function getMarketsInfo() {
const options = {
method: "GET",
url: "https://api.upbit.com/v1/market/all?isDetails=false",
headers: { accept: "application/json" },
};
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) {
reject(error);
} else {
try {
const responseBody = JSON.parse(body);
resolve(responseBody);
} catch (parseError) {
reject(parseError);
}
}
});
});
}
module.exports = {
getMarketsInfo,
};
This will ensure that when that function is called, it will output the results in the form of json as declared in the responseBody.
Furthermore, I want to generate a file with the json and export the results, so letās modify the code accordingly.
JSON file generation code
const fs = require("fs");
const request = require("request");
function getMarketsInfo() {
const options = {
method: "GET",
url: "https://api.upbit.com/v1/market/all?isDetails=false",
headers: { accept: "application/json" },
};
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) {
reject(error);
} else {
try {
const responseBody = JSON.parse(body);
// Create a JSON file
fs.writeFileSync(
"marketsInfo.json",
JSON.stringify(responseBody, null, 2)
);
resolve(responseBody);
} catch (parseError) {
reject(parseError);
}
}
});
});
}
module.exports = {
getMarketsInfo,
};
Wrapping up
The fs module in Node.js makes it simple to manipulate the file system. In addition to creating JSON files, you can also read, update, delete, and more, so use it for whatever functionality you need.
Thatās it for this simple example of working with the file system in Node.js. We hope you found it useful.