forked from RayCui/java-api-streaming
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathJavaApiStreaming.java
More file actions
80 lines (62 loc) · 2.97 KB
/
JavaApiStreaming.java
File metadata and controls
80 lines (62 loc) · 2.97 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
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.HttpClientBuilder;
import org.apache.http.client.HttpClient;
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 {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
// Set these variables to whatever personal ones are preferred
String domain = "https://stream-fxpractice.oanda.com";
String access_token = "ACCESS-TOKEN";
String account_id = "1234567";
String instruments = "EUR_USD,USD_JPY,EUR_JPY";
HttpUriRequest httpGet = new HttpGet(domain + "/v1/prices?accountId=" + account_id + "&instruments=" + instruments);
httpGet.setHeader(new BasicHeader("Authorization", "Bearer " + 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;
// unwrap if necessary
if (tick.containsKey("tick")) {
tick = (JSONObject) tick.get("tick");
}
// 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();
}
}
}