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