June

Add trading_notice and lookup_order function & Modify trading logic & Add crypto buying condition

Showing 1 changed file with 314 additions and 84 deletions
...@@ -4,12 +4,17 @@ const express = require('express'); ...@@ -4,12 +4,17 @@ const express = require('express');
4 const app = express(); 4 const app = express();
5 const { Coin } = require("./models/Coin"); 5 const { Coin } = require("./models/Coin");
6 const { User } = require('./models/User'); 6 const { User } = require('./models/User');
7 +
7 require("dotenv").config(); 8 require("dotenv").config();
8 const fs = require('fs'); 9 const fs = require('fs');
9 const path = require('path'); 10 const path = require('path');
10 const HTTPS = require('https'); 11 const HTTPS = require('https');
11 const domain = "2019102152.osschatbot.ga" 12 const domain = "2019102152.osschatbot.ga"
12 const sslport = 23023; 13 const sslport = 23023;
14 +const TARGET_URL = 'https://api.line.me/v2/bot/message/reply'
15 +const TOKEN = process.env.token;
16 +var userid = process.env.userid;
17 +
13 const bodyParser = require('body-parser'); 18 const bodyParser = require('body-parser');
14 const crypto = require('crypto'); 19 const crypto = require('crypto');
15 const queryEncode = require('querystring').encode; 20 const queryEncode = require('querystring').encode;
...@@ -20,25 +25,23 @@ const access_key = process.env.access_key; ...@@ -20,25 +25,23 @@ const access_key = process.env.access_key;
20 const secret_key = process.env.secret_key; 25 const secret_key = process.env.secret_key;
21 const server_url = "https://api.upbit.com" 26 const server_url = "https://api.upbit.com"
22 27
28 +var delay_count=1;
23 29
24 -var krw_balance = 60000; 30 +var krw_balance;
25 -var divided_money = krw_balance / 10; 31 +var divided_money;
26 32
27 var sort_info = new Array(); 33 var sort_info = new Array();
28 const mongoose = require('mongoose'); 34 const mongoose = require('mongoose');
29 const config = require('./config/key'); 35 const config = require('./config/key');
30 - 36 +app.use(bodyParser.json());
31 const connect = mongoose.connect(config.mongoURI, { 37 const connect = mongoose.connect(config.mongoURI, {
32 useNewUrlParser: true, useUnifiedTopology: true 38 useNewUrlParser: true, useUnifiedTopology: true
33 }) 39 })
34 .then(() => console.log('디비연결 성공')) 40 .then(() => console.log('디비연결 성공'))
35 .catch((err) => console.log(err)); 41 .catch((err) => console.log(err));
36 42
37 -app.use(bodyParser.json());
38 -var korean_name = new Object();
39 -
40 -
41 43
44 +var korean_name = new Object();
42 45
43 function get_asset(market) { 46 function get_asset(market) {
44 const payload = { 47 const payload = {
...@@ -52,20 +55,61 @@ function get_asset(market) { ...@@ -52,20 +55,61 @@ function get_asset(market) {
52 headers: { Authorization: `Bearer ${token}` }, 55 headers: { Authorization: `Bearer ${token}` },
53 } 56 }
54 const result = (market) => new Promise((resolve) => { 57 const result = (market) => new Promise((resolve) => {
55 - request(options, function (err, res, body) { 58 + request(options, async function (err, res, body) {
56 if (err) throw new Error(err) 59 if (err) throw new Error(err)
57 var empty = new Object(); 60 var empty = new Object();
58 data = JSON.parse(body); 61 data = JSON.parse(body);
59 if (market) { 62 if (market) {
60 - data.filter(function (item) { 63 + if (market == "asset") {
61 - if (item.currency == market.split('-')[1]) { 64 + var current_asset = 0;
62 - // resolve(item); 65 + var pre_asset = 0;
63 - empty.market = item; 66 + for (var i = 0; i < data.length; i++) {
64 - } else if (item.currency == "KRW") { 67 + var candle;
65 - empty.KRW = item 68 + if (data[i].currency == "KRW") {
69 + current_asset += Number(data[i].balance);
70 + pre_asset += Number(data[i].balance);
71 + // hold_coin[data[i].currency]={volume:data[i].balance};
72 + } else {
73 + pre_asset += Number(data[i].balance * data[i].avg_buy_price)
74 + candle = await get_candle(5, "KRW-" + data[i].currency);
75 + current_asset += Number(candle[0].trade_price * data[i].balance);
76 + // hold_coin[data[i].currency]={avg_buy_price:data[i].avg_buy_price,volume:data[i].balance,current_price:candle[0].trade_price};
77 + }
66 } 78 }
67 - resolve(empty); 79 + resolve({ pre_asset: pre_asset.toFixed(0), current_asset: current_asset.toFixed(0), profit_data: (current_asset - pre_asset).toFixed(0), yield_data: ((current_asset - pre_asset) / pre_asset * 100).toFixed(2) });
68 - }) 80 + } else if (market == "coin") {
81 + var hold_coin = new Object();
82 +
83 + for (var i = 0; i < data.length; i++) {
84 + var candle;
85 + if (data[i].currency == "KRW") {
86 + hold_coin[data[i].currency] = { volume: Number(data[i].balance).toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",") };
87 + } else {
88 + candle = await get_candle(5, "KRW-" + data[i].currency);
89 + var avg_buy_price = Number(data[i].avg_buy_price).toFixed(data[i].avg_buy_price < 1 ? 3 : 0)
90 + var volume = Number(data[i].balance).toFixed(8);
91 + var current_price = Number(candle[0].trade_price).toFixed(data[i].current_price < 1 ? 3 : 0);
92 + var yield_data = (current_price - avg_buy_price) / avg_buy_price * 100;
93 + yield_data = Number(yield_data).toFixed(2);
94 + avg_buy_price = avg_buy_price.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
95 + volume = volume.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
96 + current_price = current_price.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
97 + yield_data = yield_data.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
98 + hold_coin[data[i].currency] = { avg_buy_price, volume, current_price, yield_data };
99 + }
100 + }
101 + resolve(hold_coin);
102 + } else {
103 + data.filter(function (item) {
104 + if (item.currency == market.split('-')[1]) {
105 + // resolve(item);
106 + empty.market = item;
107 + } else if (item.currency == "KRW") {
108 + empty.KRW = item
109 + }
110 + resolve(empty);
111 + })
112 + }
69 } else { 113 } else {
70 resolve(data); 114 resolve(data);
71 } 115 }
...@@ -88,9 +132,8 @@ async function get_marketName() { ...@@ -88,9 +132,8 @@ async function get_marketName() {
88 } 132 }
89 async function transaction_coin(coin_name, side, volume, price, ord_type, first = true) { 133 async function transaction_coin(coin_name, side, volume, price, ord_type, first = true) {
90 var volume = volume; 134 var volume = volume;
91 - if (side == "ask") { 135 + if (side == "ask" && volume == "") {
92 - await User.findOne({ uid: 1 }).then((result) => { 136 + await User.findOne({ market: coin_name }).then((result) => {
93 - console.log(result.volume);
94 volume = String(result.volume); 137 volume = String(result.volume);
95 }).catch(err => { console.log(err.error) }); 138 }).catch(err => { console.log(err.error) });
96 } 139 }
...@@ -101,6 +144,7 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first ...@@ -101,6 +144,7 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first
101 price: price, 144 price: price,
102 ord_type: ord_type, 145 ord_type: ord_type,
103 } 146 }
147 + console.log(body);
104 //시장가 매수인 경우 price를 얼마치 살건지 입력 148 //시장가 매수인 경우 price를 얼마치 살건지 입력
105 //시장가 매도인경우 volume에 몇개를 팔건지 입력 149 //시장가 매도인경우 volume에 몇개를 팔건지 입력
106 const query = queryEncode(body) 150 const query = queryEncode(body)
...@@ -126,6 +170,11 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first ...@@ -126,6 +170,11 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first
126 }, delay) 170 }, delay)
127 }) 171 })
128 var my_asset = await asset(1000); 172 var my_asset = await asset(1000);
173 + if(my_asset.market&&my_asset.market.avg_buy_price){
174 + lookup_order(result.uuid,my_asset.market.avg_buy_price);
175 + }else{
176 + lookup_order(result.uuid);
177 + }
129 if (side == "bid") { 178 if (side == "bid") {
130 //처음 매수일 때 179 //처음 매수일 때
131 if (first) { 180 if (first) {
...@@ -133,28 +182,40 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first ...@@ -133,28 +182,40 @@ async function transaction_coin(coin_name, side, volume, price, ord_type, first
133 await user.save().then(() => { isuser = true }) 182 await user.save().then(() => { isuser = true })
134 //2회 이상 매수일 때 183 //2회 이상 매수일 때
135 } else { 184 } else {
136 - 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)=>{ 185 + 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) => {
137 - if(err){ 186 + if (err) {
138 - console.log(err); 187 + // console.log(err);
139 - }else{ 188 + } else {
140 - console.log(result); 189 + // console.log(result);
141 } 190 }
142 }) 191 })
143 } 192 }
144 } else if (side == "ask") { 193 } else if (side == "ask") {
145 //1회 매수 후 매도일 때 194 //1회 매수 후 매도일 때
195 + console.log("매도 쪽으로 진입");
146 if (first) { 196 if (first) {
147 - User.deleteOne({ uid: 1 }, (err, res) => { 197 + console.log("1회 매수 후 매도")
198 + User.deleteOne({ market: coin_name }, (err, res) => {
148 if (err) { 199 if (err) {
149 - console.log(err); 200 + // console.log(err);
150 } 201 }
202 + krw_balance = my_asset.KRW.balance;
203 + divided_money = krw_balance / 10;
151 }); 204 });
152 //분할 매수 분할 매도 중일 때 205 //분할 매수 분할 매도 중일 때
153 } else { 206 } else {
154 - 207 + console.log("여러번 매수 후 매도");
208 + 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) => {
209 + if (err) {
210 + // console.log(err);
211 + } else {
212 + console.log(result);
213 + }
214 + })
155 } 215 }
156 } 216 }
157 }).catch((err) => { console.log(err.error) }) 217 }).catch((err) => { console.log(err.error) })
218 + return;
158 } 219 }
159 async function get_marketInfo() { 220 async function get_marketInfo() {
160 //각 암호화폐 정보 조회 221 //각 암호화폐 정보 조회
...@@ -191,7 +252,7 @@ async function save_coin(arr) { ...@@ -191,7 +252,7 @@ async function save_coin(arr) {
191 }); 252 });
192 await coin.save((err) => { 253 await coin.save((err) => {
193 if (err) { 254 if (err) {
194 - console.log(err) 255 + // console.log(err)
195 } 256 }
196 }) 257 })
197 } 258 }
...@@ -204,14 +265,15 @@ async function refresh_db() { ...@@ -204,14 +265,15 @@ async function refresh_db() {
204 if (result.length !== 0) { 265 if (result.length !== 0) {
205 Coin.deleteMany({ tid: { $gt: 0 } }, (err, result) => { 266 Coin.deleteMany({ tid: { $gt: 0 } }, (err, result) => {
206 if (err) { 267 if (err) {
207 - console.log(err); 268 + // console.log(err);
208 } else { 269 } else {
209 - console.log(result); 270 + // console.log(result);
210 } 271 }
211 }) 272 })
212 } 273 }
213 save_coin(sort_info); 274 save_coin(sort_info);
214 }) 275 })
276 + return;
215 } 277 }
216 async function get_candle(minute, market) { 278 async function get_candle(minute, market) {
217 const url = `https://api.upbit.com/v1/candles/minutes/${minute}?market=${market}&count=1`; 279 const url = `https://api.upbit.com/v1/candles/minutes/${minute}?market=${market}&count=1`;
...@@ -221,79 +283,96 @@ async function get_candle(minute, market) { ...@@ -221,79 +283,96 @@ async function get_candle(minute, market) {
221 .then(json => candle = json) 283 .then(json => candle = json)
222 return candle; 284 return candle;
223 } 285 }
224 -async function price_comparison(candle, avg_buy_price = 0) { 286 +async function price_comparison(candle, user_data = null, isbuying = false) {
225 - var isbuying=true; 287 + //매수한 코인이 있을 때
226 - if (avg_buy_price == 0) { 288 + var isbuying = isbuying;
289 + if (user_data != null) {
290 + console.log("매수 평균가 : " + user_data.avg_buy_price + ", 현재 가격 : " + candle[0].trade_price);
291 + //매수평균가가 현재 시장 가격보다 더 비쌀 경우
292 + var yield_data = (candle[0].trade_price - user_data.avg_buy_price) / user_data.avg_buy_price * 100;
293 + if(yield_data<=-1){
294 + // if (user_data.avg_buy_price > candle[0].trade_price) {
295 + if (user_data.count < 9) {
296 + transaction_coin(user_data.market, "bid", null, divided_money, "price", false)
297 + } else if(user_data.count==9) {
298 + transaction_coin(user_data.market, "bid", null, Math.floor(user_data.krw_balance-(user_data.krw_balance*0.001)), "price", false)
299 + }
300 + //매수평균가가 현재 시장 가격보다 더 쌀 경우
301 + //수수료 포함 0.5% 이상 수익중일 때
302 + } else if (yield_data >= 0.5) {
303 + //매수 count가 1회이면서 수익률이 1.5프로 이상일때 시장가 전액 매도
304 + if (user_data.count == 1 && yield_data >= 1.5) {
305 + transaction_coin(user_data.market, "ask", user_data.volume, null, "market");
306 + //전체 계좌 제산의 10프로를 제외한 나머지 코인을 매도
307 + } else {
308 + transaction_coin(user_data.market, "ask", (user_data.volume / user_data.count) * (user_data.count - 1), null, "market", false);
309 + }
310 + }
311 + //매수한 코인이 없을 때
312 + } else {
227 await Coin.findOne({ name: candle[0].market }).then(async (result) => { 313 await Coin.findOne({ name: candle[0].market }).then(async (result) => {
228 //가격이 떨어졌을때 314 //가격이 떨어졌을때
229 - if (result.current_price > candle[0].trade_price) { 315 + //해당 코인의 count를 +1 해준다
230 - Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, $inc: { count: 1 } }, { new: true }, (err, result) => { 316 + //해당 코인의 count가 3이상이면 upbit api로 매수 주문을 보낸다.
231 - if (err) { 317 + if (candle.length!=0 && result.length!=0) {
232 - console.log(err); 318 + var yield_data = (candle[0].trade_price - result.current_price) / result.current_price * 100;
233 - } else { 319 + if (result.current_price > candle[0].trade_price) {
234 - console.log("***" + result.korean_name + "은(는)" + result.count * 5 + "분 동안 하락중"); 320 + console.log("***" + result.korean_name + " " + candle[0].unit + "분 동안 " + yield_data.toFixed(2) + "% 하락");
235 - if (result.count >= 3) { 321 + 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) => {
322 + if (isbuying == false && result.down_count >= 3&&result.name!="KRW-BTC") {
236 transaction_coin(result.name, "bid", null, divided_money, "price"); 323 transaction_coin(result.name, "bid", null, divided_money, "price");
237 - isbuying=false; 324 + isbuying = true;
238 } 325 }
239 - } 326 + }).catch(err => { console.log(err) })
240 - }) 327 + //가격이 상승했을때
241 - } else if (result.current_price < candle[0].trade_price) { 328 + //해당 코인의 count를 초기화한다.
242 - await Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, count: 0 }, { new: true }).then(async (err, result) => { 329 + } else if(result.current_price<candle[0].trade_price){
243 - if (err) { 330 + console.log(result.korean_name + " " + candle[0].unit + "분 동안" + yield_data.toFixed(2) + "% 상승");
244 - console.log(err); 331 + 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) => {
245 - } else { 332 + }).catch(err => { console.log(err); })
246 - console.log(result.korean_name + "은(는)" + result.count * 5 + "분 동안 상승 혹은 정체중"); 333 + }
247 - } 334 + }else{
248 - }) 335 + console.log(촛불);
336 + console.log(result);
249 } 337 }
250 -
251 }) 338 })
252 - } else {
253 - if (avg_buy_price < candle[0].trade_price) {
254 - transaction_coin(candle[0].market, "bid", null, divided_money, "price", false)
255 - } else {
256 - transaction_coin(candle[0].market, "ask", "", null, "market", false);
257 - }
258 } 339 }
259 return isbuying; 340 return isbuying;
260 } 341 }
261 async function check_coin(t1) { 342 async function check_coin(t1) {
262 User.find().then(async (user_data) => { 343 User.find().then(async (user_data) => {
263 - //아직 매수한 코인이 없을 때 344 + //매수한 코인이 있을 때
264 - if (user_data.length == 0) { 345 + var isbuying = user_data.length != 0 ? true : false;
265 - var isbuying = false; 346 + if (isbuying) {
266 - for (var i = 0; i < t1.length; i++) {
267 - if (isbuying) {
268 - var candle = await get_candle(5, t1[i]);
269 - isbuying=await price_comparison(candle);
270 - console.log(isbuying);
271 - }
272 - }
273 - //매수한 코인이 있을 때
274 - } else {
275 //3회 이상 매수 했을시 15분봉으로 교체해서 가격 확인 347 //3회 이상 매수 했을시 15분봉으로 교체해서 가격 확인
276 - //15분봉 처리해야함 348 + if (user_data[0].count >= 3&&delay_count%3!=0&&user_data[0].count!=10) {
277 - if (user_data[0].count > 3) { 349 + delay_count+=1;
278 - var candle = await get_candle(15, user_data[0].market);
279 - await price_comparison(candle, user_data[0].avg_buy_price);
280 } else { 350 } else {
351 + delay_count=1;
281 var candle = await get_candle(5, user_data[0].market); 352 var candle = await get_candle(5, user_data[0].market);
282 - await price_comparison(candle, user_data[0].avg_buy_price); 353 + await price_comparison(candle, user_data[0]);
354 + }
355 + }
356 + //코인 count and 매수 매도 작업
357 + for (var i = 0; i < t1.length; i++) {
358 + if (user_data[0] && user_data[0].market == t1[i]) {
359 + continue;
283 } 360 }
361 + var candle = await get_candle(5, t1[i]);
362 + isbuying = await price_comparison(candle, null, isbuying);
284 } 363 }
285 }).catch((err) => { 364 }).catch((err) => {
286 console.log(err); 365 console.log(err);
287 }) 366 })
288 - 367 + return;
289 } 368 }
290 async function latest_repeat(t1) { 369 async function latest_repeat(t1) {
291 let check_time = setInterval(async () => { 370 let check_time = setInterval(async () => {
292 let today = new Date(); 371 let today = new Date();
293 let minutes = today.getMinutes(); 372 let minutes = today.getMinutes();
294 let seconds = today.getSeconds(); 373 let seconds = today.getSeconds();
295 - // if (seconds == 0) { 374 + if (seconds == 0) {
296 - if (minutes == 0 && seconds == 0) { 375 + // if (minutes == 0 && seconds == 0) {
297 clearInterval(check_time); 376 clearInterval(check_time);
298 sort_info = (await sort_data()); 377 sort_info = (await sort_data());
299 (await refresh_db()); 378 (await refresh_db());
...@@ -309,32 +388,183 @@ async function latest_repeat(t1) { ...@@ -309,32 +388,183 @@ async function latest_repeat(t1) {
309 let minutes = today.getMinutes(); 388 let minutes = today.getMinutes();
310 let seconds = today.getSeconds(); 389 let seconds = today.getSeconds();
311 console.log("현재 시간은 " + today.toLocaleTimeString()); 390 console.log("현재 시간은 " + today.toLocaleTimeString());
312 - await (check_coin(t1).then(count++)); 391 + //24시간마다 db 최신화...
313 - //1시간마다 db 최신화... 392 + if (count == 12 * 24) {
314 - if (count == 12) {
315 count = 0; 393 count = 0;
316 sort_info = (await sort_data()); 394 sort_info = (await sort_data());
317 (await refresh_db()); 395 (await refresh_db());
318 console.log("db최신화"); 396 console.log("db최신화");
397 + } else {
398 + await (check_coin(t1).then(count++));
319 } 399 }
320 }, 60000 * 5); 400 }, 60000 * 5);
321 } 401 }
322 }, 1000); 402 }, 1000);
323 } 403 }
404 +function lookup_order(uuid,avg_buy_price=0) {
405 + const body = {
406 + uuid: uuid
407 + }
408 + const query = queryEncode(body)
409 +
410 + const hash = crypto.createHash('sha512')
411 + const queryHash = hash.update(query, 'utf-8').digest('hex')
412 +
413 + const payload = {
414 + access_key: access_key,
415 + nonce: v4(),
416 + query_hash: queryHash,
417 + query_hash_alg: 'SHA512',
418 + }
419 + const token = sign(payload, secret_key)
420 +
421 + const options = {
422 + method: "GET",
423 + url: server_url + "/v1/order?" + query,
424 + headers: { Authorization: `Bearer ${token}` },
425 + json: body
426 + }
427 + request(options, (error, response, body) => {
428 + if (error) throw new Error(error)
429 + var price = 0, volume = 0, funds = 0,yield_data=0;
430 + var leng = body.trades.length;
431 + for (var i = 0; i < leng; i++) {
432 + price += body.trades[i].price;
433 + volume += body.trades[i].volume;
434 + funds += body.trades[i].funds;
435 + }
436 + price/=leng;
437 + volume/=leng;
438 + funds/=leng;
439 + yield_data=((price-avg_buy_price)/avg_buy_price*100).toFixed(2).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
440 + price = price.toFixed(price < 1 ? 3 : 0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
441 + volume = volume.toFixed(8).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
442 + funds = funds.toFixed(0).toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
443 + if(avg_buy_price!=0){
444 + trading_notice(body.side, price, funds, volume,yield_data);
445 + }else{
446 + trading_notice(body.side, price, funds, volume);
447 + }
448 + })
449 + return;
450 +}
451 +function trading_notice(side, price, funds, volume,yield_data=0) {
452 + var messages = new Array();
453 + if (side == "bid") {
454 + messages.push({ "type": "text", "text": "매수 주문이 체결되었습니다." });
455 + messages.push({ "type": "text", "text": `체결 금액 : ${funds}원\n체결 수량 : ${volume}개\n체결 평균가 : ${price}원\n` });
456 + } else {
457 + messages.push({ "type": "text", "text": "매도 주문이 체결되었습니다." });
458 + messages.push({ "type": "text", "text": `체결 금액 : ${funds}원\n체결 수량 : ${volume}개\n체결 평균가 : ${price}원\n수익률 : ${yield_data}%` });
459 + }
460 +
461 + var TARGET_URL = 'https://api.line.me/v2/bot/message/push';
462 + request.post(
463 + {
464 + url: TARGET_URL,
465 + headers: {
466 + 'Authorization': `Bearer ${TOKEN}`
467 + },
468 + json: {
469 + "to": `${userid}`,
470 + "messages": messages
471 + }
472 + }, (error, response, body) => {
473 + });
474 + return;
475 +}
476 +async function lookup_asset(replyToken) {
477 + var result = await get_asset("asset");
478 + request.post(
479 + {
480 + url: TARGET_URL,
481 + headers: {
482 + 'Authorization': `Bearer ${TOKEN}`
483 + },
484 + json: {
485 + "replyToken": replyToken,
486 + "messages": [
487 + {
488 + "type": "text",
489 + "text": `이전 자산 : ${result.pre_asset}`
490 + },
491 + {
492 + "type": "text",
493 + "text": `평가 자산 : ${result.current_asset}`
494 + },
495 + {
496 + "type": "text",
497 + "text": `평가 손익 : ${result.profit_data}, 수익률 : ${result.yield_data}%`
498 + }
499 + ]
500 + }
501 + }, (error, response, body) => {
502 + console.log(body)
503 + });
504 + return;
505 +}
506 +async function lookup_hold_coin(replyToken) {
507 + var result = await get_asset("coin");
508 + var messages = new Array();
509 + var coin_list = Object.keys(result);
510 + if (coin_list.length == 1) {
511 + messages.push({ "type": "text", "text": "아직 보유중인 종목이 없습니다." });
512 + } else {
513 + for (var i = 0; i < coin_list.length; i++) {
514 + if (coin_list[i] == "KRW") {
515 + messages.push({ "type": "text", "text": `${coin_list[i]}\n사용 가능 원화 : ${result[coin_list[i]].volume}원` });
516 + } else {
517 + messages.push({
518 + "type": "text",
519 + "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]].yield_data}%`
520 + })
521 + }
522 + }
523 + }
524 +
525 + request.post(
526 + {
527 + url: TARGET_URL,
528 + headers: {
529 + 'Authorization': `Bearer ${TOKEN}`
530 + },
531 + json: {
532 + "replyToken": replyToken,
533 + "messages": messages
534 + }
535 + }, (error, response, body) => {
536 + console.log(body)
537 + });
538 + return;
539 +}
540 +
541 +app.post('/hook', function (req, res) {
542 + var eventObj = req.body.events[0];
543 + if (eventObj.message.text == "자산") {
544 + lookup_asset(eventObj.replyToken)
545 + } else if (eventObj.message.text == "보유 종목") {
546 + lookup_hold_coin(eventObj.replyToken);
547 + }
548 + res.sendStatus(200);
549 +});
550 +
324 try { 551 try {
325 const option = { 552 const option = {
326 ca: fs.readFileSync('/etc/letsencrypt/live/' + domain + '/fullchain.pem'), 553 ca: fs.readFileSync('/etc/letsencrypt/live/' + domain + '/fullchain.pem'),
327 key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/privkey.pem'), 'utf8').toString(), 554 key: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/privkey.pem'), 'utf8').toString(),
328 cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/cert.pem'), 'utf8').toString(), 555 cert: fs.readFileSync(path.resolve(process.cwd(), '/etc/letsencrypt/live/' + domain + '/cert.pem'), 'utf8').toString(),
329 }; 556 };
330 -
331 HTTPS.createServer(option, app).listen(sslport, async () => { 557 HTTPS.createServer(option, app).listen(sslport, async () => {
332 console.log(`[HTTPS] Server is started on port ${sslport}`); 558 console.log(`[HTTPS] Server is started on port ${sslport}`);
559 + // console.log(await get_asset());
560 + await get_asset().then((result) => {
561 + krw_balance = result[0].balance;
562 + divided_money = krw_balance / 10
563 + });
333 var t1 = new Array(); 564 var t1 = new Array();
334 await (latest_repeat(t1)); 565 await (latest_repeat(t1));
335 - // console.log(await get_asset());
336 }); 566 });
337 } catch (error) { 567 } catch (error) {
338 console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.'); 568 console.log('[HTTPS] HTTPS 오류가 발생하였습니다. HTTPS 서버는 실행되지 않습니다.');
339 console.log(error); 569 console.log(error);
340 -} 570 +}
...\ No newline at end of file ...\ No newline at end of file
......