-
Notifications
You must be signed in to change notification settings - Fork 20
/
JavaApiStreaming.java
67 lines (52 loc) · 2.49 KB
/
JavaApiStreaming.java
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
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import org.apache.http.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JavaApiStreaming {
public static void main (String[]args) throws IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpUriRequest httpGet = new HttpGet("https://stream-fxpractice.oanda.com/v1/quote?accountId=<your-account-id>&instruments=EUR_USD,USD_CAD,USD_JPY");
httpGet.setHeader(new BasicHeader("Authorization", "Bearer <your-access-token>"));
System.out.println("Executing request: " + httpGet.getRequestLine());
HttpResponse resp = httpClient.execute(httpGet);
HttpEntity entity = resp.getEntity();
if (resp.getStatusLine().getStatusCode() == 200 && entity != null) {
InputStream stream = entity.getContent();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
Object obj = JSONValue.parse(line);
JSONObject tick = (JSONObject) obj;
//ignore heartbeats
if (tick.containsKey("instrument")) {
System.out.println("-------");
String instrument = tick.get("instrument").toString();
String time = tick.get("time").toString();
double bid = Double.parseDouble(tick.get("bid").toString());
double ask = Double.parseDouble(tick.get("ask").toString());
System.out.println(instrument);
System.out.println(time);
System.out.println(bid);
System.out.println(ask);
}
}
} else {
// print error message
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
}
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}