Skip to content

Commit

Permalink
Merge pull request #37 from Adamant-im/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
dev-adamant-im authored Aug 28, 2023
2 parents f124532 + ad152ea commit f10fd28
Show file tree
Hide file tree
Showing 16 changed files with 10,184 additions and 8,289 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Profit trading is a mode in which a bot runs orders according to some strategy.
* [P2PB2B](https://p2pb2b.com)
* [Azbit](https://azbit.com?referralCode=9YVWYAF)
* [StakeCube](https://stakecube.net/?team=adm)
* [Coinstore](https://h5.coinstore.com/h5/signup?invitCode=o951vZ)

To add other exchange support, see [marketmaking.app/services](https://marketmaking.app/services/).

Expand Down
5 changes: 4 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const checker = require('./modules/checkerTransactions');
const doClearDB = process.argv.includes('clear_db');
const config = require('./modules/configReader');
const txParser = require('./modules/incomingTxsParser');
const { initApi } = require('./routes/init');

// Socket connection
const api = require('./modules/api');
Expand All @@ -12,8 +13,10 @@ api.socket.initSocket({ socket: config.socket, wsType: config.ws_type, onNewMess
setTimeout(init, 5000);

function init() {
require('./server');
try {
if (config.api?.port) {
initApi();
}
if (doClearDB) {
console.log('Clearing database…');
db.systemDb.db.drop();
Expand Down
32 changes: 25 additions & 7 deletions config.default.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"exchanges": [
"P2PB2B",
"Azbit",
"StakeCube"
"StakeCube",
"Coinstore"
],

/** Exchange to work with. Case insensitive. **/
Expand Down Expand Up @@ -91,6 +92,12 @@
/** Slack keys for priority notifications **/
"slack_priority": [],

/** Discord keys for notificationis and monitoring. Optional. **/
"discord_notify": ["https://discord.com/api/webhooks/..."],

/** Discord keys for priority notificatons. Optional. **/
"discord_notify_priority": [],

/** If you don't want to receive "not enough balance" notifications, set this to "true" **/
"silent_mode": false,

Expand All @@ -100,12 +107,23 @@
**/
"log_level": "log",

/**
Port for getting debug info.
Do not set for live bots, use only for debugging.
Allows to get DBs records like http://ip:port/db?tb=incomingTxsDb
**/
"debug_api": false,
"api": {
/** Port to listen on. Set 'false' to disable **/
"port": false,

/**
Enables health API
Allows to check if bot is running with http://ip:port/ping
**/
"health": false,

/**
Enables debug API
Do not set for live bots, use only for debugging.
Allows to get DBs records like http://ip:port/db?tb=incomingTxsDb
**/
"debug": false
},

/** Minimal amount of USDT to confirm buy/sell/fill commands **/
"amount_to_confirm_usd": 1000
Expand Down
63 changes: 45 additions & 18 deletions helpers/notify.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,24 @@ const {
adamant_notify_priority = [],
slack = [],
slack_priority = [],
discord_notify = [],
discord_notify_priority = [],
} = config;

const slackColors = {
'error': '#FF0000',
'warn': '#FFFF00',
'info': '#00FF00',
'log': '#FFFFFF',
};

const discordColors = {
'error': '16711680',
'warn': '16776960',
'info': '65280',
'log': '16777215',
};

module.exports = (messageText, type, silent_mode = false, isPriority = false) => {
try {
const prefix = isPriority ? '[Attention] ' : '';
Expand All @@ -23,26 +39,10 @@ module.exports = (messageText, type, silent_mode = false, isPriority = false) =>
slack;

if (slackKeys.length) {
let color;
switch (type) {
case ('error'):
color = '#FF0000';
break;
case ('warn'):
color = '#FFFF00';
break;
case ('info'):
color = '#00FF00';
break;
case ('log'):
color = '#FFFFFF';
break;
}

const params = {
'attachments': [{
'fallback': message,
'color': color,
'color': slackColors[type],
'text': makeBoldForSlack(message),
'mrkdwn_in': ['text'],
}],
Expand All @@ -51,7 +51,7 @@ module.exports = (messageText, type, silent_mode = false, isPriority = false) =>
slackKeys.forEach((slackApp) => {
if (typeof slackApp === 'string' && slackApp.length > 34) {
axios.post(slackApp, params)
.catch(function(error) {
.catch((error) => {
log.log(`Request to Slack with message ${message} failed. ${error}.`);
});
}
Expand All @@ -75,6 +75,29 @@ module.exports = (messageText, type, silent_mode = false, isPriority = false) =>
});
}

const discordKeys = isPriority ?
[...discord_notify, ...discord_notify_priority] :
discord_notify;

if (discordKeys.length) {
const params = {
embeds: [
{
color: discordColors[type],
description: makeBoldForDiscord(message),
},
],
};
discordKeys.forEach((discordKey) => {
if (typeof discordKey === 'string' && discordKey.length > 36) {
axios.post(discordKey, params)
.catch((error) => {
log.log(`Request to Discord with message ${message} failed. ${error}.`);
});
}
});
}

} else {
log[type](`/No notification, Silent mode, Logging only/ ${removeMarkdown(message)}`);
}
Expand Down Expand Up @@ -102,3 +125,7 @@ function makeBoldForMarkdown(text) {
function makeBoldForSlack(text) {
return doubleAsterisksToSingle(text);
}

function makeBoldForDiscord(text) {
return singleAsteriskToDouble(text);
}
88 changes: 74 additions & 14 deletions helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ module.exports = {
liquidity[key].amountTotalQuote = 0;
liquidity[key].lowPrice = averagePrice * (1 - liquidity[key].spreadPercent/100);
liquidity[key].highPrice = averagePrice * (1 + liquidity[key].spreadPercent/100);
liquidity[key].spread = averagePrice * liquidity[key].spreadPercent / 100;
liquidity[key].spread = liquidity[key].highPrice - liquidity[key].lowPrice;
// average price is the same for any spread
}

Expand Down Expand Up @@ -1300,34 +1300,75 @@ module.exports = {
return Math.round(-Math.log10(+precision));
},

/**
* Returns decimals for arbitrary number
* 0.00001 -> 5
* 1000.00001 -> 5
* 1 -> 0
* 0 -> 0
* @param {Number|String} number
* @returns {Number|undefined}
*/
getDecimalsFromNumber(number) {
number = number?.toString();

if (!isFinite(number)) return undefined;

const split = number.split('.');

if (split.length === 1) {
return 0;
}

return split[1]?.length;
},

/**
* Checks if order price is out of order book custom percent (as mm_liquiditySpreadPercent) spread
* @param order Object of ordersDb
* @param orderBookInfo Object of utils.getOrderBookInfo()
* @param obInfo Object of utils.getOrderBookInfo()
* @returns {Boolean}
*/
isOrderOutOfSpread(order, orderBookInfo) {
isOrderOutOfSpread(order, obInfo) {
try {
const liqInfo = order.subPurpose === 'ss' ? orderBookInfo.liquidity.percentSpreadSupport : orderBookInfo.liquidity.percentCustom;
const outOfSpreadInfo = {
isOrderOutOfSpread: false,
isOrderOutOfMinMaxSpread: false,
isOrderOutOfInnerSpread: false,
isSsOrder: order.subPurpose === 'ss',
orderPrice: order.price,
minPrice: undefined,
maxPrice: undefined,
innerLowPrice: undefined,
innerHighPrice: undefined,
spreadPercent: tradeParams.mm_liquiditySpreadPercent,
spreadPercentMin: tradeParams.mm_liquiditySpreadPercentMin,
};

const liqInfo = outOfSpreadInfo.isSsOrder ? obInfo.liquidity.percentSpreadSupport : obInfo.liquidity.percentCustom;
const roughness = liqInfo.spread * AVERAGE_SPREAD_DEVIATION;

// First, check mm_liquiditySpreadPercent
const minPrice = liqInfo.lowPrice - roughness;
const maxPrice = liqInfo.highPrice + roughness;
if (order.price < minPrice || order.price > maxPrice) {
return true;
outOfSpreadInfo.minPrice = liqInfo.lowPrice - roughness;
outOfSpreadInfo.maxPrice = liqInfo.highPrice + roughness;
if (order.price < outOfSpreadInfo.minPrice || order.price > outOfSpreadInfo.maxPrice) {
outOfSpreadInfo.isOrderOutOfSpread = true;
outOfSpreadInfo.isOrderOutOfMinMaxSpread = true;
return outOfSpreadInfo;
}

// Second, check mm_liquiditySpreadPercentMin: 'depth' orders should be not close to mid of spread
if (order.subPurpose !== 'ss' && tradeParams.mm_liquiditySpreadPercentMin) {
const innerLowPrice = orderBookInfo.averagePrice * (1 - tradeParams.mm_liquiditySpreadPercentMin/100) + roughness;
const innerHighPrice = orderBookInfo.averagePrice * (1 + tradeParams.mm_liquiditySpreadPercentMin/100) - roughness;
if (order.price > innerLowPrice && order.price < innerHighPrice) {
return true;
if (!outOfSpreadInfo.isSsOrder && tradeParams.mm_liquiditySpreadPercentMin) {
outOfSpreadInfo.innerLowPrice = obInfo.averagePrice * (1 - tradeParams.mm_liquiditySpreadPercentMin/100) + roughness;
outOfSpreadInfo.innerHighPrice = obInfo.averagePrice * (1 + tradeParams.mm_liquiditySpreadPercentMin/100) - roughness;
if (order.price > outOfSpreadInfo.innerLowPrice && order.price < outOfSpreadInfo.innerHighPrice) {
outOfSpreadInfo.isOrderOutOfSpread = true;
outOfSpreadInfo.isOrderOutOfInnerSpread = true;
return outOfSpreadInfo;
}
}

return false;
return outOfSpreadInfo;
} catch (e) {
log.error(`Error in isOrderOutOfSpread() of ${this.getModuleName(module.id)} module: ${e}.`);
return false;
Expand Down Expand Up @@ -1738,4 +1779,23 @@ module.exports = {
date.setMonth(date.getMonth() - 1);
return +(date.getTime() / 1000).toFixed(0) + 86400;
},

/**
* Creates an url params string as: key1=value1&key2=value2
* @param {Object} data Request params
* @returns {String}
*/
getParamsString(data) {
const params = [];

for (const key in data) {
const value = data[key];

if (value !== undefined) {
params.push(`${key}=${value}`);
}
}

return params.join('&');
},
};
5 changes: 3 additions & 2 deletions modules/configReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ const fields = {
type: String,
default: 'Hello 😊. This is a stub. I have nothing to say. Please check my config.',
},
debug_api: {
type: Number,
api: {
type: Object,
default: {},
},
amount_to_confirm_usd: {
type: Number,
Expand Down
Loading

0 comments on commit f10fd28

Please sign in to comment.