Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Lee committed Aug 10, 2020
0 parents commit f71afc0
Show file tree
Hide file tree
Showing 31 changed files with 16,998 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
.DS_Store
node_modules
/dist

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

coverage
build
data
log

.env

examples/sample1-output.jpg
references/*
6 changes: 6 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
13 changes: 13 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## Live
BINANCE_LIVE_API_KEY=
BINANCE_LIVE_SECRET_KEY=

## Test
BINANCE_TEST_API_KEY=
BINANCE_TEST_SECRET_KEY=

## Slack
BINANCE_SLACK_ENABLED=false
BINANCE_SLACK_WEBHOOL_URL=
BINANCE_SLACK_CHANNEL=
BINANCE_SLACK_USERNAME=
15 changes: 15 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": ["airbnb", "prettier", "plugin:jest/recommended"],
"plugins": ["prettier", "jest"],
"rules": {
"prettier/prettier": ["error"],
"comma-dangle": ["error", "never"],
"max-len": ["error", { "code": 120 }],
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
},
"settings": {
"react": {
"version": "999.999.999"
}
}
}
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
.DS_Store
node_modules
/dist

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

coverage
build
data
log

.env

examples/sample1-output.jpg
references/*
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/node_modules/**
/dist/**
/tests/unit/coverage/**
14 changes: 14 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
printWidth: 120,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
jsxBracketSameLine: false,
arrowParens: 'avoid',
proseWrap: 'never',
htmlWhitespaceSensitivity: 'strict',
endOfLine: 'lf'
};
20 changes: 20 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"editor.tabSize": 2,
"eslint.enable": true,
"eslint.alwaysShowStatus": true,
"eslint.autoFixOnSave": true,
"files.trimTrailingWhitespace": true,
"files.exclude": {},
"files.insertFinalNewline": true,
"typescript.preferences.importModuleSpecifier": "relative",
"search.exclude": {
".git": true,
".build": true,
"**/.DS_Store": true,
"**/.vscode": true,
"**/coverage": true,
"**/node_modules": true
}
}
40 changes: 40 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# development stage
FROM node:13-alpine AS dev-stage

RUN apk add --no-cache make gcc g++ python

WORKDIR /srv

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

CMD [ "npm", "run", "dev" ]

# build stage
FROM dev-stage AS build-stage

RUN npm run build

RUN rm -rf node_modules

RUN npm install --production

# production stage
FROM node:13-alpine AS production-stage

ARG PACKAGE_VERSION=untagged
LABEL PackageVersion=${PACKAGE_VERSION}

ARG NODE_ENV=production
LABEL Environment=${NODE_ENV}

WORKDIR /srv

COPY --from=build-stage /srv /srv

CMD [ "npm", "start"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 chrisleekr

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Binance Auto Trading API

## How to use

1. Create `.env` file based on `.env.dist`.

2. Check `docker-compose.yml` for `BINANCE_MODE` environment parameter

3. Launch docker compose

```bash
$ docker-compose up -d
```

or

```bash
$ docker-compose -f docker-compose.server.yml up -d
```

## Environment Parameters

Use environment parameter to adjust parameters. Checkout `/config/custom-environment-variables.json`
45 changes: 45 additions & 0 deletions app/helpers/binance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const _ = require('lodash');
const config = require('config');

const Binance = require('binance-api-node').default;
const cache = require('./cache');

const binanceOptions = {};

if (process.env.BINANCE_MODE === 'live') {
binanceOptions.apiKey = config.get('binance.live.apiKey') || '';
binanceOptions.apiSecret = config.get('binance.live.secretKey') || '';
} else {
binanceOptions.httpBase = 'https://testnet.binance.vision';
binanceOptions.apiKey = config.get('binance.test.apiKey') || '';
binanceOptions.apiSecret = config.get('binance.test.secretKey') || '';
}

const client = Binance(binanceOptions);

const getSymbolInfo = async (logger, symbol) => {
const cachedSymbolInfo = await cache.get('symbol-info');
if (cachedSymbolInfo) {
logger.info({ cachedSymbolInfo }, 'Retreived symbol info from cache');
return JSON.parse(cachedSymbolInfo);
}

logger.info({}, 'Request exchange info from Binance');
const exchangeInfo = await client.exchangeInfo();
logger.info({}, 'Retrieved exchange info from Binance');
const symbolInfo =
_.filter(exchangeInfo.symbols, s => {
return s.symbol === symbol;
})[0] || {};

symbolInfo.filterLotSize = _.filter(symbolInfo.filters, f => f.filterType === 'LOT_SIZE')[0] || {};
symbolInfo.filterPrice = _.filter(symbolInfo.filters, f => f.filterType === 'PRICE_FILTER')[0] || {};
symbolInfo.filterPercent = _.filter(symbolInfo.filters, f => f.filterType === 'PERCENT_PRICE')[0] || {};
symbolInfo.filterMinNotional = _.filter(symbolInfo.filters, f => f.filterType === 'MIN_NOTIONAL')[0] || {};

const success = cache.set('symbol-info', JSON.stringify(symbolInfo), 600);
logger.info({ success, symbolInfo }, 'Retreived symbol info from Binance');
return symbolInfo;
};

module.exports = { client, getSymbolInfo };
13 changes: 13 additions & 0 deletions app/helpers/cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const NodeCache = require('node-cache');

const nodeCache = new NodeCache();

const set = (key, obj, ttl) => {
return nodeCache.set(key, obj, ttl);
};

const get = key => {
return nodeCache.get(key);
};

module.exports = { set, get };
13 changes: 13 additions & 0 deletions app/helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const cache = require('./cache');
const logger = require('./logger');
const slack = require('./slack');
const binance = require('./binance');
const tulind = require('./tulind');

module.exports = {
cache,
logger,
slack,
binance,
tulind
};
11 changes: 11 additions & 0 deletions app/helpers/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const bunyan = require('bunyan');
const packageJson = require('../../package.json');

const logger = bunyan.createLogger({
name: 'api',
version: packageJson.version,
streams: [{ stream: process.stdout, level: process.env.NODE_ENV !== 'test' ? bunyan.TRACE : bunyan.FATAL }]
});
logger.info({ NODE_ENV: process.env.NODE_ENV }, 'API logger loaded');

module.exports = logger;
17 changes: 17 additions & 0 deletions app/helpers/slack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const axios = require('axios');
const config = require('config');

const sendMessage = text => {
if (config.get('slack.enabled') === false) {
return Promise.resolve({});
}

return axios.post(config.get('slack.webhookUrl'), {
channel: config.get('slack.channel'),
username: config.get('slack.username'),
type: 'mrkdwn',
text
});
};

module.exports = { sendMessage };
11 changes: 11 additions & 0 deletions app/helpers/tulind.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const tulind = require('tulind');

const bbands = (candlesData, period, stddev) => {
return tulind.indicators.bbands.indicator([candlesData.close], [period, stddev]);
};

const sma = (candlesData, period) => {
return tulind.indicators.sma.indicator([candlesData.close], [period]);
};

module.exports = { bbands, sma };
27 changes: 27 additions & 0 deletions app/jobs/alive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const aliveHelper = require('./alive/helper');
const { slack } = require('../helpers');

const execute = async logger => {
logger.info('Alive: Notify balance and current candle');

try {
// 1. Get balance
const balanceInfo = await aliveHelper.getBalance(logger);

// 2. Get current candle
const lastCandle = await aliveHelper.getLastCandle(logger);

slack.sendMessage(
`Account Balance:\`\`\`${JSON.stringify(balanceInfo, undefined, 2)}\`\`\`\nLast Candle:\`\`\`${JSON.stringify(
lastCandle,
undefined,
2
)}\`\`\``
);
} catch (e) {
logger.error(e, 'Execution failed.');
slack.sendMessage(`Execution failed\n\`\`\`${e.message}\`\`\``);
}
};

module.exports = { execute };
25 changes: 25 additions & 0 deletions app/jobs/alive/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const _ = require('lodash');
const config = require('config');
const { binance } = require('../../helpers');

const getBalance = async logger => {
const balanceSymbols = config.get('jobs.alive.balanceSymbols').split(',');
const accountInfo = await binance.client.accountInfo();
const balances = _.filter(accountInfo.balances, b => balanceSymbols.includes(b.asset));

logger.info({ balances }, 'Retrieved balances');
return balances;
};

const getLastCandle = async logger => {
const candle = await binance.client.candles({
symbol: config.get('jobs.alive.priceSymbol'),
interval: '1m',
limit: 1
});

logger.info({ candle }, 'Retrieved last candle');
return candle;
};

module.exports = { getBalance, getLastCandle };
Loading

0 comments on commit f71afc0

Please sign in to comment.