2019102152 김다빈

Modify check_coin function

const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const url1 = 'https://api.upbit.com/v1/market/all';
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 crypto=require('crypto');
const queryEncode=require('querystring').encode;
const request = require('request')
const {v4} = require("uuid")
const sign = require('jsonwebtoken').sign
var sort_info = new Array();
const mongoose = require('mongoose');
const config = require('./config/key');
const { json } = require('express');
const connect = mongoose.connect(config.mongoURI, {
useNewUrlParser: true, useUnifiedTopology: true
})
.then(() => console.log('디비연결 성공'))
.catch((err) => console.log(err));
var korean_name = new Object();
const access_key = process.env.access_key;
const secret_key = process.env.secret_key;
const server_url = "https://api.upbit.com"
function get_asset(){
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}`},
}
return new Promise(resolve=>{
request(options,function(err,res,body){
if (err) throw new Error(err)
// test=res.json();
data=JSON.parse(body);
// console.log(data[0].currency)
data.filter(function(item){
if(item.currency=="PLA"){
resolve(item);
}
})
})
})
}
async function get_marketName() {
var data = new Array();
//전체 암호화폐 리스트 불러오기
let response = await fetch(url1, options)
let response = await fetch(`${server_url}/v1/market/all`, options)
.then(res => res.json())
.then(json => {
for (i in json) {
......@@ -30,10 +76,45 @@ async function get_marketName() {
})
return data;
}
async function transaction_coin(coin_name,side,volume,price,ord_type){
const body = {
market: coin_name,
side: side,
volume: volume,
price: price,
ord_type: 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}`},
json: body
}
request(options, (error, response, body) => {
if (error) throw new Error(error)
console.log(body)
})
}
async function get_marketInfo() {
//각 암호화폐 정보 조회
var name_list = await get_marketName();
const url2 = `https://api.upbit.com/v1/ticker/?markets=${name_list}`;
const url2 = `${server_url}/v1/ticker/?markets=${name_list}`;
var arr = new Array();
let response2 = await fetch(url2, options)
.then(res => res.json())
......@@ -106,6 +187,9 @@ async function check_coin(t1) {
console.log(err);
} else {
console.log("***" + result.korean_name + "은(는)" + result.count * 5 + "분 동안 하락중");
if(count>=3){
transaction_coin(result.name,"bid",null,"얼마치 살건지","price");
}
}
})
}//그대로 이거나 올랐을때
......@@ -114,6 +198,8 @@ async function check_coin(t1) {
if (err) {
console.log(err);
} else {
//특정 조건...
transaction_coin(result.name,"ask","몇개를 팔건지",null,"market");
console.log(result.korean_name + "은(는)" + result.count * 5 + "분 동안 상승 혹은 정체중");
}
})
......@@ -122,29 +208,6 @@ async function check_coin(t1) {
})
}
}
// async function repeat_check(t1) {
// await Coin.find().sort({ tid: 1 }).then(result => {
// for (var key in result) {
// t1.push(result[key].name)
// }
// })
// let check_time = setInterval(() => {
// let today = new Date();
// let minutes = today.getMinutes();
// let seconds = today.getSeconds();
// if (minutes % 5 == 0 && seconds == 0) {
// clearInterval(check_time);
// console.log("현재 시간은 " + today.toLocaleTimeString());
// check_coin(t1);
// setInterval(async () => {
// let today = new Date();
// console.log("현재 시간은 " + today.toLocaleTimeString());
// check_coin(t1);
// }, 60000 * 5);
// }
// }, 1000)
// }
async function latest_repeat(t1) {
await Coin.find().sort({ tid: 1 }).then(result => {
for (var key in result) {
......@@ -161,16 +224,19 @@ async function latest_repeat(t1) {
sort_info = (await sort_data());
(await refresh_db());
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());
await (check_coin(t1));
if(minutes==0&&seconds==0){
sort_info = (await sort_data());
await (check_coin(t1).then(count++));
//1시간마다 db 최신화...
if(count==12){
count=0;
sort_info=(await sort_data());
(await refresh_db());
console.log("db 최신화");
console.log("db최신화");
}
}, 60000*5);
}
......@@ -182,5 +248,6 @@ app.listen(5000, async () => {
//5분마다 현재 가격 가져와서 db랑 비교후 매수 매도 기준잡기
var t1 = new Array();
test_data=await (latest_repeat(t1));
//반복
//계좌 정보 db 최신화
console.log(await get_asset());
})
\ No newline at end of file
......
const mongoose=require('mongoose');
const userSchema=mongoose.Schema({
krw_balance:{
type:Number,
},
market:{
type:String,
},
count:{
type:Number,
},
avg_buy_price:{
type:Number
}
})
const User=mongoose.model("User",userSchema);
module.exports={User};
\ No newline at end of file
This diff is collapsed. Click to expand it.
......@@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node index.js"
"start": "node index.js"
},
"repository": {
"type": "git",
......@@ -14,9 +14,16 @@
"author": "",
"license": "ISC",
"dependencies": {
"crypto": "^1.0.1",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.0.12",
"node-fetch": "^3.0.0"
"node-fetch": "^3.0.0",
"querystring": "^0.2.1",
"request": "^2.88.2",
"requests": "^0.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"nodemon": "^2.0.14"
......