Commit 3667f1b7 authored by Ahmad Nemati's avatar Ahmad Nemati

init

parent a2703f5d
......@@ -4,28 +4,30 @@ const fs = require('fs');
let plus = 'plus'
let zarib = 'zarib'
let base = 'base'
let dynamic = 'dynamic'
function run(data, config, risk, pfTrade, riskFreeLevel,detail,loss) {
let type=config.type + ' param:' + config.param + ' base:' + config.base + ' target:' + config.target
let saveData=[]
let needPrintData=shouldPrint(detail,data[0].signal+'&'+type)
// console.log(needPrintData)
function run(data, config, risk, pfTrade, riskFreeLevel, detail, loss) {
let type = config.type + ' param:' + config.param + ' base:' + config.base + ' target:' + config.target
let saveData = []
let needPrintData = shouldPrint(detail, data[0].signal + '&' + type)
// console.log(needPrintData)
let commision = config.commision
let money = config.base
let total = 0
let allTotal=0
let allTotal = 0
let maxReserve = 0
let maxMeta=0
let allLoss=0
let maxMeta = 0
let allLoss = 0
let curDrawDown = 0
let maxAllocatedMoney = 0
let maxLevel = 0
// console.log(data)
let step = 0
let reserv = 0
let meta=0
let meta = 0
let profit = 0
let lastCom = 0
let lastMoney = 0
......@@ -33,16 +35,14 @@ function run(data, config, risk, pfTrade, riskFreeLevel,detail,loss) {
let dur
try {
dur =getMinDiff(data[0].openDate, data[data.length - 1].closeDate)
}
catch (e)
{
return null
dur = getMinDiff(data[0].openDate, data[data.length - 1].closeDate)
} catch (e) {
return null
}
if (dur <300)
return null
if (dur < 300)
return null
let newP = dur / data.length
// console.log(data.length)
......@@ -50,7 +50,7 @@ function run(data, config, risk, pfTrade, riskFreeLevel,detail,loss) {
if (pfTrade < newP)
return null
for (let i = 0; i < data.length; i++) {
let obj
let obj
if (step === 0)
money = config.base
else {
......@@ -60,19 +60,26 @@ let obj
money = config.base * config.param * step
else if (config.type === plus)
money = config.base * (step + 1)
else if (config.type === dynamic) {
if (curDrawDown <= 0)
money = lastMoney
else {
money = percentage2(lastMoney, config.param * curDrawDown)
}
}
}
let riskfree = false
if (step > riskFreeLevel)
riskfree = true
let d = inlineCheck(money, commision, data[i], profit, lastCom, config.target,riskfree)
let d = inlineCheck(money, commision, data[i], profit, lastCom, config.target, riskfree)
if (d.reserve<0 && Math.abs(d.reserve) > Math.abs(maxReserve))
if (d.reserve < 0 && Math.abs(d.reserve) > Math.abs(maxReserve))
maxReserve = d.reserve
if (d.meta <0 && Math.abs(d.meta) > Math.abs(maxMeta))
maxMeta=d.meta
if (d.meta < 0 && Math.abs(d.meta) > Math.abs(maxMeta))
maxMeta = d.meta
// console.log(maxAllocatedMoney)
if (money > maxAllocatedMoney)
......@@ -83,33 +90,29 @@ let obj
// console.log(d)
if (step > maxLevel)
maxLevel = step
if (needPrintData)
{
if (needPrintData) {
obj=d
obj.signal=data[i]
obj = d
obj.signal = data[i]
if (d.meta <0 )
obj.currentDrawDown=Math.abs(((d.meta * 100) / money))
if (d.meta < 0)
obj.currentDrawDown = Math.abs(((d.meta * 100) / money))
else
obj.currentDrawDown=0
obj.maxReserve=maxReserve
obj.maxAllocatedMoney=maxAllocatedMoney
obj.maxLevel=maxLevel
obj.step=step
obj.currentDrawDown = 0
obj.maxReserve = maxReserve
obj.maxAllocatedMoney = maxAllocatedMoney
obj.maxLevel = maxLevel
obj.step = step
}
if (loss !==0 && d.meta <0 && Math.abs(d.meta) > loss)
{
allLoss=allLoss+d.meta
if (loss !== 0 && d.meta < 0 && Math.abs(d.meta) > loss) {
allLoss = allLoss + d.meta
levels.push(step)
step = 0
reserv = 0
......@@ -130,23 +133,27 @@ let obj
reserv = 0
profit = 0
lastCom = 0
curDrawDown=0
lastMoney = 0
allTotal++
if (!d.riskFree)
total++
total++
} else {
step++
profit = profit + d.profit
lastMoney = d.lastMoney
lastCom = lastCom + d.com
if (needPrintData)
{
obj.profitAll=profit
obj.lastMoney=lastMoney
if (d.meta < 0)
curDrawDown = Math.abs(((d.meta * 100) / money))
else
curDrawDown = 0
if (needPrintData) {
obj.profitAll = profit
obj.lastMoney = lastMoney
}
......@@ -158,33 +165,28 @@ let obj
}
let newReserv=maxReserve
maxReserve=maxMeta
let newReserv = maxReserve
maxReserve = maxMeta
let firstMaxAllocatedMoney = maxAllocatedMoney
if (config.param !== 0) {
for (let i = 0; i < risk; i++)
maxAllocatedMoney = maxAllocatedMoney * config.param
}
if (needPrintData)
{
for (let i=0;i<saveData.length;i++)
{
if (needPrintData) {
for (let i = 0; i < saveData.length; i++) {
try {
if (saveData[i].meta <0)
saveData[i].perMeta=Math.abs(((saveData[i].meta * 100) / maxAllocatedMoney))
if (saveData[i].meta < 0)
saveData[i].perMeta = Math.abs(((saveData[i].meta * 100) / maxAllocatedMoney))
else
saveData[i].perMeta=0
saveData[i].perMeta = 0
if (saveData[i].reserve <0)
saveData[i].perReserve=Math.abs(((saveData[i].reserve * 100) / maxAllocatedMoney))
if (saveData[i].reserve < 0)
saveData[i].perReserve = Math.abs(((saveData[i].reserve * 100) / maxAllocatedMoney))
else
saveData[i].perReserve=0
saveData[i].perReserve = 0
}
catch (e)
{
} catch (e) {
}
}
......@@ -213,9 +215,9 @@ let obj
let totalFinal = total * config.target
let totalPlus=totalFinal+allLoss
let oldTotalFinal=totalFinal
totalFinal=totalPlus
let totalPlus = totalFinal + allLoss
let oldTotalFinal = totalFinal
totalFinal = totalPlus
let newT = totalFinal / dur
let percentage = maxReserve + totalFinal
percentage = maxAllocatedMoney / percentage
......@@ -253,13 +255,13 @@ let obj
platform: data[0].signal,
type: type,
total: total,
allTotal:allTotal,
allTotal: allTotal,
avgLevel: maxLevel / total,
maxLevel: maxLevel,
dur: dur,
allLoss:allLoss,
allLoss: allLoss,
totalFinal: oldTotalFinal,
totalPlus:totalPlus,
totalPlus: totalPlus,
totalCompound: sum,
profitPerMonth: Math.abs(profitPerMonth),
compoundPerMonth: compoundPerMonth,
......@@ -272,7 +274,7 @@ let obj
CompoundPerMonthDrawDown: compoundPerMonth / drawDown,
profitPerMonthDrawDown: Math.abs(profitPerMonth) / drawDown,
maxReseve: newReserv,
maxMeta:maxMeta,
maxMeta: maxMeta,
avgReserve: maxReserve / total,
percentage: percentage,
avgProfitPerDay: newT,
......@@ -287,15 +289,13 @@ let obj
}
if (needPrintData)
{
fs.writeFile('detail/'+opt.platform+'-'+'param' + config.param + 'base' + config.base + 'target' + config.target+'.json', JSON.stringify(saveData, null, 2), 'utf8', function (err) {
if (needPrintData) {
fs.writeFile('detail/' + opt.platform + '-' + 'param' + config.param + 'base' + config.base + 'target' + config.target + '.json', JSON.stringify(saveData, null, 2), 'utf8', function (err) {
});
}
return opt
......@@ -323,18 +323,17 @@ function percentage2(base, per) {
}
function inlineCheck(money, com, data, profit, lastCom, tar,riskFree) {
function inlineCheck(money, com, data, profit, lastCom, tar, riskFree) {
// console.log(profit)
com = com * money
let minProf=profit*-1
let minProf = profit * -1
let target = money + minProf + com + lastCom
let targetDetail='('+money+')' +'+'+'('+minProf+')+('+com +')+('+lastCom+')'
if (!riskFree)
{
target=target+tar
targetDetail=targetDetail+'+('+tar+')'
let targetDetail = '(' + money + ')' + '+' + '(' + minProf + ')+(' + com + ')+(' + lastCom + ')'
if (!riskFree) {
target = target + tar
targetDetail = targetDetail + '+(' + tar + ')'
}
......@@ -345,15 +344,38 @@ let targetDetail='('+money+')' +'+'+'('+minProf+')+('+com +')+('+lastCom+')'
let diff = reserve - money
diff = diff - com - lastCom + profit
let meta=profitMoney+profit-com-lastCom
let meta = profitMoney + profit - com - lastCom
// console.log('reserve->'+reserve + ' money->'+money +' com->'+com +' lastCom->'+lastCom + 'profit->'+profit +' diff->'+diff)
if (percentage(money, data.runUp) > target)
return {done: true,money:money, meta:meta,reserve: diff,riskFree,profitLastSteps:profit,profit: profitMoney,lastCom:lastCom,com: com,target:target,targetDetail:targetDetail}
return {
done: true,
money: money,
meta: meta,
reserve: diff,
riskFree,
profitLastSteps: profit,
profit: profitMoney,
lastCom: lastCom,
com: com,
target: target,
targetDetail: targetDetail
}
else
return {done: false,money:money,meta:meta, reserve: diff, profitLastSteps:profit,profit: profitMoney, lastMoney: money,com: com,target:target,targetDetail:targetDetail}
return {
done: false,
money: money,
meta: meta,
reserve: diff,
profitLastSteps: profit,
profit: profitMoney,
lastMoney: money,
com: com,
target: target,
targetDetail: targetDetail
}
}
......@@ -363,11 +385,9 @@ function calPer(entry, last) {
return ((last - entry) / entry) * 100
}
function shouldPrint(details,type)
{
for (let i=0;i<details.length;i++)
{
if (details[i] ===type)
function shouldPrint(details, type) {
for (let i = 0; i < details.length; i++) {
if (details[i] === type)
return true
}
......
var AWS = require('aws-sdk');
var shell = require('shelljs');
const request = require('request');
let moment = require('moment-timezone')
let utils = require('./utils')
const fs = require('fs');
const db = require('./../database/db')
var lightsail
class Amazon {
constructor(account, regionParam, serverParam) {
this.region = regionParam
this.server = serverParam
console.log(percentage(200,2))
}
function percentage(base, per) {
async init() {
let ip = await utils.getIp()
let acc = await db.getAccByIp(ip)
var config = new AWS.Config({
accessKeyId: acc.access, secretAccessKey: acc.secret, region: this.region
});
lightsail = new AWS.Lightsail(config)
}
async getIp(proxy) {
try {
await this.deAttachStaticIp()
} catch (e) {
}
await this.attachStaticIp(proxy.instance)
await this.deAttachStaticIp()
let ip = await this.getIpAddressOfInstance(proxy.instance)
try {
await this.doRequest(ip)
} catch (e) {
await this.initFirewall(proxy.instance)
await this.doRequest(ip)
}
return ip
}
async createInstance(snap, nparam) {
let name
if (nparam)
name = nparam
else
name = 'Cluster' + this.randomInt(0, 500000)
await this.createInstanceFromSnashot(name, snap)
await this.sleep(15000)
// try {
// await this.initFirewall(name)
// }
// catch (e) {
//
// }
let ip
try {
ip = await this.getIpAddressOfInstance(name)
} catch (e) {
}
// await this.doRequest(ip)
//await rebootInstance(name)
return {name: name, ip: ip}
}
sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
attachStaticIp(instance) {
let ipname = 'StaticIp-1'
return new Promise(function (resolve, reject) {
lightsail.attachStaticIp({staticIpName: ipname, instanceName: instance}
, function (error, data) {
if (error) {
console.log(error)
reject('Error attachStaticIp')
}
if (data)
resolve(true)
});
});
}
deAttachStaticIp() {
let ipname = 'StaticIp-1'
return new Promise(function (resolve, reject) {
lightsail.detachStaticIp({staticIpName: ipname}, function (error, data) {
if (error) {
reject('Error deAttachStaticIp')
}
if (data)
resolve(true)
})
});
}
releaseStaticIp(name) {
return new Promise(function (resolve, reject) {
var params = {
staticIpName: name /* required */
};
lightsail.releaseStaticIp(params
, function (error, data) {
if (error)
reject('Error releaseStaticIp')
if (data)
resolve(true)
});
});
}
createSnapshutFromInstace() {
return new Promise(function (resolve, reject) {
var params = {
instanceName: 'Ubuntu-1', /* required */
instanceSnapshotName: 'snapx', /* required */
};
lightsail.createInstanceSnapshot(params, function (err, data) {
if (err)
reject('Error create snapx')
if (data)
resolve(true)
});
});
}
createStaticIp(name) {
return new Promise(function (resolve, reject) {
var params = {
staticIpName: name /* required */
};
lightsail.allocateStaticIp(params
, function (error, data) {
if (error) {
console.log(error)
reject('Error createStaticIp')
}
if (data)
resolve(data)
});
});
}
getAllInstances() {
return new Promise(function (resolve, reject) {
lightsail.getInstances(function (error, data) {
if (error) {
console.log(error)
reject('Error getAllInstances')
}
if (data)
resolve(data.instances)
})
});
}
getAllIps() {
return new Promise(function (resolve, reject) {
lightsail.getStaticIps(function (error, data) {
if (error)
reject('Error getAllIps')
if (data)
resolve(data.staticIps)
})
});
}
rebootInstance(proxy) {
return new Promise(function (resolve, reject) {
lightsail.rebootInstance({instanceName: proxy.instance}, function (error, data) {
if (error) {
console.log(error)
resolve(false)
}
if (data)
resolve(true)
})
});
}
getIpAddressOfInstance(instance) {
return new Promise(function (resolve, reject) {
lightsail.getInstance({instanceName: instance}, function (error, data) {
if (error) {
console.log(error)
reject('Error getIpAddressOfInstance')
}
if (data)
resolve(data.instance.publicIpAddress)
});
});
}
deleteInstance(instance) {
var params = {
instanceName: instance /* required */
};
return new Promise(function (resolve, reject) {
lightsail.deleteInstance(params, function (error, data) {
if (error)
reject('Error deleteInstance')
if (data)
resolve(data)
});
});
}
getInstance(instance) {
return new Promise(function (resolve, reject) {
lightsail.getInstance({instanceName: instance}, function (error, data) {
if (error)
reject('Error getInstance')
if (data)
resolve(data.instance)
});
});
}
initFirewall(instance) {
return new Promise(function (resolve, reject) {
var params = {
instanceName: instance,
portInfos: [
{
fromPort: 0,
protocol: 'all',
toPort: 65535
},
]
};
lightsail.putInstancePublicPorts(params, function (error, data) {
if (error) {
console.log(error)
reject('Error putInstancePublicPorts')
}
if (data)
resolve(data)
});
});
}
copySnapShut(snap, region) {
return new Promise(function (resolve, reject) {
var params = {
sourceRegion: region,
targetSnapshotName: snap,
sourceSnapshotName: snap,
};
lightsail.copySnapshot(params, function (error, data) {
if (error) {
console.log(error)
reject('Error copySnapshot')
}
if (data)
resolve(data)
});
});
}
getInstanceOpenPort(instance) {
return new Promise(function (resolve, reject) {
lightsail.getInstancePortStates({instanceName: instance}, function (error, data) {
if (error)
reject(error)
if (data)
resolve(data)
});
});
}
createInstanceFromSnashot(instanceName, snap) {
let reg = this.region
let server = this.server
return new Promise(function (resolve, reject) {
var params = {
availabilityZone: reg + 'a', /* required */
bundleId: server, /* required */
instanceNames: [instanceName],
instanceSnapshotName: snap, /* required */
};
lightsail.createInstancesFromSnapshot(params, function (error, data) {
if (error) {
console.log(error)
reject('Error createInstancesFromSnapshot')
}
if (data)
resolve(data)
});
});
}
createInstanceFromNormalWay() {
let reg = this.region
let server = 'large_2_0'
let command = " cd /home/ubuntu && " +
" git clone http://49.12.200.60/root/mt2oldAmazon.git" +
" && mv mt2oldAmazon mt" +
" && cd mt && chmod 777 " +
"* && ./install.sh && cd .." +
" && git clone http://49.12.200.60/root/rt2old.git " +
"&& mv rt2old rt2 && " +
"cd rt2 && chmod" +
" 777 * && ./run.sh && " +
"sudo pm2 start app.js && " +
"sudo pm2 startup && "
+ "sudo pm2 save && " +
"sleep 5 && reboot"
return new Promise(function (resolve, reject) {
var params = {
availabilityZone: reg + 'a', /* required */
blueprintId: 'ubuntu_18_04', /* required */
bundleId: 'large_2_0', /* required */
instanceNames: [ /* required */
'Ubuntu-1',
'Ubuntu-2'
],
userData: command
};
if (reg === 'eu-north-1')
params.bundleId = 'large_2_3'
lightsail.createInstances(params, function (error, data) {
if (error) {
console.log(error)
reject('Error createInstancesFromNormalWay')
}
if (data) {
console.log(data)
resolve(data)
}
});
});
}
async foundInstance(meta) {
let instance = await this.getAllInstances()
for (let i = 0; i < instance.length; i++) {
if (instance[i].name === meta) {
return {found: true, createdAt: instance[i].createdAt}
}
}
return {found: false}
}
async foundNormalInstance(meta) {
let instance = await this.getAllInstances()
for (let i = 0; i < instance.length; i++) {
if (instance[i].name === meta) {
return true
}
}
return false
}
async getDaysCreate(meta) {
let instance = await this.getAllInstances()
for (let i = 0; i < instance.length; i++) {
if (instance[i].name === meta)
return this.getMinDays(instance[i].createdAt)
}
return false
}
getMinDays(end) {
var now = moment(moment().tz('Asia/Tehran').format());
var end = moment.duration(now.diff(moment(end).tz('Asia/Tehran')));
return parseInt(end.asDays())
}
async isIpAlive(ip) {
let a = await shell.exec('ping ' + ip + ' -c 3', {silent: true}).stdout;
a = a.split(',')[2].split('%')[0]
a = parseInt(a)
return a <= 30
}
randomInt(low, high) {
return Math.floor(Math.random() * (high - low) + low)
}
doRequest(ip) {
let url = 'http://' + ip + ':3000'
return new Promise(function (resolve, reject) {
request(url, {timeout: 6000}, function (error, res, body) {
try {
if (!error && res.statusCode === 200) {
resolve(body);
} else {
reject(error);
}
} catch (e) {
reject('Error Request');
}
});
});
}
}
module.exports = Amazon;
\ No newline at end of file
base = parseFloat(base)
per = parseFloat(per)
let percentager = per / 100
let temp = base * percentager
return base + temp
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment