Introducing initial support for the 'get_objects' API call

This commit is contained in:
Nelson R. Perez 2017-01-13 16:22:25 -05:00
parent 7db116a894
commit d8e7dc9c31
9 changed files with 166 additions and 18 deletions

View file

@ -147,6 +147,7 @@ public class Converter {
MathContext mathContext = new MathContext(Math.max(base.getPrecision(), quote.getPrecision())); MathContext mathContext = new MathContext(Math.max(base.getPrecision(), quote.getPrecision()));
BigDecimal baseValue = BigDecimal.valueOf(price.base.getAmount().longValue()); BigDecimal baseValue = BigDecimal.valueOf(price.base.getAmount().longValue());
BigDecimal quoteValue = BigDecimal.valueOf(price.quote.getAmount().doubleValue()); BigDecimal quoteValue = BigDecimal.valueOf(price.quote.getAmount().doubleValue());
// System.out.println(String.format("base: %d, quote: %d", baseValue.longValue(), quoteValue.longValue()));
if(direction == BASE_TO_QUOTE){ if(direction == BASE_TO_QUOTE){
conversionRate = quoteValue.divide(baseValue, mathContext).doubleValue(); conversionRate = quoteValue.divide(baseValue, mathContext).doubleValue();
precisionFactor = Math.pow(10, base.getPrecision()) / Math.pow(10, quote.getPrecision()); precisionFactor = Math.pow(10, base.getPrecision()) / Math.pow(10, quote.getPrecision());
@ -154,6 +155,7 @@ public class Converter {
conversionRate = baseValue.divide(quoteValue, mathContext).doubleValue(); conversionRate = baseValue.divide(quoteValue, mathContext).doubleValue();
precisionFactor = Math.pow(10, quote.getPrecision()) / Math.pow(10, base.getPrecision()); precisionFactor = Math.pow(10, quote.getPrecision()) / Math.pow(10, base.getPrecision());
} }
// System.out.println(String.format("conversion rate: %.4f, precision factor: %.2f", conversionRate, precisionFactor));
return conversionRate * precisionFactor; return conversionRate * precisionFactor;
} }
} }

View file

@ -65,9 +65,10 @@ public class Main {
// test.testDecodeMemo(); // test.testDecodeMemo();
// test.testGetRelativeAccountHistory(); // test.testGetRelativeAccountHistory();
// test.testLookupAssetSymbols(); // test.testLookupAssetSymbols();
test.testListAssets(); // test.testListAssets();
test.testGetObjects();
// test.testGetBlockHeader(); // test.testGetBlockHeader();
//test.testGetLimitOrders(); // test.testGetLimitOrders();
// test.testGetTradeHistory(); // test.testGetTradeHistory();
// test.testAssetSerialization(); // test.testAssetSerialization();
// test.testGetMarketHistory(); // test.testGetMarketHistory();

View file

@ -1,5 +1,12 @@
package de.bitsharesmunich.graphenej; package de.bitsharesmunich.graphenej;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
/** /**
* The price struct stores asset prices in the Graphene system. * The price struct stores asset prices in the Graphene system.
* *

View file

@ -18,6 +18,7 @@ public class RPC {
public static final String CALL_GET_RELATIVE_ACCOUNT_HISTORY = "get_relative_account_history"; public static final String CALL_GET_RELATIVE_ACCOUNT_HISTORY = "get_relative_account_history";
public static final String CALL_LOOKUP_ACCOUNTS = "lookup_accounts"; public static final String CALL_LOOKUP_ACCOUNTS = "lookup_accounts";
public static final String CALL_LIST_ASSETS = "list_assets"; public static final String CALL_LIST_ASSETS = "list_assets";
public static final String GET_OBJECTS = "get_objects";
public static final String CALL_LOOKUP_ASSET_SYMBOLS = "lookup_asset_symbols"; public static final String CALL_LOOKUP_ASSET_SYMBOLS = "lookup_asset_symbols";
public static final String CALL_GET_BLOCK_HEADER = "get_block_header"; public static final String CALL_GET_BLOCK_HEADER = "get_block_header";
public static final String CALL_GET_LIMIT_ORDERS = "get_limit_orders"; public static final String CALL_GET_LIMIT_ORDERS = "get_limit_orders";

View file

@ -24,6 +24,7 @@ import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -602,7 +603,7 @@ public class Test {
} }
public void testingInvoiceGeneration() { public void testingInvoiceGeneration() {
Invoice.LineItem[] lineItem = new Invoice.LineItem[]{new Invoice.LineItem("Apples", 2, "20 CSD")}; LineItem[] lineItem = new LineItem[]{new LineItem("Apples", 2, 2.00)};
Invoice invoice = new Invoice("bilthon-83", "Bilthon's store", "Invoice #12", "BTS", lineItem, "Thank you", ""); Invoice invoice = new Invoice("bilthon-83", "Bilthon's store", "Invoice #12", "BTS", lineItem, "Thank you", "");
String qrCodeData = Invoice.toQrCode(invoice); String qrCodeData = Invoice.toQrCode(invoice);
System.out.println("qrCodeData"); System.out.println("qrCodeData");
@ -862,10 +863,16 @@ public class Test {
System.out.println("onSuccess"); System.out.println("onSuccess");
List<Asset> resp = (List<Asset>) response.result; List<Asset> resp = (List<Asset>) response.result;
System.out.println(String.format("Got %d assets", resp.size())); System.out.println(String.format("Got %d assets", resp.size()));
int count = 0;
for(Asset asset : resp){ for(Asset asset : resp){
if(asset.isSmartcoin()) if(asset.getBitassetId() != null){
System.out.println("Asset: "+asset.getObjectId()+", Symbol: "+asset.getSymbol()); System.out.println("Asset: " + asset.getObjectId() +
", Symbol: "+asset.getSymbol() +
", bitasset id: "+asset.getBitassetId());
count++;
}
} }
System.out.println("Got "+count+" smartcoins");
} }
@Override @Override
@ -896,6 +903,48 @@ public class Test {
} }
} }
public void testGetObjects(){
WitnessResponseListener listener = new WitnessResponseListener() {
@Override
public void onSuccess(WitnessResponse response) {
System.out.println("onSuccess");
List<BitAssetData> bitAssetDataArray = (List<BitAssetData>) response.result;
for(BitAssetData bitAssetData : bitAssetDataArray){
// System.out.println(String.format("is prediction market: %b", bitAssetData.is_prediction_market));
System.out.println("base: "+bitAssetData.current_feed.core_exchange_rate.base.getAmount().longValue());
System.out.println("quote: "+bitAssetData.current_feed.core_exchange_rate.quote.getAmount().longValue());
}
}
@Override
public void onError(BaseResponse.Error error) {
System.out.println("onError");
}
};
SSLContext context = null;
try {
context = NaiveSSLContext.getInstance("TLS");
WebSocketFactory factory = new WebSocketFactory();
// Set the custom SSL context.
factory.setSSLContext(context);
WebSocket mWebSocket = factory.createSocket(BLOCK_PAY_DE);
ArrayList<String> ids = new ArrayList<>();
ids.add("2.4.54");
mWebSocket.addListener(new GetObjects(ids, listener));
mWebSocket.connect();
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException. Msg: " + e.getMessage());
} catch (WebSocketException e) {
System.out.println("WebSocketException. Msg: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException. Msg: " + e.getMessage());
}
}
public void testGetBlockHeader(){ public void testGetBlockHeader(){
WitnessResponseListener listener = new WitnessResponseListener() { WitnessResponseListener listener = new WitnessResponseListener() {
@Override @Override
@ -943,20 +992,24 @@ public class Test {
WebSocket mWebSocket = factory.createSocket(BLOCK_PAY_DE); WebSocket mWebSocket = factory.createSocket(BLOCK_PAY_DE);
mWebSocket.addListener(new GetLimitOrders("1.3.562", "1.3.0", 100, new WitnessResponseListener() { Asset base = new Asset("1.3.120", "EUR", 4);
Asset quote = new Asset("1.3.121", "USD", 4);
mWebSocket.addListener(new GetLimitOrders(base.getObjectId(), quote.getObjectId(), 100, new WitnessResponseListener() {
@Override @Override
public void onSuccess(WitnessResponse response) { public void onSuccess(WitnessResponse response) {
List<LimitOrder> orders = (List<LimitOrder>) response.result; List<LimitOrder> orders = (List<LimitOrder>) response.result;
Converter converter = new Converter();
System.out.println();
for(LimitOrder order : orders){ for(LimitOrder order : orders){
System.out.println(String.format("OBITS: %d, BTS: %d", order.sell_price.base.getAmount().longValue(), order.sell_price.quote.getAmount().longValue())); // System.out.println(String.format("base: %d, quote: %d",
double price = (((double) order.sell_price.quote.getAmount().longValue()) / ((double) order.sell_price.base.getAmount().longValue())); // order.sell_price.base.getAmount().longValue(),
System.out.println(String.format("Selling %s for %s at %f %s/%s, expiration: %s", // order.sell_price.quote.getAmount().longValue()));
order.sell_price.base.getAsset().getObjectId(), order.sell_price.base.getAsset().setPrecision(base.getPrecision());
order.sell_price.quote.getAsset().getObjectId(), order.sell_price.quote.getAsset().setPrecision(quote.getPrecision());
price, double baseToQuoteExchange = converter.getConversionRate(order.sell_price, Converter.BASE_TO_QUOTE);
order.sell_price.base.getAsset().getObjectId(), double quoteToBaseExchange = converter.getConversionRate(order.sell_price, Converter.QUOTE_TO_BASE);
order.sell_price.quote.getAsset().getObjectId(), System.out.println(String.format("base to quote: %.5f, quote to base: %.5f", baseToQuoteExchange, quoteToBaseExchange));
order.expiration));
} }
} }
@ -1056,7 +1109,7 @@ public class Test {
WebSocket mWebSocket = factory.createSocket(BLOCK_PAY_FR); WebSocket mWebSocket = factory.createSocket(BLOCK_PAY_FR);
long posixInstant = 1482436057000l; long posixInstant = 1484089226000l;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(posixInstant); cal.setTimeInMillis(posixInstant);
cal.set(Calendar.SECOND, 0); cal.set(Calendar.SECOND, 0);

View file

@ -26,7 +26,7 @@ public abstract class BaseGrapheneHandler extends WebSocketAdapter {
@Override @Override
public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception { public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception {
System.out.println("handleCallbackError. cause: "+cause.getMessage()+", error: "+cause.getClass()); System.out.println("handleCallbackError. message: "+cause.getMessage()+", error: "+cause.getClass());
for (StackTraceElement element : cause.getStackTrace()){ for (StackTraceElement element : cause.getStackTrace()){
System.out.println(element.getFileName()+"#"+element.getClassName()+":"+element.getLineNumber()); System.out.println(element.getFileName()+"#"+element.getClassName()+":"+element.getLineNumber());
} }

View file

@ -1,7 +1,71 @@
package de.bitsharesmunich.graphenej.api; package de.bitsharesmunich.graphenej.api;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketFrame;
import de.bitsharesmunich.graphenej.Asset;
import de.bitsharesmunich.graphenej.AssetAmount;
import de.bitsharesmunich.graphenej.RPC;
import de.bitsharesmunich.graphenej.interfaces.WitnessResponseListener;
import de.bitsharesmunich.graphenej.models.ApiCall;
import de.bitsharesmunich.graphenej.models.BitAssetData;
import de.bitsharesmunich.graphenej.models.WitnessResponse;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** /**
* Created by nelson on 1/8/17. * Created by nelson on 1/8/17.
*/ */
public class GetObjects { public class GetObjects extends BaseGrapheneHandler {
private List<String> ids;
public GetObjects(List<String> ids, WitnessResponseListener listener){
super(listener);
this.ids = ids;
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
ArrayList<Serializable> params = new ArrayList<>();
ArrayList<Serializable> subParams = new ArrayList<>();
for(String id : this.ids){
subParams.add(id);
}
params.add(subParams);
ApiCall apiCall = new ApiCall(0, RPC.GET_OBJECTS, params, RPC.VERSION, 0);
websocket.sendText(apiCall.toJsonString());
}
@Override
public void onTextFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
if(frame.isTextFrame()){
System.out.println("<< "+frame.getPayloadText());
}
String response = frame.getPayloadText();
GsonBuilder gsonBuilder = new GsonBuilder();
//TODO: Uncomment this line after the deserializer is implemented.
gsonBuilder.registerTypeAdapter(AssetAmount.class, new AssetAmount.AssetDeserializer());
// gsonBuilder.registerTypeAdapter(BitAssetData.class, new BitAssetData.BitAssetDeserializer());
// Only homogeneus array is currently supported
if(ids.get(0).split("\\.")[1].equals("4")){
Type BitAssetDataType = new TypeToken<WitnessResponse<List<BitAssetData>>>(){}.getType();
WitnessResponse<List<BitAssetData>> witnessResponse = gsonBuilder.create().fromJson(response, BitAssetDataType);
mListener.onSuccess(witnessResponse);
}
websocket.disconnect();
}
@Override
public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
if(frame.isTextFrame()){
System.out.println(">> "+frame.getPayloadText());
}
}
} }

View file

@ -1,7 +1,13 @@
package de.bitsharesmunich.graphenej.models; package de.bitsharesmunich.graphenej.models;
import de.bitsharesmunich.graphenej.Price;
/** /**
* Created by nelson on 1/9/17. * Created by nelson on 1/9/17.
*/ */
public class AssetFeed { public class AssetFeed {
public Price settlement_price;
public long maintenance_collateral_ratio;
public long maximum_short_squeeze_ratio;
public Price core_exchange_rate;
} }

View file

@ -1,7 +1,21 @@
package de.bitsharesmunich.graphenej.models; package de.bitsharesmunich.graphenej.models;
import de.bitsharesmunich.graphenej.Price;
/** /**
* This is the representation of the response from the 'get_objects' call with
* a 2.4.x id, which will retrieve a 'impl_asset_bitasset_data_type'.
*
* Created by nelson on 1/8/17. * Created by nelson on 1/8/17.
*/ */
public class BitAssetData { public class BitAssetData {
public String id;
public Object[] feeds;
public AssetFeed current_feed;
public String current_feed_publication_time;
public Object options;
public long force_settled_volume;
public boolean is_prediction_market;
public Price settlement_price;
public long settlement_fund;
} }