View Javadoc
1   package org.oxerr.okcoin.rest;
2   
3   import static java.util.stream.Collectors.toList;
4   
5   import java.math.BigDecimal;
6   import java.util.ArrayList;
7   import java.util.Arrays;
8   import java.util.Collection;
9   import java.util.Collections;
10  import java.util.Date;
11  import java.util.HashSet;
12  import java.util.List;
13  import java.util.Set;
14  
15  import org.knowm.xchange.currency.Currency;
16  import org.knowm.xchange.currency.CurrencyPair;
17  import org.knowm.xchange.dto.Order.OrderType;
18  import org.knowm.xchange.dto.account.AccountInfo;
19  import org.knowm.xchange.dto.account.Balance;
20  import org.knowm.xchange.dto.account.Wallet;
21  import org.knowm.xchange.dto.marketdata.OrderBook;
22  import org.knowm.xchange.dto.marketdata.Ticker;
23  import org.knowm.xchange.dto.marketdata.Trades;
24  import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
25  import org.knowm.xchange.dto.trade.LimitOrder;
26  import org.knowm.xchange.dto.trade.OpenOrders;
27  import org.knowm.xchange.dto.trade.UserTrade;
28  import org.knowm.xchange.dto.trade.UserTrades;
29  import org.oxerr.okcoin.rest.dto.Depth;
30  import org.oxerr.okcoin.rest.dto.Funds;
31  import org.oxerr.okcoin.rest.dto.Order;
32  import org.oxerr.okcoin.rest.dto.OrderHistory;
33  import org.oxerr.okcoin.rest.dto.OrderResult;
34  import org.oxerr.okcoin.rest.dto.TickerResponse;
35  import org.oxerr.okcoin.rest.dto.Trade;
36  import org.oxerr.okcoin.rest.dto.Type;
37  import org.oxerr.okcoin.rest.dto.UserInfo;
38  
39  /**
40   * Various adapters for converting from OKCoin DTOs to XChange DTOs.
41   */
42  public final class OKCoinAdapters {
43  
44  	/**
45  	 * Private constructor.
46  	 */
47  	private OKCoinAdapters() {
48  	}
49  
50  	public static String adaptSymbol(CurrencyPair currencyPair) {
51  		return String.format("%1$s_%2$s",
52  				currencyPair.base.getCurrencyCode(),
53  				currencyPair.counter.getCurrencyCode())
54  				.toLowerCase();
55  	}
56  
57  	public static CurrencyPair adaptSymbol(String symbol) {
58  		String[] currencies = symbol.toUpperCase().split("_");
59  		return new CurrencyPair(currencies[0], currencies[1]);
60  	}
61  
62  	public static Ticker adaptTicker(TickerResponse tickerResponse,
63  			CurrencyPair currencyPair) {
64  		return new Ticker.Builder()
65  				.currencyPair(currencyPair)
66  				.timestamp(Date.from(tickerResponse.getDate()))
67  				.high(tickerResponse.getTicker().getHigh())
68  				.low(tickerResponse.getTicker().getLow())
69  				.bid(tickerResponse.getTicker().getBuy())
70  				.ask(tickerResponse.getTicker().getSell())
71  				.last(tickerResponse.getTicker().getLast())
72  				.volume(tickerResponse.getTicker().getVol())
73  				.build();
74  	}
75  
76  	public static OrderBook adaptOrderBook(Depth depth, CurrencyPair currencyPair) {
77  		List<LimitOrder> asks = adaptLimitOrders(OrderType.ASK, depth.getAsks(), currencyPair);
78  		Collections.reverse(asks);
79  
80  		List<LimitOrder> bids = adaptLimitOrders(OrderType.BID, depth.getBids(), currencyPair);
81  
82  		return new OrderBook(null, asks, bids);
83  	}
84  
85  	public static Trades adaptTrades(Trade[] trades, CurrencyPair currencyPair) {
86  		List<org.knowm.xchange.dto.marketdata.Trade> tradeList = new ArrayList<>(
87  				trades.length);
88  		for (Trade trade : trades) {
89  			tradeList.add(adaptTrade(trade, currencyPair));
90  		}
91  		long lastTid = trades.length > 0
92  				? trades[trades.length - 1].getTid()
93  				: 0L;
94  		return new Trades(tradeList, lastTid, TradeSortType.SortByTimestamp);
95  	}
96  
97  	public static AccountInfo adaptAccountInfo(UserInfo userInfo) {
98  		final Funds funds = userInfo.getInfo().getFunds();
99  
100 		final Set<String> currencies = new HashSet<>();
101 		currencies.addAll(funds.getBorrow().keySet());
102 		currencies.addAll(funds.getFree().keySet());
103 		currencies.addAll(funds.getFrozen().keySet());
104 		currencies.addAll(funds.getUnionFund().keySet());
105 
106 		final List<Balance> balances = new ArrayList<>(currencies.size());
107 		for (String currency : currencies) {
108 			final Balance balance = new Balance(
109 				Currency.getInstance(currency.toUpperCase()),
110 				null,
111 				funds.getFree().getOrDefault(currency, BigDecimal.ZERO),
112 				funds.getFrozen().getOrDefault(currency, BigDecimal.ZERO),
113 				funds.getBorrow().getOrDefault(currency, BigDecimal.ZERO),
114 				null,
115 				null,
116 				null);
117 			balances.add(balance);
118 		}
119 
120 		final Wallet wallet = new Wallet(balances);
121 		return new AccountInfo(wallet);
122 	}
123 
124 	public static OpenOrders adaptOpenOrders(Collection<OrderResult> orderResults) {
125 		List<LimitOrder> openOrders = new ArrayList<>();
126 		for (OrderResult orderResult : orderResults) {
127 			openOrders.addAll(adaptOpenOrders(orderResult));
128 		}
129 		return new OpenOrders(openOrders);
130 	}
131 
132 	public static UserTrades adaptUserTrades(OrderHistory orderHistory) {
133 		List<UserTrade> userTrades = Arrays
134 			.stream(orderHistory.getOrders())
135 			.map(order -> adaptUserTrade(order))
136 			.collect(toList());
137 		return new UserTrades(userTrades, TradeSortType.SortByTimestamp);
138 	}
139 
140 	private static List<LimitOrder> adaptLimitOrders(OrderType type,
141 			BigDecimal[][] list, CurrencyPair currencyPair) {
142 		List<LimitOrder> limitOrders = new ArrayList<>(list.length);
143 		for (BigDecimal[] data : list) {
144 			limitOrders.add(adaptLimitOrder(type, data, currencyPair, null,
145 					null));
146 		}
147 		return limitOrders;
148 	}
149 
150 	private static LimitOrder adaptLimitOrder(OrderType type, BigDecimal[] data,
151 			CurrencyPair currencyPair, String id, Date timestamp) {
152 		return new LimitOrder(type, data[1], currencyPair, id,
153 				timestamp, data[0]);
154 	}
155 
156 	private static org.knowm.xchange.dto.marketdata.Trade adaptTrade(
157 			Trade trade, CurrencyPair currencyPair) {
158 		return new org.knowm.xchange.dto.marketdata.Trade.Builder()
159 			.id(String.valueOf(trade.getTid()))
160 			.timestamp(Date.from(trade.getDate()))
161 			.currencyPair(currencyPair)
162 			.type(trade.getType() == Type.BUY ? OrderType.BID : OrderType.ASK)
163 			.tradableAmount(trade.getAmount())
164 			.price(trade.getPrice())
165 			.build();
166 	}
167 
168 	private static List<LimitOrder> adaptOpenOrders(OrderResult orderResult) {
169 		List<LimitOrder> openOrders = new ArrayList<>(orderResult.getOrders().length);
170 		for (Order order : orderResult.getOrders()) {
171 			LimitOrder openOrder = adaptOpenOrder(order);
172 			if (openOrder != null) {
173 				openOrders.add(openOrder);
174 			}
175 		}
176 		return openOrders;
177 	}
178 
179 	private static LimitOrder adaptOpenOrder(Order order) {
180 		return new LimitOrder(
181 				adaptOrderType(order.getType()),
182 				order.getAmount().subtract(order.getDealAmount()),
183 				adaptSymbol(order.getSymbol()),
184 				String.valueOf(order.getOrderId()),
185 				Date.from(order.getCreateDate()),
186 				order.getPrice());
187 	}
188 
189 	public static OrderType adaptOrderType(Type type) {
190 		return type == Type.BUY || type == Type.BUY_MARKET
191 				? OrderType.BID : OrderType.ASK;
192 	}
193 
194 	private static org.knowm.xchange.dto.trade.UserTrade adaptUserTrade(
195 			Order order) {
196 		return new UserTrade.Builder()
197 			.type(adaptOrderType(order.getType()))
198 			.tradableAmount(order.getDealAmount())
199 			.currencyPair(adaptSymbol(order.getSymbol()))
200 			.price(order.getAvgPrice())
201 			.timestamp(Date.from(order.getCreateDate()))
202 			.orderId(String.valueOf(order.getOrderId()))
203 			.build();
204 	}
205 
206 }