package gui.tests;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import singlejartest.MA_Play;
import com.dukascopy.api.DataType;
import com.dukascopy.api.Filter;
import com.dukascopy.api.IChart;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.LoadingProgressListener;
import com.dukascopy.api.OfferSide;
import com.dukascopy.api.Period;
import com.dukascopy.api.PriceRange;
import com.dukascopy.api.ReversalAmount;
import com.dukascopy.api.TickBarSize;
import com.dukascopy.api.feed.FeedDescriptor;
import com.dukascopy.api.feed.IFeedDescriptor;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.ITesterClient;
import com.dukascopy.api.system.TesterFactory;
import com.dukascopy.api.system.tester.ITesterChartController;
import com.dukascopy.api.system.tester.ITesterExecution;
import com.dukascopy.api.system.tester.ITesterExecutionControl;
import com.dukascopy.api.system.tester.ITesterGui;
import com.dukascopy.api.system.tester.ITesterUserInterface;
import static com.dukascopy.api.DataType.*;
import static com.dukascopy.api.Instrument.*;
import static com.dukascopy.api.PriceRange.*;
import static com.dukascopy.api.TickBarSize.*;
@SuppressWarnings("serial")
public class GUIModeChartTypes extends JFrame implements ITesterUserInterface, ITesterExecution {
private static final Logger LOGGER = LoggerFactory.getLogger(GUIModeChartTypes.class);
private final int frameWidth = 1000;
private final int frameHeight = 600;
private final int controlPanelHeight = 40;
private JPanel currentChartPanel = null;
private ITesterExecutionControl executionControl = null;
private JPanel controlPanel = null;
private JButton startStrategyButton = null;
private JButton pauseButton = null;
private JButton continueButton = null;
private JButton cancelButton = null;
private FeedDescriptorPanel feedDescriptorPanel;
private ITesterChartController chartController;
private IChart currentChart;
private IFeedDescriptor feedDescriptor = new FeedDescriptor();
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "userName";
private static String password = "password";
public GUIModeChartTypes(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
}
@Override
public void setChartPanels(Map<IChart, ITesterGui> chartPanels) {
if(chartPanels != null && chartPanels.size() > 0){
IChart chart = chartPanels.keySet().iterator().next();
currentChart = chart;
chartController = chartPanels.get(chart).getTesterChartController();
setTitle("Chart type example");
chartController.setFeedDescriptor(feedDescriptor);
JPanel chartPanel = chartPanels.get(chart).getChartPanel();
addChartPanel(chartPanel);
}
}
@Override
public void setExecutionControl(ITesterExecutionControl executionControl) {
this.executionControl = executionControl;
}
public void startStrategy() throws Exception {
final ITesterClient client = TesterFactory.getDefaultInstance();
client.setSystemListener(new ISystemListener() {
@Override
public void onStart(long processId) {
LOGGER.info("ストラテジー起動: " + processId);
updateButtons();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onStop(long processId) {
LOGGER.info("ストラテジー停止: " + processId);
resetButtons();
File reportFile = new File("C:\\report.html");
try {
client.createReport(processId, reportFile);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
if (client.getStartedStrategies().size() == 0) {
}
}
@Override
public void onConnect() {
LOGGER.info("接続完了");
}
@Override
public void onDisconnect() {
}
});
LOGGER.info("接続中…");
client.connect(jnlpUrl, userName, password);
int i = 10;
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("デューカスコピーのサーバーに接続出来ませんでした");
System.exit(1);
}
final Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("通貨ペア登録…");
client.setSubscribedInstruments(instruments);
client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 50000);
LOGGER.info("データのダウンロード中");
Future<?> future = client.downloadData(null);
future.get();
LOGGER.info("ストラテジー開始");
client.startStrategy(
new MA_Play(),
new LoadingProgressListener() {
@Override
public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
LOGGER.info("dataLoaded " + information);
}
@Override
public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {
LOGGER.info("loadingFinished " + allDataLoaded);
}
@Override
public boolean stopJob() {
return false;
}
}, this, this
);
Runnable r2 = new Runnable() {
public void run() {
try {
int waitTimeSecs = 300;
LOGGER.info("チャートロード完了するまで最大で" + waitTimeSecs + "秒かかります。 " +
"ロードを短縮するにはcurrentChart.getBarsCount()を減らしてください" +
"(手動でチャートの水平スケールを減らして下さい)。");
executionControl.pauseExecution();
updateButtons();
long startTime = System.currentTimeMillis();
try {
while ((currentChart == null ||
Math.abs(currentChart.priceMin(0)) < 0.00001) && System.currentTimeMillis() - startTime < waitTimeSecs * 1000) {
if (currentChart != null){
int secsLeft = (int) (waitTimeSecs - (System.currentTimeMillis() - startTime) /1000);
LOGGER.info(String.format("安値=%.5f, チャート上のバー数=%s, 残り時間=%s秒",
currentChart.priceMin(0), currentChart.getBarsCount(), secsLeft));
}
Thread.sleep(1000);
}
} catch (Exception e2) {
LOGGER.error(e2.getMessage(), e2);
e2.printStackTrace();
}
LOGGER.info("チャートロード完了。経過時間:" + ((System.currentTimeMillis() - startTime)/1000) + "秒。" +
"テストを開始するにはcontinueボタンを押してください。");
} catch (Exception e2) {
LOGGER.error(e2.getMessage(), e2);
e2.printStackTrace();
}
}
};
Thread t2 = new Thread(r2);
t2.start();
}
private class FeedDescriptorPanel extends JPanel{
private JComboBox comboBoxDataType;
private JComboBox comboBoxInstrument;
private JComboBox comboBoxOfferSide;
private JComboBox comboBoxFilter;
private JComboBox comboBoxPeriod;
private JComboBox comboBoxPriceRange;
private JComboBox comboBoxReversalAmount;
private JComboBox comboBoxTickBarSize;
private JButton buttonApplyChanges;
public FeedDescriptorPanel(){
this.setLayout(new FlowLayout(FlowLayout.LEFT));
comboBoxDataType = setupComboBox(DataType.values(),"Data type", DataType.TIME_PERIOD_AGGREGATION);
comboBoxInstrument = setupComboBox(new Instrument [] {EURUSD, USDJPY, USDCAD}, "Instrument", EURUSD);
comboBoxOfferSide = setupComboBox(OfferSide.values(), "Offer Side", OfferSide.BID);
comboBoxFilter = setupComboBox(Filter.values(), "Filter", Filter.NO_FILTER);
comboBoxPeriod = setupComboBox(Period.values(), "Period", Period.TEN_MINS);
comboBoxPriceRange = setupComboBox(new PriceRange [] {ONE_PIP, TWO_PIPS, THREE_PIPS, FOUR_PIPS, FIVE_PIPS, SIX_PIPS},
"Price Range", TWO_PIPS);
comboBoxReversalAmount = setupComboBox(new ReversalAmount [] {ReversalAmount.ONE, ReversalAmount.TWO, ReversalAmount.THREE},
"Reversal Amount", ReversalAmount.TWO);
comboBoxTickBarSize = setupComboBox(new TickBarSize [] {TWO, THREE, FOUR, FIVE}, "Tick Bar Size", THREE);
add(comboBoxDataType);
add(comboBoxPeriod);
add(comboBoxInstrument);
add(comboBoxOfferSide);
add(comboBoxFilter);
add(comboBoxPriceRange);
add(comboBoxReversalAmount);
add(comboBoxTickBarSize);
buttonApplyChanges = new JButton("Apply changes");
buttonApplyChanges.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
updateFeedDesciptor();
}
});
add(buttonApplyChanges);
updateFeedDesciptor();
updateComboBoxes();
}
private JComboBox setupComboBox(final Object items[], String name, Object defaultValue){
JComboBox comboBox = new JComboBox(items);
comboBox.setSelectedItem(defaultValue);
comboBox.addActionListener(new ActionListener (){
@Override
public void actionPerformed(ActionEvent e) {
updateComboBoxes();
}
});
comboBox.setToolTipText(name);
return comboBox;
}
private void updateComboBoxes(){
DataType dataType = (DataType)comboBoxDataType.getSelectedItem();
comboBoxDataType.setVisible(true);
comboBoxInstrument.setVisible(true);
comboBoxOfferSide.setVisible( dataType != TICKS);
comboBoxFilter.setVisible( dataType == TIME_PERIOD_AGGREGATION);
comboBoxPeriod.setVisible( dataType == TIME_PERIOD_AGGREGATION);
comboBoxPriceRange.setVisible( dataType == PRICE_RANGE_AGGREGATION
|| dataType == POINT_AND_FIGURE
|| dataType == RENKO);
comboBoxReversalAmount.setVisible(dataType == POINT_AND_FIGURE);
comboBoxTickBarSize.setVisible( dataType == TICK_BAR);
}
private void updateFeedDesciptor(){
feedDescriptor.setDataType( (DataType )comboBoxDataType.getSelectedItem());
feedDescriptor.setInstrument( (Instrument )comboBoxInstrument.getSelectedItem());
feedDescriptor.setPeriod( (Period )comboBoxPeriod.getSelectedItem());
feedDescriptor.setOfferSide( (OfferSide )comboBoxOfferSide.getSelectedItem());
feedDescriptor.setFilter( (Filter )comboBoxFilter.getSelectedItem());
feedDescriptor.setPriceRange( (PriceRange )comboBoxPriceRange.getSelectedItem());
feedDescriptor.setReversalAmount((ReversalAmount)comboBoxReversalAmount.getSelectedItem());
feedDescriptor.setTickBarSize( (TickBarSize )comboBoxTickBarSize.getSelectedItem());
if(chartController != null)
chartController.setFeedDescriptor(feedDescriptor);
}
}
private void centerFrame(){
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
}
private void addChartPanel(JPanel chartPanel){
removecurrentChartPanel();
this.currentChartPanel = chartPanel;
chartPanel.setPreferredSize(new Dimension(frameWidth, frameHeight - controlPanelHeight));
chartPanel.setMinimumSize(new Dimension(frameWidth, 200));
chartPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
getContentPane().add(chartPanel);
this.validate();
chartPanel.repaint();
}
private void addControlPanel(){
controlPanel = new JPanel();
FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT);
controlPanel.setLayout(flowLayout);
controlPanel.setPreferredSize(new Dimension(frameWidth, controlPanelHeight));
controlPanel.setMinimumSize(new Dimension(frameWidth, controlPanelHeight));
controlPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, controlPanelHeight));
startStrategyButton = new JButton("Start strategy");
startStrategyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startStrategyButton.setEnabled(false);
Runnable r = new Runnable() {
public void run() {
try {
startStrategy();
} catch (Exception e2) {
LOGGER.error(e2.getMessage(), e2);
e2.printStackTrace();
resetButtons();
}
}
};
Thread t = new Thread(r);
t.start();
}
});
pauseButton = new JButton("Pause");
pauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(executionControl != null){
executionControl.pauseExecution();
updateButtons();
}
}
});
continueButton = new JButton("Continue");
continueButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(executionControl != null){
executionControl.continueExecution();
updateButtons();
}
}
});
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(executionControl != null){
executionControl.cancelExecution();
updateButtons();
}
}
});
controlPanel.add(startStrategyButton);
controlPanel.add(pauseButton);
controlPanel.add(continueButton);
controlPanel.add(cancelButton);
getContentPane().add(controlPanel);
feedDescriptorPanel = new FeedDescriptorPanel();
getContentPane().add(feedDescriptorPanel);
pauseButton.setEnabled(false);
continueButton.setEnabled(false);
cancelButton.setEnabled(false);
}
private void updateButtons(){
if(executionControl != null){
startStrategyButton.setEnabled(executionControl.isExecutionCanceled());
pauseButton.setEnabled(!executionControl.isExecutionPaused() && !executionControl.isExecutionCanceled());
cancelButton.setEnabled(!executionControl.isExecutionCanceled());
continueButton.setEnabled(executionControl.isExecutionPaused());
}
}
private void resetButtons(){
startStrategyButton.setEnabled(true);
pauseButton.setEnabled(false);
continueButton.setEnabled(false);
cancelButton.setEnabled(false);
}
private void removecurrentChartPanel(){
if(this.currentChartPanel != null){
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
GUIModeChartTypes.this.getContentPane().remove(GUIModeChartTypes.this.currentChartPanel);
GUIModeChartTypes.this.getContentPane().repaint();
}
});
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
public void showChartFrame(){
setSize(frameWidth, frameHeight);
centerFrame();
addControlPanel();
setVisible(true);
}
public static void main(String[] args) throws Exception {
GUIModeChartTypes testerMainGUI = new GUIModeChartTypes();
testerMainGUI.showChartFrame();
}
}