-
Notifications
You must be signed in to change notification settings - Fork 7
/
justcoin.js
199 lines (168 loc) · 6.04 KB
/
justcoin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
var _ = require('lodash');
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
module.exports = function(conf, trader){
_.extend(this, conf);
var self = this;
var initDeferred = Promise.defer();
this.initialized = initDeferred.promise;
this.pollingInterval = 500;
this._url = function(path){
return 'https://justcoin.com/api/v1/' + path +'?key=' + self.key;
};
this._doRequest = function(path, method, options){
var requestOptions = {
json : true
};
if(method){
requestOptions.method = method;
}
if(options){
requestOptions.body = options;
}
return request(this._url(path), requestOptions).spread(function(request, data){
return data;
});
};
this.getSpread = function(currency){
currency = currency || 'EUR';
return this._doRequest('markets/BTC' + currency + '/depth').then(function(data){
_.extend(data, {exchange: 'justcoin', currency: currency});
if(! data.exchange){
throw "Justcoin weird missing data error";
}
trader.emit('spread_data', data);
return data;
});
};
var balanceMapper = function(data){
var balance = {};
_.each(self.currencies, function(currency){
balance[currency] = parseFloat(_.find(data, {currency: currency}).available)
});
// hard coding for now a fix so that justcoin balance in BTC _includes_ fees.
balance['BTC'] *= (1-self.fee);
return balance;
};
self.tradeCommand = function(options){
var typeMapper = {
'buy' : 'bid',
'sell' : 'ask'
};
return self._doRequest('orders', 'POST', {
market : 'BTC'+options.currency,
type : typeMapper[options.buySell],
amount : options.volume.toString(),
price : options.price.toString()
});
};
self.getOrders = function(){
return self._doRequest('orders');
};
self.getOrderHistory = function(){
return self._doRequest('orders/history');
};
self.cancel = function(id){
return self._doRequest('orders/'+id, 'DELETE');
};
self.idExtractor = function(response){
if(response.message){
throw new Error('justcoin trade error: ' + response.message);
}
if( ! response.id){
throw new Error('justcoin unknown trade error: ' + response);
}
console.log('justcoin order id: ', response.id);
this.id = response.id;
this.retries = 0;
return response;
};
self.tradeChecker = function(){
console.log('tradecheck justcoin: ', this.id);
return self.getOrders()
.bind(this)
.then(self.responseProcessor)
.then(self.tradeCheckLooper);
}
self.responseProcessor = function(response){
var myOrder = _.find(response, {id:this.id});
if( ! myOrder){ // order is not remaining, either complete or rejected
return self.getOrderHistory().bind(this).then(function(orders){
var myOrder = _.find(orders, {id:this.id});
if(!myOrder){// not in history, rejecting
throw new Error('order ' + this.id + ' cancelled');
} else {
return {
success : true,
response: myOrder
}
}
});
} else {
return false;
}
};
// these can be generalized, broken out
self.tradeValidator = function(options){
return new Promise(function(resolve, reject){
var neededOptions = ['currency', 'buySell', 'price', 'volume'];
for (var i = neededOptions.length - 1; i >= 0; i--) {
if(!_.has(options, neededOptions[i])){
reject("Trade doesn't have needed properties; 'currency', 'buySell', 'price', 'volume'");
return;
}
}
resolve(options);
});
};
self.tradeCheckLooper = function(finishedResponse){
if(finishedResponse){
return finishedResponse;
}
console.log('order ', this.id, 'is still running, iteration', this.retries++);
// keep looping this baby
if(this.retries <= 1){
return Promise.bind(this).then(self.tradeChecker); // first retry do immediately
} else {
return Promise.delay(self.pollingInterval).bind(this).then(self.tradeChecker);
}
};
self.trade = function(options){
return self.tradeValidator(options)
.then(self.tradeCommand)
.bind({}) // create a shared this property
.then(self.idExtractor)
.then(function(response){
if(options.timeout && _.isNumber(options.timeout)){
return Promise.bind(this).then(self.tradeChecker).timeout(options.timeout);
} else {
return Promise.bind(this).then(self.tradeChecker);
}
}).catch(Promise.TimeoutError, function(e){
console.log('Trade timeout, cancelling');
self.cancel(this.id);
throw e;
});
};
this.getBalance = function(){
return self._doRequest('balances').then(function(data){
self.balance = balanceMapper(data);
return self.balance;
})
}
self.getBalance().then(function(data){
console.log('justcoin balance: ', data);
initDeferred.resolve();
// id: 2361955
// var options = {
// currency : 'EUR',
// buySell : 'sell',
// price : 999,
// volume : 0.01
// };
// self.trade(options).then(console.log).error(console.error).catch(function(a,b){
// console.error(a, b);
// });
// self.getOrders().then(console.log);
});
}