blinktrade
Version:
BlinkTrade client for node.js
1,883 lines • 116 kB
JavaScript
!function(global, factory) {
"object" == typeof exports && "undefined" != typeof module ? factory(exports) : "function" == typeof define && define.amd ? define([ "exports" ], factory) : factory(global.blinktrade = {});
}(this, function(exports) {
"use strict";
var BROKERS = {
VBTC: 3,
TESTNET: 5,
URDUBIT: 8,
CHILEBIT: 9,
BITCAMBIO: 11
};
function _typeof(obj) {
return (_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
})(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0,
"value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
return protoProps && _defineProperties(Constructor.prototype, protoProps), staticProps && _defineProperties(Constructor, staticProps),
Constructor;
}
function _defineProperty(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {}, ownKeys = Object.keys(source);
"function" == typeof Object.getOwnPropertySymbols && (ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}))), ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw new TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: !0,
configurable: !0
}
}), superClass && _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {
return o.__proto__ || Object.getPrototypeOf(o);
})(o);
}
function _setPrototypeOf(o, p) {
return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) {
return o.__proto__ = p, o;
})(o, p);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (null == source) return {};
var key, i, target = {}, sourceKeys = Object.keys(source);
for (i = 0; i < sourceKeys.length; i++) excluded.indexOf(key = sourceKeys[i]) < 0 && (target[key] = source[key]);
return target;
}
function _objectWithoutProperties(source, excluded) {
if (null == source) return {};
var key, i, target = _objectWithoutPropertiesLoose(source, excluded);
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) excluded.indexOf(key = sourceSymbolKeys[i]) < 0 && Object.prototype.propertyIsEnumerable.call(source, key) && (target[key] = source[key]);
}
return target;
}
function _assertThisInitialized(self) {
if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _possibleConstructorReturn(self, call) {
return !call || "object" != typeof call && "function" != typeof call ? _assertThisInitialized(self) : call;
}
function _superPropBase(object, property) {
for (;!Object.prototype.hasOwnProperty.call(object, property) && null !== (object = _getPrototypeOf(object)); ) ;
return object;
}
function _get(target, property, receiver) {
return (_get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get : function(target, property, receiver) {
var base = _superPropBase(target, property);
if (base) {
var desc = Object.getOwnPropertyDescriptor(base, property);
return desc.get ? desc.get.call(receiver) : desc.value;
}
})(target, property, receiver || target);
}
var os = {}, isPromise_1 = isPromise, nextTick;
function isPromise(obj) {
return obj && "function" == typeof obj.then;
}
nextTick = "function" == typeof setImediate ? setImediate : "object" === ("undefined" == typeof process ? "undefined" : _typeof(process)) && process && process.nextTick ? process.nextTick : function(cb) {
setTimeout(cb, 0);
};
var extensions = [], promise = Promise$1, nextTick$1;
function Promise$1(fn) {
if (!(this instanceof Promise$1)) return "function" == typeof fn ? new Promise$1(fn) : defer();
var value, isResolved = !1, isFulfilled = !1, waiting = [], running = !1;
function next(skipTimeout) {
waiting.length ? (running = !0, waiting.shift()(skipTimeout || !1)) : running = !1;
}
this.then = function(cb, eb) {
return new Promise$1(function(resolver) {
waiting.push(function(skipTimeout) {
var callback = isFulfilled ? cb : eb;
if ("function" == typeof callback) {
var timeoutDone = function() {
var val;
try {
val = callback(value);
} catch (ex) {
return resolver.reject(ex), next();
}
resolver.fulfill(val), next(!0);
};
skipTimeout ? timeoutDone() : nextTick(timeoutDone);
} else isFulfilled ? resolver.fulfill(value) : resolver.reject(value), next(skipTimeout);
}), isResolved && !running && next();
});
}, function() {
function reject(err) {
isResolved || (isFulfilled = !(isResolved = !0), value = err, next());
}
for (var resolver = {
fulfill: function fulfill(val) {
isResolved || (isPromise_1(val) ? val.then(fulfill, reject) : (isResolved = isFulfilled = !0,
value = val, next()));
},
reject: reject
}, i = 0; i < extensions.length; i++) extensions[i](this, resolver);
if ("function" == typeof fn) try {
fn(resolver);
} catch (ex) {
resolver.reject(ex);
}
}();
}
function defer() {
var resolver, promise = new Promise$1(function(res) {
resolver = res;
});
return {
resolver: resolver,
promise: promise
};
}
Promise$1.use = function(extension) {
extensions.push(extension);
}, nextTick$1 = "function" == typeof setImmediate ? setImmediate : "object" === ("undefined" == typeof process ? "undefined" : _typeof(process)) && process && process.nextTick ? process.nextTick : function(cb) {
setTimeout(cb, 0);
};
var nodeify_1 = nodeify;
function nodeify(promise$$1, cb) {
return "function" != typeof cb ? promise$$1 : promise$$1.then(function(res) {
nextTick$1(function() {
cb(null, res);
});
}, function(err) {
nextTick$1(function() {
cb(err);
});
});
}
function nodeifyThis(cb) {
return nodeify(this, cb);
}
function extend(prom) {
if (prom && isPromise_1(prom)) {
prom.nodeify = nodeifyThis;
var then = prom.then;
return prom.then = function() {
return extend(then.apply(this, arguments));
}, prom;
}
"function" == typeof prom ? prom.prototype.nodeify = nodeifyThis : promise.prototype.nodeify = nodeifyThis;
}
function NodeifyPromise(fn) {
if (!(this instanceof NodeifyPromise)) return new NodeifyPromise(fn);
promise.call(this, fn), extend(this);
}
nodeify.extend = extend, nodeify.Promise = NodeifyPromise, NodeifyPromise.prototype = Object.create(promise.prototype),
NodeifyPromise.prototype.constructor = NodeifyPromise;
var commonjsGlobal = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {};
function createCommonjsModule(fn, module) {
return fn(module = {
exports: {}
}, module.exports), module.exports;
}
var eventemitter2 = createCommonjsModule(function(module, exports) {
!function(undefined) {
var isArray = Array.isArray ? Array.isArray : function(obj) {
return "[object Array]" === Object.prototype.toString.call(obj);
}, defaultMaxListeners = 10;
function init() {
this._events = {}, this._conf && configure.call(this, this._conf);
}
function configure(conf) {
conf ? ((this._conf = conf).delimiter && (this.delimiter = conf.delimiter), this._maxListeners = conf.maxListeners !== undefined ? conf.maxListeners : defaultMaxListeners,
conf.wildcard && (this.wildcard = conf.wildcard), conf.newListener && (this._newListener = conf.newListener),
conf.removeListener && (this._removeListener = conf.removeListener), conf.verboseMemoryLeak && (this.verboseMemoryLeak = conf.verboseMemoryLeak),
this.wildcard && (this.listenerTree = {})) : this._maxListeners = defaultMaxListeners;
}
function logPossibleMemoryLeak(count, eventName) {
var errorMsg = "(node) warning: possible EventEmitter memory leak detected. " + count + " listeners added. Use emitter.setMaxListeners() to increase limit.";
if (this.verboseMemoryLeak && (errorMsg += " Event name: " + eventName + "."), "undefined" != typeof process && process.emitWarning) {
var e = Error(errorMsg);
e.name = "MaxListenersExceededWarning", e.emitter = this, e.count = count, process.emitWarning(e);
} else console.error(errorMsg), console.trace && console.trace();
}
function EventEmitter(conf) {
this._events = {}, this._newListener = !1, this._removeListener = !1, this.verboseMemoryLeak = !1,
configure.call(this, conf);
}
function searchListenerTree(handlers, type, tree, i) {
if (!tree) return [];
var leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, listeners = [], typeLength = type.length, currentType = type[i], nextType = type[i + 1];
if (i === typeLength && tree._listeners) {
if ("function" == typeof tree._listeners) return handlers && handlers.push(tree._listeners),
[ tree ];
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) handlers && handlers.push(tree._listeners[leaf]);
return [ tree ];
}
if ("*" === currentType || "**" === currentType || tree[currentType]) {
if ("*" === currentType) {
for (branch in tree) "_listeners" !== branch && tree.hasOwnProperty(branch) && (listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i + 1)));
return listeners;
}
if ("**" === currentType) {
for (branch in (endReached = i + 1 === typeLength || i + 2 === typeLength && "*" === nextType) && tree._listeners && (listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength))),
tree) "_listeners" !== branch && tree.hasOwnProperty(branch) && (listeners = "*" === branch || "**" === branch ? (tree[branch]._listeners && !endReached && (listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength))),
listeners.concat(searchListenerTree(handlers, type, tree[branch], i))) : listeners.concat(searchListenerTree(handlers, type, tree[branch], branch === nextType ? i + 2 : i)));
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i + 1));
}
if ((xTree = tree["*"]) && searchListenerTree(handlers, type, xTree, i + 1), xxTree = tree["**"]) if (i < typeLength) for (branch in xxTree._listeners && searchListenerTree(handlers, type, xxTree, typeLength),
xxTree) "_listeners" !== branch && xxTree.hasOwnProperty(branch) && (branch === nextType ? searchListenerTree(handlers, type, xxTree[branch], i + 2) : branch === currentType ? searchListenerTree(handlers, type, xxTree[branch], i + 1) : ((isolatedBranch = {})[branch] = xxTree[branch],
searchListenerTree(handlers, type, {
"**": isolatedBranch
}, i + 1))); else xxTree._listeners ? searchListenerTree(handlers, type, xxTree, typeLength) : xxTree["*"] && xxTree["*"]._listeners && searchListenerTree(handlers, type, xxTree["*"], typeLength);
return listeners;
}
(EventEmitter.EventEmitter2 = EventEmitter).prototype.delimiter = ".", EventEmitter.prototype.setMaxListeners = function(n) {
n !== undefined && (this._maxListeners = n, this._conf || (this._conf = {}), this._conf.maxListeners = n);
}, EventEmitter.prototype.event = "", EventEmitter.prototype.once = function(event, fn) {
return this._once(event, fn, !1);
}, EventEmitter.prototype.prependOnceListener = function(event, fn) {
return this._once(event, fn, !0);
}, EventEmitter.prototype._once = function(event, fn, prepend) {
return this._many(event, 1, fn, prepend), this;
}, EventEmitter.prototype.many = function(event, ttl, fn) {
return this._many(event, ttl, fn, !1);
}, EventEmitter.prototype.prependMany = function(event, ttl, fn) {
return this._many(event, ttl, fn, !0);
}, EventEmitter.prototype._many = function(event, ttl, fn, prepend) {
var self = this;
if ("function" != typeof fn) throw Error("many only accepts instances of Function");
function listener() {
return 0 == --ttl && self.off(event, listener), fn.apply(this, arguments);
}
return listener._origin = fn, this._on(event, listener, prepend), self;
}, EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if ("newListener" === type && !this._newListener && !this._events.newListener) return !1;
var args, l, i, j, handler, al = arguments.length;
if (this._all && this._all.length) {
if (handler = this._all.slice(), 3 < al) for (args = Array(al), j = 0; j < al; j++) args[j] = arguments[j];
for (i = 0, l = handler.length; i < l; i++) switch (this.event = type, al) {
case 1:
handler[i].call(this, type);
break;
case 2:
handler[i].call(this, type, arguments[1]);
break;
case 3:
handler[i].call(this, type, arguments[1], arguments[2]);
break;
default:
handler[i].apply(this, args);
}
}
if (this.wildcard) {
searchListenerTree(handler = [], "string" == typeof type ? type.split(this.delimiter) : type.slice(), this.listenerTree, 0);
} else {
if ("function" == typeof (handler = this._events[type])) {
switch (this.event = type, al) {
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
default:
for (args = Array(al - 1), j = 1; j < al; j++) args[j - 1] = arguments[j];
handler.apply(this, args);
}
return !0;
}
handler && (handler = handler.slice());
}
if (handler && handler.length) {
if (3 < al) for (args = Array(al - 1), j = 1; j < al; j++) args[j - 1] = arguments[j];
for (i = 0, l = handler.length; i < l; i++) switch (this.event = type, al) {
case 1:
handler[i].call(this);
break;
case 2:
handler[i].call(this, arguments[1]);
break;
case 3:
handler[i].call(this, arguments[1], arguments[2]);
break;
default:
handler[i].apply(this, args);
}
return !0;
}
if (!this._all && "error" === type) throw arguments[1] instanceof Error ? arguments[1] : Error("Uncaught, unspecified 'error' event.");
return !!this._all;
}, EventEmitter.prototype.emitAsync = function() {
this._events || init.call(this);
var type = arguments[0];
if ("newListener" === type && !this._newListener && !this._events.newListener) return Promise.resolve([ !1 ]);
var args, l, i, j, handler, promises = [], al = arguments.length;
if (this._all) {
if (3 < al) for (args = Array(al), j = 1; j < al; j++) args[j] = arguments[j];
for (i = 0, l = this._all.length; i < l; i++) switch (this.event = type, al) {
case 1:
promises.push(this._all[i].call(this, type));
break;
case 2:
promises.push(this._all[i].call(this, type, arguments[1]));
break;
case 3:
promises.push(this._all[i].call(this, type, arguments[1], arguments[2]));
break;
default:
promises.push(this._all[i].apply(this, args));
}
}
this.wildcard ? searchListenerTree(handler = [], "string" == typeof type ? type.split(this.delimiter) : type.slice(), this.listenerTree, 0) : handler = this._events[type];
if ("function" == typeof handler) switch (this.event = type, al) {
case 1:
promises.push(handler.call(this));
break;
case 2:
promises.push(handler.call(this, arguments[1]));
break;
case 3:
promises.push(handler.call(this, arguments[1], arguments[2]));
break;
default:
for (args = Array(al - 1), j = 1; j < al; j++) args[j - 1] = arguments[j];
promises.push(handler.apply(this, args));
} else if (handler && handler.length) {
if (handler = handler.slice(), 3 < al) for (args = Array(al - 1), j = 1; j < al; j++) args[j - 1] = arguments[j];
for (i = 0, l = handler.length; i < l; i++) switch (this.event = type, al) {
case 1:
promises.push(handler[i].call(this));
break;
case 2:
promises.push(handler[i].call(this, arguments[1]));
break;
case 3:
promises.push(handler[i].call(this, arguments[1], arguments[2]));
break;
default:
promises.push(handler[i].apply(this, args));
}
} else if (!this._all && "error" === type) return arguments[1] instanceof Error ? Promise.reject(arguments[1]) : Promise.reject("Uncaught, unspecified 'error' event.");
return Promise.all(promises);
}, EventEmitter.prototype.on = function(type, listener) {
return this._on(type, listener, !1);
}, EventEmitter.prototype.prependListener = function(type, listener) {
return this._on(type, listener, !0);
}, EventEmitter.prototype.onAny = function(fn) {
return this._onAny(fn, !1);
}, EventEmitter.prototype.prependAny = function(fn) {
return this._onAny(fn, !0);
}, EventEmitter.prototype.addListener = EventEmitter.prototype.on, EventEmitter.prototype._onAny = function(fn, prepend) {
if ("function" != typeof fn) throw Error("onAny only accepts instances of Function");
return this._all || (this._all = []), prepend ? this._all.unshift(fn) : this._all.push(fn),
this;
}, EventEmitter.prototype._on = function(type, listener, prepend) {
if ("function" == typeof type) return this._onAny(type, listener), this;
if ("function" != typeof listener) throw Error("on only accepts instances of Function");
return this._events || init.call(this), this._newListener && this.emit("newListener", type, listener),
this.wildcard ? function(type, listener) {
for (var i = 0, len = (type = "string" == typeof type ? type.split(this.delimiter) : type.slice()).length; i + 1 < len; i++) if ("**" === type[i] && "**" === type[i + 1]) return;
for (var tree = this.listenerTree, name = type.shift(); name !== undefined; ) {
if (tree[name] || (tree[name] = {}), tree = tree[name], 0 === type.length) return tree._listeners ? ("function" == typeof tree._listeners && (tree._listeners = [ tree._listeners ]),
tree._listeners.push(listener), !tree._listeners.warned && 0 < this._maxListeners && this._maxListeners < tree._listeners.length && (tree._listeners.warned = !0,
logPossibleMemoryLeak.call(this, tree._listeners.length, name))) : tree._listeners = listener,
!0;
name = type.shift();
}
return !0;
}.call(this, type, listener) : this._events[type] ? ("function" == typeof this._events[type] && (this._events[type] = [ this._events[type] ]),
prepend ? this._events[type].unshift(listener) : this._events[type].push(listener),
!this._events[type].warned && 0 < this._maxListeners && this._maxListeners < this._events[type].length && (this._events[type].warned = !0,
logPossibleMemoryLeak.call(this, this._events[type].length, type))) : this._events[type] = listener,
this;
}, EventEmitter.prototype.off = function(type, listener) {
if ("function" != typeof listener) throw Error("removeListener only takes instances of Function");
var handlers, leafs = [];
if (this.wildcard) {
leafs = searchListenerTree(null, "string" == typeof type ? type.split(this.delimiter) : type.slice(), this.listenerTree, 0);
} else {
if (!this._events[type]) return this;
leafs.push({
_listeners: handlers = this._events[type]
});
}
for (var iLeaf = 0; iLeaf < leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
if (isArray(handlers = leaf._listeners)) {
for (var position = -1, i = 0, length = handlers.length; i < length; i++) if (handlers[i] === listener || handlers[i].listener && handlers[i].listener === listener || handlers[i]._origin && handlers[i]._origin === listener) {
position = i;
break;
}
if (position < 0) continue;
return this.wildcard ? leaf._listeners.splice(position, 1) : this._events[type].splice(position, 1),
0 === handlers.length && (this.wildcard ? delete leaf._listeners : delete this._events[type]),
this._removeListener && this.emit("removeListener", type, listener), this;
}
(handlers === listener || handlers.listener && handlers.listener === listener || handlers._origin && handlers._origin === listener) && (this.wildcard ? delete leaf._listeners : delete this._events[type],
this._removeListener && this.emit("removeListener", type, listener));
}
return function recursivelyGarbageCollect(root) {
if (root !== undefined) {
var keys = Object.keys(root);
for (var i in keys) {
var key = keys[i], obj = root[key];
obj instanceof Function || "object" !== _typeof(obj) || null === obj || (0 < Object.keys(obj).length && recursivelyGarbageCollect(root[key]),
0 === Object.keys(obj).length && delete root[key]);
}
}
}(this.listenerTree), this;
}, EventEmitter.prototype.offAny = function(fn) {
var fns, i = 0, l = 0;
if (fn && this._all && 0 < this._all.length) {
for (i = 0, l = (fns = this._all).length; i < l; i++) if (fn === fns[i]) return fns.splice(i, 1),
this._removeListener && this.emit("removeListenerAny", fn), this;
} else {
if (fns = this._all, this._removeListener) for (i = 0, l = fns.length; i < l; i++) this.emit("removeListenerAny", fns[i]);
this._all = [];
}
return this;
}, EventEmitter.prototype.removeListener = EventEmitter.prototype.off, EventEmitter.prototype.removeAllListeners = function(type) {
if (type === undefined) return !this._events || init.call(this), this;
if (this.wildcard) for (var leafs = searchListenerTree(null, "string" == typeof type ? type.split(this.delimiter) : type.slice(), this.listenerTree, 0), iLeaf = 0; iLeaf < leafs.length; iLeaf++) {
leafs[iLeaf]._listeners = null;
} else this._events && (this._events[type] = null);
return this;
}, EventEmitter.prototype.listeners = function(type) {
if (this.wildcard) {
var handlers = [];
return searchListenerTree(handlers, "string" == typeof type ? type.split(this.delimiter) : type.slice(), this.listenerTree, 0),
handlers;
}
return this._events || init.call(this), this._events[type] || (this._events[type] = []),
isArray(this._events[type]) || (this._events[type] = [ this._events[type] ]), this._events[type];
}, EventEmitter.prototype.eventNames = function() {
return Object.keys(this._events);
}, EventEmitter.prototype.listenerCount = function(type) {
return this.listeners(type).length;
}, EventEmitter.prototype.listenersAny = function() {
return this._all ? this._all : [];
}, "function" == typeof undefined && undefined.amd ? undefined(function() {
return EventEmitter;
}) : module.exports = EventEmitter;
}();
}), TestReqID = "TestReqID", UserReqID = "UserReqID", SecurityReqID = "SecurityReqID", DepositReqID = "DepositReqID", WithdrawReqID = "WithdrawReqID", BalanceReqID = "BalanceReqID", OrdersReqID = "OrdersReqID", DepositMethodReqID = "DepositMethodReqID", WithdrawListReqID = "WithdrawListReqID", WithdrawCancelReqID = "WithdrawCancelReqID", BrokerListReqID = "BrokerListReqID", DepositListReqID = "DepositListReqID", TradeHistoryReqID = "TradeHistoryReqID", LedgerListReqID = "LedgerListReqID", PositionReqID = "PositionReqID", SecurityStatusReqID = "SecurityStatusReqID", ProcessDepositReqID = "ProcessDepositReqID", CustomerListReqID = "CustomerListReqID", CustomerReqID = "CustomerReqID", ProcessWithdrawReqID = "ProcessWithdrawReqID", VerifyCustomerReqID = "VerifyCustomerReqID", MDReqID = "MDReqID", ClOrdID = "ClOrdID", HEARTBEAT = "HEARTBEAT", BROKER_LIST = "BROKER_LIST", SECURITY_LIST = "SECURITY_LIST", SECURITY_STATUS_SUBSCRIBE = "SECURITY_STATUS_SUBSCRIBE", MD_INCREMENT = "MD_INCREMENT", MD_FULL_REFRESH = "MD_FULL_REFRESH", EXECUTION_REPORT = "EXECUTION_REPORT", ORDER_HISTORY = "ORDER_HISTORY", ORDER_SEND = "ORDER_SEND", ORDER_CANCEL = "ORDER_CANCEL", TRADE_HISTORY = "TRADE_HISTORY", LOGIN = "LOGIN", BALANCE = "BALANCE", POSITIONS = "POSITIONS", CUSTOMER_LIST = "CUSTOMER_LIST", CUSTOMER_REFRESH = "CUSTOMER_REFRESH", KYC_VERIFY = "KYC_VERIFY", KYC_REQUEST = "KYC_REQUEST", WITHDRAW_LIST = "WITHDRAW_LIST", WITHDRAW_CANCEL = "WITHDRAW_CANCEL", WITHDRAW_REFRESH = "WITHDRAW_REFRESH", WITHDRAW_PROCESS = "WITHDRAW_PROCESS", WITHDRAW_CONFIRM = "WITHDRAW_CONFIRM", WITHDRAW_COMMENT = "WITHDRAW_COMMENT", WITHDRAW_REQUEST = "WITHDRAW_REQUEST", DEPOSIT_LIST = "DEPOSIT_LIST", DEPOSIT_REFRESH = "DEPOSIT_REFRESH", DEPOSIT_PROCESS = "DEPOSIT_PROCESS", DEPOSIT_REQUEST = "DEPOSIT_REQUEST", DEPOSIT_METHODS = "DEPOSIT_METHODS", LEDGER_LIST = "LEDGER_LIST", zipColumns = function(arr, columns) {
return arr.reduce(function(prev, val, i) {
return prev[columns[i]] = val, prev;
}, {});
}, msgToAction = function(messages) {
return Object.entries(messages).reduce(function(prev, val) {
return prev[val[1][0]] = val[0], prev;
}, {});
}, formatColumns = function(field, level) {
return function(data) {
if (2 !== level) return Promise.resolve(data);
var list = data[field].map(function(row) {
return zipColumns(row, data.Columns);
});
return Promise.resolve(_objectSpread({}, data, _defineProperty({}, field, list)));
};
}, formatBrokerList = function(level) {
return function(data) {
if (2 !== level) return Promise.resolve(data);
var BrokerListGrp = data.BrokerListGrp.map(function(row) {
return zipColumns(row, data.Columns);
}).reduce(function(prev, val) {
return prev[val.BrokerID] = val, prev;
}, {});
return Promise.resolve(_objectSpread({}, data, {
BrokerListGrp: BrokerListGrp
}));
};
}, formatTradeHistory = function(level) {
return function(data) {
if (2 !== level) return Promise.resolve(data);
var TradeHistoryGrp = data.TradeHistoryGrp.map(function(row) {
return zipColumns(row, data.Columns);
}).reduce(function(prev, val) {
return (prev[val.Market] = prev[val.Market] || []).push(val), prev;
}, {});
return Promise.resolve(_objectSpread({}, data, {
TradeHistoryGrp: TradeHistoryGrp
}));
};
}, formatOrderBook = function(data, level) {
if (2 !== level) return data;
var _data$MDFullGrp$filte = data.MDFullGrp.filter(function(order) {
return "0" === order.MDEntryType || "1" === order.MDEntryType;
}).reduce(function(prev, order) {
var side = "0" === order.MDEntryType ? "bids" : "asks";
return (prev[side] || (prev[side] = [])).push(order), prev;
}, []);
return _objectSpread({}, data, {
MDFullGrp: _defineProperty({}, data.Symbol, {
bids: _data$MDFullGrp$filte.bids || [],
asks: _data$MDFullGrp$filte.asks || []
})
});
}, MsgActionReq = {
1: [ HEARTBEAT, TestReqID ],
BE: [ LOGIN, UserReqID ],
V: [ MD_FULL_REFRESH, MDReqID ],
x: [ SECURITY_LIST, SecurityReqID ],
e: [ SECURITY_STATUS_SUBSCRIBE, SecurityStatusReqID ],
D: [ ORDER_SEND, ClOrdID ],
F: [ ORDER_CANCEL, ClOrdID ],
U2: [ BALANCE, BalanceReqID ],
U6: [ WITHDRAW_REQUEST, WithdrawReqID ],
U4: [ ORDER_HISTORY, OrdersReqID ],
U18: [ DEPOSIT_REQUEST, DepositReqID ],
U20: [ DEPOSIT_METHODS, DepositMethodReqID ],
U24: [ WITHDRAW_CONFIRM, WithdrawReqID ],
U26: [ WITHDRAW_LIST, WithdrawListReqID ],
U28: [ BROKER_LIST, BrokerListReqID ],
U30: [ DEPOSIT_LIST, DepositListReqID ],
U32: [ TRADE_HISTORY, TradeHistoryReqID ],
U34: [ LEDGER_LIST, LedgerListReqID ],
U42: [ POSITIONS, PositionReqID ],
U70: [ WITHDRAW_CANCEL, WithdrawCancelReqID ],
B0: [ DEPOSIT_PROCESS, ProcessDepositReqID ],
B2: [ CUSTOMER_LIST, CustomerListReqID ],
B4: [ KYC_REQUEST, CustomerReqID ],
B6: [ WITHDRAW_PROCESS, ProcessWithdrawReqID ],
B8: [ KYC_VERIFY, VerifyCustomerReqID ]
}, MsgActionRes = {
0: [ HEARTBEAT, TestReqID ],
BF: [ LOGIN, UserReqID ],
W: [ MD_FULL_REFRESH, MDReqID ],
X: [ MD_INCREMENT, MDReqID ],
8: [ EXECUTION_REPORT, ClOrdID ],
y: [ SECURITY_LIST, SecurityReqID ],
f: [ SECURITY_STATUS_SUBSCRIBE, SecurityStatusReqID ],
U3: [ BALANCE, BalanceReqID ],
U7: [ WITHDRAW_REQUEST, WithdrawReqID ],
U5: [ ORDER_HISTORY, OrdersReqID ],
U9: [ WITHDRAW_REFRESH, ClOrdID ],
U19: [ DEPOSIT_REQUEST, DepositReqID ],
U21: [ DEPOSIT_METHODS, DepositMethodReqID ],
U23: [ DEPOSIT_REFRESH, ClOrdID ],
U25: [ WITHDRAW_CONFIRM, WithdrawReqID ],
U27: [ WITHDRAW_LIST, WithdrawListReqID ],
U29: [ BROKER_LIST, BrokerListReqID ],
U31: [ DEPOSIT_LIST, DepositListReqID ],
U33: [ TRADE_HISTORY, TradeHistoryReqID ],
U35: [ LEDGER_LIST, LedgerListReqID ],
U43: [ POSITIONS, PositionReqID ],
U71: [ WITHDRAW_CANCEL, WithdrawCancelReqID ],
U79: [ WITHDRAW_COMMENT, WithdrawReqID ],
B1: [ DEPOSIT_PROCESS, ProcessDepositReqID ],
B3: [ CUSTOMER_LIST, CustomerListReqID ],
B5: [ KYC_REQUEST, CustomerReqID ],
B9: [ KYC_VERIFY, VerifyCustomerReqID ],
B7: [ WITHDRAW_PROCESS, ProcessWithdrawReqID ],
B11: [ CUSTOMER_REFRESH, "" ]
}, ActionMsgReq = msgToAction(MsgActionReq), ActionMsgRes = msgToAction(MsgActionRes), reqs = new Map();
function generateRequestId() {
return parseInt(1e7 * Math.random() + "", 10);
}
function getKey(messages, msg) {
var key = messages[msg.MsgType][1];
return key + ":" + msg[key];
}
function getRequest(msg) {
return reqs.get(getKey(MsgActionRes, msg));
}
function setRequest(msg, promise) {
reqs.set(getKey(MsgActionReq, msg), promise);
}
function deleteRequest(msg) {
reqs.delete(getKey(MsgActionRes, msg));
}
var ORDER_BOOK_TRADE_NEW = "TRADE_NEW", ORDER_BOOK_NEW_ORDER = "NEW_ORDER", ORDER_BOOK_UPDATE_ORDER = "UPDATE_ORDER", ORDER_BOOK_DELETE_ORDER = "DELETE_ORDER", ORDER_BOOK_DELETE_ORDERS_THRU = "DELETE_ORDERS_THRU", EXECUTION_REPORT_NEW$1 = "NEW", EXECUTION_REPORT_PARTIAL$1 = "PARTIAL", EXECUTION_REPORT_EXECUTION$1 = "EXECUTION", EXECUTION_REPORT_CANCELED$1 = "CANCELED", EXECUTION_REPORT_REJECTED$1 = "REJECTED", EVENTS = {
ORDERBOOK: {
0: ORDER_BOOK_NEW_ORDER,
1: ORDER_BOOK_UPDATE_ORDER,
2: ORDER_BOOK_DELETE_ORDER,
3: ORDER_BOOK_DELETE_ORDERS_THRU
},
TRADES: {
0: ORDER_BOOK_TRADE_NEW
},
EXECUTION_REPORT: {
0: EXECUTION_REPORT_NEW$1,
1: EXECUTION_REPORT_PARTIAL$1,
2: EXECUTION_REPORT_EXECUTION$1,
4: EXECUTION_REPORT_CANCELED$1,
8: EXECUTION_REPORT_REJECTED$1
}
}, ORDER_TYPE = {
MARKET: "1",
LIMIT: "2",
STOP: "3",
STOP_LIMIT: "4"
}, ORDER_SIDE = {
BUY: "1",
SELL: "2"
}, TradeBase = function() {
function TradeBase() {
var params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
_classCallCheck(this, TradeBase), this.level = void 0 === params.level ? 2 : params.level,
this.brokerId = params.brokerId || 4;
}
return _createClass(TradeBase, [ {
key: "changeBrokerId",
value: function(brokerId) {
this.brokerId = brokerId;
}
}, {
key: "balance",
value: function(clientId, callback) {
var msg = {
MsgType: ActionMsgReq.BALANCE,
BalanceReqID: generateRequestId()
};
return clientId && (msg.ClientID = clientId), nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "myOrders",
value: function() {
var _ref = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref$page = _ref.page, Page = void 0 === _ref$page ? 0 : _ref$page, _ref$pageSize = _ref.pageSize, PageSize = void 0 === _ref$pageSize ? 40 : _ref$pageSize, filter = _ref.filter, callback = 1 < arguments.length ? arguments[1] : void 0, msg = {
MsgType: ActionMsgReq.ORDER_HISTORY,
OrdersReqID: generateRequestId(),
Page: Page,
PageSize: PageSize
};
filter && "all" !== filter && (msg.Filter = "open" === filter ? [ "has_leaves_qty eq 1" ] : "filled" === filter ? [ "has_cum_qty eq 1" ] : "cancelled" === filter ? [ "has_cxl_qty eq 1" ] : filter);
var format = formatColumns("OrdListGrp", this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
}, {
key: "sendOrder",
value: function(_ref2, callback) {
var type = _ref2.type, side = _ref2.side, amount = _ref2.amount, price = _ref2.price, stopPrice = _ref2.stopPrice, symbol = _ref2.symbol, postOnly = _ref2.postOnly, msg = {
MsgType: ActionMsgReq.ORDER_SEND,
ClOrdID: _ref2.clientId || "" + generateRequestId(),
Side: ORDER_SIDE[side] || side,
OrdType: ORDER_TYPE[type] || ORDER_TYPE.LIMIT,
Symbol: symbol,
OrderQty: amount,
BrokerID: this.brokerId
};
return price && (msg.Price = price), stopPrice && (msg.StopPx = stopPrice), postOnly && (msg.ExecInst = "6"),
nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "cancelOrder",
value: function() {
var param = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, callback = 1 < arguments.length ? arguments[1] : void 0, orderId = param.orderId ? param.orderId : param, msg = {
MsgType: ActionMsgReq.ORDER_CANCEL
};
return param.clientId && (msg.ClOrdID = param.clientId), param.orderId && (msg.OrderID = orderId),
nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "requestWithdrawList",
value: function() {
var _ref3 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, filter = _ref3.filter, clientId = _ref3.clientId, _ref3$page = _ref3.page, Page = void 0 === _ref3$page ? 0 : _ref3$page, _ref3$pageSize = _ref3.pageSize, PageSize = void 0 === _ref3$pageSize ? 20 : _ref3$pageSize, _ref3$status = _ref3.status, StatusList = void 0 === _ref3$status ? [ "1", "2", "4", "8" ] : _ref3$status, callback = 1 < arguments.length ? arguments[1] : void 0, msg = {
MsgType: ActionMsgReq.WITHDRAW_LIST,
WithdrawListReqID: generateRequestId(),
Page: Page,
PageSize: PageSize,
StatusList: StatusList
};
filter && filter.length && (msg.Filter = filter), clientId && (msg.ClientID = clientId);
var format = formatColumns("WithdrawListGrp", this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
}, {
key: "requestWithdraw",
value: function(_ref4, callback) {
var amount = _ref4.amount, data = _ref4.data, _ref4$currency = _ref4.currency, currency = void 0 === _ref4$currency ? "BTC" : _ref4$currency, _ref4$method = _ref4.method, method = void 0 === _ref4$method ? "bitcoin" : _ref4$method, reqId = generateRequestId();
return nodeify_1.extend(this.send({
MsgType: ActionMsgReq.WITHDRAW_REQUEST,
WithdrawReqID: reqId,
ClOrdID: reqId,
Method: method,
Amount: amount,
Currency: currency,
Data: data
})).nodeify(callback);
}
}, {
key: "confirmWithdraw",
value: function(_ref5, callback) {
var WithdrawID = _ref5.withdrawId, confirmationToken = _ref5.confirmationToken, secondFactor = _ref5.secondFactor, msg = {
MsgType: ActionMsgReq.WITHDRAW_CONFIRM,
WithdrawReqID: generateRequestId(),
WithdrawID: WithdrawID
};
return confirmationToken && (msg.ConfirmationToken = confirmationToken), secondFactor && (msg.SecondFactor = secondFactor),
nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "cancelWithdraw",
value: function(withdrawId, callback) {
var reqId = generateRequestId();
return nodeify_1.extend(this.send({
MsgType: ActionMsgReq.WITHDRAW_CANCEL,
WithdrawCancelReqID: reqId,
ClOrdID: reqId,
WithdrawID: withdrawId
})).nodeify(callback);
}
}, {
key: "requestDepositList",
value: function() {
var _ref6 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref6$page = _ref6.page, Page = void 0 === _ref6$page ? 0 : _ref6$page, _ref6$pageSize = _ref6.pageSize, PageSize = void 0 === _ref6$pageSize ? 20 : _ref6$pageSize, _ref6$status = _ref6.status, StatusList = void 0 === _ref6$status ? [ "1", "2", "4", "8" ] : _ref6$status, filter = _ref6.filter, clientId = _ref6.clientId, callback = 1 < arguments.length ? arguments[1] : void 0, msg = {
MsgType: ActionMsgReq.DEPOSIT_LIST,
DepositListReqID: generateRequestId(),
Page: Page,
PageSize: PageSize,
StatusList: StatusList
};
filter && filter.length && (msg.Filter = filter), clientId && (msg.ClientID = clientId);
var format = formatColumns("DepositListGrp", this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
}, {
key: "requestDeposit",
value: function() {
var _ref7 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref7$currency = _ref7.currency, currency = void 0 === _ref7$currency ? "BTC" : _ref7$currency, value = _ref7.value, depositMethodId = _ref7.depositMethodId, callback = 1 < arguments.length ? arguments[1] : void 0, reqId = generateRequestId(), msg = {
MsgType: ActionMsgReq.DEPOSIT_REQUEST,
DepositReqID: reqId,
ClOrdID: reqId,
Currency: currency,
BrokerID: this.brokerId
};
return "BTC" !== currency && (msg.DepositMethodID = depositMethodId, msg.Value = value),
nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "requestDepositMethods",
value: function(callback) {
var msg = {
MsgType: ActionMsgReq.DEPOSIT_METHODS,
DepositMethodReqID: generateRequestId(),
BrokerID: this.brokerId
};
return nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "requestBrokerList",
value: function(callback) {
var msg = {
MsgType: ActionMsgReq.BROKER_LIST,
BrokerListReqID: generateRequestId(),
Page: 0,
PageSize: 20,
StatusList: [ "1" ]
}, format = formatBrokerList(this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
}, {
key: "requestLedger",
value: function() {
var _ref8 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref8$page = _ref8.page, Page = void 0 === _ref8$page ? 0 : _ref8$page, _ref8$pageSize = _ref8.pageSize, PageSize = void 0 === _ref8$pageSize ? 20 : _ref8$pageSize, brokerId = _ref8.brokerId, clientId = _ref8.clientId, currency = _ref8.currency, callback = 1 < arguments.length ? arguments[1] : void 0, msg = {
MsgType: ActionMsgReq.LEDGER_LIST,
LedgerListReqID: generateRequestId(),
BrokerID: this.brokerId,
Page: Page,
PageSize: PageSize
};
brokerId && (msg.BrokerID = brokerId), currency && (msg.Currency = currency), clientId && (msg.ClientID = clientId);
var format = formatColumns("LedgerListGrp", this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
} ]), TradeBase;
}(), WS = {};
function getMac() {}
var sha256 = createCommonjsModule(function(module) {
!function() {
var ERROR = "input is invalid type", WINDOW = "object" === ("undefined" == typeof window ? "undefined" : _typeof(window)), root = WINDOW ? window : {};
root.JS_SHA256_NO_WINDOW && (WINDOW = !1);
var WEB_WORKER = !WINDOW && "object" === ("undefined" == typeof self ? "undefined" : _typeof(self)), NODE_JS = !root.JS_SHA256_NO_NODE_JS && "object" === ("undefined" == typeof process ? "undefined" : _typeof(process)) && process.versions && process.versions.node;
NODE_JS ? root = commonjsGlobal : WEB_WORKER && (root = self);
var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && module.exports, ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && "undefined" != typeof ArrayBuffer, HEX_CHARS = "0123456789abcdef".split(""), EXTRA = [ -2147483648, 8388608, 32768, 128 ], SHIFT = [ 24, 16, 8, 0 ], K = [ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ], OUTPUT_TYPES = [ "hex", "array", "digest", "arrayBuffer" ], blocks = [];
!root.JS_SHA256_NO_NODE_JS && Array.isArray || (Array.isArray = function(obj) {
return "[object Array]" === Object.prototype.toString.call(obj);
}), !ARRAY_BUFFER || !root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW && ArrayBuffer.isView || (ArrayBuffer.isView = function(obj) {
return "object" === _typeof(obj) && obj.buffer && obj.buffer.constructor === ArrayBuffer;
});
var createOutputMethod = function(outputType, is224) {
return function(message) {
return new Sha256(is224, !0).update(message)[outputType]();
};
}, createMethod = function(is224) {
var method = createOutputMethod("hex", is224);
NODE_JS && (method = nodeWrap(method, is224)), method.create = function() {
return new Sha256(is224);
}, method.update = function(message) {
return method.create().update(message);
};
for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
var type = OUTPUT_TYPES[i];
method[type] = createOutputMethod(type, is224);
}
return method;
}, nodeWrap = function nodeWrap(method, is224) {
var crypto = eval("require('crypto')"), Buffer = eval("require('buffer').Buffer"), algorithm = is224 ? "sha224" : "sha256", nodeMethod = function(message) {
if ("string" == typeof message) return crypto.createHash(algorithm).update(message, "utf8").digest("hex");
if (null == message) throw Error(ERROR);
return message.constructor === ArrayBuffer && (message = new Uint8Array(message)),
Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer ? crypto.createHash(algorithm).update(new Buffer(message)).digest("hex") : method(message);
};
return nodeMethod;
}, createHmacOutputMethod = function(outputType, is224) {
return function(key, message) {
return new HmacSha256(key, is224, !0).update(message)[outputType]();
};
}, createHmacMethod = function(is224) {
var method = createHmacOutputMethod("hex", is224);
method.create = function(key) {
return new HmacSha256(key, is224);
}, method.update = function(key, message) {
return method.create(key).update(message);
};
for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
var type = OUTPUT_TYPES[i];
method[type] = createHmacOutputMethod(type, is224);
}
return method;
};
function Sha256(is224, sharedMemory) {
this.blocks = sharedMemory ? (blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0,
blocks) : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], this.h7 = is224 ? (this.h0 = 3238371032,
this.h1 = 914150663, this.h2 = 812702999, this.h3 = 4144912697, this.h4 = 4290775857,
this.h5 = 1750603025, this.h6 = 1694076839, 3204075428) : (this.h0 = 1779033703,
this.h1 = 3144134277, this.h2 = 1013904242, this.h3 = 2773480762, this.h4 = 1359893119,
this.h5 = 2600822924, this.h6 = 528734635, 1541459225), this.block = this.start = this.bytes = this.hBytes = 0,
this.finalized = this.hashed = !1, this.first = !0, this.is224 = is224;
}
function HmacSha256(key, is224, sharedMemory) {
var i, type = _typeof(key);
if ("string" === type) {
var code, bytes = [], length = key.length, index = 0;
for (i = 0; i < length; ++i) code = key.charCodeAt(i), bytes[index++] = code < 128 ? code : (bytes[index++] = code < 2048 ? 192 | code >> 6 : (bytes[index++] = code < 55296 || 57344 <= code ? 224 | code >> 12 : (code = 65536 + ((1023 & code) << 10 | 1023 & key.charCodeAt(++i)),
bytes[index++] = 240 | code >> 18, 128 | code >> 12 & 63), 128 | code >> 6 & 63),
128 | 63 & code);
key = bytes;
} else {
if ("object" !== type) throw Error(ERROR);
if (null === key) throw Error(ERROR);
if (ARRAY_BUFFER && key.constructor === ArrayBuffer) key = new Uint8Array(key); else if (!(Array.isArray(key) || ARRAY_BUFFER && ArrayBuffer.isView(key))) throw Error(ERROR);
}
64 < key.length && (key = new Sha256(is224, !0).update(key).array());
var oKeyPad = [], iKeyPad = [];
for (i = 0; i < 64; ++i) {
var b = key[i] || 0;
oKeyPad[i] = 92 ^ b, iKeyPad[i] = 54 ^ b;
}
Sha256.call(this, is224, sharedMemory), this.update(iKeyPad), this.oKeyPad = oKeyPad,
this.inner = !0, this.sharedMemory = sharedMemory;
}
Sha256.prototype.update = function(message) {
if (!this.finalized) {
var notString, type = _typeof(message);
if ("string" !== type) {
if ("object" !== type) throw Error(ERROR);
if (null === message) throw Error(ERROR);
if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message); else if (!(Array.isArray(message) || ARRAY_BUFFER && ArrayBuffer.isView(message))) throw Error(ERROR);
notString = !0;
}
for (var code, i, index = 0, length = message.length, blocks = this.blocks; index < length; ) {
if (this.hashed && (this.hashed = !1, blocks[0] = this.block, blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0),
notString) for (i = this.start; index < length && i < 64; ++index) blocks[i >> 2] |= message[index] << SHIFT[3 & i++]; else for (i = this.start; index < length && i < 64; ++index) (code = message.charCodeAt(index)) < 128 ? blocks[i >> 2] |= code << SHIFT[3 & i++] : (code < 2048 ? blocks[i >> 2] |= (192 | code >> 6) << SHIFT[3 & i++] : (code < 55296 || 57344 <= code ? blocks[i >> 2] |= (224 | code >> 12) << SHIFT[3 & i++] : (code = 65536 + ((1023 & code) << 10 | 1023 & message.charCodeAt(++index)),
blocks[i >> 2] |= (240 | code >> 18) << SHIFT[3 & i++], blocks[i >> 2] |= (128 | code >> 12 & 63) << SHIFT[3 & i++]),
blocks[i >> 2] |= (128 | code >> 6 & 63) << SHIFT[3 & i++]), blocks[i >> 2] |= (128 | 63 & code) << SHIFT[3 & i++]);
this.lastByteIndex = i, this.bytes += i - this.start, i < 64 ? this.start = i : (this.block = blocks[16],
this.start = i - 64, this.hash(), this.hashed = !0);
}
return 4294967295 < this.bytes && (this.hBytes += this.bytes / 4294967296 << 0,
this.bytes = this.bytes % 4294967296), this;
}
}, Sha256.prototype.finalize = function() {
if (!this.finalized) {
this.finalized = !0;
var blocks = this.blocks, i = this.lastByteIndex;
blocks[16] = this.block, blocks[i >> 2] |= EXTRA[3 & i], this.block = blocks[16],
i < 56 || (this.hashed || this.hash(), blocks[0] = this.block, blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0),
blocks[14] = this.hBytes << 3 | this.bytes >>> 29, blocks[15] = this.bytes << 3,
this.hash();
}
}, Sha256.prototype.hash = function() {
var j, t1, ab, da, cd, bc, a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks;
for (j = 16; j < 64; ++j) blocks[j] = blocks[j - 16] + (((t1 = blocks[j - 15]) >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3) + blocks[j - 7] + (((t1 = blocks[j - 2]) >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10) << 0;
for (bc = b & c, j = 0; j < 64; j += 4) this.first ? (d = this.is224 ? (ab = 300032,
h = (t1 = blocks[0] - 1413257819) - 150054599 << 0, t1 + 24177077 << 0) : (ab = 704751109,
h = (t1 = blocks[0] - 210244248) - 1521486534 << 0, t1 + 143694565 << 0), this.first = !1) : (h = d + (t1 = h + ((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) + K[j] + blocks[j]) << 0,
d = t1 + (((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + ((ab = a & b) ^ a & c ^ bc)) << 0),
g = c + (t1 = g + ((h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7)) + (h & e ^ ~h & f) + K[j + 1] + blocks[j + 1]) << 0,
c = t1 + (((d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10)) + ((da = d & a) ^ d & b ^ ab)) << 0,
f = b + (t1 = f + ((g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7)) + (g & h ^ ~g & e) + K[j + 2] + blocks[j + 2]) << 0,
b = t1 + (((c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10)) + ((cd = c & d) ^ c & a ^ da)) << 0,
e = a + (t1 = e + ((f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7)) + (f & g ^ ~f & h) + K[j + 3] + blocks[j + 3]) << 0,
a = t1 + (((b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10)) + ((bc = b & c) ^ b & d ^ cd)) << 0;
this.h0 = this.h0 + a << 0, this.h1 = this.h1 + b << 0, this.h2 = this.h2 + c << 0,
this.h3 = this.h3 + d << 0, this.h4 = this.h4 + e << 0, this.h5 = this.h5 + f << 0,
this.h6 = this.h6 + g << 0, this.h7 = this.h7 + h << 0;
}, Sha256.prototype.hex = function() {
this.finalize();
var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7, hex = HEX_CHARS[h0 >> 28 & 15] + HEX_CHARS[h0 >> 24 & 15] + HEX_CHARS[h0 >> 20 & 15] + HEX_CHARS[h0 >> 16 & 15] + HEX_CHARS[h0 >> 12 & 15] + HEX_CHARS[h0 >> 8 & 15] + HEX_CHARS[h0 >> 4 & 15] + HEX_CHARS[15 & h0] + HEX_CHARS[h1 >> 28 & 15] + HEX_CHARS[h1 >> 24 & 15] + HEX_CHARS[h1 >> 20 & 15] + HEX_CHARS[h1 >> 16 & 15] + HEX_CHARS[h1 >> 12 & 15] + HEX_CHARS[h1 >> 8 & 15] + HEX_CHARS[h1 >> 4 & 15] + HEX_CHARS[15 & h1] + HEX_CHARS[h2 >> 28 & 15] + HEX_CHARS[h2 >> 24 & 15] + HEX_CHARS[h2 >> 20 & 15] + HEX_CHARS[h2 >> 16 & 15] + HEX_CHARS[h2 >> 12 & 15] + HEX_CHARS[h2 >> 8 & 15] + HEX_CHARS[h2 >> 4 & 15] + HEX_CHARS[15 & h2] + HEX_CHARS[h3 >> 28 & 15] + HEX_CHARS[h3 >> 24 & 15] + HEX_CHARS[h3 >> 20 & 15] + HEX_CHARS[h3 >> 16 & 15] + HEX_CHARS[h3 >> 12 & 15] + HEX_CHARS[h3 >> 8 & 15] + HEX_CHARS[h3 >> 4 & 15] + HEX_CHARS[15 & h3] + HEX_CHARS[h4 >> 28 & 15] + HEX_CHARS[h4 >> 24 & 15] + HEX_CHARS[h4 >> 20 & 15] + HEX_CHARS[h4 >> 16 & 15] + HEX_CHARS[h4 >> 12 & 15] + HEX_CHARS[h4 >> 8 & 15] + HEX_CHARS[h4 >> 4 & 15] + HEX_CHARS[15 & h4] + HEX_CHARS[h5 >> 28 & 15] + HEX_CHARS[h5 >> 24 & 15] + HEX_CHARS[h5 >> 20 & 15] + HEX_CHARS[h5 >> 16 & 15] + HEX_CHARS[h5 >> 12 & 15] + HEX_CHARS[h5 >> 8 & 15] + HEX_CHARS[h5 >> 4 & 15] + HEX_CHARS[15 & h5] + HEX_CHARS[h6 >> 28 & 15] + HEX_CHARS[h6 >> 24 & 15] + HEX_CHARS[h6 >> 20 & 15] + HEX_CHARS[h6 >> 16 & 15] + HEX_CHARS[h6 >> 12 & 15] + HEX_CHARS[h6 >> 8 & 15] + HEX_CHARS[h6 >> 4 & 15] + HEX_CHARS[15 & h6];
return this.is224 || (hex += HEX_CHARS[h7 >> 28 & 15] + HEX_CHARS[h7 >> 24 & 15] + HEX_CHARS[h7 >> 20 & 15] + HEX_CHARS[h7 >> 16 & 15] + HEX_CHARS[h7 >> 12 & 15] + HEX_CHARS[h7 >> 8 & 15] + HEX_CHARS[h7 >> 4 & 15] + HEX_CHARS[15 & h7]),
hex;
}, Sha256.prototype.toString = Sha256.prototype.hex, Sha256.prototype.digest = function() {
this.finalize();
var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7, arr = [ h0 >> 24 & 255, h0 >> 16 & 255, h0 >> 8 & 255, 255 & h0, h1 >> 24 & 255, h1 >> 16 & 255, h1 >> 8 & 255, 255 & h1, h2 >> 24 & 255, h2 >> 16 & 255, h2 >> 8 & 255, 255 & h2, h3 >> 24 & 255, h3 >> 16 & 255, h3 >> 8 & 255, 255 & h3, h4 >> 24 & 255, h4 >> 16 & 255, h4 >> 8 & 255, 255 & h4, h5 >> 24 & 255, h5 >> 16 & 255, h5 >> 8 & 255, 255 & h5, h6 >> 24 & 255, h6 >> 16 & 255, h6 >> 8 & 255, 255 & h6 ];
return this.is224 || arr.push(h7 >> 24 & 255, h7 >> 16 & 255, h7 >> 8 & 255, 255 & h7),
arr;
}, Sha256.prototype.array = Sha256.prototype.digest, Sha256.prototype.arrayBuffer = function() {
this.finalize();
var buffer = new ArrayBuffer(this.is224 ? 28 : 32), dataView = new DataView(buffer);
return dataView.setUint32(0, this.h0), dataView.setUint32(4, this.h1), dataView.setUint32(8, this.h2),
dataView.setUint32(12, this.h3), dataView.setUint32(16, this.h4), dataView.setUint32(20, this.h5),
dataView.setUint32(24, this.h6), this.is224 || dataView.setUint32(28, this.h7),
buffer;
}, HmacSha256.prototype = new Sha256(), HmacSha256.prototype.finalize = function() {
if (Sha256.prototype.finalize.call(this), this.inner) {
this.inner = !1;
var innerHash = this.array();
Sha256.call(this, this.is224, this.sharedMemory), this.update(this.oKeyPad), this.update(innerHash),
Sha256.prototype.finalize.call(this);
}
};
var exports = createMethod();
exports.sha256 = exports, exports.sha224 = createMethod(!0), exports.sha256.hmac = createHmacMethod(),
exports.sha224.hmac = createHmacMethod(!0), COMMON_JS ? module.exports = exports : (root.sha256 = exports.sha256,
root.sha224 = exports.sha224);
}();
}), SEED32 = 314159265, CONSTANT32 = -1640531527, mix32_ = function(mix) {
var a = mix.a, b = mix.b, c = mix.c;
return a -= b, a -= c, b -= c, b -= a ^= c >>> 13, c -= a, c -= b ^= a << 8, a -= b,
a -= c ^= b >>> 13, b -= c, b -= a ^= c >>> 12, c -= a, c -= b ^= a << 16, a -= b,
a -= c ^= b >>> 5, b -= c, b -= a ^= c >>> 3, c -= a, c -= b ^= a << 10, c ^= b >>> 15,
mix.a = a, mix.b = b, mix.c = c;
}, toSigned_ = function(n) {
return 127 < n ? n - 256 : n;
}, wordAt_ = function(bytes, offset) {
return toSigned_(bytes[offset + 0]) + (toSigned_(bytes[offset + 1]) << 8) + (toSigned_(bytes[offset + 2]) << 16) + (toSigned_(bytes[offset + 3]) << 24);
};
function encodeByteArray(bytes) {
var keylen, offset = 0, length = bytes.length, mix = {
a: CONSTANT32,
b: CONSTANT32,
c: SEED32
};
for (keylen = length; 12 <= keylen; keylen -= 12, offset += 12) mix.a += wordAt_(bytes, offset),
mix.b += wordAt_(bytes, offset + 4), mix.c += wordAt_(bytes, offset + 8), mix32_(mix);
switch (mix.c += length, keylen) {
case 11:
mix.c += bytes[offset + 10] << 24;
case 10:
mix.c += (255 & bytes[offset + 9]) << 16;
case 9:
mix.c += (255 & bytes[offset + 8]) << 8;
case 8:
mix.b += wordAt_(bytes, offset + 4), mix.a += wordAt_(bytes, offset);
break;
case 7:
mix.b += (255 & bytes[offset + 6]) << 16;
case 6:
mix.b += (255 & bytes[offset + 5]) << 8;
case 5:
mix.b += 255 & bytes[offset + 4];
case 4:
mix.a += wordAt_(bytes, offset);
break;
case 3:
mix.a += (255 & bytes[offset + 2]) << 16;
case 2:
mix.a += (255 & bytes[offset + 1]) << 8;
case 1:
mix.a += 255 & bytes[offset + 0];
}
return mix32_(mix);
}
function getFingerPrint() {
var keys = [];
keys.push(window.navigator.userAgent), keys.push(window.screen.colorDepth), keys.push(window.navigator.language),
Array.isArray(window.navigator.languages) ? keys.push(window.navigator.languages.join("x")) : keys.push("undefined");
var resolution = window.screen.height > window.screen.width ? [ window.screen.height, window.screen.width ] : [ window.screen.width, window.screen.height ];
keys.push(resolution.join("x")), keys.push(new Date().getTimezoneOffset()), keys.push(void 0 !== window.sessionStorage),
keys.push(void 0 !== window.localStorage), keys.push(!!window.indexedDB), document.body ? keys.push(_typeof(window.document.body.addBehavior)) : keys.push("undefined"),
keys.push(_typeof(window.openDatabase)), keys.push(window.navigator.cpuClass), keys.push(window.navigator.platform),
keys.push(window.navigator.doNotTrack);
var pluginKeyList = [];
Array.from(window.navigator.plugins).forEach(function(p) {
var mimeTypes = [];
Object.values(p).forEach(function(mt) {
mimeTypes.push([ mt.type, mt.suffixes ].join("~"));
}), pluginKeyList.push([ p.name, p.description, mimeTypes.join(",") ].join("::"));
}), keys.push(pluginKeyList.join(";"));
var canvasEl = document.createElement("canvas");
if (canvasEl.getContext && canvasEl.getContext("2d")) {
var ctx = canvasEl.getContext("2d"), txt = "http://valve.github.io";
ctx.textBaseline = "top", ctx.font = "14px 'Arial'", ctx.textBaseline = "alphabetic",
ctx.fillStyle = "#f60", ctx.fillRect(125, 1, 62, 20), ctx.fillStyle = "#069", ctx.fillText(txt, 2, 15),
ctx.fillStyle = "rgba(102, 204, 0, 0.7)", ctx.fillText(txt, 4, 17), keys.push(canvasEl.toDataURL());
}
var digest = sha256.digest(keys.join("###")), fingerPrint = parseInt(encodeByteArray(digest));
return fingerPrint < 0 && (fingerPrint *= -1), fingerPrint;
}
var common = {
prod: {
ws: "wss://ws.blinktrade.com/trade/",
wsBitcambio: "wss://bitcambio_api.blinktrade.com/trade/",
rest: "https://api.blinktrade.com/",
restBitcambio: "https://bitcambio_api.blinktrade.com/"
},
testnet: {
ws: "wss://api_testnet.blinktrade.com/trade/",
wsBitcambio: "wss://api_testnet.blinktrade.com/trade/",
rest: "https://api_testnet.blinktrade.com/",
restBitcambio: "https://api_testnet.blinktrade.com/"
}
}, IS_NODE = "undefined" == typeof window, IS_BROWSER = "undefined" != typeof document, Transport = function Transport() {
var params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, env = 1 < arguments.length ? arguments[1] : void 0;
_classCallCheck(this, Transport), this.endpoint = params.url ? params.url : params.prod ? common.prod[env] : common.testnet[env];
}, RECONNECT_INTERVAL = 5e3, WebSocketTransport = function(_Transport) {
function WebSocketTransport() {
var _this, params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
return _classCallCheck(this, WebSocketTransport), (_this = _possibleConstructorReturn(this, _getPrototypeOf(WebSocketTransport).call(this, params, params.brokerId === BROKERS.BITCAMBIO ? "wsBitcambio" : "ws"))).stun = {
local: null,
public: []
}, _this.getFingerPrint(params.fingerPrint), _this.headers = params.headers, _this.autoReconnect = params.reconnect || !1,
_this.reconnectInterval = params.reconnectInterval || RECONNECT_INTERVAL, _this.eventEmitter = new eventemitter2({
wildcard: !0,
delimiter: ":"
}), _this;
}
return _inherits(WebSocketTransport, Transport), _createClass(WebSocketTransport, [ {
key: "connect",
value: function(callback) {
var _this2 = this;
return nodeify_1.extend(new Promise(function(resolve, reject) {
_this2.connection = {
resolve: resolve,
reject: reject
};
var WebSocket = IS_NODE ? WS : window.WebSocket;
_this2.getStun(), _this2.socket = new WebSocket(_this2.endpoint, [], _this2.headers),
_this2.socket.onopen = _this2.onOpen.bind(_this2), _this2.socket.onclose = _this2.onClose.bind(_this2),
_this2.socket.onerror = _this2.onError.bind(_this2), _this2.socket.onmessage = _this2.onMessage.bind(_this2);
})).nodeify(callback);
}
}, {
key: "disconnect",
value: function() {
this.socket.close(), this.closeStun();
}
}, {
key: "onOpen",
value: function(e) {
this.eventEmitter.emit("OPEN", e), this.connection.resolve({
connected: !0
});
}
}, {
key: "onClose",
value: function(e) {
this.eventEmitter.emit("CLOSE", e, this.lastMessageSent), this.closeStun(), this.reconnect();
}
}, {
key: "onError",
value: function(error) {
this.eventEmitter.emit("ERROR", error, this.lastMessageSent);
}
}, {
key: "reconnect",
value: function() {
var _this3 = this;
this.autoReconnect && setTimeout(function() {
return _this3.connect();
}, this.reconnectInterval);
}
}, {
key: "sendMessage",
value: function(msg) {
if (1 === this.socket.readyState) {
var data = msg;
data.STUNTIP = this.stun, data.FingerPrint = this.fingerPrint, this.lastMessageSent = data,
this.eventEmitter.emit("send", data), this.socket.send(JSON.stringify(data));
}
}
}, {
key: "sendMessageAsPromise",
value: function(msg) {
var _this4 = this;
return new Promise(function(resolve, reject) {
_this4.lastPromise = {
resolve: resolve,
reject: reject
}, setRequest(msg, {
resolve: resolve,
reject: reject
}), _this4.sendMessage(msg);
});
}
}, {
key: "onMessage",
value: function(msg) {
var data = JSON.parse(msg.data);
this.eventEmitter.emit("receive", data), MsgActionRes[data.MsgType] ? (this.dispatchPromise(data),
this.dispatchEventEmitters(data)) : "ERROR" === data.MsgType && this.eventEmitter.emit("ERROR", data, this.lastMessageSent);
}
}, {
key: "dispatchPromise",
value: function(data) {
var request = getRequest(data);
if (request && request.resolve) return deleteRequest(data), request.resolve(data);
}
}, {
key: "dispatchEventEmitters",
value: function(data) {
var type = data.MsgType, reqId = MsgActionRes[type][1];
this.eventEmitter.emit(type, data), data[reqId] && this.eventEmitter.emit(type + ":" + data[reqId], data);
}
}, {
key: "getFingerPrint",
value: function(customFingerprint) {
var _this5 = this;
if (IS_NODE) return getMac(function(macAddress) {
_this5.fingerPrint = macAddress;
});
if (IS_BROWSER) this.fingerPrint = getFingerPrint(); else {
if (!customFingerprint) throw Error("FingerPrint not provided");
this.fingerPrint = customFingerprint;
}
}
}, {
key: "getStun",
value: function() {}
}, {
key: "closeStun",
value: function() {}
}, {
key: "emitterPromise",
value: function(promise, callback) {
var _this7 = this;
return promise.on = function(event, listener) {
return _this7.eventEmitter.on(event, listener), promise;
}, promise.onAny = function(listener) {
return _this7.eventEmitter.onAny(listener), promise;
}, promise.offAny = function(listener) {
return _this7.eventEmitter.offAny(listener), promise;
}, promise.once = function(event, listener) {
return _this7.eventEmitter.once(event, listener), promise;
}, promise.many = function(event, times, listener) {
return _this7.eventEmitter.many(event, times, listener), promise;
}, promise.removeListener = function(event, listener) {
return _this7.eventEmitter.removeListener(event, listener), promise;
}, promise.removeAllListeners = function(events) {
return _this7.eventEmitter.removeAllListeners(events), promise;
}, nodeify_1.extend(promise).nodeify(callback);
}
} ]), WebSocketTransport;
}(), BlinkTradeWS = function(_TradeBase) {
function BlinkTradeWS() {
var _this, params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
return _classCallCheck(this, BlinkTradeWS), (_this = _possibleConstructorReturn(this, _getPrototypeOf(BlinkTradeWS).call(this, params))).transport = params.transport || new WebSocketTransport(params),
_this.session = {}, _this.orderbook = {}, _this.isOrderBookSynced = !1, _this.syncReqId = 0,
_this;
}
return _inherits(BlinkTradeWS, TradeBase), _createClass(BlinkTradeWS, [ {
key: "connect",
value: function(callback) {
return this.emitterPromise(this.transport.connect(callback));
}
}, {
key: "disconnect",
value: function() {
return this.transport.disconnect();
}
}, {
key: "send",
value: function(msg) {
return this.transport.sendMessageAsPromise(msg);
}
}, {
key: "on",
value: function(event, callback) {
if (this.transport.eventEmitter) return this.transport.eventEmitter.on(event, callback);
}
}, {
key: "emit",
value: function(event, data) {
if (this.transport.eventEmitter) return this.transport.eventEmitter.emit(event, data);
}
}, {
key: "emitterPromise",
value: function(promise, callback) {
return this.transport.emitterPromise ? this.transport.emitterPromise(promise, callback) : promise;
}
}, {
key: "heartbeat",
value: function(callback) {
var _this2 = this, d = new Date(), msg = {
MsgType: ActionMsgReq.HEARTBEAT,
TestReqID: d.getTime(),
SendTime: d.getTime()
};
return nodeify_1.extend(new Promise(function(resolve, reject) {
return _this2.send(msg).then(function(data) {
return resolve(_objectSpread({}, data, {
Latency: new Date(Date.now()) - data.SendTime
}));
}).catch(reject);
})).nodeify(callback);
}
}, {
key: "login",
value: function(_ref, callback) {
var userAgent, _this3 = this, username = _ref.username, password = _ref.password, secondFactor = _ref.secondFactor, cancelOnDisconnect = _ref.cancelOnDisconnect, brokerId = _ref.brokerId, extraData = _objectWithoutProperties(_ref, [ "username", "password", "secondFactor", "cancelOnDisconnect", "brokerId" ]);
userAgent = IS_NODE ? {
UserAgent: "".concat(os.type(), " ").concat(os.release()),
UserAgentLanguage: "en_US",
UserAgentPlatform: "".concat(os.platform(), " (").concat(os.arch(), ")"),
UserAgentTimezoneOffset: new Date().getTimezoneOffset()
} : {
UserAgent: window.navigator.userAgent,
UserAgentLanguage: window.navigator.language,
UserAgentPlatform: window.navigator.platform,
UserAgentTimezoneOffset: new Date().getTimezoneOffset()
};
var msg = _objectSpread({
MsgType: ActionMsgReq.LOGIN,
UserReqID: generateRequestId(),
BrokerID: brokerId || this.brokerId,
Username: username,
Password: password,
UserReqTyp: "1",
CancelOnDisconnect: cancelOnDisconnect ? "1" : "0"
}, userAgent, extraData);
return secondFactor && (msg.SecondFactor = secondFactor), nodeify_1.extend(new Promise(function(resolve, reject) {
return _this3.send(msg).then(function(data) {
return 1 === data.UserStatus ? resolve(_this3.session = data) : reject(data);
}).catch(reject);
})).nodeify(callback);
}
}, {
key: "logout",
value: function(callback) {
var msg = {
MsgType: ActionMsgReq.LOGIN,
BrokerID: this.brokerId,
UserReqID: generateRequestId(),
Username: this.session.Username,
UserReqTyp: "2"
};
return nodeify_1.extend(this.send(msg)).nodeify(callback);
}
}, {
key: "profile",
value: function(callback) {
var _this$session$Profile = this.session.Profile, profile = _objectWithoutProperties(_this$session$Profile, [ "VerificationData" ]);
return nodeify_1.extend(Promise.resolve(profile)).nodeify(callback);
}
}, {
key: "balance",
value: function(clientId, callback) {
var _this4 = this;
return this.emitterPromise(new Promise(function(resolve, reject) {
return _get(_getPrototypeOf(BlinkTradeWS.prototype), "balance", _this4).call(_this4, clientId, callback).then(function(data) {
return _this4.on(ActionMsgRes.BALANCE, function(balance) {
return callback && callback(null, balance), _this4.emit(BALANCE, balance);
}), resolve(data);
}).catch(reject);
}));
}
}, {
key: "onBalanceUpdate",
value: function(callback) {
return this.on(ActionMsgRes.BALANCE, callback);
}
}, {
key: "subscribeTicker",
value: function(symbols, callback) {
var _this5 = this, msg = {
MsgType: ActionMsgReq.SECURITY_STATUS_SUBSCRIBE,
SecurityStatusReqID: generateRequestId(),
SubscriptionRequestType: "1",
Instruments: symbols
}, formatTicker = function(data) {
return _objectSpread({}, data, {
SellVolume: data.SellVolume / 1e8,
LowPx: data.LowPx / 1e8,
LastPx: data.LastPx / 1e8,
BestAsk: data.BestAsk / 1e8,
HighPx: data.HighPx / 1e8,
BuyVolume: data.BuyVolume / 1e8,
BestBid: data.BestBid / 1e8
});
};
return this.emitterPromise(new Promise(function(resolve, reject) {
return _this5.send(msg).then(function(data) {
return _this5.on(ActionMsgRes.SECURITY_STATUS_SUBSCRIBE + ":" + data.SecurityStatusReqID, function(ticker) {
var tickerFormatted = formatTicker(ticker);
return callback && callback(null, tickerFormatted), _this5.emit("".concat(ticker.Market, ":").concat(ticker.Symbol), tickerFormatted);
}), resolve(formatTicker(data));
}).catch(reject);
}), callback);
}
}, {
key: "unSubscribeTicker",
value: function(SecurityStatusReqID) {
return this.transport.sendMessage({
MsgType: ActionMsgReq.SECURITY_STATUS_SUBSCRIBE,
SubscriptionRequestType: "2",
SecurityStatusReqID: SecurityStatusReqID
}), SecurityStatusReqID;
}
}, {
key: "subscribeOrderbook",
value: function(options, callback) {
return console.warn("Warning: subscribeOrderbook is DEPRECATED, use subscribeMarketData instead"),
this.subscribeMarketData(options, callback);
}
}, {
key: "subscribeMarketData",
value: function(options, callback) {
var _this6 = this, msg = {
MsgType: ActionMsgReq.MD_FULL_REFRESH,
MDReqID: generateRequestId(),
SubscriptionRequestType: "1",
MarketDepth: 0,
MDUpdateType: "1",
MDEntryTypes: [ "0", "1" ],
BrokerID: this.brokerId
};
Array.isArray(options) ? msg.Instruments = options : (msg.Instruments = options.instruments,
msg.MDEntryTypes = options.entryTypes || msg.MDEntryTypes, msg.MarketDepth = options.marketDepth || msg.MarketDepth),
options.columns && (msg.Columns = options.columns);
var level = Array.isArray(options) || void 0 === options.level ? this.level : options.level, subscribeEvent = function(data) {
"3" === data.MDBkTyp && data.MDIncGrp.map(function(order) {
switch (order.MDEntryType) {
case "0":
case "1":
var orderbookEvent = "OB:".concat(EVENTS.ORDERBOOK[order.MDUpdateAction]), bidOfferData = _objectSpread({}, order, {
MDReqID: data.MDReqID,
type: orderbookEvent
});
return callback && callback(null, bidOfferData), _this6.emit(orderbookEvent, bidOfferData);
case "2":
var tradeEvent = "OB:".concat(EVENTS.TRADES[order.MDUpdateAction]), tradeData = _objectSpread({}, order, {
type: tradeEvent
});
return callback && callback(null, tradeData), _this6.emit(tradeEvent, tradeData);
case "4":
break;
default:
return null;
}
return null;
});
};
return this.emitterPromise(new Promise(function(resolve, reject) {
return _this6.send(msg).then(function(data) {
return _this6.on(ActionMsgRes.MD_INCREMENT + ":" + data.MDReqID, subscribeEvent),
resolve(formatOrderBook(data, level));
}).catch(function(err) {
return reject(err);
});
}), callback);
}
}, {
key: "syncOrderbook",
value: function(options) {
var _this7 = this;
if (this.isOrderBookSynced) return Promise.resolve(this.orderbook);
this.isOrderBookSynced = !0;
var sides = {
0: "bids",
1: "asks"
};
return this.subscribeMarketData({
instruments: Array.isArray(options) ? options : options.instruments,
level: 2
}).on("OB:NEW_ORDER", function(order) {
order.MDReqID === _this7.syncReqId && _this7.orderbook[order.Symbol][sides[order.MDEntryType]].splice(order.MDEntryPositionNo - 1, 0, order);
}).on("OB:UPDATE_ORDER", function(order) {
order.MDReqID === _this7.syncReqId && _this7.orderbook[order.Symbol][sides[order.MDEntryType]].splice(order.MDEntryPositionNo - 1, 1, order);
}).on("OB:DELETE_ORDER", function(order) {
order.MDReqID === _this7.syncReqId && _this7.orderbook[order.Symbol][sides[order.MDEntryType]].splice(order.MDEntryPositionNo - 1, 1);
}).on("OB:DELETE_ORDERS_THRU", function(order) {
order.MDReqID === _this7.syncReqId && _this7.orderbook[order.Symbol][sides[order.MDEntryType]].splice(0, order.MDEntryPositionNo);
}).then(function(data) {
return _this7.syncReqId = data.MDReqID, _this7.orderbook = data.MDFullGrp, _this7.orderbook;
});
}
}, {
key: "unSubscribeOrderbook",
value: function(MDReqID) {
return this.transport.sendMessage({
MsgType: ActionMsgReq.MD_FULL_REFRESH,
MDReqID: MDReqID,
MarketDepth: 0,
SubscriptionRequestType: "2"
}), MDReqID;
}
}, {
key: "executionReport",
value: function(callback) {
var _this8 = this;
return this.on(ActionMsgRes.EXECUTION_REPORT, function(data) {
callback && callback(data);
var event = EVENTS.EXECUTION_REPORT[data.ExecType];
return _this8.emit("".concat(EXECUTION_REPORT, ":").concat(event), data);
});
}
}, {
key: "tradeHistory",
value: function() {
var _ref2 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, since = _ref2.since, symbols = _ref2.symbols, _ref2$page = _ref2.page, Page = void 0 === _ref2$page ? 0 : _ref2$page, _ref2$pageSize = _ref2.pageSize, PageSize = void 0 === _ref2$pageSize ? 100 : _ref2$pageSize, callback = 1 < arguments.length ? arguments[1] : void 0, msg = {
MsgType: ActionMsgReq.TRADE_HISTORY,
TradeHistoryReqID: generateRequestId(),
Page: Page,
PageSize: PageSize
};
symbols && 0 < symbols.length && (msg.SymbolList = symbols), since && "number" == typeof since && (msg.Since = since);
var format = formatTradeHistory(this.level);
return nodeify_1.extend(this.send(msg).then(format)).nodeify(callback);
}
}, {
key: "requestDeposit",
value: function() {
var _this9 = this, _ref3 = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref3$currency = _ref3.currency, currency = void 0 === _ref3$currency ? "BTC" : _ref3$currency, value = _ref3.value, depositMethodId = _ref3.depositMethodId, callback = 1 < arguments.length ? arguments[1] : void 0, subscribeEvent = function(deposit) {
return callback && callback(null, deposit), _this9.emit(DEPOSIT_REFRESH, deposit);
};
return this.emitterPromise(new Promise(function(resolve, reject) {
return _get(_getPrototypeOf(BlinkTradeWS.prototype), "requestDeposit", _this9).call(_this9, {
currency: currency,
value: value,
depositMethodId: depositMethodId
}).then(function(deposit) {
return _this9.on(ActionMsgRes.DEPOSIT_REFRESH + ":" + deposit.ClOrdID, subscribeEvent),
resolve(deposit);
}).catch(reject);
}), callback);
}
}, {
key: "onDepositRefresh",
value: function(callback) {
return this.on(ActionMsgRes.DEPOSIT_REFRESH, callback);
}
}, {
key: "requestWithdraw",
value: function(_ref4, callback) {
var _this10 = this, amount = _ref4.amount, data = _ref4.data, _ref4$currency = _ref4.currency, currency = void 0 === _ref4$currency ? "BTC" : _ref4$currency, _ref4$method = _ref4.method, method = void 0 === _ref4$method ? "bitcoin" : _ref4$method, subscribeEvent = function(withdraw) {
return callback && callback(null, withdraw), _this10.emit(WITHDRAW_REFRESH, withdraw);
};
return this.emitterPromise(new Promise(function(resolve, reject) {
return _get(_getPrototypeOf(BlinkTradeWS.prototype), "requestWithdraw", _this10).call(_this10, {
amount: amount,
data: data,
currency: currency,
method: method
}).then(function(withdraw) {
return _this10.on(ActionMsgRes.WITHDRAW_REFRESH + ":" + withdraw.ClOrdID, subscribeEvent),
resolve(withdraw);
}).catch(reject);
}), callback);
}
}, {
key: "onWithdrawRefresh",
value: function(callback) {
return this.on(ActionMsgRes.WITHDRAW_REFRESH, callback);
}
} ]), BlinkTradeWS;
}(), invariant = function(condition, format, a, b, c, d, e, f) {
if ("production" !== process.env.NODE_ENV && void 0 === format) throw Error("invariant requires an error message argument");
if (!condition) {
var error;
if (void 0 === format) error = Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings."); else {
var args = [ a, b, c, d, e, f ], argIndex = 0;
(error = Error(format.replace(/%s/g, function() {
return args[argIndex++];
}))).name = "Invariant Violation";
}
throw error.framesToPop = 1, error;
}
}, browser = invariant, fetchBrowser = createCommonjsModule(function(module, exports) {
!function(self) {
module.exports = function(options) {
var Promise = options && options.Promise || self.Promise, XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest, global = self;
return function() {
var self = Object.create(global, {
fetch: {
value: void 0,
writable: !0
}
});
return function(self) {
if (!self.fetch) {
var support_searchParams = "URLSearchParams" in self, support_iterable = "Symbol" in self && "iterator" in Symbol, support_blob = "FileReader" in self && "Blob" in self && function() {
try {
return new Blob(), !0;
} catch (e) {
return !1;
}
}(), support_formData = "FormData" in self, support_arrayBuffer = "ArrayBuffer" in self;
if (support_arrayBuffer) var viewClasses = [ "[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]" ], isDataView = function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
}, isArrayBufferView = ArrayBuffer.isView || function(obj) {
return obj && -1 < viewClasses.indexOf(Object.prototype.toString.call(obj));
};
Headers.prototype.append = function(name, value) {
name = normalizeName(name), value = normalizeValue(value);
var oldValue = this.map[name];
this.map[name] = oldValue ? oldValue + "," + value : value;
}, Headers.prototype.delete = function(name) {
delete this.map[normalizeName(name)];
}, Headers.prototype.get = function(name) {
return name = normalizeName(name), this.has(name) ? this.map[name] : null;
}, Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name));
}, Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = normalizeValue(value);
}, Headers.prototype.forEach = function(callback, thisArg) {
for (var name in this.map) this.map.hasOwnProperty(name) && callback.call(thisArg, this.map[name], name, this);
}, Headers.prototype.keys = function() {
var items = [];
return this.forEach(function(value, name) {
items.push(name);
}), iteratorFor(items);
}, Headers.prototype.values = function() {
var items = [];
return this.forEach(function(value) {
items.push(value);
}), iteratorFor(items);
}, Headers.prototype.entries = function() {
var items = [];
return this.forEach(function(value, name) {
items.push([ name, value ]);
}), iteratorFor(items);
}, support_iterable && (Headers.prototype[Symbol.iterator] = Headers.prototype.entries);
var methods = [ "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT" ];
Request.prototype.clone = function() {
return new Request(this, {
body: this._bodyInit
});
}, Body.call(Request.prototype), Body.call(Response.prototype), Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
});
}, Response.error = function() {
var response = new Response(null, {
status: 0,
statusText: ""
});
return response.type = "error", response;
};
var redirectStatuses = [ 301, 302, 303, 307, 308 ];
Response.redirect = function(url, status) {
if (-1 == redirectStatuses.indexOf(status)) throw new RangeError("Invalid status code");
return new Response(null, {
status: status,
headers: {
location: url
}
});
}, self.Headers = Headers, self.Request = Request, self.Response = Response, self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request = new Request(input, init), xhr = new XMLHttpRequest();
xhr.onload = function() {
var rawHeaders, headers, options = {
status: xhr.status,
statusText: xhr.statusText,
headers: (rawHeaders = xhr.getAllResponseHeaders() || "", headers = new Headers(),
rawHeaders.split(/\r?\n/).forEach(function(line) {
var parts = line.split(":"), key = parts.shift().trim();
if (key) {
var value = parts.join(":").trim();
headers.append(key, value);
}
}), headers)
};
options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"),
resolve(new Response("response" in xhr ? xhr.response : xhr.responseText, options));
}, xhr.onerror = function() {
reject(new TypeError("Network request failed"));
}, xhr.ontimeout = function() {
reject(new TypeError("Network request failed"));
}, xhr.open(request.method, request.url, !0), "include" === request.credentials && (xhr.withCredentials = !0),
"responseType" in xhr && support_blob && (xhr.responseType = "blob"), request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
}), xhr.send(void 0 === request._bodyInit ? null : request._bodyInit);
});
}, self.fetch.polyfill = !0;
}
function normalizeName(name) {
if ("string" != typeof name && (name += ""), /[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) throw new TypeError("Invalid character in header field name");
return name.toLowerCase();
}
function normalizeValue(value) {
return "string" != typeof value && (value += ""), value;
}
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift();
return {
done: void 0 === value,
value: value
};
}
};
return support_iterable && (iterator[Symbol.iterator] = function() {
return iterator;
}), iterator;
}
function Headers(headers) {
this.map = {}, headers instanceof Headers ? headers.forEach(function(value, name) {
this.append(name, value);
}, this) : Array.isArray(headers) ? headers.forEach(function(header) {
this.append(header[0], header[1]);
}, this) : headers && Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name]);
}, this);
}
function consumed(body) {
if (body.bodyUsed) return Promise.reject(new TypeError("Already read"));
body.bodyUsed = !0;
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
}, reader.onerror = function() {
reject(reader.error);
};
});
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader(), promise = fileReaderReady(reader);
return reader.readAsArrayBuffer(blob), promise;
}
function bufferClone(buf) {
if (buf.slice) return buf.slice(0);
var view = new Uint8Array(buf.byteLength);
return view.set(new Uint8Array(buf)), view.buffer;
}
function Body() {
return this.bodyUsed = !1, this._initBody = function(body) {
if (this._bodyInit = body) if ("string" == typeof body) this._bodyText = body; else if (support_blob && Blob.prototype.isPrototypeOf(body)) this._bodyBlob = body; else if (support_formData && FormData.prototype.isPrototypeOf(body)) this._bodyFormData = body; else if (support_searchParams && URLSearchParams.prototype.isPrototypeOf(body)) this._bodyText = "" + body; else if (support_arrayBuffer && support_blob && isDataView(body)) this._bodyArrayBuffer = bufferClone(body.buffer),
this._bodyInit = new Blob([ this._bodyArrayBuffer ]); else {
if (!support_arrayBuffer || !ArrayBuffer.prototype.isPrototypeOf(body) && !isArrayBufferView(body)) throw Error("unsupported BodyInit type");
this._bodyArrayBuffer = bufferClone(body);
} else this._bodyText = "";
this.headers.get("content-type") || ("string" == typeof body ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : support_searchParams && URLSearchParams.prototype.isPrototypeOf(body) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"));
}, support_blob && (this.blob = function() {
var rejected = consumed(this);
if (rejected) return rejected;
if (this._bodyBlob) return Promise.resolve(this._bodyBlob);
if (this._bodyArrayBuffer) return Promise.resolve(new Blob([ this._bodyArrayBuffer ]));
if (this._bodyFormData) throw Error("could not read FormData body as blob");
return Promise.resolve(new Blob([ this._bodyText ]));
}, this.arrayBuffer = function() {
return this._bodyArrayBuffer ? consumed(this) || Promise.resolve(this._bodyArrayBuffer) : this.blob().then(readBlobAsArrayBuffer);
}), this.text = function() {
var blob, reader, promise, rejected = consumed(this);
if (rejected) return rejected;
if (this._bodyBlob) return blob = this._bodyBlob, reader = new FileReader(), promise = fileReaderReady(reader),
reader.readAsText(blob), promise;
if (this._bodyArrayBuffer) return Promise.resolve(function(buf) {
for (var view = new Uint8Array(buf), chars = Array(view.length), i = 0; i < view.length; i++) chars[i] = String.fromCharCode(view[i]);
return chars.join("");
}(this._bodyArrayBuffer));
if (this._bodyFormData) throw Error("could not read FormData body as text");
return Promise.resolve(this._bodyText);
}, support_formData && (this.formData = function() {
return this.text().then(decode);
}), this.json = function() {
return this.text().then(JSON.parse);
}, this;
}
function Request(input, options) {
var method, upcased, body = (options = options || {}).body;
if (input instanceof Request) {
if (input.bodyUsed) throw new TypeError("Already read");
this.url = input.url, this.credentials = input.credentials, options.headers || (this.headers = new Headers(input.headers)),
this.method = input.method, this.mode = input.mode, body || null == input._bodyInit || (body = input._bodyInit,
input.bodyUsed = !0);
} else this.url = input + "";
if (this.credentials = options.credentials || this.credentials || "omit", !options.headers && this.headers || (this.headers = new Headers(options.headers)),
this.method = (upcased = (method = options.method || this.method || "GET").toUpperCase(),
-1 < methods.indexOf(upcased) ? upcased : method), this.mode = options.mode || this.mode || null,
this.referrer = null, ("GET" === this.method || "HEAD" === this.method) && body) throw new TypeError("Body not allowed for GET or HEAD requests");
this._initBody(body);
}
function decode(body) {
var form = new FormData();
return body.trim().split("&").forEach(function(bytes) {
if (bytes) {
var split = bytes.split("="), name = split.shift().replace(/\+/g, " "), value = split.join("=").replace(/\+/g, " ");
form.append(decodeURIComponent(name), decodeURIComponent(value));
}
}), form;
}
function Response(bodyInit, options) {
options || (options = {}), this.type = "default", this.status = "status" in options ? options.status : 200,
this.ok = 200 <= this.status && this.status < 300, this.statusText = "statusText" in options ? options.statusText : "OK",
this.headers = new Headers(options.headers), this.url = options.url || "", this._initBody(bodyInit);
}
}(void 0 !== self ? self : this), {
fetch: self.fetch,
Headers: self.Headers,
Request: self.Request,
Response: self.Response
};
}();
};
}("undefined" != typeof self ? self : commonjsGlobal);
}), _fetchPonyfill = fetchBrowser({
Promise: Promise
}), _fetch = _fetchPonyfill.fetch, RestTransport = function(_Transport) {
function RestTransport() {
var _this, params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
return _classCallCheck(this, RestTransport), (_this = _possibleConstructorReturn(this, _getPrototypeOf(RestTransport).call(this, params, params.brokerId === BROKERS.BITCAMBIO ? "restBitcambio" : "rest"))).key = params.key,
_this.secret = params.secret, _this.currency = params.currency || "BRL", _this;
}
return _inherits(RestTransport, Transport), _createClass(RestTransport, [ {
key: "headers",
value: function(method, body) {
var timeStamp = "" + Date.now(), Signature = sha256.hmac.create(this.secret).update(timeStamp).hex();
return {
method: method,
headers: {
"Content-Type": "application/json",
Nonce: timeStamp,
APIKey: this.key,
Signature: Signature
},
body: JSON.stringify(body)
};
}
}, {
key: "fetch",
value: function(api) {
return _fetch(this.endpoint + api, 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}).then(function(response) {
return response.json();
});
}
}, {
key: "fetchPublic",
value: function(api) {
return this.fetch("api/v1/".concat(this.currency, "/").concat(api));
}
}, {
key: "fetchTrade",
value: function(msg) {
browser(this.key && this.secret, "Key or Secret not provided");
var headers = this.headers("POST", msg);
return this.fetch("tapi/v1/message", headers).then(function(response) {
return 500 === response.Status ? Promise.reject(response) : response.Responses;
}).then(function(response) {
return 1 === response.length ? response[0] : response;
});
}
} ]), RestTransport;
}(), BlinkTradeRest = function(_TradeBase) {
function BlinkTradeRest() {
var _this, params = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {};
return _classCallCheck(this, BlinkTradeRest), (_this = _possibleConstructorReturn(this, _getPrototypeOf(BlinkTradeRest).call(this, params))).transport = params.transport || new RestTransport(params),
_this;
}
return _inherits(BlinkTradeRest, TradeBase), _createClass(BlinkTradeRest, [ {
key: "send",
value: function(msg) {
return this.transport.fetchTrade(msg);
}
}, {
key: "fetchPublic",
value: function(path) {
return this.transport.fetchPublic(path);
}
}, {
key: "ticker",
value: function(callback) {
return nodeify_1.extend(this.fetchPublic("ticker")).nodeify(callback);
}
}, {
key: "trades",
value: function() {
var _ref = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, _ref$limit = _ref.limit, _ref$since = _ref.since, since = void 0 === _ref$since ? 0 : _ref$since, callback = 1 < arguments.length ? arguments[1] : void 0;
return nodeify_1.extend(this.fetchPublic("trades?limit=".concat(void 0 === _ref$limit ? 100 : _ref$limit, "&since=").concat(since))).nodeify(callback);
}
}, {
key: "orderbook",
value: function(callback) {
return nodeify_1.extend(this.fetchPublic("orderbook")).nodeify(callback);
}
} ]), BlinkTradeRest;
}();
exports.Brokers = BROKERS, exports.BlinkTradeWS = BlinkTradeWS, exports.BlinkTradeRest = BlinkTradeRest,
Object.defineProperty(exports, "__esModule", {
value: !0
});
});