-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdukascopyHttpPostJForex.java
More file actions
316 lines (260 loc) · 12.7 KB
/
dukascopyHttpPostJForex.java
File metadata and controls
316 lines (260 loc) · 12.7 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package singlejartest;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class Main {
// login credentials contest demo account
private static String userName = "DEMO";
private static String password = "PASS";
private static int forceSsl = 0;
// server file path http
private static String postUrl = "http://localhost/index.php";
// user browser
private static String USER_AGENT = "Mozilla/5.0";
// dukascopy demo account login
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String accountId = "0";
private static double accountBalance = 0;
private static double accountEquity = 0;
private static String serverResult = "";
// log
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
// open positions string
private static String pos ="";
//static String[] columns = {"AccountId","OpenTime", "Id", "Instrument", "Side", "Amount", "Open Price", "Stop Loss", "Take Profit","Label","Comment"};
//static String[][] data = new String[50][11];
public static void main(String[] args) throws Exception {
final IClient client = ClientFactory.getDefaultInstance();
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
public void onStart(long procid) {
//IConsole console = context.getConsole();
LOGGER.info("Welcome");
}
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
@Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 10000000;
}
@Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
//LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting ...");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
private IEngine engine;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
engine = context.getEngine();
// force ssl
if(forceSsl == 1){
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
}// end force ssl
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
//console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onAccount(IAccount account) throws JFException {
accountId = account.getAccountId();
accountBalance = account.getBalance();
accountEquity = account.getEquity();
}
public void onTick(Instrument instrument, ITick tick) throws JFException {
try {
pos = "";
for(IOrder o : engine.getOrders()){
if(o.getProfitLossInUSD() != 987654231){
console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Get order
String Account = "" + accountId;
String OpenTime = "" + o.getFillTime();
String Id = "" + o.getId();
String Instrument = "" + o.getInstrument();
String Isbuy = "" + o.getOrderCommand().isLong();
String Volume = "" + o.getAmount();
String Open = "" + o.getOpenPrice();
String Sl = "" + o.getStopLossPrice();
String Tp = "" + o.getTakeProfitPrice();
String Comment = "" + o.getComment();
String Label = "" + o.getLabel();
pos = pos +
Account + ";" +
OpenTime + ";" +
Id + ";" +
Instrument + ";" +
Isbuy + ";" +
Volume + ";" +
Open + ";" +
Sl + ";" +
Tp + ";" +
Label + ";" +
Comment + "[space]";
}
}
//=================================================================== send get == need commerciall ssl like startssl.com and serveralias and servername in virtualhost
//URL hp = new URL("http://localhost/index.php?line="+pos);
//HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
//boolean isProxy = hpCon.usingProxy();
//System.out.println("is using proxy " + isProxy);
//InputStream obj = hpCon.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(obj));
//String s;
//while ((s = br.readLine()) != null) {
//System.out.println("From Server : " + s);
//}
//===================================================================== end
//===================================================================== send post request to server
console.getOut().println("=====================================================================================" );
System.out.println("Equity: " + accountEquity);
System.out.println("Balance: " + accountBalance);
console.getOut().println("=====================================================================================" );
console.getOut().println("=====================================================================================" );
System.out.println("From Client : " + pos);
console.getOut().println("=====================================================================================" );
URL obj = new URL(postUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "line=" + pos + "&balance=" + accountBalance + "&equity=" + accountEquity;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//int responseCode = con.getResponseCode();
//System.out.println("\nSending 'POST' request to URL : " + url);
//System.out.println("Post parameters : " + urlParameters);
//System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// save result
serverResult = response.toString();
//print result
System.out.println("From Server : " + serverResult );
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
// context.stop();
}
console.getOut().println("=====================================================================================" );
}
public void onMessage(IMessage message) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop program
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
s.close();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}