Created
May 16, 2019 20:37
-
-
Save cesardeazevedo/6991942f9cff0a853715ac96f03c1011 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package blinktrade; | |
import java.net.URI; | |
import java.util.Arrays; | |
import java.util.stream.Collectors; | |
import java.lang.reflect.Field; | |
import java.lang.Math; | |
import org.java_websocket.WebSocketImpl; | |
import org.java_websocket.client.WebSocketClient; | |
import org.java_websocket.handshake.ServerHandshake; | |
public class BlinkTrade { | |
private static final String ENDPOINT = "ws://bitcambio_api.blinktrade.com/trade/"; | |
private static final String HOST = "bitcambio_api.blinktrade.com"; | |
private WebSocketClient client; | |
public void heartbeat() { | |
long date = System.currentTimeMillis() / 1000L; | |
String msg = String.format("{\"MsgType\": \"1\", \"TestReqID\": %d, \"SendTime\": %d}", date, date); | |
client.send(msg); | |
} | |
public void subscribeTicker(String[] data) { | |
int reqId = (int) (Math.random() * 1e7); | |
String instruments = Arrays | |
.stream(data) | |
.map(x -> "\"" + x + "\"") | |
.collect(Collectors.joining(",")); | |
String msg = String.format( | |
"{\"MsgType\": \"e\", \"SecurityStatusReqID\": %d, \"SubscriptionRequestType\": \"1\", \"Instruments\": [%s]}", | |
reqId, | |
instruments | |
); | |
client.send(msg); | |
} | |
// Reflection hack to supports endpoints with underscores | |
public static URI getURI(String url, String host) throws Exception { | |
URI uri = new URI(BlinkTrade.ENDPOINT); | |
if (uri.getHost() == null) { | |
final Field hostField = URI.class.getDeclaredField("host"); | |
hostField.setAccessible(true); | |
hostField.set(uri, host); | |
} | |
return uri; | |
} | |
public static void main(String[] args) throws Exception { | |
BlinkTrade blinktrade = new BlinkTrade(); | |
URI uri = BlinkTrade.getURI(BlinkTrade.ENDPOINT, BlinkTrade.HOST); | |
blinktrade.client = new WebSocketClient(uri) { | |
@Override | |
public void onOpen(ServerHandshake handshake) { | |
System.out.println("Opened"); | |
} | |
@Override | |
public void onClose(int code, String reason, boolean remote) { | |
System.out.println("Closed: " + code + " : " + reason); | |
} | |
@Override | |
public void onError(Exception ex) { | |
System.out.println("Error"); | |
ex.printStackTrace(System.out); | |
} | |
@Override | |
public void onMessage(String message) { | |
if (message.indexOf("\"f\"") != -1) { | |
System.out.println(message); | |
} | |
} | |
}; | |
// Connect! | |
blinktrade.client.connectBlocking(); | |
blinktrade.heartbeat(); | |
blinktrade.subscribeTicker(new String[] { "BLINK:BTCBRL", "UOL:USDBRT", "UOL:USDBRL" }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment