-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathBitso.java
More file actions
979 lines (832 loc) · 39.7 KB
/
Copy pathBitso.java
File metadata and controls
979 lines (832 loc) · 39.7 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
package com.bitso;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bitso.exceptions.BitsoAPIException;
import com.bitso.exceptions.BitsoPayloadException;
import com.bitso.exceptions.BitsoServerException;
import com.bitso.exceptions.BitsoValidationException;
import com.bitso.exchange.BookInfo;
import com.bitso.helpers.Helpers;
import com.bitso.http.BlockingHttpClient;
/**
* An implementation of the Bitso API.
*/
public class Bitso {
private final String ETHER = "ether";
private final String BITCOIN = "bitcoin";
public static long THROTTLE_MS = 1000;
private final String key;
private final String secret;
private boolean log;
private String baseUrl;
private BlockingHttpClient client = new BlockingHttpClient(false, THROTTLE_MS);
public Bitso(String key, String secret) {
this(key, secret, true, Target.production);
}
public Bitso(String key, String secret, boolean log) {
this(key, secret, log, Target.production);
}
/** Creates a new instance with the specified parameters.
* @param key The Bitso API key to use.
* @param secret The corresponding secret for the specified API key.
* @param log Whether to print log messages or not
* @param env The target environment to connect to.
*/
public Bitso(String key, String secret, boolean log, Target env) {
this.key = key;
this.secret = secret;
this.log = log;
this.baseUrl = env.uri();
}
/** Changes the base URL to use. */
public void setBaseURL(String url) {
baseUrl = url;
}
public String getKey() {
return key;
}
public String getSecret() {
return secret;
}
public void setLog(boolean log) {
this.log = log;
}
private void logError(String error) {
if (log) {
System.err.println(error);
}
}
private void log(String msg) {
if (log) {
System.out.println(msg);
}
}
// Public Functions
public BookInfo[] getAvailableBooks()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/available_books";
String getResponse = sendGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BookInfo[] books = new BookInfo[totalElements];
for (int i = 0; i < totalElements; i++) {
books[i] = new BookInfo(payloadJSON.getJSONObject(i));
}
return books;
}
public BitsoTicker[] getTicker() throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/ticker";
String getResponse = sendGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoTicker[] tickers = new BitsoTicker[totalElements];
for (int i = 0; i < totalElements; i++) {
tickers[i] = new BitsoTicker(payloadJSON.getJSONObject(i));
}
return tickers;
}
public BitsoOrderBook getOrderBook(String book, boolean... aggregate)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/order_book?book=" + book;
if (aggregate != null && aggregate.length == 1) {
if (aggregate[0]) {
request += "&aggregate=true";
} else {
request += "&aggregate=false";
}
}
String getResponse = sendGet(request);
JSONObject payloadJSON = (JSONObject) getJSONPayload(getResponse);
return new BitsoOrderBook(payloadJSON);
}
public BitsoTransactions getTrades(String book, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String parsedQueryParametes = processQueryParameters("&", queryParameters);
String request = "/api/v3/trades?book=" + book
+ ((parsedQueryParametes != null) ? "&" + parsedQueryParametes : "");
String getResponse = sendGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
return new BitsoTransactions(payloadJSON);
}
//Public Functions Signed
public BitsoTicker[] getSignedTicker() throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/ticker";
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoTicker[] tickers = new BitsoTicker[totalElements];
for (int i = 0; i < totalElements; i++) {
tickers[i] = new BitsoTicker(payloadJSON.getJSONObject(i));
}
return tickers;
}
public BookInfo[] getSignedAvailableBooks()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/available_books";
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BookInfo[] books = new BookInfo[totalElements];
for (int i = 0; i < totalElements; i++) {
books[i] = new BookInfo(payloadJSON.getJSONObject(i));
}
return books;
}
// Private Functions
public BitsoAccountStatus getAccountStatus()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/account_status";
String getResponse = sendBitsoGet(request);
JSONObject payloadJSON = (JSONObject) getJSONPayload(getResponse);
return new BitsoAccountStatus(payloadJSON);
}
public BitsoBalance getAccountBalance()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/balance";
String getResponse = sendBitsoGet(request);
JSONObject payloadJSON = (JSONObject) getJSONPayload(getResponse);
return new BitsoBalance(payloadJSON);
}
public BitsoFee getFees() throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/fees";
String getResponse = sendBitsoGet(request);
JSONObject payloadJSON = (JSONObject) getJSONPayload(getResponse);
return new BitsoFee(payloadJSON);
}
public BitsoOperation[] getLedger(String specificOperation, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/ledger";
if (specificOperation != null && specificOperation.length() > 0) {
request += "/" + specificOperation;
}
String parsedQueryParametes = processQueryParameters("&", queryParameters);
request += ((parsedQueryParametes != null) ? "?" + parsedQueryParametes : "");
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoOperation[] operations = new BitsoOperation[totalElements];
for (int i = 0; i < totalElements; i++) {
operations[i] = new BitsoOperation(payloadJSON.getJSONObject(i));
}
return operations;
}
/**
* The request needs withdrawalsIds or queryParameters, not both. In case both parameters are provided
* null will be returned
*
* @param withdrawalsIds
* @param queryParameters
* @return BitsoWithdrawal[]
* @throws BitsoAPIException
*/
public BitsoWithdrawal[] getWithdrawals(String[] withdrawalsIds, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/withdrawals";
if ((withdrawalsIds != null) && (queryParameters != null && queryParameters.length > 0)) {
return null;
}
if (withdrawalsIds != null) {
String withdrawalsIdsParameters = processQueryParameters("-", withdrawalsIds);
request += ((withdrawalsIdsParameters != null) ? "/" + withdrawalsIdsParameters : "");
}
if (queryParameters != null && queryParameters.length > 0) {
String parsedQueryParametes = processQueryParameters("&", queryParameters);
request += ((parsedQueryParametes != null) ? "?" + parsedQueryParametes : "");
}
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoWithdrawal[] withdrawals = new BitsoWithdrawal[totalElements];
for (int i = 0; i < totalElements; i++) {
withdrawals[i] = new BitsoWithdrawal(payloadJSON.getJSONObject(i));
}
return withdrawals;
}
/**
* The request needs fundingssIds or queryParameters, not both. In case both parameters are provided null
* will be returned
*
* @param fundingssIds
* @param queryParameters
* @return
* @throws BitsoAPIException
*/
public BitsoFunding[] getFundings(String[] fundingssIds, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/fundings";
if ((fundingssIds != null && (queryParameters != null && queryParameters.length > 0))) {
return null;
}
if (fundingssIds != null) {
String fundingssIdsParameters = processQueryParameters("-", fundingssIds);
request += ((fundingssIdsParameters != null) ? "/" + fundingssIdsParameters : "");
}
if (queryParameters != null && queryParameters.length > 0) {
String parsedQueryParametes = processQueryParameters("&", queryParameters);
request += ((parsedQueryParametes != null) ? "?" + parsedQueryParametes : "");
}
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoFunding[] fundings = new BitsoFunding[totalElements];
for (int i = 0; i < totalElements; i++) {
fundings[i] = new BitsoFunding(payloadJSON.getJSONObject(i));
}
return fundings;
}
/**
* The request needs tradesIds or queryParameters, not both. In case both parameters are provided null
* will be returned
*
* @param tradesIds
* @param queryParameters
* @return
* @throws BitsoAPIException
*/
public BitsoTrade[] getUserTrades(String[] tradesIds, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/user_trades";
if ((tradesIds != null && (queryParameters != null && queryParameters.length > 0))) {
return null;
}
if (tradesIds != null) {
String fundingssIdsParameters = processQueryParameters("-", tradesIds);
request += ((fundingssIdsParameters != null) ? "/" + fundingssIdsParameters : "");
}
if (queryParameters != null && queryParameters.length > 0) {
String parsedQueryParametes = processQueryParameters("&", queryParameters);
request += ((parsedQueryParametes != null) ? "?" + parsedQueryParametes : "");
}
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoTrade[] trades = new BitsoTrade[totalElements];
for (int i = 0; i < totalElements; i++) {
trades[i] = new BitsoTrade(payloadJSON.getJSONObject(i));
}
return trades;
}
public BitsoTrade[] getOrderTrades(String orderId)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/order_trades";
if (orderId == null || orderId.trim().length() == 0) {
return null;
}
request += "/" + orderId;
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoTrade[] trades = new BitsoTrade[totalElements];
for (int i = 0; i < totalElements; i++) {
trades[i] = new BitsoTrade(payloadJSON.getJSONObject(i));
}
return trades;
}
public BitsoOrder[] getOpenOrders(String book, String... queryParameters)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/open_orders";
request += "?" + "book=" + book;
String parsedQueryParametes = processQueryParameters("&", queryParameters);
request += ((parsedQueryParametes != null) ? "&" + parsedQueryParametes : "");
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoOrder[] orders = new BitsoOrder[totalElements];
for (int i = 0; i < totalElements; i++) {
orders[i] = new BitsoOrder(payloadJSON.getJSONObject(i));
}
return orders;
}
public BitsoOrder[] lookupOrders(String... ordersId)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/orders";
if (ordersId == null || ordersId.length == 0) {
return null;
}
String ordersIdsParameters = processQueryParameters("-", ordersId);
request += "/" + ordersIdsParameters;
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
int totalElements = payloadJSON.length();
BitsoOrder[] orders = new BitsoOrder[totalElements];
for (int i = 0; i < totalElements; i++) {
orders[i] = new BitsoOrder(payloadJSON.getJSONObject(i));
}
return orders;
}
/** Place a market order to sell the specified amount.
* @param book The trading pair for this order.
* @param amount The amount to sell, in major currency.
* @return The generated order ID.
*/
public String placeMarketSellOrder(String book, BigDecimal amount)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return placeOrder(book, BitsoOrder.SIDE.SELL, BitsoOrder.TYPE.MARKET, amount, null, null, null);
}
/** Place a market order to buy the specified value.
* @param book The trading pair for this order.
* @param value The value to buy, in minor currency.
*/
public String placeMarketBuyOrder(String book, BigDecimal value)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return placeOrder(book, BitsoOrder.SIDE.SELL, BitsoOrder.TYPE.MARKET, null, value, null, null);
}
/** Place a limit order.
* @param book The trading pair for this order.
* @param side Buy or sell
* @param major The amount to buy or sell, in major currency.
* @param minor The value to buy or sell, in minor currency.
* @param price The maximum price at which to buy, or minimum price at which to sell,
* expressed in minor currency.
* @param tif The time-in-force attribute.
*/
public String placeLimitOrder(String book, BitsoOrder.SIDE side, BigDecimal major, BigDecimal minor,
BigDecimal price, BitsoOrder.TIME_IN_FORCE tif)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return placeOrder(book, side, BitsoOrder.TYPE.LIMIT, major, minor, price, tif);
}
/** Place an order, using GOODTILLCANCELLED.
* @param book The trading pair for the order.
* @param side Whether it's a buy or sell order.
* @param type A limit or market order.
* @param major The amount of the order, in major currency.
* @param minor The value of the order, in minor currency.
* @param price The price of the order, in minor currency. Use null for market orders.
*/
public String placeOrder(String book, BitsoOrder.SIDE side, BitsoOrder.TYPE type, BigDecimal major,
BigDecimal minor, BigDecimal price)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return placeOrder(book, side, type, major, minor, price, BitsoOrder.TIME_IN_FORCE.GOODTILLCANCELLED);
}
/** Place an order, using the specified parameters.
* Only one of the major (amount) or the minor (value) must be specified.
*
* @param book The trading pair for the order.
* @param side Whether it's a buy or sell order.
* @param type A limit or market order.
* @param major The amount of the order, in major currency.
* @param minor The value of the order, in minor currency.
* @param price The price of the order, in minor currency. Use null for market orders.
* @param tif The time-in-force attribute, for limit orders.
* @return The order ID generated by the system.
*/
public String placeOrder(String book, BitsoOrder.SIDE side, BitsoOrder.TYPE type, BigDecimal major,
BigDecimal minor, BigDecimal price, BitsoOrder.TIME_IN_FORCE tif)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/orders";
JSONObject parameters = new JSONObject();
if ((major != null && minor != null) || (major == null && minor == null)) {
log("An order should be specified in terms of major or minor, never both or any");
return null;
}
if (type.equals(BitsoOrder.TYPE.MARKET) && (price != null)) {
log("On market order a price does not need to be specified");
return null;
}
// Filling data for request
parameters.put("book", book);
parameters.put("side", side.toString().toLowerCase());
parameters.put("type", type.toString().toLowerCase());
if (type.equals(BitsoOrder.TYPE.LIMIT) && (price != null)) {
parameters.put("price", price.toString());
if (tif != null) {
parameters.put("time_in_force", tif.name().toLowerCase());
}
}
if (major != null) {
parameters.put("major", major.toString());
} else {
parameters.put("minor", minor.toString());
}
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return Helpers.getString(payloadJSON, "oid");
}
public String[] cancelOrder(String... ordersIds)
throws BitsoAPIException, BitsoValidationException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/orders";
if (ordersIds.length == 0) {
throw new BitsoValidationException("No orders to cancel");
}
String ordersIdsParameters = processQueryParameters("-", ordersIds);
request += "/" + ordersIdsParameters;
log(request);
String deleteResponse = sendBitsoDelete(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(deleteResponse);
return Helpers.getJSONArrayElements(payloadJSON);
}
public String[] cancelAllOrders()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/orders/all";
log(request);
String deleteResponse = sendBitsoDelete(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(deleteResponse);
return Helpers.getJSONArrayElements(payloadJSON);
}
public Map<String, String> fundingDestination(String currencyParameter)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/funding_destination";
if (currencyParameter == null || currencyParameter.trim().length() == 0) {
return null;
}
request += "?" + currencyParameter;
String getResponse = sendBitsoGet(request);
JSONObject payloadJSON = (JSONObject) getJSONPayload(getResponse);
Map<String, String> fundingDestination = new HashMap<String, String>();
fundingDestination.put("account_identifier_name",
Helpers.getString(payloadJSON, "account_identifier_name"));
fundingDestination.put("account_identifier", Helpers.getString(payloadJSON, "account_identifier"));
return fundingDestination;
}
public BitsoWithdrawal bitcoinWithdrawal(BigDecimal amount, String address, boolean saveAccount,
String... savedName) throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return currencyWithdrawal(BITCOIN, amount, address, saveAccount, savedName);
}
public BitsoWithdrawal etherWithdrawal(BigDecimal amount, String address, boolean saveAccount,
String... savedName) throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
return currencyWithdrawal(ETHER, amount, address, saveAccount, savedName);
}
public BitsoWithdrawal speiWithdrawal(BigDecimal amount, String recipientGivenNames,
String recipientFamilyNames, String clabe, String notesReference, String numericReference,
boolean saveAccount, String... savedName)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/spei_withdrawal";
JSONObject parameters = new JSONObject();
parameters.put("amount", amount.toString());
parameters.put("recipient_given_names", recipientGivenNames);
parameters.put("recipient_family_names", recipientFamilyNames);
parameters.put("clabe", clabe);
parameters.put("notes_ref", notesReference);
parameters.put("numeric_ref", numericReference);
if (saveAccount && savedName.length == 1) {
parameters.put("save", saveAccount);
parameters.put("saved_name", savedName[0]);
}
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return new BitsoWithdrawal(payloadJSON);
}
public Map<String, String> getBanks()
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/mx_bank_codes";
String getResponse = sendBitsoGet(request);
JSONArray payloadJSON = (JSONArray) getJSONPayload(getResponse);
Map<String, String> banks = new HashMap<String, String>();
String currentBankCode = "";
String currentBankName = "";
JSONObject currentJSON = null;
int totalElements = payloadJSON.length();
for (int i = 0; i < totalElements; i++) {
currentJSON = payloadJSON.getJSONObject(i);
currentBankCode = Helpers.getString(currentJSON, "code");
currentBankName = Helpers.getString(currentJSON, "name");
banks.put(currentBankCode, currentBankName);
}
return banks;
}
public BitsoWithdrawal debitCardWithdrawal(BigDecimal amount, String recipientGivenNames,
String recipientFamilyNames, String cardNumber, String bankCode, boolean saveAccount,
String... savedName) throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/debit_card_withdrawal";
JSONObject parameters = new JSONObject();
parameters.put("amount", amount.toString());
parameters.put("recipient_given_names", recipientGivenNames);
parameters.put("recipient_family_names", recipientFamilyNames);
parameters.put("card_number", cardNumber);
parameters.put("bank_code", bankCode);
if (saveAccount && savedName.length == 1) {
parameters.put("save", saveAccount);
parameters.put("saved_name", savedName[0]);
}
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return new BitsoWithdrawal(payloadJSON);
}
public String numberRegistration(String phoneNumber)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
if (phoneNumber == null) {
}
phoneNumber = phoneNumber.trim();
if (phoneNumber.length() == 0) {
}
String request = "/api/v3/phone_number";
JSONObject parameters = new JSONObject();
parameters.put("phone_number", phoneNumber);
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return payloadJSON.getString("phone");
}
public String phoneVerification(String verificationCode)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
if (verificationCode == null) {
}
verificationCode = verificationCode.trim();
if (verificationCode.length() == 0) {
}
String request = "/api/v3/phone_verification";
JSONObject parameters = new JSONObject();
parameters.put("verification_code", verificationCode);
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return payloadJSON.getString("phone");
}
public BitsoWithdrawal phoneWithdrawal(BigDecimal amount, String recipientGivenNames,
String recipientFamilyNames, String phoneNumber, String bankCode)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/phone_withdrawal";
JSONObject parameters = new JSONObject();
parameters.put("amount", amount.toString());
parameters.put("recipient_given_names", recipientGivenNames);
parameters.put("recipient_family_names", recipientFamilyNames);
parameters.put("phone_number", phoneNumber);
parameters.put("bank_code", bankCode);
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return new BitsoWithdrawal(payloadJSON);
}
private BitsoWithdrawal currencyWithdrawal(String currency, BigDecimal amount, String address,
boolean saveAccount, String... savedName)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
String request = "/api/v3/" + currency + "_withdrawal";
JSONObject parameters = new JSONObject();
parameters.put("amount", amount.toString());
parameters.put("address", address);
if (saveAccount && savedName.length == 1) {
parameters.put("save", saveAccount);
parameters.put("saved_name", savedName[0]);
}
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return new BitsoWithdrawal(payloadJSON);
}
/**
* @param currency
* The currency you want to withdraw [bitcoin | ether | ripple | litecoin | bcash]
* @param address
* The address you want to send the specified amount
* @param amount
* The total amount you want to send
* @param save
* Set if you want to save the withdrawal destination
* @param extraParameters
* Allows to add extra parameters to the withdrawal operation, could be: tag: If you want to
* withdraw ripple and need to set a destination tag set this key name: If save parameter is
* set to positive, name tag should be added to get a name for the destination
* @return
* @throws BitsoValidationException
* If any of the parameters is not valid
* @throws BitsoAPIException
* If server detected something was wrong with the request
* @throws BitsoPayloadException
* If server response is wrong in any way
* @throws BitsoServerException
* If something is wrong in the server
*/
public BitsoWithdrawal currencyWithdrawal(String currency, String address, String amount, boolean save,
HashMap<String, String> extraParameters)
throws BitsoValidationException, BitsoAPIException, BitsoPayloadException, BitsoServerException {
if (currency == null || currency.isEmpty()) {
throw new BitsoValidationException("Currency can't be empty");
}
if (address == null || address.isEmpty()) {
throw new BitsoValidationException("Address can't be empty");
}
if (amount == null || amount.isEmpty()) {
throw new BitsoValidationException("Amount can't be empty");
}
try {
BigDecimal amountValue = new BigDecimal(amount);
if (amountValue.doubleValue() <= 0) {
throw new BitsoValidationException("You cannot withdraw cero or negative amounts");
}
} catch (NumberFormatException e) {
throw new BitsoValidationException("Amount is not valid a number to process withdrawal");
}
if (save && (extraParameters == null || extraParameters.size() == 0)) {
throw new BitsoValidationException(
"You are inidcating that th operation must be saved, but no save name has been provided");
}
String request = "/api/v3/" + currency + "_withdrawal";
JSONObject parameters = new JSONObject();
parameters.put("amount", amount.toString());
parameters.put("address", address);
if (currency.equals("ripple") && extraParameters.containsKey("tag")) {
parameters.put("destination_tag", extraParameters.get("tag"));
}
parameters.put("save", save);
if (save) {
parameters.put("saved_name", extraParameters.get("name"));
}
String postResponse = sendBitsoPost(request, parameters);
JSONObject payloadJSON = (JSONObject) getJSONPayload(postResponse);
return new BitsoWithdrawal(payloadJSON);
}
public String getDepositAddress() throws BitsoAPIException {
String postResponse = sendBitsoPost(baseUrl + "bitcoin_deposit_address");
return quoteEliminator(postResponse);
}
private String quoteEliminator(String input) {
if (input == null) {
logError("input to quoteEliminator cannot be null");
return null;
}
int length = input.length();
if (input.charAt(0) != '"' || input.charAt(length - 1) != '"') {
logError("invalid input to quoteEliminator: " + input);
return null;
}
return input.substring(1, length - 1);
}
public String buildBitsoAuthHeader(String requestPath, String httpMethod, String apiKey, String secret)
throws BitsoAPIException {
if (apiKey == null || secret == null) {
throw new BitsoAPIException("Bitso API key or secret is null");
}
byte[] secretBytes = secret.getBytes();
if (secretBytes.length == 0) {
throw new BitsoAPIException("Bitso API key is empty");
}
long nonce = System.currentTimeMillis() + System.currentTimeMillis();
String message = nonce + httpMethod + requestPath;
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(secretBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
byte[] arrayOfByte = mac.doFinal(message.getBytes());
BigInteger bigInteger = new BigInteger(1, arrayOfByte);
String signature = String.format("%0" + (arrayOfByte.length << 1) + "x",
new Object[] { bigInteger });
return String.format("Bitso %s:%s:%s", apiKey, nonce, signature);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new BitsoAPIException(e);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new BitsoAPIException(e);
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new BitsoAPIException(e);
}
}
private static Entry<String, String> buildBitsoAuthHeader(String secretKey, String publicKey, long nonce,
String httpMethod, String requestPath, String jsonPayload) {
if (jsonPayload == null) jsonPayload = "";
String message = String.valueOf(nonce) + httpMethod + requestPath + jsonPayload;
String signature = "";
byte[] secretBytes = secretKey.getBytes();
SecretKeySpec localMac = new SecretKeySpec(secretBytes, "HmacSHA256");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(localMac);
// Compute the hmac on input data bytes
byte[] arrayOfByte = mac.doFinal(message.getBytes());
BigInteger localBigInteger = new BigInteger(1, arrayOfByte);
signature = String.format("%0" + (arrayOfByte.length << 1) + "x",
new Object[] { localBigInteger });
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
String authHeader = String.format("Bitso %s:%s:%s", publicKey, nonce, signature);
Entry<String, String> entry = new AbstractMap.SimpleEntry<String, String>("Authorization",
authHeader);
return entry;
}
public String sendGet(String requestedURL) throws BitsoAPIException {
HttpsURLConnection connection = null;
try {
URL url = new URL(baseUrl + requestedURL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Android");
return Helpers.convertInputStreamToString(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
throw new BitsoAPIException(322, "Not a Valid URL", e);
} catch (ProtocolException e) {
e.printStackTrace();
throw new BitsoAPIException(901, "Unsupported HTTP method", e);
} catch (IOException e) {
e.printStackTrace();
return Helpers.convertInputStreamToString(connection.getErrorStream());
}
}
public String sendBitsoGet(String requestPath) throws BitsoAPIException {
return sendBitsoHttpRequest(requestPath, "GET");
}
private String sendBitsoHttpRequest(String requestPath, String method) throws BitsoAPIException {
String requestURL = baseUrl + requestPath;
HttpsURLConnection connection = null;
try {
URL url = new URL(requestURL);
connection = (HttpsURLConnection) url.openConnection();
connection.addRequestProperty("Authorization",
buildBitsoAuthHeader(requestPath, "GET", key, secret));
connection.setRequestProperty("User-Agent", "Bitso-java-api");
connection.setRequestMethod(method);
return Helpers.convertInputStreamToString(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
throw new BitsoAPIException(322, "Not a Valid URL", e);
} catch (ProtocolException e) {
e.printStackTrace();
throw new BitsoAPIException(901, "Unsupported HTTP method", e);
} catch (IOException e) {
e.printStackTrace();
return Helpers.convertInputStreamToString(connection.getErrorStream());
}
}
private String sendBitsoDelete(String requestPath) throws BitsoAPIException {
long nonce = System.currentTimeMillis() + System.currentTimeMillis();
Entry<String, String> authHeader = buildBitsoAuthHeader(secret, key, nonce, "DELETE", requestPath,
null);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put(authHeader.getKey(), authHeader.getValue());
return client.sendDelete(baseUrl + requestPath, headers);
}
public String sendBitsoPost(String url) throws BitsoAPIException {
return sendBitsoPost(url, null);
}
public String sendBitsoPost(String requestPath, JSONObject jsonPayload) throws BitsoAPIException {
long nonce = System.currentTimeMillis() + System.currentTimeMillis();
String jsonString = "";
if (jsonPayload != null) {
jsonString = jsonPayload.toString();
}
Entry<String, String> header = buildBitsoAuthHeader(secret, key, nonce, "POST", requestPath,
jsonString);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put(header.getKey(), header.getValue());
return client.sendPost(baseUrl + requestPath, jsonString, headers);
}
public String processQueryParameters(String separator, String... parameters) {
if (parameters == null) {
return null;
}
int totalParameters = parameters.length;
if (totalParameters == 0) {
return null;
}
String queryString = "";
for (int i = 0; i < (totalParameters - 1); i++) {
String currentParameter = parameters[i].trim();
if (currentParameter.length() == 0) {
continue;
}
queryString += currentParameter + separator;
}
String lastParameter = parameters[totalParameters - 1].trim();
// Meaning that the last parameter is not empty
if (lastParameter.length() != 0) {
queryString += parameters[totalParameters - 1];
// Remove the separator symbol at the end if query string has it
} else if (queryString.endsWith(separator)) {
queryString = queryString.substring(0, (queryString.length() - 1));
}
return queryString;
}
public Object getJSONPayload(String jsonResponse)
throws BitsoAPIException, BitsoPayloadException, BitsoServerException {
if (jsonResponse == null) {
throw new BitsoServerException("Server response is null");
}
try {
JSONObject o = Helpers.parseJson(jsonResponse);
if (o.has("error")) {
JSONObject errorJson = o.getJSONObject("error");
int errorCode = Helpers.getInt(errorJson, "code");
String errorMessage = Helpers.getString(errorJson, "message");
throw new BitsoAPIException(errorCode, errorMessage);
}
if (o.has("payload")) {
return o.get("payload");
} else {
throw new BitsoPayloadException("Server response does not contain payload");
}
} catch (JSONException e) {
e.printStackTrace();
throw new BitsoServerException("Server response is not a valid JSON", e);
}
}
}