-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmongodb.js
More file actions
280 lines (252 loc) · 7.91 KB
/
mongodb.js
File metadata and controls
280 lines (252 loc) · 7.91 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
const mongoose = require('mongoose');
const config = require('./config/database.json')
const db = mongoose.connection
const crypto = require('crypto')
let _ALL_ACCOUNTS; //_ALL_ACCOUNTS[0]._doc.accounts[0]._doc.currency
let _ALL_USERSAUTH; //_ALL_USERSAUTH[0]._doc.accessKey
function getSavedAccounts(){
/*
ACCESSKEY : {
_id : 'ACCESSKEY',
accessKey : 'ACCESSKEY',
accounts : []
},
ACCESSKEY2 : {
} ...
*/
retJSON = {};
for(var i in _ALL_ACCOUNTS){
let accessKey = _ALL_ACCOUNTS[i]._doc.accessKey
let accounts = _ALL_ACCOUNTS[i]._doc.accounts
retJSON[accessKey] = {
_id : accessKey,
accessKey : accessKey,
accounts : accounts
}
}
return retJSON
}
function getSavedUserAuth(){
let retJSON = {}
/*
{"accessKey" : "secretKey", ...}
*/
for(var i in _ALL_USERSAUTH){
accessKey = _ALL_USERSAUTH[i]._doc.accessKey;
secretKey = _ALL_USERSAUTH[i]._doc.secretKey;
retJSON[accessKey] = secretKey
}
return retJSON
}
async function mongooseConnect(){
return new Promise((resolve, reject)=>{
mongoose.connect(config.mongodbURI, {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false
}).then(() => resolve())
.catch(error => reject(error))
})
}
db.on('error', function(err) { console.log("Unable to connect to database. Error: " + err) } )
db.once('open', function() {
console.log('Mongoose database connection established.')
})
db.on('disconnected', function() {
console.log('MongoDB disconnected. Attempting to reconnect...')
})
db.on('reconnected', function() { console.log('Mongoose reconnected.')})
const userAuthStructure = {
_id : String,
accessKey : {type:String, unique:true},
secretKey : String,
defaultBalance : Number,
}
const orderStructure = {
_id : String,
accessKey : String,
uuid : {type:String, unique:true},
side : String,
ord_type : String,
price : Number,
avg_price : Number,
state : String,
market : String,
created_at : String,
volume : Number,
remaining_volume : String,
reserved_fee : String,
remaining_fee : String,
paid_fee : String,
locked : String,
executed_volume : Number,
trades_count : Number
}
// const accountStructure = {
// _id : String,
// currency : String,
// balance : String,
// locked : String,
// avg_buy_price : String,
// avg_buy_price_modified : Boolean,
// unit_currency : String,
// timestamp : String
// }
const userAccountStructure = {
_id : String,
accessKey : {type:String, unique:true},
accounts : {}
// 배열로 하지말자...진짜..
}
const userAuthSchema = new mongoose.Schema(userAuthStructure);
const orderSchema = new mongoose.Schema(orderStructure);
const userAccountSchema = new mongoose.Schema(userAccountStructure);
const logSchema = new mongoose.Schema({
timestamp : String,
detail : mongoose.Schema.Types.Mixed,
accessKey : String
})
const userAuthModel = mongoose.model('userAuthModel', userAuthSchema);
const orderModel = mongoose.model('orderModel', orderSchema);
const userAccountModel = mongoose.model('userAccountModel', userAccountSchema);
const logModel = mongoose.model('logModel', logSchema)
async function saveErrorLog(accessKey, message){
var instance = new logModel({
timestamp : new Date().toLocaleString('en', {timeZone: "Asia/Seoul"}),
detail : message,
accessKey : accessKey
});
ret = await instance.save()
return ret;
}
async function saveOrderLog(accessKey, message){
try{
let order = {
_id : message.uuid,
accessKey : accessKey,
uuid : message.uuid,
side : message.side,
ord_type : message.ord_type,
price : message.price,
avg_price : message.avg_price,
state : message.state,
market : message.market,
created_at : message.created_at,
volume : message.volume,
remaining_volume : message.remaining_volume,
reserved_fee : message.reserved_fee,
remaining_fee : message.remaining_fee,
paid_fee : message.paid_fee,
locked : message.locked,
executed_volume : message.executed_volume,
trades_count : message.trades_count
}
var instance = new orderModel(order);
let ret = await instance.save()
return ret;
}catch(E){
console.log(E)
saveErrorLog(accessKey, E)
}
}
// accessKey : String,
// secretKey : String,
// defaultBalance : Number,
async function addUserAuth(accessKey, secretKey, defaultBalance){
var user = new userAuthModel({_id:accessKey, accessKey:accessKey, secretKey:secretKey, defaultBalance:defaultBalance});
ret = await user.save()
return ret;
}
async function addAccount(accessKey, balance){
var account = new userAccountModel({
_id:accessKey,
accessKey:accessKey,
accounts : [
{
currency : "KRW",
balance : balance.toString(),
//locked:"0.0",
//avg_buy_price:"0",
//avg_buy_price_modified:false,
//unit_currency: "KRW",
timestamp : new Date().toLocaleString('en', {timeZone: "Asia/Seoul"})
}
]
});
ret = await account.save()
return ret;
}
async function loadAllAccountAndAuth(){
ret = await userAccountModel.find();
_ALL_ACCOUNTS = ret;
ret = await userAuthModel.find();
_ALL_USERSAUTH = ret
}
async function makeAccountAndAuth(accessKey, balance, secretKey){
if(typeof secretKey == "undefined") {
secretKey = crypto.createHash('sha256').update(config.hashkey + accessKey).digest('base64');
}
ret = await addUserAuth(accessKey, secretKey, balance);
ret = await addAccount(accessKey, balance);
}
async function makeAllTestAccountsAndAuth(balance){
for(var i in config.users){
userKEY = "test" + config.users[i];
await addUserAuth(userKEY, "TEST_SECRET_KET", balance);
await addAccount(userKEY, balance);
console.log("MADE : "+ userKEY)
}
}
async function makeAllRealAccountsAndAuth(balance){
for(var i in config.users){
userKEY = config.users[i];
await makeAccountAndAuth(userKEY, balance)
console.log("MADE : "+ userKEY)
}
}
async function saveAccount(accessKey, account){
timestamp = new Date().toLocaleString('en', {timeZone: "Asia/Seoul"})
var dynSet = {$set: {"accounts":account}};
//var dynSet = {"accounts":{"KRW":{"balance":KRW_balance, "timestamp":timestamp}}};
//dynSet.accounts[market] = {balance:market_balance, avg_buy_price:avg_buy_price, timestamp:timestamp}
result = await userAccountModel.findByIdAndUpdate(accessKey, dynSet, {
new : true //true 여야지 반환하는 값이 업데이트된 데이터임.
})
return result
}
//https://backend-intro.vlpt.us/2/05.html
async function getAccount(accessKey){
result = await userAccountModel.findById(accessKey);
return result;
}
async function printAllAccountsSecret(){
for(var i in _ALL_USERSAUTH){
console.log(_ALL_USERSAUTH[i].accessKey + " : " + _ALL_USERSAUTH[i].secretKey);
}
}
async function init(){
let ret = await mongooseConnect();
ret = await loadAllAccountAndAuth();
console.log(ret);
await printAllAccountsSecret()
return ret;
}
//init()
async function initCreate(){
await init()
userKEY = "tunabaguette"
balance = 50000000
await makeAccountAndAuth(userKEY, balance)
//ret = await makeAllRealAccountsAndAuth(50000000)
console.log(ret)
}
init();
module.exports = {
init,
getAccount,
saveAccount,
saveErrorLog,
saveOrderLog,
_ALL_ACCOUNTS,
_ALL_USERSAUTH,
getSavedAccounts,
getSavedUserAuth
}