index.js 21.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const options = { method: 'GET', headers: { Accept: 'application/json' } };
const express = require('express');
const app = express();
const { Coin } = require("./models/Coin");
const { User } = require('./models/User');

require("dotenv").config();
const fs = require('fs');
const path = require('path');
const HTTPS = require('https');
const domain = "2019102152.osschatbot.ga"
const sslport = 23023;
const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
const BROAD_TARGET_URL = 'https://api.line.me/v2/bot/message/broadcast'
const bodyParser = require('body-parser');
const crypto = require('crypto');
const queryEncode = require('querystring').encode;
const request = require('request-promise-native');
const { v4 } = require("uuid")
const sign = require('jsonwebtoken').sign
const access_key = process.env.access_key;
const secret_key = process.env.secret_key;
const server_url = "https://api.upbit.com"
const TOKEN = process.env.token;
const userid = process.env.userid;

var delay_count=1;

var krw_balance;
var divided_money;

var sort_info = new Array();
const mongoose = require('mongoose');
const config = require('./config/key');
app.use(bodyParser.json());
const connect = mongoose.connect(config.mongoURI, {
    useNewUrlParser: true, useUnifiedTopology: true
})
    .then(() => console.log('db connected...'))
    .catch((err) => console.log(err));


var korean_name = new Object();

function get_asset(market) {
    const payload = {
        access_key: access_key,
        nonce: v4(),
    }
    const token = sign(payload, secret_key)
    const options = {
        method: "GET",
        url: server_url + "/v1/accounts",
        headers: { Authorization: `Bearer ${token}` },
    }
    const result = (market) => new Promise((resolve) => {
        request(options, async function (err, res, body) {
            if (err) throw new Error(err)
            var empty = new Object();
            data = JSON.parse(body);
            if (market) {
                if (market == "asset") {
                    var current_asset = 0;
                    var pre_asset = 0;
                    for (var i = 0; i < data.length; i++) {
                        var candle;
                        if (data[i].currency == "KRW") {
                            current_asset += Number(data[i].balance);
                            pre_asset += Number(data[i].balance);
                        } else {
                            pre_asset += Number(data[i].balance * data[i].avg_buy_price)
                            candle = await get_candle(5, "KRW-" + data[i].currency);
                            current_asset += Number(candle[0].trade_price * data[i].balance);
                        }
                    }
                    resolve({ pre_asset: pre_asset.toFixed(0).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ","), current_asset: current_asset.toFixed(0).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ","), profit_data: (current_asset - pre_asset).toFixed(0).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") , yield_data: Number((current_asset - pre_asset) / pre_asset * 100).toFixed(2).replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") });
                } else if (market == "coin") {
                    var hold_coin = new Object();
                    for (var i = 0; i < data.length; i++) {
                        var candle;
                        if (data[i].currency == "KRW") {
                            hold_coin[data[i].currency] = { volume: Number(data[i].balance).toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") };
                        } else {
                            candle = await get_candle(5, "KRW-" + data[i].currency);
                            var avg_buy_price = Number(data[i].avg_buy_price).toFixed(data[i].avg_buy_price < 1 ? 3 : 0)
                            var volume = Number(data[i].balance).toFixed(8);
                            var current_price = Number(candle[0].trade_price).toFixed(data[i].current_price < 1 ? 3 : 0);
                            var buying_money=(avg_buy_price*volume).toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");;
                            var evaluation_money=(current_price*volume).toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");;
                            var yield_data = (current_price - avg_buy_price) / avg_buy_price * 100;
                            yield_data = Number(yield_data).toFixed(2);
                            avg_buy_price = avg_buy_price.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                            volume = volume.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                            current_price = current_price.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                            yield_data = yield_data.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
                            hold_coin[data[i].currency] = { avg_buy_price, volume, current_price, yield_data,buying_money,evaluation_money };
                        }
                    }
                    resolve(hold_coin);
                } else {
                    data.filter(function (item) {
                        if (item.currency == market.split('-')[1]) {
                            empty.market = item;
                        } else if (item.currency == "KRW") {
                            empty.KRW = item
                        }
                        resolve(empty);
                    })
                }
            } else {
                resolve(data);
            }
        })
    })
    return result(market);
}
async function get_marketName() {
    var data = new Array();
    let response = await fetch(`${server_url}/v1/market/all`, options)
        .then(res => res.json())
        .then(json => {
            for (i in json) {
                data.push(json[i].market);
                korean_name[json[i].market] = json[i].korean_name;
            }
        })
    return data;
}
async function transaction_coin(coin_name, side, volume, price, ord_type, first = true) {
    var volume = volume;
    var avg_buy_price=0;
    if (side == "ask") {
        await User.findOne({ market: coin_name }).then((result) => {
            if(volume == ""){
                volume = String(result.volume);
            }
            avg_buy_price=result.avg_buy_price;
        }).catch(err => { console.log(err.error) });
    }
    const body = {
        market: coin_name,
        side: side,
        volume: volume,
        price: price,
        ord_type: ord_type,
    }
    const query = queryEncode(body)
    const hash = crypto.createHash('sha512')
    const queryHash = hash.update(query, 'utf-8').digest('hex')
    const payload = {
        access_key: access_key,
        nonce: v4(),
        query_hash: queryHash,
        query_hash_alg: 'SHA512',
    }
    const token = sign(payload, secret_key)
    const options = {
        method: "POST",
        url: server_url + "/v1/orders",
        headers: { Authorization: `Bearer ${token}` },
        json: body
    }
    await request(options).then(async (result) => {
        const asset = (delay) => new Promise((resolve) => {
            setTimeout(async () => {
                resolve(await get_asset(result.market));
            }, delay)
        })
        var my_asset = await asset(1000);
        
        if(avg_buy_price!=0){
            lookup_order(result.uuid,avg_buy_price,result.market.split("-")[1]);
        }else{
            lookup_order(result.uuid,0,result.market.split("-")[1]);
        }
        if (side == "bid") {
            if (first) {
                const user = new User({ uid: 1, krw_balance: my_asset.KRW.balance, market: coin_name, count: 1, avg_buy_price: my_asset.market.avg_buy_price, volume: my_asset.market.balance });
                await user.save().then(() => { isuser = true })
            } else {
                User.findOneAndUpdate({ uid: 1 }, { krw_balance: my_asset.KRW.balance, avg_buy_price: my_asset.market.avg_buy_price, volume: my_asset.market.balance, $inc: { count: 1 } }, { new: true }, (err, result) => {
                    if (err) {
                        console.log(err);
                    } else {
                    }
                })
            }
        } else if (side == "ask") {
            if (first) {
                User.findOneAndDelete({market:coin_name},(err,res)=>{
                    if(err){
                        console.log(err);
                    }else{
                        krw_balance=my_asset.KRW.balance;
                        divided_money=krw_balance/10;
                    }
                })
            } else {
                User.findOneAndUpdate({ uid: 1 }, { krw_balance: my_asset.KRW.balance, avg_buy_price: my_asset.market.avg_buy_price, volume: my_asset.market.balance, count: 1 }, { new: true }, (err, result) => {
                    if (err) {
                        console.log(err);
                    }
                })
            }
        }
    }).catch((err) => { console.log(err.error) })
    return;
}
async function get_marketInfo() {
    var name_list = await get_marketName();
    const url2 = `${server_url}/v1/ticker/?markets=${name_list}`;
    var arr = new Array();
    let response2 = await fetch(url2, options)
        .then(res => res.json())
        .then(json => {
            for (i in json) {
                if (json[i].acc_trade_price_24h > 100000000000) {
                    arr.push([json[i].market, json[i].acc_trade_price_24h, json[i].trade_price]);
                }
            }
        })
    return arr
}
async function sort_data() {
    arr = await get_marketInfo();
    arr.sort((a, b) => {
        return b[1] - a[1];
    })
    return arr;
}
async function save_coin(arr) {
    for (var i = 0; i < 10; i++) {
        if (arr[i]) {
            const coin = new Coin({
                tid: i + 1,
                name: arr[i][0],
                korean_name: korean_name[arr[i][0]],
                acc_trade_price_24h: arr[i][1],
                current_price: arr[i][2]
            });
            await coin.save((err) => {
                if (err) {
                    console.log(err)
                }
            })
        }
    }
    return true;
}
async function refresh_db() {
    Coin.find()
        .then(result => {
            if (result.length !== 0) {
                Coin.deleteMany({ tid: { $gt: 0 } }, (err, result) => {
                    if (err) {
                        console.log(err);
                    } else {
                    }
                })
            }
            save_coin(sort_info);
        })
    return;
}
async function get_candle(minute, market) {
    const url = `https://api.upbit.com/v1/candles/minutes/${minute}?market=${market}&count=1`;
    var candle = new Array();
    let response = await fetch(url, options)
        .then(res => res.json())
        .then(json => candle = json)
    return candle;
}
async function price_comparison(candle, user_data = null, isbuying = false) {
    var isbuying = isbuying;
    if (user_data != null) {
        console.log("매수 평균가 : " + user_data.avg_buy_price + ", 현재 가격 : " + candle[0].trade_price);
        var yield_data = (candle[0].trade_price - user_data.avg_buy_price) / user_data.avg_buy_price * 100;
        if(yield_data<=-1){
            if (user_data.count < 9) {
                transaction_coin(user_data.market, "bid", null, divided_money, "price", false)
            } else if(user_data.count==9) {
                transaction_coin(user_data.market, "bid", null, Math.floor(user_data.krw_balance-(user_data.krw_balance*0.001)), "price", false)
            }  
        } else if (yield_data >= 0.5) {
            console.log(user_data);
            if (user_data.count == 1) {
                if(yield_data>=1.5){
                    transaction_coin(user_data.market, "ask", user_data.volume, null, "market");
                }else{
                }
            } else {
                transaction_coin(user_data.market, "ask", (user_data.volume / user_data.count) * (user_data.count - 1), null, "market", false);
            }
        }
    } else {
        await Coin.findOne({ name: candle[0].market }).then(async (result) => {
            if (candle.length!=0 && result.length!=0) {
                var yield_data = (candle[0].trade_price - result.current_price) / result.current_price * 100;
                if (result.current_price > candle[0].trade_price) {
                    console.log("***" + result.korean_name + " " + candle[0].unit + "분 동안 " + yield_data.toFixed(2) + "% 하락");
                    await Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, up_count: 0, $inc: { down_count: 1 } }, { new: true }).then(async (result) => {
                        if (isbuying == false && result.down_count >= 3&&result.name!="KRW-BTC") {
                            transaction_coin(result.name, "bid", null, divided_money, "price");
                            isbuying = true;
                        }
                    }).catch(err => { console.log(err) })
                } else if(result.current_price<candle[0].trade_price){
                    console.log(result.korean_name + " " + candle[0].unit + "분 동안" + yield_data.toFixed(2) + "% 상승");
                    await Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, down_count: 0, $inc: { up_count: 1 } }, { new: true }).then(async (result) => {
                    }).catch(err => { console.log(err); })
                }
            }else{
            }
        })
    }
    return isbuying;
}
async function check_coin(t1) {
    User.find().then(async (user_data) => {
        var isbuying = user_data.length != 0 ? true : false;
        if (isbuying) {
            if (user_data[0].count >= 3&&delay_count%3!=0&&user_data[0].count!=10) {
                delay_count+=1;
            } else {
                delay_count=1;
                var candle = await get_candle(5, user_data[0].market);
                await price_comparison(candle, user_data[0]);
            }
        }
        for (var i = 0; i < t1.length; i++) {
            // if (user_data[0] && user_data[0].market == t1[i]) {
            //     continue;
            // }
            var candle = await get_candle(5, t1[i]);
            isbuying = await price_comparison(candle, null, isbuying);
        }
    }).catch((err) => {
        console.log(err);
    })
    return;
}
async function latest_repeat(t1) {
    let check_time = setInterval(async () => {
        let today = new Date();
        let minutes = today.getMinutes();
        let seconds = today.getSeconds();
        if (seconds ==0) {
            clearInterval(check_time);
            sort_info = (await sort_data());
            (await refresh_db());
            Coin.find().sort({ tid: 1 }).then(result => {
                for (var key in result) {
                    t1.push(result[key].name)
                }
            })
            console.log("현재 시간은 " + today.toLocaleTimeString());
            var count = 0;
            let coin = setInterval(async () => {
                let today = new Date();
                let minutes = today.getMinutes();
                let seconds = today.getSeconds();
                console.log("현재 시간은 " + today.toLocaleTimeString());
                if (count == 12 * 24) {
                    count = 0;
                    sort_info = (await sort_data());
                    (await refresh_db());
                    console.log("db최신화");
                } else {
                    await (check_coin(t1).then(count++));
                }
            }, 60000 * 5);
        }
    }, 1000);
}
function lookup_order(uuid,avg_buy_price=0,market="") {
    const body = {
        uuid: uuid
    }
    const query = queryEncode(body)

    const hash = crypto.createHash('sha512')
    const queryHash = hash.update(query, 'utf-8').digest('hex')

    const payload = {
        access_key: access_key,
        nonce: v4(),
        query_hash: queryHash,
        query_hash_alg: 'SHA512',
    }
    const token = sign(payload, secret_key)

    const options = {
        method: "GET",
        url: server_url + "/v1/order?" + query,
        headers: { Authorization: `Bearer ${token}` },
        json: body
    }
    request(options, (error, response, body) => {
        if (error) throw new Error(error)
        var price = 0, volume = 0, funds = 0,yield_data=0;
        var leng = body.trades.length;
        for (var i = 0; i < leng; i++) {
            price += body.trades[i].price;
            volume += body.trades[i].volume;
            funds += body.trades[i].funds;
        }
        price/=leng;
        volume/=leng;
        funds/=leng;
        yield_data=((price-avg_buy_price)/avg_buy_price*100).toFixed(2).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
        price = price.toFixed(price < 1 ? 3 : 0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
        volume = volume.toFixed(8).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
        funds = funds.toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
        if(avg_buy_price!=0){
            trading_notice(body.side, price, funds, volume,yield_data,market);
        }else{
            trading_notice(body.side, price, funds, volume,0,market);
        }
    })
    return;
}
function trading_notice(side, price, funds, volume,yield_data=0,market) {
    var messages = new Array();
    if (side == "bid") {
        messages.push({ "type": "text", "text": "매수 주문이 체결되었습니다." });
        messages.push({ "type": "text", "text": `${market}\n체결 금액 : ${funds}원\n체결 수량 : ${volume}개\n체결 평균가 : ${price}원` });
    } else {
        messages.push({ "type": "text", "text": "매도 주문이 체결되었습니다." });
        messages.push({ "type": "text", "text": `${market}\n체결 금액 : ${funds}원\n체결 수량 : ${volume}개\n체결 평균가 : ${price}원\n수익률 : ${yield_data}%` });
    }
    request.post(
        {
            url: BROAD_TARGET_URL,
            headers: {
                'Authorization': `Bearer ${TOKEN}`
            },
            json: {
                "messages": messages
            }
        }, (error, response, body) => {
        });
    return;
}
async function lookup_asset(replyToken) {
    var result = await get_asset("asset");
    request.post(
        {
            url: TARGET_URL,
            headers: {
                'Authorization': `Bearer ${TOKEN}`
            },
            json: {
                "replyToken": replyToken,
                "messages": [
                    {
                        "type": "text",
                        "text": `이전 자산 : ${result.pre_asset}`
                    },
                    {
                        "type": "text",
                        "text": `평가 자산 : ${result.current_asset}`
                    },
                    {
                        "type": "text",
                        "text": `평가 손익 : ${result.profit_data}, 수익률 : ${result.yield_data}%`
                    }
                ]
            }
        }, (error, response, body) => {
        });
        return;
}
async function lookup_hold_coin(replyToken) {
    var result = await get_asset("coin");
    var messages = new Array();
    var coin_list = Object.keys(result);
    if (coin_list.length == 1) {
        messages.push({ "type": "text", "text": "아직 보유중인 종목이 없습니다." });
    } else {
        for (var i = 0; i < coin_list.length; i++) {
            if (coin_list[i] == "KRW") {
                messages.push({ "type": "text", "text": `${coin_list[i]}\n사용 가능 원화 : ${result[coin_list[i]].volume}원` });
            } else {
                messages.push({
                    "type": "text",
                    "text": `${coin_list[i]}\n보유 수량 : ${(result[coin_list[i]].volume)}개\n매수 평균가 : ${result[coin_list[i]].avg_buy_price}원\n현재가 ${result[coin_list[i]].current_price}원\n매수 금액 : ${result[coin_list[i]].buying_money}\n평가 금액 : ${result[coin_list[i]].evaluation_money}\n수익률 : ${result[coin_list[i]].yield_data}%`
                })
            }
        }
    }

    request.post(
        {
            url: TARGET_URL,
            headers: {
                'Authorization': `Bearer ${TOKEN}`
            },
            json: {
                "replyToken": replyToken,
                "messages": messages
            }
        }, (error, response, body) => {
            console.log(body)
        });
        return;
}
app.post('/hook', function (req, res) {
    var eventObj = req.body.events[0];
    if (eventObj.message.text == "자산") {
        lookup_asset(eventObj.replyToken)
    } else if (eventObj.message.text == "보유 종목") {
        lookup_hold_coin(eventObj.replyToken);
    }
    res.sendStatus(200);
});

try {
    const option = {
        ca: fs.readFileSync('/etc/letsencrypt/live/' + domain + '/fullchain.pem'),
        key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/privkey.pem'), 'utf8').toString(),
        cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/cert.pem'), 'utf8').toString(),
    };
    HTTPS.createServer(option, app).listen(sslport, async () => {
        console.log(`[HTTPS] Server is started on port ${sslport}`);
        await get_asset().then((result) => {
            krw_balance = result[0].balance;
            divided_money = krw_balance / 10
        });
        var t1 = new Array();
        await (latest_repeat(t1));
    });
} catch (error) {
    console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
    console.log(error);
}