A Blog by Hangindev

Bitcoin Dollar Cost Averaging With Binance API, Node.js

/**
* Disclaimer:
*
* Any action you take upon the information on this page is strictly at your own
* risk. Do your own research.
*
* Prerequisite:
*
* 1. Get a Binance account
*
* You may use the referal link below so both of us get 10% commission fee
*
* @link https://www.binance.com/en/register?ref=I6Z9DEQD
*
* 2. Store your Binance api key and secret key in a `.env` file
*
* @link https://www.binance.com/en/support/faq/360002502072-How-to-create-API
*
* 3. Buy some stablecoins (e.g. USDT) for making orders
*
* @link https://www.binance.com/en/buy-TetherUS
*
*/
require("dotenv").config();
const cron = require("node-cron");
const axios = require("axios");
const qs = require("qs");
const crypto = require("crypto");
/**
* Sign the payload with your Binance secret key
*
* @link https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#signed-trade-and-user_data-endpoint-security
*/
function signPayload(payload) {
const data = { ...payload, timestamp: Date.now() };
const signature = crypto
.createHmac("sha256", process.env.BINANCE_SECRET_KEY)
.update(qs.stringify(data))
.digest("hex");
return { ...data, signature };
}
/**
* Send in a new order.
*
* @link https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#new-order--trade
*/
function order(params) {
return axios({
method: "POST",
// url: `https://api.binance.com/api/v3/order/test`,
url: `https://api.binance.com/api/v3/order`,
params: signPayload(params),
headers: { "X-MBX-APIKEY": process.env.BINANCE_API_KEY },
});
}
/**
* Order as many Bitcoin as 10 USDT can.
*/
async function orderBitcoin() {
try {
const { data } = await order({
symbol: "BTCUSDT",
side: "BUY",
type: "MARKET",
quoteOrderQty: 10,
});
// if test endpoint is used, the response will be an empty object
if (data.fills) {
const { price, commission, qty } = data.fills[0];
console.log(
`Ordered ${qty}BTC at price ${price}, commission ${commission}.`,
);
} else {
console.log("Successfully create a test order.");
}
} catch (error) {
console.log(error.response?.data || error.message);
}
}
/**
* Schedule to run the orderBitcoin function everyday at 00:00, America/New_York.
*/
cron.schedule("0 0 * * *", orderBitcoin, {
timezone: "America/New_York",
});
/**
* That's it. Now you may deploy on the `application` on DigitalOcean/Heroku to
* keep it running and manage the process with PM2.
*
* @link https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-20-04
*
* Explore what you can do with other Binance APIs and have fun.
*
* -- THE END --
*/