Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cryptomarket

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cryptomarket - npm Package Compare versions

Comparing version 1.0.0 to 1.0.1

.eslintrc.json

44

lib/Base.js

@@ -1,31 +0,27 @@

"use strict";
/* eslint-disable no-prototype-builtins */
/* eslint-disable class-methods-use-this */
const assign = require('object-assign');
var assign = require('object-assign');
class Base {
hasField(obj, field) {
return (obj && obj.hasOwnProperty(field) && obj[field]);
}
function Base() {
if(!(this instanceof Base)) {
return new Base()
getProps() {
const tmp = {};
assign(tmp, this);
delete tmp.client;
delete tmp.account;
return tmp;
}
}
Base.prototype.hasField = function(obj, field) {
return (obj && obj.hasOwnProperty(field) && obj[field]);
dumpJSON() {
return JSON.stringify(this.getProps());
}
toString() {
return this.dumpJSON();
}
}
Base.prototype.getProps = function() {
var tmp = {};
assign(tmp, this);
delete tmp.client;
delete tmp.account;
return tmp;
};
Base.prototype.dumpJSON = function() {
return JSON.stringify(this.getProps());
};
Base.prototype.toString = function() {
return this.dumpJSON();
};
module.exports = Base;

@@ -1,153 +0,242 @@

"use strict";
/* eslint-disable no-underscore-dangle */
var ClientBase = require('./ClientBase'),
request = require("request"),
handleError = require('./ErrorHandler').handleError,
Order = require("./model/Order"),
crypto = require("crypto"),
_ = require("lodash"),
qs = require("querystring"),
assign = require("object-assign");
const _ = require('lodash');
function Client(opts) {
const ClientBase = require('./ClientBase');
const Socket = require('./Socket');
// const {
// Order,
// } = require('./model');
if (!(this instanceof Client)) {
return new Client(opts);
}
ClientBase.call(this, opts);
}
Client.prototype = Object.create(ClientBase.prototype);
class Client extends ClientBase {
constructor(opts) {
super(opts);
this.socket = new Socket(this);
}
Client.prototype.getMarkets = function(args, callback) {
// REST
// ===============================================================================================
var opts = {
'path': 'market',
};
getMarkets(callback = null) {
const opts = {
path: 'market',
};
this._getOneHttp(opts, 'base', callback);
};
return this._getOneHttp(opts, 'base', callback);
}
Client.prototype.getTicker = function(args, callback) {
getTicker(args, callback) {
// if (!args.market) throw new Error('market not provided');
if(!args.market) throw new Error("market not provided");
var opts = {
'path': 'ticker',
'params': args
};
const opts = {
path: 'ticker',
params: args,
};
this._getOneHttp(opts, 'base', callback);
};
return this._getOneHttp(opts, 'base', callback);
}
Client.prototype.getOrders = function(args, callback) {
getBook(args, callback) {
if (!args.market) throw new Error('market not provided');
if (!args.side) throw new Error('type not provided');
if(!args.market) throw new Error("market not provided");
if(!args.type) throw new Error("type not provided");
const opts = {
path: 'book',
params: args,
};
var opts = {
'path': 'book',
'params': args
};
return this._getOneHttp(opts, 'base', callback);
}
this._getOneHttp(opts, 'base', callback);
};
getTrades(args, callback) {
if (!args.market) throw new Error('market not provided');
Client.prototype.getTrades = function(args, callback) {
const opts = {
path: 'trades',
params: args,
};
if(!args.market) throw new Error("market not provided");
return this._getOneHttp(opts, 'base', callback);
}
var opts = {
'path': 'trades',
'params': args
};
getActiveOrders(args, callback) {
if (!args.market) throw new Error('market not provided');
this._getOneHttp(opts, 'base', callback);
}
const opts = {
path: 'orders/active',
params: args,
};
Client.prototype.getActiveOrders = function(args, callback) {
return this._getOneHttp(opts, 'base', callback);
}
if(!args.market) throw new Error("market not provided");
getExecutedOrders(args, callback) {
if (!args.market) throw new Error('market not provided');
var opts = {
'path': 'orders/active',
'params': args,
};
const opts = {
path: 'orders/executed',
params: args,
};
this._getOneHttp(opts, 'base', callback);
};
return this._getOneHttp(opts, 'base', callback);
}
Client.prototype.getExecutedOrders = function(args, callback) {
createOrder(args, callback) {
if (!args.market) throw new Error('market not provided');
if (!args.type) throw new Error('type not provided');
if (!args.side) throw new Error('side not provided');
if (!args.amount) throw new Error('amount not provided');
if(!args.market) throw new Error("market not provided");
// optional args.price. required for limit and stop-limit order
// optional args.limit. required for stop-limit order
var opts = {
'path': 'orders/executed',
'params': args,
};
const opts = {
path: 'orders/create',
params: args,
this._getOneHttp(opts, 'base', callback);
};
// 'colName' : 'orders',
// 'ObjFunc' : Order,
};
Client.prototype.getExecutedOrders = function(args, callback) {
return this._postOneHttp(opts, 'base', callback);
}
if(!args.market) throw new Error("market not provided");
createMultiOrders(args, callback) {
_.forEach(args, (arg) => {
if (!arg.market) throw new Error('market not provided');
if (!arg.type) throw new Error('type not provided');
if (!arg.side) throw new Error('side not provided');
if (!arg.amount) throw new Error('amount not provided');
// optional arg.price. required for limit and stop-limit order
// optional arg.limit. required for stop-limit order
});
var opts = {
'path': 'orders/executed',
'params': args,
};
const opts = {
path: 'orders/create/bulk',
params: {
orders: JSON.stringify(args),
},
};
return this._postOneHttp(opts, 'base', callback);
}
this._getOneHttp(opts, 'base', callback);
};
getOrderStatus(args, callback) {
if (!args.id) throw new Error('order id not provided');
Client.prototype.createOrder = function(args, callback) {
const opts = {
path: 'orders/status',
params: args,
};
if(!args.market) throw new Error("market not provided");
if(!args.amount) throw new Error("amount not provided");
if(!args.price) throw new Error("price not provided");
if(!args.type) throw new Error("type not provided");
return this._getOneHttp(opts, 'base', callback);
}
var opts = {
'path': 'orders/create',
'params': args
};
cancelOrder(args, callback) {
if (!args.id) throw new Error('id not provided');
this._postOneHttp(opts, 'base', callback);
};
const opts = {
path: 'orders/cancel',
params: args,
};
Client.prototype.getOrderStatus = function(args, callback) {
return this._postOneHttp(opts, 'base', callback);
}
if(!args.id) throw new Error("order id not provided");
cancelMultiOrders(args, callback) {
_.forEach(args, (arg) => {
if (!arg.id) throw new Error('id not provided');
});
var opts = {
'path': 'orders/status',
'params': args,
};
const opts = {
path: 'orders/cancel/bulk',
params: {
ids: JSON.stringify(args),
},
};
this._getOneHttp(opts, 'base', callback);
};
return this._postOneHttp(opts, 'base', callback);
}
Client.prototype.cancelOrder = function(args, callback) {
transfer(args, callback) {
if (!args.currency) throw new Error('address not provided');
if (!args.address) throw new Error('address not provided');
if (!args.amount) throw new Error('address not provided');
if(!args.id) throw new Error("order id not provided");
// optional args.memo
var opts = {
'path': 'orders/cancel',
'params': args
};
const opts = {
path: 'transfer',
params: args,
};
this._postOneHttp(opts, 'base', callback);
};
return this._postOneHttp(opts, 'base', callback);
}
Client.prototype.getBalance = function(args, callback) {
notifyDeposit(args, callback) {
if (!args.bank_account) throw new Error('bank_account not provided');
if (!args.amount) throw new Error('amount not provided');
var opts = {
'path': 'balance',
'params': args
};
// optional args.tracking_code. required for mxn
// optional args.date. required for mxn
// optional args.voucher. required for mxn, brl, ars, eur
this._getOneHttp(opts, 'base', callback);
};
const opts = {
path: 'deposit',
params: args,
};
module.exports = Client;
return this._postOneHttp(opts, 'base', callback);
}
notifyWithdrawal(args, callback) {
if (!args.bank_account) throw new Error('bank_account not provided');
if (!args.amount) throw new Error('amount not provided');
const opts = {
path: 'withdrawal',
params: args,
};
return this._postOneHttp(opts, 'base', callback);
}
getAccount(callback) {
const opts = {
path: 'account',
};
return this._getOneHttp(opts, 'base', callback);
}
getTransactions(args, callback) {
if (!args.currency) throw new Error('currency not provided');
const opts = {
path: 'transactions',
params: args,
};
return this._getOneHttp(opts, 'base', callback);
}
getBalance(callback) {
const opts = {
path: 'balance',
};
return this._getOneHttp(opts, 'base', callback);
}
// SOCKET
// ======================================================================
_getAuthSocket() {
const opts = {
path: 'socket/auth',
};
return this._getOneHttp(opts, 'base');
}
}
module.exports = Client;

@@ -1,19 +0,24 @@

"use strict";
/* eslint-disable class-methods-use-this */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-underscore-dangle */
const request = require('request');
const crypto = require('crypto');
const _ = require('lodash');
const assign = require('object-assign');
var request = require('request'),
handleError = require('./ErrorHandler').handleError,
handleHttpError = require('./ErrorHandler').handleHttpError,
BaseModel = require('./model/BaseModel'),
Base = require('./Base'),
Order = require('./model/Order'),
crypto = require('crypto'),
_ = require('lodash'),
qs = require('querystring'),
assign = require('object-assign');
const Base = require('./Base');
const {
BaseModel,
Order,
} = require('./model');
const {
handleError,
handleHttpError,
} = require('./ErrorHandler');
var BASE_URI = 'https://api.cryptomkt.com/v1/';
const BASE_URI = 'https://api.cryptomkt.com/v2/';
var MODELS = {
'base': BaseModel,
'order': Order
const MODELS = {
base: BaseModel,
order: Order,
};

@@ -30,214 +35,245 @@

function ClientBase(opts) {
if (!(this instanceof ClientBase)) {
return new ClientBase(opts);
class ClientBase extends Base {
constructor(opts) {
super();
assign(this, {
baseApiUri: BASE_URI,
strictSSL: true,
timeout: 5000,
}, opts);
this.api = !!(this.apiKey && this.apiSecret);
if (!(this.api)) {
throw new Error('you must either provide the "apiKey" & "apiSecret" parameters');
}
}
// assign defaults and options to the context
assign(this, {
baseApiUri: BASE_URI
}, opts);
_generateSignature(path, bodyStr) {
let values = '';
const keys = [];
// check for the different auth strategies
var api = !!(this.apiKey && this.apiSecret)
};
_.forIn(bodyStr, (value, key) => {
keys.push(key);
});
ClientBase.prototype = Object.create(Base.prototype);
keys.sort();
// private methods
for (let i = 0; i < keys.length; i += 1) {
values += bodyStr[keys[i]];
}
ClientBase.prototype._setAccessToken = function(path) {
const timestamp = Math.floor(Date.now() / 1000);
const message = `${timestamp}/v2/${path}${values}`;
const signature = crypto.createHmac('sha384', this.apiSecret).update(message).digest('hex');
// OAuth access token
if (this.accessToken) {
if (path.indexOf('?') > -1) {
return path + '&access_token=' + this.accessToken;
}
return path + '?access_token=' + this.accessToken;
}
return path
};
return {
digest: signature,
timestamp,
};
}
ClientBase.prototype._generateSignature = function(path, bodyStr) {
var values = "";
var keys = [];
_generateReqOptions(method, url, path, params, headers) {
const parameters = params || {};
for (var key in bodyStr) {
keys.push(key);
}
// specify the options
const options = {
url: url + path,
strictSSL: this.strictSSL,
timeout: this.timeout,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'User-Agent': 'cryptomkt/node/1.0.0',
},
};
keys.sort();
if (method === 'get') {
options.qs = parameters;
} else if (method === 'post') {
options.form = parameters;
}
for(var i = 0; i < keys.length; i++){
values += bodyStr[keys[i]];
}
options.headers = headers || {};
var timestamp = Math.floor(Date.now() / 1000);
var message = timestamp + '/v1/' + path + values;
var signature = crypto.createHmac('sha384', this.apiSecret).update(message).digest('hex');
if (this.apiSecret && this.apiKey) {
let sig;
if (method === 'get') {
sig = this._generateSignature(path, {});
} else {
sig = this._generateSignature(path, params);
}
return {
'digest': signature,
'timestamp': timestamp
};
};
options.headers = assign(options.headers, {
'X-MKT-SIGNATURE': sig.digest,
'X-MKT-TIMESTAMP': sig.timestamp,
'X-MKT-APIKEY': this.apiKey,
});
}
return options;
}
ClientBase.prototype._generateReqOptions = function(url, path, params, body, headers) {
var body = body || '';
_newApiObject(client, obj, cls) {
let Cls = cls;
// specify the options
var options = {
'url': url,
'formData': body,
};
if (obj instanceof Array) {
return obj.map((x) => this._newApiObject(client, x, Cls));
}
options.headers = headers || {};
if (typeof obj === 'string') {
if (obj === 'null') return null;
return obj;
}
if (this.apiSecret && this.apiKey) {
var sig = this._generateSignature(path, body);
if (obj === null) {
return obj;
}
options.headers = assign(options.headers, {
'X-MKT-SIGNATURE': sig.digest,
'X-MKT-TIMESTAMP': sig.timestamp,
'X-MKT-APIKEY': this.apiKey,
});
}
if (typeof obj === 'number') {
return obj;
}
return options;
};
if (!Cls) {
Cls = BaseModel;
}
ClientBase.prototype._newApiObject = function(client, obj, cls){
var self = this;
if(obj instanceof Array){
return obj.map(function(x){
return self._newApiObject(client, x, cls);
});
}else if(typeof obj === "string"){
return obj;
}else{
if(!cls)
cls = BaseModel;
var result = new cls(client);
var keys = _.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
const result = {};
const keys = _.keys(obj);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (obj.hasOwnProperty(key)) {
var dict = {};
dict[''+ key + ''] = self._newApiObject(client, obj[key]);
assign(result, dict);
result[key] = this._newApiObject(client, obj[key]);
}
}
return result;
return new Cls(client, result);
}
return obj;
};
_makeApiObject(response, model) {
const _response = {
response,
};
if (response.pagination) {
_response.pagination = response.pagination;
}
ClientBase.prototype._makeApiObject = function(response, model) {
let obj;
var _response = {
'response': response,
'pagination': response.pagination || this._newApiObject(null, response.pagination, BaseModel),
}
if (response.data instanceof Array) {
const ObjFunc = this._stringToClass('base');
obj = new ObjFunc(this, _response);
assign(obj, {
data: this._newApiObject(this, response.data, model),
});
} else {
obj = { data: this._newApiObject(this, response.data, model) };
assign(obj, _response);
}
if(response.data instanceof Array){
var ObjFunc = this._stringToClass('base');
var obj = new ObjFunc(this, _response);
assign(obj, {"data": this._newApiObject(this, response.data, model)});
}else{
var obj = this._newApiObject(this, response.data, model);
assign(obj, _response);
return obj;
}
return obj;
};
_getHttp(path, args, callback, headers) {
let params = {};
if (args && !_.isEmpty(args)) {
params = args;
}
ClientBase.prototype._getHttp = function(path, args, callback, headers) {
const url = this.baseApiUri;
const opts = this._generateReqOptions('get', url, path, params, headers);
var params = '';
if (args && !_.isEmpty(args)) {
params = '?' + qs.stringify(args);
}
var url = this.baseApiUri + this._setAccessToken(path + params);
var opts = this._generateReqOptions(url, path , params, null, headers);
request.get(opts, function onGet(err, response, body) {
if (!handleHttpError(err, response, callback)) {
if (!body) {
callback(new Error("empty response"), null);
request.get(opts, (err, response, body) => {
const error = handleHttpError(err, response);
if (!_.isNil(error)) {
callback(error, null);
} else if (!body) {
callback(new Error('empty response'), null);
} else {
var obj = JSON.parse(body);
const obj = JSON.parse(body);
callback(null, obj);
}
});
}
_postHttp(path, args, callback, headers) {
let params = {};
if (args && !_.isEmpty(args)) {
params = args;
}
});
};
ClientBase.prototype._postHttp = function(path, body, callback, headers) {
const url = this.baseApiUri;
var url = this.baseApiUri + this._setAccessToken(path);
body = body || {}
const options = this._generateReqOptions('post', url, path, params, headers);
var options = this._generateReqOptions(url, path, null ,body, headers);
request.post(options, function onPost(err, response, body) {
if (!handleHttpError(err, response, callback)) {
if (body) {
var obj = JSON.parse(body);
callback(null, obj);
request.post(options, (err, response, body) => {
const error = handleHttpError(err, response);
if (!_.isNil(error)) {
callback(error, null);
} else if (!body) {
callback(new Error('empty response'), null);
} else {
callback(null, body);
}
}
});
};
//
// args = {
// 'path' : path,
// 'params' : params,
// }
//
ClientBase.prototype._getOneHttp = function(args, model, callback, headers) {
var self = this;
this._getHttp(args.path, args.params, function onGet(err, obj) {
if (!handleError(err, obj, callback)) {
if (obj.data) {
var ObjFunc = self._stringToClass(model);
callback(null, self._makeApiObject(obj, ObjFunc))
} else {
const obj = JSON.parse(body);
callback(null, obj);
}
}
}, headers);
};
});
}
//
// opts = {
// 'path' : path,
// 'params' : args
// }
//
ClientBase.prototype._postOneHttp = function(opts, model, callback, headers) {
var self = this;
this._postHttp(opts.path, opts.params, function onPost(err, obj) {
if (!handleError(err, obj, callback)) {
if (obj.data) {
var ObjFunc = self._stringToClass(model);
callback(null, new ObjFunc(self, obj.data, obj.pagination, obj.warning));
} else {
callback(null, obj);
}
}
}, headers);
};
/**
* args = {
* 'path' : path,
* 'params' : params,
* }
*/
_getOneHttp(args, model, callback, headers) {
const cb = callback || function () {};
return new Promise((resolve, reject) => {
this._getHttp(args.path, args.params, (err, obj) => {
const error = handleError(err, obj);
if (!_.isNil(error)) {
reject(error);
cb(error, null);
} else if (obj.data) {
const ObjFunc = this._stringToClass(model);
resolve(this._makeApiObject(obj, ObjFunc));
// resolve(new ObjFunc(this, obj.data));
cb(null, this._makeApiObject(obj, ObjFunc));
// callback(null, new ObjFunc(this, obj.data));
} else {
resolve(obj);
cb(null, obj);
}
}, headers);
});
}
ClientBase.prototype._stringToClass = function(name) {
return MODELS[name]
};
_postOneHttp(args, model, callback, headers) {
const cb = callback || function () {};
return new Promise((resolve, reject) => {
this._postHttp(args.path, args.params, (err, obj) => {
const error = handleError(err, obj);
if (!_.isNil(error)) {
reject(error);
callback(error, null);
} else if (obj.data) {
const ObjFunc = this._stringToClass(model);
// resolve(new ObjFunc(this, obj.data));
// resolve(new ObjFunc(this, obj.data));
// callback(null, new ObjFunc(this, obj.data));
// cb(null, new ObjFunc(this, obj.data));
resolve(this._makeApiObject(obj, ObjFunc));
// resolve(new ObjFunc(this, obj.data));
cb(null, this._makeApiObject(obj, ObjFunc));
// callback(null, new ObjFunc(this, obj.data));
} else {
resolve(obj);
cb(null, obj);
}
}, headers);
});
}
module.exports = ClientBase;
_stringToClass(name) {
return MODELS[name];
}
}
module.exports = ClientBase;

@@ -1,87 +0,76 @@

"use strict";
/* eslint-disable no-underscore-dangle */
const createError = require('http-errors');
var createError = require('http-errors');
const statusCodeToClass = {
400: 'InvalidRequestError',
401: 'AuthenticationError',
402: 'TwoFactorRequiredError',
403: 'InvalidScopeError',
404: 'NotFoundError',
422: 'ValidationError',
429: 'RateLimitExceededError',
500: 'InternalServerError',
503: 'ServiceUnavailableError',
};
var status_code_to_class = {
"400" : "InvalidRequestError",
"401" : "AuthenticationError",
"402" : "TwoFactorRequiredError",
"403" : "InvalidScopeError",
"404" : "NotFoundError",
"422" : "ValidationError",
"429" : "RateLimitExceededError",
"500" : "InternalServerError",
"503" : "ServiceUnavailableError",
}
function _parseError(error) {
if (error.errors) {
return error.errors[0];
}
if (error.errors) {
return error.errors[0];
}
return {
status: error.status,
message: error.message,
};
}
return {
status: error.status,
message: error.message
};
};
function handleHttpError(err, response, callback) {
if (!callback) {
throw new Error("no callback for http error handler- check method signature");
}
if (err) {
callback(err, null);
return true;
}
if (!response) {
callback(createError('no response'), null);
return true;
}
if (response.statusCode !== 200 &&
response.statusCode !== 201 &&
response.statusCode !== 204) {
var error;
try {
var errorBody = _parseError(JSON.parse(response.body));
error = createError(response.statusCode,
errorBody.message,
{name: status_code_to_class[response.statusCode]});
} catch (ex) {
error = createError(response.statusCode, response.body);
}
callback(error, null);
return true;
}
return false;
function handleHttpError(err, response) {
if (err) {
return err;
}
if (!response) {
return createError('no response');
}
if (response.statusCode !== 200 && response.statusCode !== 201 && response.statusCode !== 204) {
let error;
try {
const errorBody = _parseError(JSON.parse(response.body));
error = createError(response.statusCode,
errorBody.message, {
name: statusCodeToClass[response.statusCode],
});
} catch (ex) {
error = createError(response.statusCode, response.body);
}
return error;
}
return null;
}
function handleError(err, obj, callback) {
function handleError(err, obj) {
if (err) {
return err;
}
if (obj.error) {
return createError(obj.error, {
name: 'APIError',
});
}
if (obj.errors) {
return createError(obj, {
name: 'APIError',
});
}
if (obj.success !== undefined && obj.success !== true) {
return createError(obj, {
name: 'APIError',
});
}
if (!callback) {throw "no callback - check method signature";}
if (err) {
callback(err, null);
return true;
}
if (obj.error) {
callback(createError(obj.error, {name: 'APIError'}), null);
return true;
}
if (obj.errors) {
callback(createError(obj, {name: 'APIError'}), null);
return true;
}
if (obj.success !== undefined && obj.success !== true) {
callback(createError(obj, {name: 'APIError'}), null);
return true;
}
return false;
return null;
}
module.exports.handleError = handleError;
module.exports.handleHttpError = handleHttpError;
module.exports = {
handleError,
handleHttpError,
};

@@ -1,16 +0,21 @@

"use strict";
const assign = require('object-assign');
const _ = require('lodash');
var Base = require('../Base');
var assign = require('object-assign');
const Base = require('../Base');
function BaseModel(client, data, pagination, warning) {
if (!(this instanceof BaseModel)) {
return new BaseModel(client, data);
}
// this.client = client;
assign(this, data);
class BaseModel extends Base {
constructor(client, data) {
super();
if (_.isNil(client)) {
throw new Error('client is null');
}
if (_.isNil(data)) {
throw new Error('data is null');
}
this.client = client;
assign(this, data);
}
}
BaseModel.prototype = Object.create(Base.prototype);
module.exports = BaseModel;
module.exports = BaseModel;

@@ -1,15 +0,13 @@

"use strict";
const BaseModel = require('./BaseModel');
// const {
// handleError,
// } = require('../ErrorHandler');
var BaseModel = require('./BaseModel'),
handleError = require('../ErrorHandler').handleError;
function Order(client, data) {
if (!(this instanceof Order)) {
return new Order(client, data);
}
BaseModel.call(this, client, data);
class Order extends BaseModel {
constructor(client, data, pagination) {
super(client, data);
this.pagination = pagination;
}
}
Order.prototype = Object.create(BaseModel.prototype);
module.exports = Order;
module.exports = Order;
{
"name": "cryptomarket",
"version": "1.0.0",
"description": "The CryptoMarket for Node.js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"directories": {
"lib": "./lib"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cryptomkt/cryptomkt-node.git"
},
"keywords": [
"API",
"CryptoMarket",
"CryptoMkt",
"exchange",
"ethereum",
"ether"
],
"author": "CryptoMarket",
"license": "MIT",
"bugs": {
"url": "https://github.com/cryptomkt/cryptomkt-node/issues"
},
"homepage": "https://github.com/cryptomkt/cryptomkt-node#readme",
"dependencies": {
"crypto": "^1.0.1",
"http-errors": "^1.6.2",
"lodash": "^4.17.4",
"object-assign": "^4.1.1",
"querystring": "^0.2.0",
"request": "^2.82.0"
}
"name": "cryptomarket",
"version": "1.0.1",
"description": "The CryptoMarket for Node.js",
"homepage": "https://www.cryptomkt.com",
"main": "./index.js",
"author": "Pedro Bustamante",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"engines": {
"node": "*"
},
"directories": {
"lib": "./lib"
},
"repository": {
"type": "git",
"url": "https://github.com/cryptomkt/cryptomkt-node.git"
},
"bugs": {
"url": "https://github.com/cryptomkt/cryptomkt-node/issues"
},
"keywords": [
"api",
"cryptomarket",
"cryptomkt",
"exchange",
"ethereum",
"ether",
"bitcoin",
"btc",
"eos",
"stellar",
"xlm"
],
"license": "Apache-2.0",
"dependencies": {
"http-errors": "1.7.3",
"js-event-bus": "1.0.0",
"jsondiffpatch": "0.4.1",
"lodash": "4.17.15",
"object-assign": "4.1.1",
"request": "2.88.0",
"socket.io-client": "2.3.0"
},
"devDependencies": {
"eslint": "6.7.2",
"eslint-config-airbnb-base": "14.0.0",
"eslint-plugin-import": "2.18.2"
}
}

@@ -1,1 +0,797 @@

# cryptomkt-node
# cryptomkt-node
## Installation
`npm install cryptomarket`
## Quick Start
The first thing you'll need to do is [sign up for cryptomkt](https://www.cryptomkt.com).
## API Key
If you're writing code for your own CryptoMarket account, [enable an API key](https://www.cryptomkt.com/platform/account#api_tab). Next, create a ``Client`` object for interacting with the API:
```javascript
var { Client } = require('cryptomarket');
var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});
```
## Making API Calls
With a `client instance`, you can now make API calls. We've included some examples below. Each API method returns an ``object`` representing the JSON response from the API.
### Public endpoints
**Using the functions**
Client functions returns Promises(ECMAScript 2015), these functions can be called by three different ways: Then method, Await operator or a Callback function.
***Example***
```javascript
async function example(){
// Method 1: standard promise (Then)
client.getMarkets()
.then((obj) => {
const data = obj.data;
console.log(data);
}).catch((err) => {
console.error(err);
})
// Method 2: Await promise
try {
let result = await client.getMarkets();
console.log(result);
} catch (e){
console.error(err);
}
// Method 3: Callback
client.getMarkets(function(error, result){
if(error){
console.error(err);
return;
}
console.log(result);
})
}
example();
```
***Expected output***
```javascript
//Any of the 3 ways to call the function should return an output like this
response: {
status: 'success',
data: [
'ETHCLP', 'ETHARS', 'ETHEUR',
'ETHBRL', 'ETHMXN', 'XLMCLP',
'XLMARS', 'XLMEUR', 'XLMBRL',
'XLMMXN', 'BTCCLP', 'BTCARS',
'BTCEUR', 'BTCBRL', 'BTCMXN',
'EOSCLP', 'EOSARS', 'EOSEUR',
'EOSBRL', 'EOSMXN'
]
}
````
**Listing available markets**
```javascript
var { Client } = require('cryptomarket');
var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getMarkets()
.then((obj) => {
const data = obj.data;
data.forEach((market) => {
console.log(data);
});
}).catch((err) => {
console.error(err);
})
```
***Expected output***
```javascript
[
'ETHCLP', 'ETHARS', 'ETHEUR',
'ETHBRL', 'ETHMXN', 'XLMCLP',
'XLMARS', 'XLMEUR', 'XLMBRL',
'XLMMXN', 'BTCCLP', 'BTCARS',
'BTCEUR', 'BTCBRL', 'BTCMXN',
'EOSCLP', 'EOSARS', 'EOSEUR',
'EOSBRL', 'EOSMXN'
]
...
```
**Obtain Book**
```javascript
//receives a Js object. "market" and "side" are mandatory (ex: {"market": "XLMCLP","side":"sell"}).
client.getBook(dictionary, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
{
"status": "success",
"pagination": {
"previous": 0,
"limit": 20,
"page": 0,
"next": "null"
},
"data": [
BaseModel {
client: [Client],
price: '59.8',
amount: '20025.749',
timestamp: '2020-02-21T04:16:07.789000'
},
BaseModel {
client: [Client],
price: '59.8',
amount: '29736.0992',
timestamp: '2020-02-21T04:20:30.925000'
},
BaseModel {
client: [Client],
price: '59.8',
amount: '24229.3228',
timestamp: '2020-02-21T04:32:26.686000'
}
...
]
```
**Obtain ticker info**
```javascript
//receives a Js object that contains the market. (ex: {"market":"XLMARS"})
client.getTicker(market, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
{
"status": "success",
"data": [
{
client: [Client],
timestamp: '2020-02-21T04:52:17.416448',
market: 'XLMCLP',
bid: '58.2',
ask: '68.4',
last_price: '59.75',
low: '56',
high: '58.3',
volume: '87572.82220768983161'
}
]
}
```
### Authenticated endpoints
**Get account info**
```javascript
var { Client } = require('cryptomarket');
var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccount()
.then((obj) => {
const data = obj.data;
console.log(data);
}).catch((err) => {
console.error(err);
})
```
***Expected output***
```javascript
{
name: 'John Doe',
email: 'john.doe@gmail.com',
rate: BaseModel {
client: <ref *1> Client {
baseApiUri: 'https://api.cryptomkt.com/v2/',
strictSSL: true,
timeout: 5000,
apiKey: 'FS24FJ7',
apiSecret: 'SFT23GSD',
api: true,
socket: [Socket]
},
market_maker: '0.0039',
market_taker: '0.0068'
},
bank_accounts: [
BaseModel {
client: [Client],
id: 00001,
bank: 'BANCO DE CHILE - EDWARDS',
description: '',
country: 'CL',
number: '1234567890',
dv: null,
agency: null,
clabe: ''
}
]
}
```
**Create an order**
```javascript
//receives a Js object. "market","type","side" and "amount" are mandatory. (ex: {"amount": 1, "market": "XLMCLP", "price": 50.5, "type": "limit", "side": "sell"}).
client.createOrder(order, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
response: {
status: 'success',
data: {
id: 'O000001',
amount: [Object],
price: '50.5',
stop: null,
avg_execution_price: '0',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0',
created_at: '2020-02-21T05:08:58.700000',
updated_at: '2020-02-21T05:08:58.768314',
status: 'filled'
}
}
```
**Create multiple orders**
```javascript
//receives object array that contains multiple orders. "market","type","side" and "amount" are mandatory. (ex: [{"amount": 1, "market": "XLMCLP", "price": 50.5, "type": "limit", "side": "sell"},{Order2},...]).
client.createMultiOrders(orders, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
response: {
status: 'success',
data: {
created: [{Order1},{Order2},...],
not_created: []
}
}
```
**Obtain active orders**
```javascript
//receives a Js object that contains the market (ex: {"market":"XLMCLP"})
client.getActiveOrders(market, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
{
status: 'success',
pagination: { page: 0, limit: 20, next: null, previous: null },
data: [
BaseModel {
client: [Client],
id: 'O000001',
amount: [BaseModel],
price: '72',
stop: null,
avg_execution_price: '0',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0',
created_at: '2020-02-21T14:05:30.313000',
updated_at: '2020-02-21T14:05:30.334726',
status: 'queued'
},
BaseModel {
client: [Client],
id: 'O000002',
amount: [BaseModel],
price: '71',
stop: null,
avg_execution_price: '0',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0',
created_at: '2020-02-21T14:05:30.216000',
updated_at: '2020-02-21T14:05:30.245189',
status: 'queued'
}
...
]
}
```
**Cancel an order**
```javascript
//receives object that contains the order's ID (ex: {"id":"O000004"}).
client.cancelOrder(order, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
response: {
status: 'success',
data: {
id: 'O000004',
amount: [Object],
price: '72',
stop: null,
avg_execution_price: '0',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0',
created_at: '2020-02-21T14:05:30.313000',
updated_at: '2020-02-21T14:24:08.897689',
status: 'cancelled'
}
}
```
**Cancel multiple orders**
```javascript
//receives object array that contains multiple order's IDs (ex: [{"id":"O000001"},{"id":"O000002"},...]).
client.cancelMultiOrders(orders, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
response: {
status: 'success',
data: { canceled: [{Order1},{Order2},...], not_canceled: [] } }
```
**Make a transfer**
```javascript
//receives a Js object. "currency", "address", and "amount" are mandatory. (ex: {"currency":'ETH',"address":'0xf2ec...',"amount":0.02}).
client.transfer(transfer, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
{ status: 'success', data: '' }
```
**Obtain executed orders**
```javascript
//receives a Js object that contains the market (ex: {"market":"XLMCLP"})
client.getExecutedOrders(market, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
{
"status": "success",
"pagination": {
"previous": "null",
"limit": 20,
"page": 0,
"next": "null"
},
"data": [
client: [Client],
id: 'O000003',
amount: {
"original": "1.4044",
"remaining": "1.4044"
},
price: '50.5',
stop: null,
avg_execution_price: '58',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0.394',
created_at: '2020-02-21T05:08:58.700000',
updated_at: '2020-02-21T05:08:59.549126',
status: 'filled',
fills: [Array]
]
}
```
**Obtain order status**
```javascript
//receives a Js object that contains the ID (ex: {"id":"O000005"})
client.getOrderStatus(id, (err, output) => {
if(err){
console.log('error');
}
console.log(output);
});
```
***Expected output***
```javascript
response: {
status: 'success',
data: {
id: 'O000005',
amount: [Object],
price: '71',
stop: null,
avg_execution_price: '0',
market: 'XLMCLP',
type: 'limit',
side: 'sell',
fee: '0',
created_at: '2020-02-21T14:05:30.216000',
updated_at: '2020-02-21T14:05:30.245189',
status: 'queued',
fills: []
}
}
```
**Obtain account balance**
```javascript
client.getBalance((err, output) => {
if(err){
console.log('error');
return
}
console.log(output);
});
```
***Expected Output***
```javascript
{
"status": "success",
"data": [
{
"available": "1203.1231",
"wallet": "CLP",
"balance": "120347"
},
{
"available": "10.3399",
"wallet": "ETH",
"balance": "11.3399"
},
...
]
}
```
## Using socket
### Get socket instance
```javascript
var { Client } = require('cryptomarket');
var client = new Client({'apiKey': mykey, 'apiSecret': mysecret});
var socket;
client.socket.connect()
.then((skt) => {
socket = skt
}).catch((err) => {
console.error(err);
});
//or
var socket= await client.socket.connect();
```
### Receive socket events
**Market subscription**
```javascript
socket.subscribe('ETHCLP');
```
**Unsubscribe from market**
```javascript
socket.unsubscribe('ETHCLP');
```
**Receive open book info**
```javascript
// Subscription required*
socket.on('open-book', (data) => {
console.log('open-book', data);
});
```
***Expected Output***
```javascript
open-book {
ETHCLP: {
sell: [
[Order1], [Order2],...
],
buy: [
[Order1], [Order2],...
]
}
}
```
**Receive Historical book info**
```javascript
// Subscription required*
socket.on('historical-book', (data) => {
console.log('historical-book', data);
});
```
***Expected Output***
```javascript
[
{
requestId: 'OOETHCLP0000000000000000000001',
tradeId: 'O232937',
stockId: 'ETHCLP',
kind: 1,
type: 2,
side: 1,
price: '204820.000000000000000000000000000000',
limit: null,
condition: null,
flag: 'GENERAL',
amount: '0.00000000000000000000000000000000000',
initAmount: '2.07330000000000000000000000000000000',
dateReceived: 1582205310697,
executed_price: '204820.000000000000000000000000000000',
executed_amount: '2.07330000000000000000000000000000000',
executed_date: 1582205310745
},
{
requestId: 'OOETHCLP0000000000000000000002',
tradeId: 'O232665',
stockId: 'ETHCLP',
kind: 1,
type: 2,
side: 1,
price: '201540.000000000000000000000000000000',
limit: null,
condition: null,
flag: 'GENERAL',
amount: '1.66960000000000000000000000000000000',
initAmount: '1.92640000000000000000000000000000000',
dateReceived: 1582204925623,
executed_price: '201260.000000000000000000000000000000',
executed_amount: '0.256800000000000000000000000000000000',
executed_date: 1582204925645
}
]
```
**Receive candles info**
```javascript
// Subscription required*
socket.on('candles', (data) => {
console.log('candles', data);
});
```
***Expected Output***
```javascript
candles {
'buy': {
'1': [
[{
date: '21/02/2020 04:56:00',
stockId: 'ETHCLP',
type: 1,
timeFrame: 1,
lowPrice: 212060,
hightPrice: 212060,
openPrice: 212060,
closePrice: 212100,
count: 3,
volume: 0,
lastBuyPrice: 217900,
lastSellPrice: 227220
}],[Object],...],
'5': [[Object],[Object],...],
'15':[[Object],[Object],...],
'60': [[Object],[Object],...],
'240':[[Object],[Object],...],
'1440':[[Object],[Object],...],
'10080':[[Object],[Object],...],
'44640':[[Object],[Object],...]
}
'sell':{
'1':[[Object],...],
'5':...
},
lastBuyPrice: 218880,lastSellPrice: 227220
}
```
**Receive ticker info**
```javascript
socket.on('ticker', (data) => {
console.log('ticker', data);
});
```
***Expected Output***
```javascript
ticker {
EOSARS: {
BID: 346.95,
ASK: 364.65,
delta1d: -13.04511278195489,
delta7d: -21.928442844284426
},
BTCCLP: {
BID: 7914600,
ASK: 8038600,
delta1d: -2.4334319526627217,
delta7d: -2.1318164956102383
},
ETHCLP: {
BID: 213600,
ASK: 218880,
delta1d: 1.0598031794095382,
delta7d: 0.6692430954849656
},
...
}
```
**Receive balance info**
```javascript
socket.on('balance', (data) => {
console.log('balance', data);
});
```
***Expected Output***
```javascript
balance {
ETH: {
currency: 'ETH',
countable: '0.0700000000000000000000000000000000000',
available: '0.0700000000000000000000000000000000000',
currency_kind: 1,
currency_name: 'ETH',
currency_big_name: 'Ether',
currency_prefix: '',
currency_postfix: ' ETH',
currency_decimals: 4
},
...
}
```
**Receive user orders info**
```javascript
socket.on('open-orders', (data) => {
console.log('open-orders', data);
});
```
***Expected Output***
```javascript
open-orders [
{
requestId: 'OOXLMCLP0000000000000000000001',
tradeId: 'O000001',
traderId: '2',
stockId: 'XLMCLP',
kind: 2,
type: 2,
side: 2,
price: '80.0000000000000000000000000000000000',
limit: null,
condition: null,
flag: 'GENERAL',
amount: '1.00000000000000000000000000000000000',
initAmount: '1.00000000000000000000000000000000000',
dateReceived: 1582301424510
},
{Order2},...
]
```
**Receive historical user orders info**
```javascript
socket.on('historical-orders', (data) => {
console.log('historical-orders', data);
});
```
***Expected Output***
```javascript
historical-orders [
{
requestId: 'OOXLMCLP000000000000000000001',
tradeId: 'O000001',
traderId: '1',
stockId: 'XLMCLP',
kind: 2,
type: 2,
side: 2,
price: '50.5000000000000000000000000000000000',
limit: null,
condition: null,
flag: 'GENERAL',
amount: '0.00000000000000000000000000000000000',
initAmount: '1.00000000000000000000000000000000000',
dateReceived: 1582261738700
},
{
requestId: 'OOXLMCLP000000000000000000002',
tradeId: 'O0000022',
traderId: '1',
stockId: 'XLMCLP',
kind: 2,
type: 2,
side: 2,
price: '72.0000000000000000000000000000000000',
limit: null,
condition: null,
flag: 'GENERAL',
amount: '1.00000000000000000000000000000000000',
initAmount: '1.00000000000000000000000000000000000',
dateReceived: 1582293930313,
dateTriggered: null
},
...
]
```
**Receive User´s operated volume**
```javascript
socket.on('operated', (data) => {
console.log('operated', data);
});
```
***Expected Output***
```javascript
operated {
flag: 'L0',
threshold: '0.00000000000000000000000000000000000',
traded: '0.0718085391503182500000000000000000000',
tk: '0.00680000000000000000000000000000000000',
mk: '0.00390000000000000000000000000000000000'
}
```

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc