· 8 years ago · Apr 07, 2018, 08:42 PM
1// ==UserScript==
2// @name PTUI
3// @namespace http://45.76.49.214:8081/monitoring
4// @version 0.1
5// @description try to take over the world!
6// @author You
7// @match http://45.76.49.214:8081/monitoring
8// @grant none
9// ==/UserScript==
10
11//Graphing-Tracker.js
12//Graphing-Tracker.js
13//Graphing-Tracker.js
14(function(){
15 var util = {};
16
17 //=========================================
18 //=============== SETTINGS ==============
19 //=========================================
20
21 util.graphMinutes = 15; //how many minutes of graph to show?
22 util.extendGraphColumn = true; //if you set more than 10 minutes, set this to true.
23 util.drawZeroLine = true; //display line at purchase price
24 util.drawSellThreshold = true; //draw
25 util.zeroLineColor = '#333';
26 util.sellThresholdColor = '#ff5';
27 util.graphLineColor = '#00f';
28
29 // --- border percentages add padding to the top or bottom of the graph based on the height of the box.
30 // --- the percentages are percent out of the original max to min spread.
31
32 util.topOffsetPercentage = 2; // value between 60 and 2;
33 util.bottomOffsetPercentage = 2; // value between 60 and 2;
34
35 // --- the below settings are experimental... please let me know if they aren't working and you're using them.
36
37 util.testHangWarning = false; // --- true to enable hang warnings; false to disable.
38 util.hangThreshold = 15; // --- the number of ticks with an identical price that will cause a hang warning alert.
39 util.percentHanging = .9; // --- percentage of items needed to appear to hang before a warning is given
40 util.hangWarningMessage = '{n} Prices seem to be stagnant... did the bot hang?'; // --- hang message
41
42 util.displayMarketCap = true;
43 //=========================================
44 //=========== END SETTINGS ==============
45 //=========================================
46
47 util.coinMarketCapAPI = 'https://api.coinmarketcap.com/v1/global/';
48 util.msPerDataFrame = 12900; //assumed average time
49 util.topOffsetPercentage = Math.min( 60, Math.max( 2, util.topOffsetPercentage ));
50 util.bottomOffsetPercentage = Math.min( 60, Math.max( 2, util.bottomOffsetPercentage ));
51 util.graphFrames = ((util.graphMinutes || 5) * 6) >> 0;
52 util.hangThreshold = Math.min( 999, Math.max( 1, util.hangThreshold ));
53 util.percentHanging = Math.min( 1, Math.max( .001, util.percentHanging ));
54
55 util.createHiDPICanvas = function( w, h, ratio, elementUse ) {
56 if( !window.PIXEL_RATIO ) {
57 window.PIXEL_RATIO = ( function () {
58 var ctx = document.createElement( "canvas" ).getContext( "2d" ),
59 dpr = window.devicePixelRatio || 1,
60 bsr = ctx.webkitBackingStorePixelRatio ||
61 ctx.mozBackingStorePixelRatio ||
62 ctx.msBackingStorePixelRatio ||
63 ctx.oBackingStorePixelRatio ||
64 ctx.backingStorePixelRatio || 1;
65
66 return dpr / bsr;
67 })();
68 }
69 if ( !ratio ) { ratio = window.PIXEL_RATIO; }
70 var can = ( Array.isArray( elementUse ) ? elementUse[0] : elementUse );
71 can.width = w * ratio;
72 can.height = h * ratio;
73 can.style.width = w + "px";
74 can.style.height = h + "px";
75 can.getContext( "2d" ).setTransform( ratio, 0, 0, ratio, 0, 0 );
76 return can;
77 };
78
79 util.graph = function( drawZero, drawProfit ) {
80 this.stats = {
81 totalSamples: util.graphFrames,
82 profitLine: .01,
83 data: []
84 };
85 this.stats.data = new Array( this.stats.totalSamples );
86 this.stats.data = this.stats.data.join( ',' ).split( ',' ).map( function() { return null; });
87 this.drawZero = drawZero;
88 this.drawProfit = drawProfit;
89 };
90
91 util.graph.prototype.setSelector = function( selector ) {
92 this.destination = selector[0];
93
94 var width = selector.width();
95 var height = selector.height();
96
97 var canvas = $( '#myCanvas' );
98 var self = this;
99 if( canvas.length < 1 ) {
100 $( 'body' ).append( '<div style="position:absolute;display:none;"><canvas id="myCanvas"></canvas></div>' );
101 var canvas = $( '#myCanvas' );
102 canvas = util.createHiDPICanvas( width, height, 1, canvas[0] );
103 util.canvas = canvas;
104 util.canvasContext = canvas.getContext( '2d' );
105 }
106 this.canvas = canvas;
107 };
108
109 util.graph.prototype.updateStats = function( value, sellTrigger ) {
110 this.stats.data.push( value );
111 this.stats.profitLine = sellTrigger;
112 this.stats.data.shift(); // remove the oldest value
113 };
114
115 util.graph.prototype.drawStats = function() {
116 var ctx = util.canvasContext;
117 var size = this.destination.getBoundingClientRect();
118 var totalRun = this.stats.totalSamples;
119
120 if( util.extendGraphColumn && size.width < totalRun ) {
121 this.destination.style['width'] = totalRun+'px';
122 size.width = totalRun;
123 }
124
125 if( util.canvas == undefined || util.canvas.height == undefined ) {
126 return;
127 }
128
129 if( size.width != util.canvas.width || size.height != util.canvas.height ) {
130 util.canvas = util.createHiDPICanvas(size.width, size.height, 1, $( '#myCanvas' )[0] );
131 util.canvasContext = util.canvas.getContext( '2d' );
132 }
133 ctx.clearRect( 0, 0, size.width, size.height );
134 var first = true;
135 var range = { min: 1e8, max: -1e8, size: 0 };
136 this.stats.data.forEach( function( c ){
137 if( c !== null ) {
138 range.min = Math.min( c, range.min );
139 range.max = Math.max( c, range.max );
140 }
141 });
142
143 if( this.drawZero ) {
144 range.min = Math.min( range.min, 0 );
145 range.max = Math.max( range.max, 0 );
146 }
147
148 if( this.drawProfit ) {
149 range.max = Math.max( range.max, this.stats.profitLine );
150 range.min = Math.min( range.min, this.stats.profitLine );
151 }
152
153 range.size = range.max - range.min;
154
155 range.max += range.size * (util.topOffsetPercentage / 100);
156 range.min -= range.size * (util.bottomOffsetPercentage / 100);
157
158 range.size = range.max - range.min;
159
160 if( util.drawZeroLine && this.drawZero ) {
161 var percent = Math.abs(range.max - 0) / range.size;
162 ctx.strokeStyle = util.zeroLineColor;
163 ctx.fillStyle = util.zeroLineColor;
164 ctx.lineWidth = 1;
165 ctx.font = '12px calibri';
166 ctx.fillText( '0%', 0, (percent * size.height >> 0) + .5 );
167 ctx.beginPath();
168 ctx.moveTo( 20, (percent * size.height >> 0) + .5 );
169 ctx.lineTo( size.width, (percent * size.height >> 0) + .5 );
170 ctx.stroke();
171 }
172
173 if( util.drawSellThreshold && this.drawProfit ) {
174 var percent = Math.abs(range.max - this.stats.profitLine) / range.size;
175 ctx.strokeStyle = util.sellThresholdColor;
176 ctx.lineWidth = 1;
177 ctx.beginPath();
178 ctx.moveTo( 0, (percent * size.height >> 0) +.5 );
179 ctx.lineTo( size.width, (percent * size.height >> 0) +.5 );
180 ctx.stroke();
181 }
182
183 ctx.strokeStyle = util.graphLineColor;
184 ctx.lineWidth = 1;
185 ctx.beginPath();
186 var first = true;
187 var index = 0;
188 for( var i = 0; i < totalRun; i++ ) {
189 if( this.stats.data[i] != null && this.stats.data[i] != '' ) {
190 if( first ) {
191 first = false;
192 ctx.moveTo( (index/totalRun * size.width) , (size.height - (( this.stats.data[i] - range.min ) / range.size * size.height )));
193 } else {
194 ctx.lineTo( (index/totalRun * size.width) , (size.height - (( this.stats.data[i] - range.min ) / range.size * size.height )));
195 }
196 index++;
197 } /*else if( this.stats.data[i] == '' ) {
198 if( !first ) {
199 ctx.stroke();
200 first = true;
201 }
202 index++;
203 }*/
204 }
205 ctx.stroke();
206 var res = 'url(' + util.canvas.toDataURL() + ')';
207
208 this.destination.style['backgroundImage'] = res;
209 this.destination.style['backgroundRepeat'] = 'no-repeat';
210
211 };
212
213 var containers = {
214 dca: {
215 dataName: 'dcaLogData',
216 name: 'dtDcaLogs',
217 statName: 'profit',
218 childDestination: 'profit',
219 drawZero: true,
220 drawProfit: true,
221 hangCheck: true,
222 pairAppend: ''
223 },
224 pairs: {
225 dataName: 'gainLogData',
226 name: 'dtPairsLogs',
227 statName: 'profit',
228 childDestination: 'profit',
229 drawZero: true,
230 drawProfit: true,
231 hangCheck: true,
232 pairAppend: ''
233 },
234 pbl: {
235 dataName: 'bbBuyLogData',
236 name: 'dtPossibleBuysLog',
237 statName: 'currentValue',
238 childDestination: 'current-value',
239 drawZero: false,
240 drawProfit: false,
241 hangCheck: true,
242 pairAppend: '_PBL'
243 },
244 dust: {
245 dataName: 'dustLogData',
246 name: 'dtDustLogs',
247 statName: 'profit',
248 childDestination: 'profit',
249 drawZero: true,
250 drawProfit: false,
251 hangCheck: false,
252 pairAppend: '_DUST'
253 },
254 pending: {
255 dataName: 'pendingLogData',
256 name: 'dtPendingLogs',
257 statName: 'profit',
258 childDestination: 'profit',
259 drawZero: true,
260 drawProfit: true,
261 hangCheck: false,
262 pairAppend: '_PEND'
263 }
264 };
265
266 var pairData = {};
267
268 var freshPairCutoff = 60000;
269 function tick( data ) {
270 if( util.displayMarketCap ) {
271 displayMarketCap();
272 }
273 var now = Date.now();
274
275 var hangStats = {signaled: 0, max: 0};
276
277 var keys = Object.keys( pairData );
278 for( var i = 0; i < keys.length; i++ ) {
279 if( now - pairData[keys[i]].lastTick > freshPairCutoff ) {
280 delete pairData[keys[i]];
281 }
282 }
283
284 var dataTypes = Object.keys( containers );
285 for( var i = 0; i < dataTypes.length; i++ ) {
286 var source = data[containers[dataTypes[i]].dataName];
287 for( var j = 0; j < source.length; j++ ) {
288 var pair = source[j].market + containers[dataTypes[i]].pairAppend;
289 if( pairData[pair] == undefined ) {
290 pairData[pair] = {
291 lastTick: now,
292 graph: new util.graph( containers[dataTypes[i]].drawZero, containers[dataTypes[i]].drawProfit )
293 };
294 var cachedData = getCacheData( pair );
295 for( var z = 0; z < cachedData.length; z++ ) {
296 pairData[pair].graph.updateStats( cachedData[z], 0 );
297 }
298 } else {
299 pairData[pair].lastTick = now;
300 }
301 pairData[pair].graph.updateStats(
302 source[j][containers[dataTypes[i]].statName] / 100, //current profit
303 (source[j].triggerValue || 0) / 100 //sell threshold
304 );
305 setCacheData( pair, pairData[pair].graph.stats.data, pairData[pair].lastTick );
306 if( util.testHangWarning && containers[dataTypes[i]].hangCheck ) {
307 hangStats.max++;
308 var result = hangCheck( pairData[pair] );
309 if( result >= util.hangThreshold ) {
310 console.log( pair + ' is signaling a hang.');
311 hangStats.signaled++;
312 }
313 }
314 }
315 }
316
317 if( util.testHangWarning && hangStats.max > 0 && hangStats.signaled / hangStats.max >= util.percentHanging ) {
318 alert( util.hangWarningMessage.replace( '{n}', hangStats.signaled ));
319 }
320 }
321
322 function hangCheck( pair ) {
323 var start = pair.graph.stats.totalSamples - 1;
324 var runs = {};
325 var lastValue = null;
326 var run = 0;
327 for( var i = pair.graph.stats.totalSamples-1; i > -1; i-- ) {
328 var curValue = pair.graph.stats.data[i];
329 if( curValue != null && curValue != '' && lastValue == null ) {
330 lastValue = curValue;
331
332 run++;
333 } else if( curValue == lastValue ) {
334 run++;
335 } else if( lastValue != null ) {
336 return run;
337 }
338 }
339 return 0;
340 }
341
342 function render() {
343
344 var renderTypes = Object.keys( containers );
345 for( var i = 0; i < renderTypes.length; i++ ) {
346 var curContainer = containers[renderTypes[i]];
347 var curParent = $( '#' + curContainer.name );
348 if( curParent.width() != 100 ) {
349 var curParent = $( '#' + curContainer.name + ' tbody tr' );
350 for( var j = 0; j < curParent.length; j++ ) {
351 var curType = $( curParent[j] ).children( '.market' ).children( 'a' ).html();
352 var cur = pairData[curType+curContainer.pairAppend];
353 if( cur !== undefined ) {
354 //we can render it!
355 cur.graph.setSelector( $( curParent[j] ).children( '.' + curContainer.childDestination ));
356 cur.graph.drawStats();
357 }
358 }
359 return; // --- we rendered this one, dont render any others.
360 }
361 }
362 }
363
364 function setCacheData( key, values, lastTick ) {
365 var graphing = localStorage.getItem('graphing');
366 if( graphing == null ) {
367 graphing = {};
368 } else {
369 graphing = JSON.parse( graphing );
370 }
371
372 var store = [];
373 for( var i = 0; i < values.length; i++ ) {
374 if( values[i] == null || values[i] == '' ) {
375 // do nothing
376 } else {
377 store.push(parseFloat(values[i].toFixed(4)));
378 }
379 }
380
381 graphing[key] = {time: lastTick, values: store};
382
383 localStorage.setItem( 'graphing', JSON.stringify( graphing ));
384 }
385
386 function getCacheData( key ) {
387 var graphing = localStorage.getItem('graphing');
388 if( graphing == null ) {
389 graphing = {};
390 } else {
391 graphing = JSON.parse( graphing );
392 }
393
394 if( graphing[key] != undefined ) {
395 var elapsedTime = Date.now() - graphing[key].time;
396 var ticksElapsed = (elapsedTime / util.msPerDataFrame) >> 0;
397 var results = graphing[key].values;
398 for( var i = 0; i < ticksElapsed; i++ ) {
399 results.push(null);
400 }
401 return results;
402 }
403 return [];
404 }
405
406
407
408 function displayMarketCap() {
409 $.get( util.coinMarketCapAPI, function( data ) {
410 if( data && data.total_market_cap_usd ) {
411 var value = data.total_market_cap_usd.toLocaleString( 'en', { useGrouping: true });
412 var delta = 0;
413 var exists = $( '#nMCAPTotal' );
414 if( exists.length ) {
415 exists.attr( 'title', value ).html( value );
416 } else {
417 $('.monitor-summary').append('<li class="list-inline-item tdbitcoin font-16 ticker-text"><label id="nMCAP" data-toggle="tooltip" data-placement="bottom" title="Total Crypto MarketCap" data-original-title="Total Crypto MarketCap">MCAP</label>: <span id="nMCAPTotal" title="'+value+'">'+value+'</span></li>');
418 // --- coinmarketcap does not currently return the 24hr % change, so save this for when it does.
419 //$('.monitor-summary').append('<li class="list-inline-item tdbitcoin font-16 ticker-text"><label id="nMarket" data-toggle="tooltip" data-placement="bottom" title="Total Crypto MarketCap" data-original-title="Total Crypto MarketCap">MCAP</label>: <span id="nMarketPrice" title="'+value+'">'+value+'</span> <span id="nMarketPercChange" title="'+delta+' %" class="text-danger">('+delta+' %)</span></li>');
420 }
421 }
422 });
423 }
424
425 // listen to AJAX requests:
426
427 function addXMLRequestCallback( callback ) {
428 var oldSend, i;
429 if( XMLHttpRequest.callbacks ) {
430 // we've already overridden send() so just add the callback
431 XMLHttpRequest.callbacks.push( callback );
432 } else {
433 // create a callback queue
434 XMLHttpRequest.callbacks = [callback];
435 // store the native send()
436 oldSend = XMLHttpRequest.prototype.send;
437 // override the native send()
438 XMLHttpRequest.prototype.send = function() {
439
440 for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
441 XMLHttpRequest.callbacks[i]( this );
442 }
443 // call the native send()
444 oldSend.apply( this, arguments );
445 };
446 }
447 }
448
449 addXMLRequestCallback( function( xhr ) {
450 xhr.onreadystatechange = function() {
451 if( xhr.readyState == 4 && xhr.status == 200 ) {
452 if( xhr.responseURL.indexOf( 'data' ) > -1 ) {
453 var data = JSON.parse( xhr.response );
454 tick( data );
455 }
456 }
457 };
458 });
459
460 $( "body" ).on( 'DOMSubtreeModified', "#dvLastUpdatedOn", function() {
461 render();
462 });
463 $( ".dca-log,.dust-log,.pairs-log,.possible-buys-log,.pending-log" ).on( "click", function(){
464 setTimeout( function(){ render(); }, 100 );
465 });
466})();
467
468
469//Advanced-Exchange.js
470//Advanced-Exchange.js
471//Advanced-Exchange.js
472function AdvancedExchange() {
473 $("table td.market.all a").each(function() {
474 var value = $(this).attr("href");
475 var exchanges = ["BTC", "ETH", "BNB", "USDT"];
476 var newSymbol = "";
477 var exchange = "BINANCE";
478 var queryParams = new URLSearchParams($(this).prop("search"));
479
480 var symbolParam = queryParams.get("symbol");
481 if (symbolParam == null) { // Try to parse for Bittrex
482 exchange = "BITTREX";
483 var symbolParam = queryParams.get("MarketName");
484 symbolParam = symbolParam.split("-").reverse().join("");
485 }
486
487 $.each(exchanges, (function(i, exchange) {
488 var parts = symbolParam.split(exchange);
489
490 if(parts[1] === "") {
491 newSymbol = parts[0].replace("_", "") + "_" + exchange;
492 return false;
493 }
494 }));
495
496 $(this).siblings(".trading-view").remove();
497 $(this).unwrap("span");
498 $(this).wrap("<span class=\"market-wrapper\" style=\"white-space:nowrap;\"></span>");
499 $(this).parent().append("<span class=\"trading-view\" style=\"margin-left:5px;\"><a href=\"https://www.tradingview.com/chart/?symbol=" + exchange + ":" + symbolParam.replace("_", "") + "\" target=\"_blank\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"25\"viewBox=\"0 0 33 19\"><path fill=\"#3BB3E4\" d=\"M29.032 7.382a5.47 5.47 0 0 1 .963 2.872A4.502 4.502 0 0 1 28.5 19H6a5.98 5.98 0 0 1-4.222-1.737l9.546-7.556c.35.187.75.293 1.176.293a2.49 2.49 0 0 0 1.066-.238l4.55 3.981a2.5 2.5 0 1 0 4.711-.157l6.205-6.204zm-1.414-1.414l-6.204 6.204A2.494 2.494 0 0 0 20.5 12a2.49 2.49 0 0 0-1.066.238l-4.55-3.981a2.5 2.5 0 1 0-4.801-.118L.608 15.638A6 6 0 0 1 6.061 7a8.001 8.001 0 0 1 15.625-1.227A5.474 5.474 0 0 1 24.5 5c1.157 0 2.231.358 3.118.968z\"></path></svg></a></span>");
500
501 queryParams.set("symbol", newSymbol);
502
503 $(this).attr("href", value.replace("www.binance.com/trade.html","www.binance.com/tradeDetail.html"));
504 $(this).prop("search", "?" + queryParams.toString());
505 });
506}
507
508$("body").on('DOMSubtreeModified', "#dvLastUpdatedOn", function() {
509 AdvancedExchange();
510});
511$(".dca-log, .pairs-log, .dust-log, .sales-log, .pending-log, .possible-buys-log").on("click", function() {
512 setTimeout(function(){ AdvancedExchange(); }, 100 );
513});
514
515//Estimated-Percent-Gain.js
516//Estimated-Percent-Gain.js
517//Estimated-Percent-Gain.js
518function estimateYesterdayPercent() {
519 var previousTCV = $("#mTotalCurrentVal").text() - $("#mTodayProfit").text();
520 var prevPercentCalc = ($("#mYesterdayProfit").text()/previousTCV*100).toFixed(2);
521 var prevPercent = prevPercentCalc + '%';
522 if ($("#mYesterdayProfit").text() !== "")
523 {
524 if ($("#mYesterdayProfitPCTValue").text() === "") {
525 $("span.market-price-calculations.text-profityd").append('<br><label class="usd-value"><span class="full-text">Estimated Percent Gain </span><span class="short-text">Est. % Gain </span></label><span class="mb-0 main-text" id="mYesterdayProfitPCTValue" title="'+prevPercent+'">'+prevPercent+'</span>');
526 } else {
527 $("#mYesterdayProfitPCTValue").attr("title",prevPercent);
528 $("#mYesterdayProfitPCTValue").text(prevPercent);
529 }
530 }
531}
532
533function estimatePercent() {
534 var todayPercentCalc = ($("#mTodayProfit").text()/$("#mTotalCurrentVal").text()*100).toFixed(2);
535 var todayPercent = todayPercentCalc + '%';
536 $(".usd-value").css({'margin-bottom':'0px'});
537 if ($("#mTodayProfit").text() !== "")
538 {
539 if ($("#mTodayProfitPCTValue").text() === "") {
540 $("span.market-price-calculations.text-profittd").append('<br><label class="usd-value"><span class="full-text">Estimated Percent Gain </span><span class="short-text">Est. % Gain </span></label><span class="mb-0 main-text" id="mTodayProfitPCTValue" title="'+todayPercent+'">'+todayPercent+'</span>');
541 } else {
542 $("#mTodayProfitPCTValue").attr("title",todayPercent);
543 $("#mTodayProfitPCTValue").text(todayPercent);
544 }
545 }
546}
547
548estimateYesterdayPercent();
549$("body").on('DOMSubtreeModified', "#mYesterdayProfitUSDValue", function() {
550 estimateYesterdayPercent();
551});
552
553estimatePercent();
554$("body").on('DOMSubtreeModified', "#mTodayProfitUSDValue", function() {
555 estimatePercent();
556});
557
558
559
560//USD-Estimate.js
561//USD-Estimate.js
562//USD-Estimate.js
563function estimate() {
564 var btc1 = $('#nMarketPrice').attr("title");
565 $("#dtDcaLogs th.total-cost").text('Estimated Value');
566 $('.summary-table').removeClass('col-md-3').removeClass('col-md-4').addClass('col-md-4');
567 //DCA
568 if ($('#dtDcaLogs thead').length > 0) {
569 if ($('#dtDcaLogs thead .est-usd').length < 1) {
570 $('#dtDcaLogs thead tr').append('<th class="text-right est-usd all sorting" rowspan="1" colspan="1" style="width: 92px;">Estimated Value</th>');
571 };
572 $('#dtDcaLogs tbody tr').each(function() {
573 $(this).find('.est-usd').remove();
574 $(this).append('<td class="text-right est-usd all"></td>');
575 var num1 = $(this).find('.current-value').html().split("<br>")[1];
576 var num2 = $(this).find('.current-value').html().split("<br>")[0];
577 var calc = num2 - num1;
578 var btc = calc.toFixed(8);
579 var usd = btc * btc1;
580 var difference = usd.toFixed(2);
581 var sta = num2 * btc1;
582 var total = sta.toFixed(2);
583 if (difference > 0) {
584 $(this).find('.est-usd').html('<span style="color:#05b16f;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
585 } else {
586 $(this).find('.est-usd').html('<span style="color:#d85353;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
587 }
588 });
589 $("#dcLogDifference").find('b').remove();
590 $("#dcLogTotalCurrentVal").find('b').remove();
591 $("#dcLogRealCost").find('b').remove();
592 var val = $('#dcLogTotalCurrentVal').text();
593 var bou = $('#dcLogRealCost').text();
594 var calc = val - bou;
595 var btc = calc.toFixed(8);
596 var est = bou * btc1;
597 var bought = est.toFixed(2);
598 var usd = btc * btc1;
599 var difference = usd.toFixed(2);
600 var sta = val * btc1;
601 var total = sta.toFixed(2);
602 $("#dcLogDifference").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:5px">($' + difference + ')</b>');
603 $("#dcLogTotalCurrentVal").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + total + ')</b>');
604 $("#dcLogRealCost").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + bought + ')</b>');
605 }
606 //Pairs
607 if ($('#dtPairsLogs thead').length > 0) {
608 if ($('#dtPairsLogs thead .est-usd').length < 1) {
609 $('#dtPairsLogs thead tr').append('<th class="text-right est-usd all sorting" rowspan="1" colspan="1" style="width: 92px;">Estimated Value</th>');
610 }
611 $('#dtPairsLogs tbody tr').each(function() {
612 $(this).find('.est-usd').remove();
613 $(this).append('<td class=" text-right est-usd all"></td>');
614 var num1 = $(this).find('.bought-cost').text();
615 var num2 = $(this).find('.current-value').text();
616 var calc = num2 - num1;
617 var btc = calc.toFixed(8);
618 var usd = btc * btc1;
619 var difference = usd.toFixed(2);
620 var sta = num2 * btc1;
621 var total = sta.toFixed(2);
622 if (difference > 0) {
623 $(this).find('.est-usd').html('<span style="color:#05b16f;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
624 } else {
625 $(this).find('.est-usd').html('<span style="color:#d85353;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
626 }
627 });
628 $("#pairsLogDifference").find('b').remove();
629 $("#pairsLogTotalCurrentVal").find('b').remove();
630 $("#pairsLogRealCost").find('b').remove();
631 var val = $('#pairsLogTotalCurrentVal').text();
632 var bou = $('#pairsLogRealCost').text();
633 var calc = val - bou;
634 var btc = calc.toFixed(8);
635 var est = bou * btc1;
636 var bought = est.toFixed(2);
637 var usd = btc * btc1;
638 var difference = usd.toFixed(2);
639 var sta = val * btc1;
640 var total = sta.toFixed(2);
641 $("#pairsLogDifference").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:5px">($' + difference + ')</b>');
642 $("#pairsLogTotalCurrentVal").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + total + ')</b>');
643 $("#pairsLogRealCost").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + bought + ')</b>');
644 }
645 //Dust
646 if ($('#dtDustLogs thead').length > 0) {
647 if ($('#dtDustLogs thead .est-usd').length < 1) {
648 $('#dtDustLogs thead tr').append('<th class="text-right est-usd all sorting" rowspan="1" colspan="1" style="width: 92px;">Estimated Value</th>');
649 }
650 $('#dtDustLogs tbody tr').each(function() {
651 $(this).find('.est-usd').remove();
652 $(this).append('<td class=" text-right est-usd all"></td>');
653 var num1 = $(this).find('.bought-cost').text();
654 var num2 = $(this).find('.current-value').text();
655 var calc = num2 - num1;
656 var btc = calc.toFixed(8);
657 var usd = btc * btc1;
658 var difference = usd.toFixed(2);
659 var sta = num2 * btc1;
660 var total = sta.toFixed(2);
661 if (difference > 0) {
662 $(this).find('.est-usd').html('<span style="color:#05b16f;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
663 } else {
664 $(this).find('.est-usd').html('<span style="color:#d85353;"><i style="color:#98a6ad;font-style:normal;">$' + total + '</i><br>$' + difference + '</span>');
665 }
666 });
667 $("#dustLogDifference").find('b').remove();
668 $("#dustLogTotalCurrentVal").find('b').remove();
669 $("#dustLogRealCost").find('b').remove();
670 var val = $('#dustLogTotalCurrentVal').text();
671 var bou = $('#dustLogRealCost').text();
672 var calc = val - bou;
673 var btc = calc.toFixed(8);
674 var est = bou * btc1;
675 var bought = est.toFixed(2);
676 var usd = btc * btc1;
677 var difference = usd.toFixed(2);
678 var sta = val * btc1;
679 var total = sta.toFixed(2);
680 $("#dustLogDifference").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:5px">($' + difference + ')</b>');
681 $("#dustLogTotalCurrentVal").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + total + ')</b>');
682 $("#dustLogRealCost").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + bought + ')</b>');
683 }
684 //Sales
685 if ($('#dtSalesLog thead').length > 0) {
686 $("#salesLogDifference").find('b').remove();
687 $("#salesLogTotalCurrentVal").find('b').remove();
688 $("#salesLogBoughtCost").find('b').remove();
689 var val = $('#salesLogTotalCurrentVal').text();
690 var bou = $('#salesLogBoughtCost').text();
691 var calc = val - bou;
692 var btc = calc.toFixed(8);
693 var est = bou * btc1;
694 var bought = est.toFixed(2);
695 var usd = btc * btc1;
696 var difference = usd.toFixed(2);
697 var sta = val * btc1;
698 var total = sta.toFixed(2);
699 $("#salesLogDifference").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:5px">($' + difference + ')</b>');
700 $("#salesLogTotalCurrentVal").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + total + ')</b>');
701 $("#salesLogBoughtCost").prepend('<b style="color:#98a6ad;font-weight:400;margin-right:8px">($' + bought + ')</b>');
702 }
703 //Balance
704 $('.ticker-text').css('position','relative');
705 $('#nBalanceVal span').remove();
706 var btc = $('#nBalanceVal').attr("title");
707 var usd = btc * btc1;
708 var total = usd.toFixed(2);
709 $('#nBalanceVal').append('<span style="display:inline-block;position:absolute;bottom:-8px;right:0;font-size: 10px">($'+total+')</span>');
710 //Current
711 $('#nTotalCurrentVal span').remove();
712 var btc = $('#nTotalCurrentVal').attr("title");
713 var usd = btc * btc1;
714 var total = usd.toFixed(2);
715 $('#nTotalCurrentVal').append('<span style="display:inline-block;position:absolute;bottom:-8px;right:0;font-size: 10px">($'+total+')</span>');
716 //Pending
717 $('#nTotalPendingVal span').remove();
718 var btc = $('#nTotalPendingVal').attr("title");
719 var usd = btc * btc1;
720 var total = usd.toFixed(2);
721 $('#nTotalPendingVal').append('<span style="display:inline-block;position:absolute;bottom:-8px;right:0;font-size: 10px">($'+total+')</span>');
722}
723$("body").on('DOMSubtreeModified', "#dvLastUpdatedOn", function() {
724 estimate();
725});
726$(".dca-log, .pairs-log, .dust-log, .sales-log").on("click", function() {
727 setTimeout(function() {
728 estimate();
729 }, 100);
730});
731$( document ).ready(function() {
732 setTimeout(function() {
733 estimate();
734 }, 100);
735});
736
737
738//Convert-Time-AM-PM.js
739//Convert-Time-AM-PM.js
740//Convert-Time-AM-PM.js
741var ConvertLogDates = {
742 init: function () {
743 var _parent = this;
744 $("body").on('DOMSubtreeModified', "#dvLastUpdatedOn", function() {
745 if ($('#dtDcaLogs').text() !== "")
746 _parent.convertDCADates();
747
748 if ($('#dtPairsLogs').text() !== "")
749 _parent.convertPairsDates();
750
751 if ($('#dtSalesLog').text() !== "")
752 _parent.convertSalesLogDates();
753
754 if ($('#dtDustLogs').text() !== "")
755 _parent.convertDustLogDates();
756 });
757 $("body").on('DOMSubtreeModified', "#dvCurrentUTCTime", function() {
758 _parent.convertLocalTimeToAMPM();
759 });
760
761 $(document).on("click",".dca-log, .pairs-log, .dust-log, .sales-log, th.date.all, .page-link, .page-item, .sorting_asc, .sorting_desc", function() {
762 setTimeout(function(){
763 if ($('#dtSalesLog').text() !== "")
764 _parent.convertSalesLogDates();
765 if ($('#dtDcaLogs').text() !== "")
766 _parent.convertDCADates();
767 if ($('#dtPairsLogs').text() !== "")
768 _parent.convertPairsDates();
769 if ($('#dtDustLogs').text() !== "")
770 _parent.convertDustLogDates();
771 },100);
772 });
773 },
774 calcNewDate: function(t) {
775 var originalDate = $(t).find("td.date.all").text(),
776 militaryTime = originalDate.split('(')[0].split(' ')[1],
777 mDY = originalDate.split(' ')[0],
778 day = originalDate.split('(')[1].split(')')[0],
779 amPmTime = this.toDate(militaryTime,"h:m").toLocaleString('en-US',
780 { hour: 'numeric', minute: 'numeric', hour12: true }),
781 newDate = mDY + ' ' + amPmTime + ' (' + day +')';
782 return (originalDate.indexOf('M') != '-1')?originalDate:newDate;
783 },
784 convertLocalTimeToAMPM: function () {
785 var time = this.toDate($("#dvCurrentTime").text(),"h:m"),
786 currentServerLocalAMPMTime = time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
787 $("#dvCurrentTime").hide();
788 if ($("#dvCurrentUTCTime").text() !== "")
789 {
790 if ($("#dvCurrentAMPMTime").text() === "") {
791 $("#dvCurrentTime").after("<span id='dvCurrentAMPMTime'>"+ currentServerLocalAMPMTime +"</span>");
792 } else {
793 $("#dvCurrentAMPMTime").text(currentServerLocalAMPMTime);
794 }
795 }
796 },
797 convertPairsDates: function () {
798 var _parent = this;
799 $('#dtPairsLogs tbody tr').each(function() {
800 var newDate = _parent.calcNewDate(this);
801 $(this).find("td.date.all").text(newDate);
802 });
803 },
804 convertDCADates: function () {
805 var _parent = this;
806 $('#dtDcaLogs tbody tr').each(function() {
807 var newDate = _parent.calcNewDate(this);
808 $(this).find("td.date.all").text(newDate);
809 });
810 },
811 convertSalesLogDates: function () {
812 var _parent = this;
813 $('#dtSalesLog tbody tr').each(function() {
814 var newDate = _parent.calcNewDate(this);
815 $(this).find("td.date.all").text(newDate);
816 });
817 },
818 convertDustLogDates: function () {
819 var _parent = this;
820 $('#dtDustLogs tbody tr').each(function() {
821 var newDate = _parent.calcNewDate(this);
822 $(this).find("td.date.all").text(newDate);
823 });
824 },
825 toDate: function (dStr,format) {
826 var now = new Date();
827 if (format == "h:m") {
828 now.setHours(dStr.substr(0,dStr.indexOf(":")));
829 now.setMinutes(dStr.substr(dStr.indexOf(":")+1));
830 now.setSeconds(0);
831 return now;
832 }else
833 return "Invalid Format";
834 }
835};
836ConvertLogDates.init();
837
838
839
840//Net-Income.js
841//Net-Income.js
842//Net-Income.js
843(function() {
844 'use strict';
845 $( document ).ready(function() {
846
847 //Add a new tile for net income
848 var tile =' <div class="text-right">\
849 <h3 class=" m-t-10 text-profittd main-text">\
850 <b class="counter" id="mTodayNetProfit" title=""></b>\
851 <span class="market m-l-5">ETH</span>\
852 </h3>\
853 <p class="mb-0 text-profittd main-text">Net Profit Today</p>\
854 <span class="market-price-calculations text-profittd">\
855 <label class="usd-value">\
856 <span class="full-text">Estimated USD Value</span>\
857 <span class="short-text">Est. USD Value</span>\
858 </label>\
859 <span class="mb-0 main-text" id="mTodayNetProfitUSDValue" title=""></span>\
860 </span>\
861 </div>\
862 <div class="clearfix"></div>\
863 ';
864 $('#mTodayProfit').parent().parent().parent().append(tile);
865 //Get data
866 function refresh()
867 {
868 $.getJSON( "monitoring/data?_="+ (new Date().getTime()), function( data ) {
869 var ETH_USD =data.ETHUSDTPrice;
870 var profitToday = data.totalProfitToday;
871 var todayLoss = getTodayBags(data);
872 var todayNetProfit = parseFloat(profitToday) - todayLoss;
873 var todayNetUSD = parseFloat($('#mTodayProfitUSDValue').text())*(todayNetProfit/profitToday);
874 //console.log('Today profit in coin:'+ profitToday);
875 //console.log('Today loss in coin:'+ todayLoss);
876 //console.log('Today net profit in coin:'+ todayNetProfit.toFixed(8));
877 //console.log('Today net profit in usd:'+todayNetUSD.toFixed(2));
878 $('#mTodayNetProfit').text(todayNetProfit.toFixed(8));
879 $('#mTodayNetProfitUSDValue').text(todayNetUSD.toFixed(2));
880});
881 }
882 setInterval( refresh,5000);
883 });
884
885 function isToday(date)
886 {
887 var tdate = new Date(date.date.year,date.date.month-1,date.date.day, date.time.hour, date.time.minute, date.time.second,0);
888
889 var now = new Date();
890 tdate = new Date(tdate.getTime()-now.getTimezoneOffset()*60*1000);
891 //console.log(now.getFullYear()+'/'+now.getMonth()+'/'+now.getDate());
892 return now.getFullYear()==tdate.getFullYear()&&now.getMonth()==tdate.getMonth()&&now.getDate()==tdate.getDate();
893 }
894function getTodayBags(data){
895 var sum = 0.0;
896 //Add Pairs Log
897 for(i=0; i<data.gainLogData.length; i++)
898 {
899 var coin = data.gainLogData[i];
900 if(isToday(coin.averageCalculator.firstBoughtDate))
901 {
902 sum = sum + (coin.averageCalculator.totalCost - coin.currentPrice * coin.averageCalculator.totalAmount);
903 // console.log(coin.averageCalculator.firstBoughtDate.date.year+'/'+coin.averageCalculator.firstBoughtDate.date.month+'/'+coin.averageCalculator.firstBoughtDate.date.day);
904 //console.log(coin.market+" today loss is "+ (coin.currentPrice * coin.averageCalculator.totalAmount - coin.averageCalculator.totalCost));
905 }
906 }
907
908 //Add DCA Log
909 for(i=0; i<data.dcaLogData.length; i++)
910 {
911 var coin = data.dcaLogData[i];
912 if(isToday(coin.averageCalculator.firstBoughtDate))
913 {
914 sum = sum + (coin.averageCalculator.totalCost - coin.currentPrice * coin.averageCalculator.totalAmount);
915 //console.log(coin.market+" today loss is "+ (coin.currentPrice * coin.averageCalculator.totalAmount - coin.averageCalculator.totalCost));
916 }
917 }
918 //console.log('Total loss:'+sum);
919 return sum;
920}
921})();