Hi All,
I have such a thing (save opened positions to file and display in table like text) but generates error:
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.awt.Color;
import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import javax.swing.JFrame;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "DEMO2PRFwj";
private static String password = "PRFwj";
static String[] columns = {"Open Time", "Id", "Label", "Comment", "Instrument", "Side", "Amount", "Orginal Amount", "Open Price", "Stop Loss", "Take Profit", "Profit (Pips)", "Profit Currency", "Profit in USD", "Commission", "Commission USD"};
static String[][] data = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"}};
//static String[][] data = null;
static JFrame jf = new JFrame();
public static void main(String[] args) throws Exception {
PositionsWindow t = new PositionsWindow(columns, data);
t.setBackground(Color.decode("#FFFFFF"));
jf.setTitle("Master opened positions");
jf.setBackground(Color.BLACK);
jf.setSize(1320, 300);
jf.setResizable(false);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
public void onStart(long procid) {
//IConsole console = context.getConsole();
LOGGER.info("Strategy started: ");
}
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 = 3;
}
@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 strategy");
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();
}
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 onTick(Instrument instrument, ITick tick) throws JFException {
try {
// Create file
Writer fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
String newLine = System.getProperty("line.separator");
int xx = 0;
for(IOrder o : engine.getOrders()){
if(o.getProfitLossInUSD() != 987654231){
console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Object to string
String ObjectToString = "" + o.getInstrument();
String ObjectToString1 = "" + o.getProfitLossInPips();
///========================================================== generate errors
data[xx][4] = ObjectToString;
data[xx][11] = ObjectToString1;
xx++;
// write to file
out.write(
o.getCreationTime() +
";" + o.getId() +
";" + o.getLabel() +
";" + o.getComment() +
";" + o.getInstrument() +
";" + o.getOrderCommand() +
";" + o.getAmount() +
";" + o.getOriginalAmount() +
";" + o.getOpenPrice() +
";" + o.getStopLossPrice() +
";" + o.getTakeProfitPrice() +
";" + o.getProfitLossInPips()+
";" + o.getProfitLossInAccountCurrency() +
";" + o.getProfitLossInUSD() +
";" + o.getCommission() +
";" + o.getCommissionInUSD() +
";" + newLine);
}
}
out.close();
} 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 onAccount(IAccount account) 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 the strategy
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
jf.revalidate();
jf.repaint();
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
and jtable class
package singlejartest;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
public class PositionsWindow extends JPanel{
public PositionsWindow(String[] columns, String[][] data){
JTable jt = new JTable(data,columns){
public boolean isCellEditable(int data, int columns){
return false;
}
public Component prepareRenderer(TableCellRenderer r, int data, int columns){
Component c = super.prepareRenderer(r, data, columns);
if(data % 2 == 0){
c.setBackground(Color.WHITE);
c.setForeground(Color.decode("#000000"));
}else{
c.setBackground(Color.LIGHT_GRAY);
c.setForeground(Color.decode("#FFFFFF"));
}
if(isCellSelected(data, columns)){
c.setBackground(Color.decode("#0099FF"));
c.setForeground(Color.decode("#FFFFFF"));
}
return c;
}
};
jt.setFont(new Font("Tahoma", Font.PLAIN, 11));
jt.setPreferredScrollableViewportSize(new Dimension(1300, 100));
jt.setFillsViewportHeight(true);
jt.setBackground(Color.decode("#FFFFFF"));
jt.setFillsViewportHeight(true);
//jt.repaint();
JScrollPane jps = new JScrollPane(jt);
//jt.setFillsViewportHeight(true);
add(jps);
}
}
and the question is how to improve what I wrote to work correctly.
I need to display the position of the table (as text) and refresh these when data changes (The table is updated only when I click on it)
Have a nice dayzix