2019102152 김다빈

Add transaction_coin function

......@@ -4,22 +4,17 @@ 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');
const { User } = require('./models/User');
require("dotenv").config();
const crypto=require('crypto');
const queryEncode=require('querystring').encode;
console.log("test");
console.log("test2");
console.log("tesst3");
const request = require('request')
const {v4} = require("uuid")
const crypto = require('crypto');
const queryEncode = require('querystring').encode;
const request = require('request-promise-native');
// const request = require('request')
const { v4 } = require("uuid")
const sign = require('jsonwebtoken').sign
var krw_balance=60000;
var divided_money=krw_balance/10;
var sort_info = new Array();
const mongoose = require('mongoose');
......@@ -39,7 +34,7 @@ const access_key = process.env.access_key;
const secret_key = process.env.secret_key;
const server_url = "https://api.upbit.com"
function get_asset(){
function get_asset() {
const payload = {
access_key: access_key,
nonce: v4(),
......@@ -48,16 +43,16 @@ function get_asset(){
const options = {
method: "GET",
url: server_url + "/v1/accounts",
headers: {Authorization: `Bearer ${token}`},
headers: { Authorization: `Bearer ${token}` },
}
return new Promise(resolve=>{
request(options,function(err,res,body){
return new Promise(resolve => {
request(options, function (err, res, body) {
if (err) throw new Error(err)
// test=res.json();
data=JSON.parse(body);
data = JSON.parse(body);
// console.log(data[0].currency)
data.filter(function(item){
if(item.currency=="PLA"){
data.filter(function (item) {
if (item.currency == "PLA") {
resolve(item);
}
})
......@@ -78,7 +73,7 @@ async function get_marketName() {
})
return data;
}
async function transaction_coin(coin_name,side,volume,price,ord_type){
async function transaction_coin(coin_name, side, volume, price, ord_type) {
const body = {
market: coin_name,
side: side,
......@@ -89,29 +84,31 @@ async function transaction_coin(coin_name,side,volume,price,ord_type){
//시장가 매수인 경우 price를 얼마치 살건지 입력
//시장가 매도인경우 volume에 몇개를 팔건지 입력
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}`},
headers: { Authorization: `Bearer ${token}` },
json: body
}
request(options, (error, response, body) => {
if (error) throw new Error(error)
console.log(body)
})
await request(options).then(async (result)=>{
console.log(result.body);
const user = new User({ krw_balance: 100, market: "KRW-BTC", count: 1, avg_price: 100 });
await user.save().then(() => { isuser = true })
},).catch((err)=>{console.log(err.error)})
}
async function get_marketInfo() {
//각 암호화폐 정보 조회
......@@ -179,36 +176,47 @@ async function get_candle(minute, market) {
return candle;
}
async function check_coin(t1) {
for (var i = 0; i < t1.length; i++) {
var candle = await get_candle(5, t1[i]);
await Coin.findOne({ name: candle[0].market }).then((result) => {
//가격이 떨어졌을때
if (result.current_price > candle[0].trade_price) {
Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, $inc: { count: 1 } }, { new: true }, (err, result) => {
if (err) {
console.log(err);
} else {
console.log("***" + result.korean_name + "은(는)" + result.count * 5 + "분 동안 하락중");
if(count>=3){
transaction_coin(result.name,"bid",null,"얼마치 살건지","price");
User.find().then(async (user_data) => {
if (user_data.length == 0) {
var isuser = false;
for (var i = 0; i < t1.length; i++) {
if (!isuser) {
var candle = await get_candle(5, t1[i]);
await Coin.findOne({ name: candle[0].market }).then(async (result) => {
//가격이 떨어졌을때
if (result.current_price > candle[0].trade_price) {
Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, $inc: { count: 1 } }, { new: true }, (err, result) => {
if (err) {
console.log(err);
} else {
console.log("***" + result.korean_name + "은(는)" + result.count * 5 + "분 동안 하락중");
if (result.count >= 3) {
// transaction_coin(result.name,"bid",null,divided_money,"price");
}
}
})
}//그대로 이거나 올랐을때
else {
await Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, count: 0 }, { new: true }).then(async (result) => {
//특정 조건...
const user = new User({ krw_balance: 100, market: "KRW-BTC", count: 1, avg_price: 100 });
await user.save().then(() => { isuser = true })
// transaction_coin(result.name,"ask","몇개를 팔건지",null,"market");
console.log(result.korean_name + "은(는)" + result.count * 5 + "분 동안 상승 혹은 정체중");
})
}
}
})
}//그대로 이거나 올랐을때
else {
Coin.findOneAndUpdate({ name: candle[0].market }, { current_price: candle[0].trade_price, count: 0 }, { new: true }, (err, result) => {
if (err) {
console.log(err);
} else {
//특정 조건...
transaction_coin(result.name,"ask","몇개를 팔건지",null,"market");
console.log(result.korean_name + "은(는)" + result.count * 5 + "분 동안 상승 혹은 정체중");
}
})
})
}else {
console.log("메롱");
}
}
})
}
} else {
console.log(result);
}
}).catch((err) => {
console.log(err);
})
}
async function latest_repeat(t1) {
await Coin.find().sort({ tid: 1 }).then(result => {
......@@ -220,27 +228,27 @@ async function latest_repeat(t1) {
let today = new Date();
let minutes = today.getMinutes();
let seconds = today.getSeconds();
// if (seconds == 0) {
if (minutes == 0 && seconds == 0) {
if (seconds == 0) {
// if (minutes == 0 && seconds == 0) {
clearInterval(check_time);
sort_info = (await sort_data());
(await refresh_db());
console.log("현재 시간은 " + today.toLocaleTimeString());
var count=0;
let coin=setInterval(async () => {
var count = 0;
let coin = setInterval(async () => {
let today = new Date();
let minutes=today.getMinutes();
let seconds=today.getSeconds();
let minutes = today.getMinutes();
let seconds = today.getSeconds();
console.log("현재 시간은 " + today.toLocaleTimeString());
await (check_coin(t1).then(count++));
//1시간마다 db 최신화...
if(count==12){
count=0;
sort_info=(await sort_data());
if (count == 12) {
count = 0;
sort_info = (await sort_data());
(await refresh_db());
console.log("db최신화");
}
}, 60000*5);
}, 600 * 5);
}
}, 1000);
}
......@@ -248,8 +256,9 @@ app.listen(5000, async () => {
console.log('server start')
//coin 이름,가격,거래대금 저장 , DB 최신화 1시간마다 반복
//5분마다 현재 가격 가져와서 db랑 비교후 매수 매도 기준잡기
var t1 = new Array();
test_data=await (latest_repeat(t1));
// var t1 = new Array();
// test_data = await (latest_repeat(t1));
//계좌 정보 db 최신화
console.log(await get_asset());
// console.log(await get_asset());
await transaction_coin("KRW-BTC","bid",null,divided_money,"price");
})
\ No newline at end of file
......
......@@ -17,6 +17,8 @@
"node-fetch": "^3.0.0",
"querystring": "^0.2.1",
"request": "^2.88.2",
"request-promise": "^4.2.6",
"request-promise-native": "^1.0.9",
"requests": "^0.3.0",
"uuid": "^8.3.2"
},
......@@ -229,6 +231,11 @@
"node": ">=8"
}
},
"node_modules/bluebird": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
"integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg=="
},
"node_modules/body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
......@@ -1420,6 +1427,11 @@
"xhr-status": "1.0.x"
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"node_modules/lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
......@@ -2080,6 +2092,55 @@
"node": ">= 6"
}
},
"node_modules/request-promise": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/request-promise/-/request-promise-4.2.6.tgz",
"integrity": "sha512-HCHI3DJJUakkOr8fNoCc73E5nU5bqITjOYFMDrKHYOXWXrgD/SBaC7LjwuPymUprRyuF06UK7hd/lMHkmUXglQ==",
"deprecated": "request-promise has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142",
"dependencies": {
"bluebird": "^3.5.0",
"request-promise-core": "1.1.4",
"stealthy-require": "^1.1.1",
"tough-cookie": "^2.3.3"
},
"engines": {
"node": ">=0.10.0"
},
"peerDependencies": {
"request": "^2.34"
}
},
"node_modules/request-promise-core": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.4.tgz",
"integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==",
"dependencies": {
"lodash": "^4.17.19"
},
"engines": {
"node": ">=0.10.0"
},
"peerDependencies": {
"request": "^2.34"
}
},
"node_modules/request-promise-native": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.9.tgz",
"integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==",
"deprecated": "request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142",
"dependencies": {
"request-promise-core": "1.1.4",
"stealthy-require": "^1.1.1",
"tough-cookie": "^2.3.3"
},
"engines": {
"node": ">=0.12.0"
},
"peerDependencies": {
"request": "^2.34"
}
},
"node_modules/request/node_modules/qs": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
......@@ -2275,6 +2336,14 @@
"node": ">= 0.6"
}
},
"node_modules/stealthy-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz",
"integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
......@@ -2825,6 +2894,11 @@
"integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==",
"dev": true
},
"bluebird": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
"integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg=="
},
"body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
......@@ -3737,6 +3811,11 @@
"xhr-status": "1.0.x"
}
},
"lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"lodash.includes": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
......@@ -4258,6 +4337,35 @@
}
}
},
"request-promise": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/request-promise/-/request-promise-4.2.6.tgz",
"integrity": "sha512-HCHI3DJJUakkOr8fNoCc73E5nU5bqITjOYFMDrKHYOXWXrgD/SBaC7LjwuPymUprRyuF06UK7hd/lMHkmUXglQ==",
"requires": {
"bluebird": "^3.5.0",
"request-promise-core": "1.1.4",
"stealthy-require": "^1.1.1",
"tough-cookie": "^2.3.3"
}
},
"request-promise-core": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.4.tgz",
"integrity": "sha512-TTbAfBBRdWD7aNNOoVOBH4pN/KigV6LyapYNNlAPA8JwbovRti1E88m3sYAwsLi5ryhPKsE9APwnjFTgdUjTpw==",
"requires": {
"lodash": "^4.17.19"
}
},
"request-promise-native": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.9.tgz",
"integrity": "sha512-wcW+sIUiWnKgNY0dqCpOZkUbF/I+YPi+f09JZIDa39Ec+q82CpSYniDp+ISgTTbKmnpJWASeJBPZmoxH84wt3g==",
"requires": {
"request-promise-core": "1.1.4",
"stealthy-require": "^1.1.1",
"tough-cookie": "^2.3.3"
}
},
"requests": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/requests/-/requests-0.3.0.tgz",
......@@ -4411,6 +4519,11 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
"integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow="
},
"stealthy-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz",
"integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks="
},
"string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
......
......@@ -22,6 +22,8 @@
"node-fetch": "^3.0.0",
"querystring": "^0.2.1",
"request": "^2.88.2",
"request-promise": "^4.2.6",
"request-promise-native": "^1.0.9",
"requests": "^0.3.0",
"uuid": "^8.3.2"
},
......