const mysql = require('mysql'); const CryptoJS = require("crypto-js"); // PRODUCTION_ENV // const con = mysql.createConnection({ // host: "127.0.0.1", // database: "defutur2_chaincool", // user: "defutur2_chaincool_username", // password: "Qwerty123!@#", // port: '3306' // }, console.log("Connected to the election database") // ); const DBNAME = "defutur2_chaincool" const con = mysql.createConnection({ host: "localhost", database: DBNAME, user: "root", password: "", port: '3306', timezone: 'ID' }, console.log("Connected to the election database") ); const nodeBase64 = require('nodejs-base64-converter'); const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const CronJob = require("cron").CronJob; const app = express(); app.use(cors()); const { default: axios } = require("axios"); const base64 = require("base-64"); // const moment = require("moment"); const moment = require('moment-timezone'); const port = 8002; const goldenRationEntry = 0.618 const fibbonaciStoploss = 1 const fibbonaciTakeprofit = 2 con.connect(function(err) { console.log("err 51", err) console.log("Connected!"); app.get("/marketlist", async (req,res)=> { }) }); function indexOfMax(arr) { if (arr.length === 0) { return -1; } var max = arr[0]; var maxIndex = 0; for (var i = 1; i < arr.length; i++) { if (arr[i] > max) { maxIndex = i; max = arr[i]; } } return maxIndex; } // https://api.telegram.org/bot7357494685:AAE60DbKsQZjbWU1rlX1iGXUDcBLp8CrYpI/sendMessage?chat_id=@pasivincomeofficial&text=Pibot%20coming%20to%20you function getmarket() { // app.get("/market", async (req,res)=> { let response = null; new Promise(async (resolve, reject) => { try { response = await axios.get('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=100&convert=USDT', { // response = await axios.get('https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=2&convert=USDT', { headers: { 'X-CMC_PRO_API_KEY': 'a095115a-ff97-437f-866d-7df05cc3190f', // 'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c', }, }); } catch(ex) { response = null; // error // console.log(ex); // res.status(402).json(json); reject(ex); } if (response) { // success const json = response.data.data; if(response.status == 200) { console.log('time: '+ moment(new Date()).format('HH:mm:ss')); console.log(response.data.data); } else { axios.get("https://api.telegram.org/bot7403157322:AAFJtzWX2MGSxVjhJF0X4H3UHwA8u4OqmGk/sendMessage?chat_id=@piboterror&text=" + response ) // console.log(response.status, response) } // createIfTableNotExists(json); // splitPriceCoin(json); // let a = nodeBase64.encode(JSON.stringify(json)) // const b = JSON.parse(a) // console.log("js1", b) // res.status(200).json(json); // const sql = "INSERT INTO `market` (`slang`)"+ `VALUES ("${a}")`; // con.query(sql, function (err, result) { // if (err) throw err; // res.status(200).json(result); // console.log("1 record inserted",json); // res.status(200).json({response:"1 record inserted"}); // }); // resolve(json); } }); // }) } function getRandomCoin() { con.query("SHOW tables", function (err, result, fields) { if (err) throw err; if(result) { const result_ = result.map(table => table['Tables_in_defutur2_chaincool']) // console.log("res1", result_[(Math.floor(Math.random() * result.length))]) const coin = result_[(Math.floor(Math.random() * result.length))] sendSignalToTelegram(coin) } }) } function sendSignalToTelegram(coin) { con.query(`SELECT price FROM ${coin} ORDER BY id DESC LIMIT 24`, function (err, result, fields) { let coin_ = coin let leverage = 50 if (err) throw err; let data_decode = [] // console.log("aa", result) if(result) { result.forEach(element => { data_decode.push(element.price) }); // return let data_decode_reversed = [...data_decode].reverse() // console.log("rev", data_decode_reversed) // return; // res.status(200).json(data_decode); // get fibonnaci 61% const priceHighest = Math.max( ...data_decode_reversed ) const priceLowest = Math.min( ...data_decode_reversed ) const priceGap = priceHighest - priceLowest // entry price for fibbonaci61 let entryPrice = priceGap*goldenRationEntry + Math.min( ...data_decode_reversed ) // end const indexMax = indexOfMax(result) // get index highest price const indexHighest = data_decode_reversed.indexOf(Math.max(...data_decode_reversed)); // get index lowest price const indexLowest = data_decode_reversed.indexOf(Math.min(...data_decode_reversed)); // entry position for LONG or SHORT let entryPosition = indexLowest < indexHighest ? "LONG" : "SHORT" // TAKE PROFIT PRICE let pointTP = priceGap * fibbonaciTakeprofit; let priceTP = indexLowest < indexHighest ? (priceHighest + pointTP) : (priceHighest - (priceGap * fibbonaciTakeprofit)); let rateTP = pointTP/(entryPrice*0.01)*leverage // SL PRICE let pointSL = priceGap * fibbonaciStoploss let priceSL = indexLowest < indexHighest ? (entryPrice - pointSL) : (entryPrice + (priceGap * fibbonaciStoploss)); let rateSL = pointSL/(entryPrice*0.01)*leverage // PRICE FIB let priceGapFibo = priceGap * goldenRationEntry if(coin == 'BTC')leverage = 125 if(coin == 'ETH')leverage = 125 if(coin == 'BNB')leverage = 75 if(coin == 'XRP')leverage = 75 if(coin == 'BONK' || coin == 'SHIB' || coin == 'FLOKI' || coin == 'PEPE' || coin == 'RATS' || coin == 'XEC') { coin_ =1000+coin // console.log(coin_) entryPrice=entryPrice*1000 priceTP=priceTP*1000 priceSL=priceSL*1000 rateTP=rateTP*1000 rateSL=rateSL*1000 } const counting = Math.trunc(entryPrice) const countingLength = counting.toString().split('').length const decimalDigits = 5 const decimalEnd = decimalDigits - countingLength // console.log(counting, counting.toString().split('').length, decimalEnd) let signal = `-Coin/Token: ${coin_}/USDT (${leverage}X) %0A-Position: ${entryPosition}(Scalping) %0A-Harga entry: ${entryPrice.toFixed(decimalEnd)} %0A%0A-TP: ${priceTP.toFixed(decimalEnd)} (${rateTP.toFixed(decimalEnd)}%) %0A-SL: ${priceSL.toFixed(decimalEnd)} (${-rateSL.toFixed(decimalEnd)}%) %0A%0A-Time(Z8): ${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}`; let signalJson = { coinName: `${coin}`, pair: `USDT`, position: `${entryPosition}`, type: 'SCALPING', entryPrice: `${entryPrice.toFixed(decimalEnd)}`, tp: `${priceTP.toFixed(decimalEnd)}`, sl: `${priceSL.toFixed(decimalEnd)}`, time: `${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}`, result: 'NONE', resultDate: 'NONE' } // console.log("signal",priceGap, entryPrice, priceHighest, priceLowest, data_decode_reversed) // res.status(200).json(signal); // axios.get("https://api.telegram.org/bot7357494685:AAE60DbKsQZjbWU1rlX1iGXUDcBLp8CrYpI/sendMessage?chat_id=@pasivincomeofficial&text=" // +signal // ) saveSignal(signalJson) } }); } function saveSignal(signal) { console.log("token:", signal.coinName) var sql = `CREATE TABLE IF NOT EXISTS 1_SIGNAL_RELEASED (id INT AUTO_INCREMENT PRIMARY KEY, coinName text DEFAULT NULL, pair text DEFAULT NULL, position text DEFAULT NULL, type text DEFAULT NULL, entryPrice FLOAT NOT NULL, tp FLOAT NOT NULL, sl FLOAT NOT NULL, time text DEFAULT NULL, result text DEFAULT NULL, resultDate text DEFAULT NULL)` con.query(sql, function (err, result) { if (err) throw err; // console.log("Table created for: ", signal); const sql_ = `INSERT INTO 1_SIGNAL_RELEASED` + " (`coinName`,`pair`,`position`,`type`,`entryPrice`,`tp`,`sl`,`time`,`result`, `resultDate`)" + ` VALUES ("${signal.coinName}", "${signal.pair}", "${signal.position}", "${signal.type}", "${signal.entryPrice}", "${signal.tp}", "${signal.sl}", "${signal.time}", "${signal.result}", "${signal.resultDate}")`; con.query(sql_, function (err, result) { if (err) throw err; // console.log("1 record inserted: "+ a.symbol); }); }); } function createIfTableNotExists(json) { // con.query("SELECT * FROM market ORDER BY id DESC LIMIT 1", function (err, result, fields) { // if (err) throw err; // let symbol let decodeSlang // console.log("res", result) if(json) { // let result_ = result.map(a => a.symbol); json.map((a,idx) => { ///////////////////////////////////////// // console.log("Table created for: "+idx+" "+ a.symbol); if(a.symbol !== 'NOT') { var sql = `CREATE TABLE IF NOT EXISTS ${a.symbol} (id INT AUTO_INCREMENT PRIMARY KEY, price FLOAT NULL, added_data timestamp NOT NULL DEFAULT current_timestamp())` con.query(sql, function (err, result) { if (err) throw err; // console.log("Table created for: "+ a.symbol); }); } }) } } function splitPriceCoin(json) { // console.log(json.quote) // console.log(json[0].symbol + ": " + json[0]["quote"]["USDT"]["price"]) // setTimeout(() => { json.map(a => { // console.log(a.symbol + ": " + a["quote"]["USDT"]["price"]) if(a.symbol !== 'NOT') { const sql = `INSERT INTO ${a.symbol}` + " (`price`)" + ` VALUES ("${a["quote"]["USDT"]["price"]}")`; con.query(sql, function (err, result) { if (err) throw err; console.log("1 record inserted: "+ a.symbol); }); } }) // }, 2000); } app.get("/", async function (req, res) { console.log("hit home") res.send("Today1234: " + moment.tz("Asia/Jakarta").format()); }); function getSignalReleased() { con.query(`SELECT * FROM 1_SIGNAL_RELEASED WHERE result != 'NONE' `, function (err, result, fields) { if (err) throw err; if(result) { // console.log(result[0].sl, result[0].tp,result[0].position) result.forEach(res_ => { extractSignalToResult(res_) }) // let data = result[0].slang } }); } // con.query(`SELECT * FROM ${data.coinName} WHERE added_data BETWEEN '2024-08-03 07:00:00' AND '2024-08-03 08:00:00'`, function (err, result, fields) { // 2024-08-03T07:40:01.000Z function extractSignalToResult(data) { con.query(`SELECT price, added_data FROM ${data.coinName} WHERE added_data >= '${data.time}'`, function (err, result, fields) { if (err) throw err; if(result) { // console.log("data", data.coinName) // console.log(result) let flag = "loop" result.forEach(res_ => { if(flag !== "stop") { // console.log("res11", res_.price) if(data.position == "LONG" && data.tp < res_.price) { // console.log(data.coinName, data.position, data.time, res_.price, res_.added_data, ": kena TP #1") editResultSignal(data, "TP", res_.added_data) flag = "stop" return } else if(data.position == "LONG" && data.sl > res_.price) { // console.log(data.coinName, data.position, data.time, res_.price, res_.added_data, "kena SL #2") editResultSignal(data, "SL", res_.added_data) flag = "stop" return } else if(data.position == "SHORT" && data.tp > res_.price) { // console.log(data.coinName, data.position, data.time, res_.price, res_.added_data, ": kena TP #3") editResultSignal(data, "TP", res_.added_data) flag = "stop" return } else if(data.position == "SHORT" && data.sl < res_.price) { // console.log(data.coinName, data.position, data.time, res_.price, res_.added_data, ": kena SL #4") editResultSignal(data, "SL", res_.added_data) flag = "stop" return } else { // console.log(data.coinName, data.time, res_.price, res_.added_data, ": masi open") // flag = "stop" return } } }) // let data = result[0].slang } }); } function editResultSignal(data, result_, date) { con.query(`UPDATE 1_SIGNAL_RELEASED SET result = '${result_}', resultDate = '${date}' WHERE coinName = '${data.coinName}'`, function (err, result, fields) { if(err) throw err console.log("update success", result_, data.coinName) }) } //============================= MOBEE ============================= const apiKey = "0832b9e0-510b-41ec-8886-f3791b89cf59" const apiSecret = "71740fed-59cb-40f8-9ee9-a42ed35c850a" // const apiKey = "d7640232-4092-4bfb-b773-e57b30b21076" // const apiSecret = "c0ca5730-a6d7-4425-9221-6ca842fb4fe9" const getMethod = "GET" const postMethod = "POST" const BASE_URL = 'https://open-api.mobee.io' // BALANCE const pathWalletBalance = '/v1/wallets/balances' // ADDRESSES const pathWalletAddresses = '/v1/wallets/addresses' // SUMMARY const pathSummary = '/v1/markets/summary' const pathCurrencies = '/v1/currencies' const pathCreateOrder = '/v1/orders' const network_id = 7 let timestamp = Math.floor(Date.now() / 1000) function getSummary() { let strToSign = getMethod + '\n' + pathSummary + '\n' + timestamp const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); const options = { method: getMethod, url: BASE_URL+pathSummary, headers: { accept: 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp } }; axios .request(options) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); } function getWalletBalance(currency) { let strToSign = getMethod + '\n' + pathWalletBalance + '\n' + timestamp const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); const options = { method: getMethod, url: BASE_URL+pathWalletBalance, headers: { accept: 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp }, params: { currency:"IDR" } }; console.log("opt", options) axios .request(options) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); } function getWalletAddresses() { let strToSign = getMethod + '\n' + pathWalletAddresses + '\n' + timestamp if (getMethod == "POST" || getMethod == "PUT") { strToSign += '\n' + pm.request.body.raw } const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); // console.log("wew", signBase64, timestamp) const options = { method: getMethod, url: BASE_URL+pathWalletAddresses, headers: { accept: 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp } }; axios .request(options) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); } function createAddress() { let strToSign = postMethod + '\n' + pathWalletAddresses + '\n' + timestamp + '\n' + {network_id:network_id} const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); console.log("ap2", postMethod, pathWalletAddresses, timestamp, network_id) const options = { method: postMethod, url: BASE_URL+pathWalletAddresses, headers: { accept: 'application/json', 'content-type': 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp }, body: { network_id:network_id } }; axios .request(options) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); } function getCurrencies() { let strToSign = getMethod + '\n' + pathCurrencies + '\n' + timestamp const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); const options = { method: getMethod, url: BASE_URL+pathCurrencies, headers: { accept: 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp } }; axios .request(options) .then(function (response) { response.data.data.forEach(element=> { console.log(element.symbol, element.networks); // element.networks }) }) .catch(function (error) { console.error(error); }); } function createNewOrder() { // apiKey = cf59 // apiSecret 850a // const pathCreateOrder = '/v1/orders' const data_ = { "side":"BUY", "market":"IDR", "trade":"PEPE", "type":"MARKET", "volume":140000, "rate":0.1536 } let strToSign = postMethod + '\n' + pathCreateOrder + '\n' + timestamp strToSign += '\n' + JSON.stringify(data_) const signBytes = CryptoJS.HmacSHA256(strToSign, apiSecret); const signBase64 = CryptoJS.enc.Base64.stringify(signBytes); console.log("ap2", postMethod, pathCreateOrder, timestamp, strToSign, signBytes, signBase64) const options = { method: postMethod, url: BASE_URL+pathCreateOrder, headers: { accept: 'application/json', 'content-type': 'application/json', 'X-Api-Key': apiKey, 'X-Request-Signature': signBase64, 'X-Request-Timestamp': timestamp }, data: data_ }; axios .request(options) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }); } //============================= CLOSE MOBEE ============================= function summarySignalCounter() { con.query(`SELECT result, count(result) FROM 1_SIGNAL_RELEASED WHERE result = 'NONE' OR result = 'SL' OR result = 'TP' GROUP BY result`, function (err, result, fields) { if (err) throw err; if(result) { console.log(result) const PNL = 100*result[2]['count(result)']*2 / result[1]['count(result)'] // result.forEach((res_, index) => { // console.log("coin: ", index, res_.result, res_['count(result)']) // }) axios.get("https://api.telegram.org/bot7257548278:AAGp1WLSGlcbXkkGl1zCQGnrxrAHWKfXb0U/sendMessage?chat_id=@pibotscalping&text=All Time Signal Performance : " + '\n' + "TP: " + result[2]['count(result)'] + '\n' + "SL: " + result[1]['count(result)'] + '\n' + "OPEN: " + result[0]['count(result)'] + '\n' + 'RR(2:1)' + '\n\n' + 'PnL: ' + PNL.toFixed(2) + "%" ) } }); } const job = new CronJob( '*/05 * * * *', // cronTime // '*/10 * * * * *', // cronTime function () { // console.log('You will see this message at'+ moment(new Date()).format('HH:mm:ss')); // getmarket() // getSummary() // createAddress() // getWalletAddresses() // getWalletBalance('IDR') // getCurrencies() }, // onTick null, // onComplete true, // start 'Asia/Jakarta' // timeZone ); const job2 = new CronJob( // '*/3 * * *', // cronTime '*/02 * * * * *', // cronTime function () { // console.log('You will see this message at'+ moment(new Date()).format('HH:mm:ss')); // getWalletAddresses() // getRandomCoin() // saveSignal(signal) // createNewOrder() // getSummary() // getWalletAddresses() // getWalletBalance('USDT') // getCurrencies() // createNewOrder() }, // onTick null, // onComplete true, // start 'Asia/Jakarta' // timeZone ); const job3 = new CronJob( // '*/3 * * *', // cronTime '*/05 * * * * *', // cronTime function () { // console.log('You will see this message at'+ moment(new Date()).format('HH:mm:ss')); // getSignalReleased() summarySignalCounter() }, // onTick null, // onComplete true, // start 'Asia/Jakarta' // timeZone ); app.listen(port, () => console.log(`Server running in ${port}`));