/**
* Stocks Component<BR>
* <BR><BR><img src=/tk/lib/components/w/img/stocks.png width=30% style="border:1px lime dashed;padding:20px">
* <BR><BR><a href="/tk/lib/components/w/html/stocks.html">DEMO</a>
*/
class Stocks extends HTMLElement {
constructor() {
wc.group("Stocks.constructor")
super();
wc.groupEnd();
};
/**
* Set observable values here. When Changed, attributeChangedCallback is invoked
* @observedAttributes
*/
static get observedAttributes() {
wc.group("Stocks.observedAttributes");
this.observables = [];
wc.groupEnd();
return this.observables;
};
/**
* Called when this is attached to DOM
* @connectedCallback.
*/
connectedCallback() {
wc.group("Stocks.connectedCallback")
let self = this;
// ADD A RANDOM ID IF NONE EXIST
if (!this.id) {
this.id = this.constructor.name.toLowerCase() + "-" + wc.uid();
}
// GET PROPERTIES AND INTERESTING ELEMENTS
this._initialize();
// ADD COMPONENT MARKTOP
this.innerHTML = this._template()
wc.wait4(".wc-stocks-symbols", () => {
$(".wc-stocks-symbols").focus();
wc.enterKey(".wc-stocks-symbols", () => {
let symbols = $(".wc-stocks-symbols").val().toUpperCase();
$(".wc-stocks-panel-0, .wc-stocks-panel-1").slideToggle(300)
this._process(symbols);
});
});
// ADD STATS AND OTHER FINAL STUFF
this._finalize();
ga('send', {'hitType': 'event','eventCategory': 'wc-connected','eventAction': 'connected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
wc.groupEnd();
};
/**
* Initial Markup
* @private
* @_template
*/
_template() {
wc.group("Stocks.template");
var temp = "<wc-include href=/tk/lib/components/misc/webpack/src/w/html/parts/stocks/main.html></wc-include>";
wc.groupEnd();
return temp;
};
/**
* Called with .setAttribute(...) function call
* @attributeChangedCallback
*/
attributeChangedCallback(attr, oldval, newval) {
wc.group("Stocks.attributeChangedCallback:", attr, oldval, newval);
this.properties = this.properties || [];
let obs = Stocks.observedAttributes;
for (let i = 0; i < obs.length; i++) {
if (newval) {
this.properties[obs[i]] = newval;
}
}
// YOUR CODE FOR CHANGES GO HERE (MAYBE NULL FIRST TIME THROUGH)
try {
switch(attr)
{
case "header":
//this.querySelector("h1").innerHTML = newval;
break;
default:
break;
}
} catch(e) {
wc.warn(e.name + ' > ' + e.message);
}
wc.groupEnd();
};
/**
* Stores DOM elements of interest for future use
* @private
* @_fetchElements
*/
_fetchElements() {
wc.group("Stocks._fetchElements");
this.dom = this.dom || [];
this.dom.content = this.innerHTML;
wc.groupEnd();
};
/**
* Component attributes are _fetched and defaults are set if undefined
* @private
* @_fetchAttributes
*/
_fetchAttributes() {
wc.group("Stocks._fetchAttributes");
this.properties = {
uparam : "",
cname : "Stocks",
author : "Mel M. Heravi, Ph.D.",
version : "1.0"
};
// SAVE WIDGET SPECIFIC PROPERTIES
this.propertiesW = [];
// SAVE ALL OTHER PROPERTIES
let attrs = wc.getAttributes(this)
for (var key in attrs) {
let attr = this.getAttribute(key) || this.properties.key;
this.properties[key] = this.getAttribute(key);
this.propertiesW[key] = this.getAttribute(key);
wc.log(key + ": " + attrs[key]);
}
// SET ALL INITIAL ATTRIBUTES
for (var key in this.properties) {
switch(key)
{
case "header":
break;
default:
break;
}
}
wc.log("ATTRIBUTES: ", this.properties);
wc.groupEnd();
};
/**
* Initialize component
* @private
* @_initialize
*/
_initialize() {
wc.group("Stocks._initialize:", this.id);
// FETCH ALL INTERESTING ELEMENTS
this._fetchElements();
// FETCH ALL ATTRIBUTES
this._fetchAttributes();
wc.groupEnd();
};
/**
* Save data for analytics and final wrap up
* @private
* @_finalize
*/
_finalize() {
wc.group("Stocks._finalize:", this.id);
this.classList.add("wc");
// ADD ANALYTICS HERE
wc.setStats(this, this.properties.cname, this.properties.version);
// SHOW IT NOW (NO FLICKERS)
this.style.visibility = "visible";
wc.groupEnd();
};
/**
* Invoked When component is removed. Usually with a .remove() function call
* @disconnectedCallback
*/
disconnectedCallback() {
wc.group("Stocks.disconnectedCallback")
ga('send', {'hitType': 'event','eventCategory': 'wc-disconnected','eventAction': 'disconnected','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
wc.groupEnd();
};
/**
* Destroy the instance object and artifacts
* @destroy
*/
destroy() {
wc.group("Stocks.destroy");
// FREE ALL MEMORY
// you should delete all created objects here
// FREE POINTER
delete this;
// REMOVE ITEM FROM DOM
this.parentNode.removeChild(this);
ga('send', {'hitType': 'event','eventCategory': 'wc-destroyed','eventAction': 'distroy','eventLabel': this.properties.cname, 'eventValue':JSON.stringify({'env':wcENV,'app':wcAPP,'url':wcURL})});
wc.groupEnd();
};
/**
* @_publish
*/
_publish(type) {
wc.group("Stocks._publish:", type);
wc.publish("wc-stocks", {
time: new Date().getTime(),
action: type,
id: this.id
});
wc.groupEnd();
return true;
};
/**
* @_request
*/
_request(e) {
wc.group("Stocks._request:", this.id, JSON.stringify(e.detail));
switch(e.detail.request)
{
case "label":
let h1 = this.querySelector("h1");
h1.innerHTML = e.detail.str;
this._publish("labelChanged");
break;
default:
alert("DO NOT HAVE SUCH REQUEST: " + e.detail.request);
break;
}
wc.groupEnd();
return true;
};
/**
* @_process
*/
_process(symbols) {
wc.group("Stocks._process:", symbols);
let self = this;
let syms = symbols.split(",").sort();
$(".wc-stocks-panel-1 table tbody").empty();
for (var i = 0; i < syms.length; i++) {
$(".wc-stocks-panel-1 table tbody").append(`
<tr id="${syms[i]}">
<td class="animated c-symbol" data-key="${syms[i]}symbol" id="${syms[i]}symbol">${syms[i]}</td>
<td class="animated c-price" data-key="${syms[i]}price" id="${syms[i]}price"></td>
<td class="animated c-change"data-key="${syms[i]}change" id="${syms[i]}change"></td>
<td class="animated c-bid" data-key="${syms[i]}bid" id="${syms[i]}bid"></td>
<td class="animated c-ask" data-key="${syms[i]}ask" id="${syms[i]}ask"></td>
<td class="animated c-volume" data-key="${syms[i]}volume" id="${syms[i]}volume"></td>
<td class="animated c-updated" data-key="${syms[i]}updated" id="${syms[i]}updated"></td>
<td class="animated c-high" data-key="${syms[i]}high" id="${syms[i]}high"></td>
<td class="animated c-low" data-key="${syms[i]}low" id="${syms[i]}low"></td>
<td class="animated c-open" data-key="${syms[i]}open" id="${syms[i]}open"></td>
<td class="animated c-close" data-key="${syms[i]}close" id="${syms[i]}close"></td>
</tr>`);
}
tkBindAll(function(e) {
if (e.data.oldValue != e.data.newValue) {
// CHECK PRICE CHANGE
if ($("#" + e.data.key).hasClass("c-price")) {
self._change(e);
}
// FLASH ON CHANGE
self._flash("#" + e.data.key);
}
})
this._update(symbols);
wc.groupEnd();
return true;
};
/**
* @_update
*/
_update(symbols) {
wc.group("Stocks._update:", symbols);
let self = this;
let key = "2b6d2ea54bdc7846b2725d26ecc9307a";
let syms = symbols.toUpperCase();
if (this.properties.testing == "true") {
var url = `/tk/lib/components/misc/webpack/src/w/html/parts/stocks/symbols.json`
function task(data,i) {
setTimeout(() => {
self._show(data);
}, 1000*i);
}
} else {
var url = `https://api.tdameritrade.com/v1/marketdata/quotes?apikey=N6RSFI69A6DPXUVJM22BB8T7HFUMXOIW&symbol=${symbols}`
}
$.getJSON(url, function(data) {
let s = symbols.split(",");
for (var i = 0; i < s.length; i++) {
let p = s[i];
self._show(data[p]);
}
}).fail(function(jqXHR, textStatus, errorThrown) {
wc.error("incoming Text " + jqXHR.responseText);
});
if (this.properties.testing == "false") {
setTimeout(() => {
this._update(symbols)
}, 3000);
}
wc.groupEnd();
return true;
};
/**
* @_show
*/
_show(data) {
wc.group("Stocks._show:", JSON.stringify(data));
let vol = wc.commify(parseInt(data.totalVolume))
let tim = moment(data.quoteTimeInLong).format("YYYY-MM-DD HH:mm:ss");
let prin = data.lastPrice;
let prio = tkModel[`${data.symbol}price`];
if (prin > prio) {
var cls = "wc-stocks-color-up";
} else {
var cls = "wc-stocks-color-dn";
}
$(`.wc-stocks-panel-1 table tbody tr#${data.symbol} td.c-price`)
.removeClass("wc-stocks-color-up")
.removeClass("wc-stocks-color-dn")
.removeClass("wc-stocks-color-no")
.addClass(cls);
tkModel[`${data.symbol}price`] = `${parseFloat(data.lastPrice).toFixed(2)}`;
tkModel[`${data.symbol}change`] = `${parseFloat(data.netChange).toFixed(2)}`;
tkModel[`${data.symbol}bid`] = `${parseFloat(data.bidPrice).toFixed(2)}`;
tkModel[`${data.symbol}ask`] = `${parseFloat(data.askPrice).toFixed(2)}`;
tkModel[`${data.symbol}volume`] = `${vol}`;
tkModel[`${data.symbol}updated`] = `${tim}`;
tkModel[`${data.symbol}high`] = `${parseFloat(data.highPrice).toFixed(2)}`;
tkModel[`${data.symbol}low`] = `${parseFloat(data.lowPrice).toFixed(2)}`;
tkModel[`${data.symbol}open`] = `${parseFloat(data.openPrice).toFixed(2)}`;
tkModel[`${data.symbol}close`] = `${parseFloat(data.closePrice).toFixed(2)}`;
//$("table th, table td").addClass("shadow");
wc.groupEnd();
}
/**
* @_flash
*/
_flash(ele) {
//wc.group("Stocks._flash:", ele);
$(ele).removeClass("flash");
setTimeout(() => {
$(ele).addClass("flash");
}, 0);
//wc.groupEnd();
}
/**
* @_change
*/
_change(e) {
wc.group("Stocks._change:", e);
let tds = $("#" + e.data.key).closest("tr").find("td");
if (typeof e.data.oldValue === "undefined") {
// FIRST TIME THROUGH - GRAY COLOR
$(tds).css("color", this.noColor)
} else {
// SET UP/DOWN COLORS
if (e.data.newValue > e.data.oldValue) {
$(tds).css("color", this.dnColor)
} else {
$(tds).css("color", this.upColor)
}
}
wc.groupEnd();
}
}
window.customElements.define('wc-stocks', Stocks);