Untitled
unknown
apex
3 years ago
58 kB
12
Indexable
***************/
package JForex.myStrategies;
import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.system.tester.ITesterExecutionControl;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Main Class of the strategy
*/
@RequiresFullAccess // Some functions may need this
public class NephewSamBacktester implements IStrategy {
// configurable variables
@Configurable("Select instrument:")
public Instrument myInstrument = Instrument.EURUSD;
public double myPipValue;
public int myPipScale;
public double bidPrice = 0.00;
public double askPrice = 0.00;
public double spreadDiff = 0.00;
// controls
public boolean isPaused = false;
public Period pauseEvery = null;
// <editor-fold defaultstate="" desc="Main class variables">
// base objects creation
private IContext myContext = null;
private IEngine myEngine = null;
private IConsole myConsole = null;
private IHistory myHistory = null;
private IAccount myAccount = null;
// other variables
private OfflineForm myForm = null;
public Filter filterWeekend = Filter.WEEKENDS;
// </editor-fold>
@Override
public void onStart(IContext context) throws JFException {
try {
// Set cross-platform Java L&F (also called "Metal")
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (IllegalAccessException e) {
JOptionPane.showMessageDialog(null, "IllegalAccessException !", "Strategy Alert",
JOptionPane.WARNING_MESSAGE);
} catch (InstantiationException e) {
JOptionPane.showMessageDialog(null, "InstantiationException !", "Strategy Alert",
JOptionPane.WARNING_MESSAGE);
} catch (UnsupportedLookAndFeelException e) {
JOptionPane.showMessageDialog(null, "UnsupportedLookAndFeelException !", "Strategy Alert",
JOptionPane.WARNING_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "ClassNotFoundException !", "Strategy Alert",
JOptionPane.WARNING_MESSAGE);
}
// objects and variable initialization
myContext = context;
myEngine = context.getEngine();
myConsole = myContext.getConsole();
myHistory = myContext.getHistory();
myAccount = myContext.getAccount();
myPipValue = myInstrument.getPipValue();
myPipScale = myInstrument.getPipScale();
myForm = new OfflineForm();
// avoid to run outside of Historical Tester
if (myEngine.getType() != IEngine.Type.TEST) {
JOptionPane.showMessageDialog(null, "This strategy only runs on Historical Tester !", "Strategy Alert",
JOptionPane.WARNING_MESSAGE);
myContext.stop();
} else {
Set subscribedInstruments = new HashSet();
subscribedInstruments.add(myInstrument);
myContext.setSubscribedInstruments(subscribedInstruments);
myForm.setVisible(true);
}
}// end onStart
@Override
public void onTick(Instrument instrument, ITick tick) throws JFException {
if (myInstrument == instrument) { // filter
bidPrice = tick.getBid();
askPrice = tick.getAsk();
spreadDiff = (askPrice - bidPrice) / instrument.getPipValue();
myForm.updatePrices();
myForm.updateTableOrders();
}
}// end onTick
@Override
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
boolean marketClose = isWeekend();
if (period.equals(pauseEvery) && !marketClose) {
myContext.pause();
}
}// end onBar
// use of calendar
private boolean isWeekend() throws JFException {
long lastTickTime = myHistory.getLastTick(myInstrument).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(lastTickTime);
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
int currentMinute = calendar.get(Calendar.MINUTE);
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentDay = calendar.get(Calendar.DAY_OF_WEEK);
// print("Current Day: " + currentDay + ", Current Hour: " + currentHour + ",
// Current Minute: " + currentMinute);
boolean result = (currentDay == 1 && currentHour <= 21) || (currentDay == 7)
|| (currentDay == 6 && currentHour >= 20 && currentMinute > 58);
return result;
}
@Override
public void onMessage(IMessage message) throws JFException {
// remove of the order on the table at order close
// if(message.getType() == IMessage.Type.ORDER_CLOSE_OK){
// myForm.removeTableOrder(message.getOrder().getId());
// }
// when the server accepted the order fill the stop loss and take profit
// if we choose them and put the order on the table
// if(message.getType() == IMessage.Type.ORDER_SUBMIT_OK){
// if(!(message.getOrder().getOrderCommand() == OrderCommand.BUY ||
// message.getOrder().getOrderCommand() == OrderCommand.SELL)){
// myForm.setTpSl(message.getOrder());
// }
// }
// // same as before but for order fill and only update the order status
// // if not filled on the table
// if (message.getType() == IMessage.Type.ORDER_FILL_OK){
// if(message.getOrder().getOrderCommand() == OrderCommand.BUY ||
// message.getOrder().getOrderCommand() == OrderCommand.SELL){
// myForm.setTpSl(message.getOrder());
// }
// }
// update of the table at any order change
// if(message.getType() == IMessage.Type.ORDER_CHANGED_OK){
// myForm.updateTableOrder(message.getOrder());
// }
}// end onMessage
@Override
public void onAccount(IAccount account) throws JFException {
}// end onAccount
@Override
public void onStop() throws JFException {
myForm.setVisible(false);
myForm.dispose();
}// end onStop
public void print(String string) {
myConsole.getOut().println(string);
}// end print
class OfflineForm extends JFrame implements ActionListener {
private JComboBox lotsDropdown = new JComboBox();
private JComboBox entryDropdown = new JComboBox();
private JComboBox tpDropdown = new JComboBox();
private JComboBox slDropdown = new JComboBox();
private JComboBox pauseEveryDropdown = new JComboBox();
private JComboBox partialsDropdown = new JComboBox();
private JTextField lotsField = new JTextField(null);
private JTextField symbolField = new JTextField(null);
private JTextField entryField = new JTextField();
private JTextField slField = new JTextField();
private JTextField tpField = new JTextField();
private JButton buyButton = new JButton();
private JButton spreadButton = new JButton();
private JButton sellButton = new JButton();
private JButton closeTradeButton = new JButton();
private JButton sl2beButton = new JButton();
private JButton updateSLTPButton = new JButton();
private JButton pauseEveryButton = new JButton();
private JPanel mainPanel = new JPanel();
private JPanel headerPanel = new JPanel();
private JPanel lotsPanel = new JPanel();
private JPanel buySellPanel = new JPanel();
private JPanel detailsPanel = new JPanel();
private JPanel tablePanel = new JPanel();
private JPanel controlsPanel = new JPanel();
private JPanel pausePanel = new JPanel();
private DefaultTableModel tradesTableModel = new DefaultTableModel();
private JTable tradesTable = new JTable(tradesTableModel);
private JScrollPane tableScrollPane1 = new JScrollPane();
private GridBagConstraints gbc = new GridBagConstraints();
private JScrollBar scrollBar1 = new JScrollBar();
// order variables
private double myEntry = Double.NaN;
private double myAmount = Double.NaN;
private double myStopLoss = Double.NaN;
private double myStopLossInPips = Double.NaN;
private double myTakeProfit = Double.NaN;
private double mySlippage = 0;
private IOrder myOrder = null;
private int myOrderCounter = 1;
private OrderCommand myOrderCommand = null;
private String selectedRow = null;
// Table Data
final String[] tableHeaders = { "#", "Direction", "Lots", "Entry", "SL", "TP", "PnL" };
Object[][] tableData = new Object[0][0];
/**
* Offline class contructor
* <p>
* Creates new form OfflineForm
*/
public OfflineForm() {
initComponents();
}// end offlineForm
@SuppressWarnings("unchecked")
private void initComponents() {
// action listeners
buyButton.addActionListener(this);
sellButton.addActionListener(this);
lotsDropdown.addActionListener(this);
entryDropdown.addActionListener(this);
slDropdown.addActionListener(this);
tpDropdown.addActionListener(this);
pauseEveryDropdown.addActionListener(this);
closeTradeButton.addActionListener(this);
sl2beButton.addActionListener(this);
pauseEveryButton.addActionListener(this);
updateSLTPButton.addActionListener(this);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// ------------------------------------
// ---------- MAIN CONTAINER ----------
// ------------------------------------
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBackground(new Color(-14933440));
mainPanel.setEnabled(true);
mainPanel.setMaximumSize(new Dimension(-1, -1));
mainPanel.setMinimumSize(new Dimension(360, 460));
mainPanel.setPreferredSize(new Dimension(360, 560));
mainPanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
// ------------------------------------
// -------- Panel 1 (HEADER) ----------
// ------------------------------------
headerPanel.setLayout(new GridBagLayout());
headerPanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 5, 10);
mainPanel.add(headerPanel, gbc);
headerPanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
final JLabel label1 = new JLabel();
Font label1Font = getFont(null, Font.BOLD, 16, label1.getFont());
if (label1Font != null)
label1.setFont(label1Font);
label1.setForeground(new Color(-1909284));
label1.setText("BACKTESTING TOOL By Nephew_Sam_");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 10, 10);
headerPanel.add(label1, gbc);
// ------------------------------------
// ---------- Panel 2 (LOTS) ----------
// ------------------------------------
lotsPanel.setLayout(new GridBagLayout());
lotsPanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
mainPanel.add(lotsPanel, gbc);
lotsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)),
null, TitledBorder.LEFT, TitledBorder.TOP));
// Symbol Label
final JLabel label2 = new JLabel();
Font label2Font = this.getFont(null, -1, 14, label2.getFont());
if (label2Font != null)
label2.setFont(label2Font);
label2.setForeground(new Color(-1909284));
label2.setText("Symbol");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 15, 0, 0);
lotsPanel.add(label2, gbc);
// Lots dropdown
lotsDropdown.setBackground(new Color(-13024660));
lotsDropdown.setForeground(new Color(-1909284));
lotsDropdown.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
defaultComboBoxModel1.addElement("Fixed Lots");
defaultComboBoxModel1.addElement("Balance %");
lotsDropdown.setModel(defaultComboBoxModel1);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.ipadx = 5;
gbc.ipady = 0;
gbc.insets = new Insets(10, 5, 0, 10);
lotsPanel.add(lotsDropdown, gbc);
// Lots field
lotsField.setBackground(new Color(-13024660));
lotsField.setForeground(new Color(-1909284));
lotsField.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
lotsField.setText("1.00");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 5;
gbc.insets = new Insets(5, 5, 10, 10);
lotsPanel.add(lotsField, gbc);
// Symbol Field
symbolField.setBackground(new Color(-13024660));
symbolField.setForeground(new Color(-1909284));
symbolField.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
symbolField.setText(myInstrument.toString());
symbolField.setEnabled(false);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 5;
gbc.insets = new Insets(5, 10, 10, 0);
lotsPanel.add(symbolField, gbc);
// ------------------------------------
// ------- Panel 3 (BUY/SELL) ---------
// ------------------------------------
buySellPanel.setLayout(new GridBagLayout());
buySellPanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
mainPanel.add(buySellPanel, gbc);
buySellPanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
// Buy button
buyButton.setBackground(new Color(-14570184));
buyButton.setBorderPainted(true);
buyButton.setContentAreaFilled(true);
buyButton.setDefaultCapable(true);
buyButton.setEnabled(true);
buyButton.setForeground(new Color(-1909284));
buyButton.setHideActionText(false);
buyButton.setOpaque(true);
buyButton.setRequestFocusEnabled(true);
buyButton.setRolloverEnabled(true);
buyButton.setMaximumSize(new Dimension(85, 30));
buyButton.setMinimumSize(new Dimension(85, 30));
buyButton.setPreferredSize(new Dimension(85, 30));
buyButton.setText("BUY");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 2.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 50;
gbc.insets = new Insets(10, 10, 10, 10);
buySellPanel.add(buyButton, gbc);
// Spread Button
spreadButton.setBackground(new Color(-12762013));
spreadButton.setContentAreaFilled(true);
spreadButton.setEnabled(false);
Font spreadButtonFont = this.getFont(null, -1, 9, spreadButton.getFont());
if (spreadButtonFont != null)
spreadButton.setFont(spreadButtonFont);
spreadButton.setForeground(new Color(-1909284));
spreadButton.setMaximumSize(new Dimension(70, 60));
spreadButton.setMinimumSize(new Dimension(70, 60));
spreadButton.setPreferredSize(new Dimension(70, 60));
spreadButton.setText("SPREAD");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
buySellPanel.add(spreadButton, gbc);
// Sell Button
sellButton.setBackground(new Color(-2341081));
sellButton.setForeground(new Color(-1909284));
sellButton.setText("SELL");
sellButton.setMaximumSize(new Dimension(85, 30));
sellButton.setMinimumSize(new Dimension(85, 30));
sellButton.setPreferredSize(new Dimension(85, 30));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 2.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 50;
gbc.insets = new Insets(10, 10, 10, 10);
buySellPanel.add(sellButton, gbc);
// ------------------------------------
// -------- Panel 4 (DETAILS) ---------
// ------------------------------------
detailsPanel.setLayout(new GridBagLayout());
detailsPanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
mainPanel.add(detailsPanel, gbc);
detailsPanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
// Entry dropwdown
entryDropdown.setBackground(new Color(-13024660));
entryDropdown.setForeground(new Color(-1909284));
entryDropdown.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
final DefaultComboBoxModel defaultComboBoxModel2 = new DefaultComboBoxModel();
defaultComboBoxModel2.addElement("Market");
defaultComboBoxModel2.addElement("Limit");
entryDropdown.setModel(defaultComboBoxModel2);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 0;
gbc.insets = new Insets(10, 5, 5, 5);
detailsPanel.add(entryDropdown, gbc);
// Entry field
entryField.setBackground(new Color(-13024660));
entryField.setForeground(new Color(-4473925));
entryField.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
entryField.setEnabled(false);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 3.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 5;
gbc.insets = new Insets(10, 5, 5, 5);
detailsPanel.add(entryField, gbc);
// SL dropdown
slDropdown.setBackground(new Color(-13024660));
slDropdown.setForeground(new Color(-1909284));
slDropdown.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
final DefaultComboBoxModel defaultComboBoxModel3 = new DefaultComboBoxModel();
defaultComboBoxModel3.addElement("Pips");
defaultComboBoxModel3.addElement("Price");
slDropdown.setModel(defaultComboBoxModel3);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 0;
gbc.insets = new Insets(10, 5, 5, 5);
detailsPanel.add(slDropdown, gbc);
// SL field
slField.setBackground(new Color(-13024660));
slField.setForeground(new Color(-1909284));
slField.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
slField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.weightx = 4.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 5;
gbc.insets = new Insets(10, 5, 5, 5);
detailsPanel.add(slField, gbc);
// TP field
tpField.setBackground(new Color(-13024660));
tpField.setForeground(new Color(-1909284));
tpField.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
tpField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 2;
gbc.weightx = 4.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 5;
gbc.insets = new Insets(10, 5, 10, 5);
detailsPanel.add(tpField, gbc);
// Entry Label
final JLabel label3 = new JLabel();
label3.setForeground(new Color(-1909284));
label3.setText("Entry");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 10, 0, 0);
detailsPanel.add(label3, gbc);
// SL Label
final JLabel label4 = new JLabel();
label4.setForeground(new Color(-1909284));
label4.setText("SL");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 10, 0, 0);
detailsPanel.add(label4, gbc);
// TP Label
final JLabel label5 = new JLabel();
label5.setForeground(new Color(-1909284));
label5.setText("TP");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 10, 0, 0);
detailsPanel.add(label5, gbc);
// TP Dropdown
tpDropdown.setBackground(new Color(-13024660));
tpDropdown.setForeground(new Color(-1909284));
tpDropdown.setBorder(BorderFactory.createLineBorder(new Color(-13024660)));
final DefaultComboBoxModel defaultComboBoxModel4 = new DefaultComboBoxModel();
defaultComboBoxModel4.addElement("Pips");
defaultComboBoxModel4.addElement("Price");
defaultComboBoxModel4.addElement("RR");
tpDropdown.setModel(defaultComboBoxModel4);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.ipady = 0;
gbc.insets = new Insets(10, 5, 10, 5);
detailsPanel.add(tpDropdown, gbc);
// ------------------------------------
// --------- Panel 5 (TABLE) ----------
// ------------------------------------
// Layout and Scrollpane
tablePanel.setLayout(new CardLayout(0, 0));
tablePanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 3;
gbc.weighty = 100.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(10, 10, 10, 10);
mainPanel.add(tablePanel, gbc);
tablePanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
tableScrollPane1 = new JScrollPane();
tableScrollPane1.setBackground(new Color(-12762013));
tablePanel.add(tableScrollPane1, "Card1");
// table
// tradesTable.setBackground(new Color(-12762013));
// tradesTable.setForeground(new Color(-1909284));
tradesTable.setAutoResizeMode(0);
tradesTable.getTableHeader().setReorderingAllowed(false);
tradesTable.setModel(new DefaultTableModel(tableData, tableHeaders));
tradesTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
int row = tradesTable.rowAtPoint(evt.getPoint());
int col = tradesTable.columnAtPoint(evt.getPoint());
selectedRow = tradesTable.getModel().getValueAt(row, 0).toString();
myConsole.getOut().println("Order Selected: " + selectedRow);
}
});
tableScrollPane1.setViewportView(tradesTable);
// ------------------------------------
// -------- Panel 6 (controls) --------
// ------------------------------------
controlsPanel.setLayout(new GridBagLayout());
controlsPanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 10, 10);
mainPanel.add(controlsPanel, gbc);
controlsPanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
// Close Button
closeTradeButton.setBackground(new Color(-12762013));
closeTradeButton.setForeground(new Color(-1909284));
closeTradeButton.setText("Close");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 5, 10, 5);
controlsPanel.add(closeTradeButton, gbc);
// Partials dropdown
partialsDropdown.setBackground(new Color(-13024660));
partialsDropdown.setForeground(new Color(-1909284));
final DefaultComboBoxModel defaultComboBoxModel5 = new DefaultComboBoxModel();
defaultComboBoxModel5.addElement("20%");
defaultComboBoxModel5.addElement("30%");
defaultComboBoxModel5.addElement("40%");
defaultComboBoxModel5.addElement("50%");
defaultComboBoxModel5.addElement("60%");
defaultComboBoxModel5.addElement("70%");
defaultComboBoxModel5.addElement("80%");
defaultComboBoxModel5.addElement("90%");
defaultComboBoxModel5.addElement("100%");
partialsDropdown.setModel(defaultComboBoxModel5);
partialsDropdown.setSelectedItem("100%");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 5, 10, 5);
controlsPanel.add(partialsDropdown, gbc);
// SL to BE button
sl2beButton.setBackground(new Color(-12762013));
sl2beButton.setForeground(new Color(-1909284));
sl2beButton.setText("SL 2 BE");
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 5, 10, 5);
controlsPanel.add(sl2beButton, gbc);
// Delete TP Button
updateSLTPButton.setBackground(new Color(-12762013));
updateSLTPButton.setForeground(new Color(-1909284));
updateSLTPButton.setText("Upd SL+TP");
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 5, 10, 5);
controlsPanel.add(updateSLTPButton, gbc);
// ------------------------------------
// -------- Panel 7 (pause) --------
// ------------------------------------
pausePanel.setLayout(new GridBagLayout());
pausePanel.setBackground(new Color(-14933440));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 10, 5);
mainPanel.add(pausePanel, gbc);
pausePanel.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createLineBorder(new Color(-12762013)), null));
// Label
JLabel pauseLabel = new JLabel();
Font pauseLabelFont = this.getFont(null, -1, 12, pauseLabel.getFont());
if (pauseLabelFont != null)
pauseLabel.setFont(pauseLabelFont);
pauseLabel.setForeground(new Color(-1909284));
pauseLabel.setText("Pause Every:");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 10.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.EAST;
pausePanel.add(pauseLabel, gbc);
// Pause every dropdown
pauseEveryDropdown.setBackground(new Color(-13024660));
pauseEveryDropdown.setForeground(new Color(-1909284));
final DefaultComboBoxModel defaultComboBoxModel6 = new DefaultComboBoxModel();
defaultComboBoxModel6.addElement("None");
defaultComboBoxModel6.addElement("1m");
defaultComboBoxModel6.addElement("5m");
defaultComboBoxModel6.addElement("15m");
defaultComboBoxModel6.addElement("30m");
defaultComboBoxModel6.addElement("1hr");
defaultComboBoxModel6.addElement("4hr");
defaultComboBoxModel6.addElement("1d");
pauseEveryDropdown.setModel(defaultComboBoxModel6);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipadx = 5;
gbc.insets = new Insets(10, 5, 10, 10);
pausePanel.add(pauseEveryDropdown, gbc);
setContentPane(mainPanel);
pack();
setVisible(true);
}// </editor-fold>
private Font getFont(String fontName, int style, int size, Font currentFont) {
if (currentFont == null)
return null;
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(),
size >= 0 ? size : currentFont.getSize());
}
/**
* actionPerformed Function
* <p>
* Window events for radiobuttons and buttons
*
* @param e
*/
@Override
public void actionPerformed(ActionEvent e) {
// If Entry dropdown changed
if (e.getSource() == entryDropdown) {
String value = entryDropdown.getSelectedItem().toString();
if (value == "Market") {
entryField.setText("0");
entryField.setEnabled(false);
} else {
entryField.setText(String.valueOf(bidPrice));
entryField.setEnabled(true);
}
}
// If SL dropdown changed
if (e.getSource() == slDropdown) {
String value = slDropdown.getSelectedItem().toString();
if (value == "Limit") {
slField.setText(String.valueOf(bidPrice));
} else {
slField.setText("10");
}
}
// If SL dropdown changed
if (e.getSource() == tpDropdown) {
String value = tpDropdown.getSelectedItem().toString();
if (value == "Pips") {
tpField.setText("10");
} else if (value == "Limit") {
tpField.setText(String.valueOf(bidPrice));
} else {
tpField.setText("3");
}
}
// BUY BUTTON
if (e.getSource() == buyButton) {
boolean fieldsOk = validateFields("BUY", -111);
if (!fieldsOk) {
return;
}
try {
placeOrder("BUY");
} catch (JFException ex) {
Logger.getLogger(NephewSamBacktester.class.getName()).log(Level.SEVERE, null, ex);
}
}
// SELL BUTTON
if (e.getSource() == sellButton) {
boolean fieldsOk = validateFields("SELL", -111);
if (!fieldsOk) {
return;
}
try {
placeOrder("SELL");
} catch (JFException ex) {
Logger.getLogger(NephewSamBacktester.class.getName()).log(Level.SEVERE, null, ex);
}
}
// CLOSE BUTTON
if (e.getSource() == closeTradeButton && selectedRow != null) {
try {
IOrder order = myEngine.getOrderById(selectedRow);
String dropdownValue = partialsDropdown.getSelectedItem().toString().replace("%", "");
double percentage = Double.parseDouble(dropdownValue);
myConsole.getOut().println(percentage);
if (percentage < 100) {
double orderLots = round(order.getAmount() * percentage / 100, 2);
myConsole.getOut().println(orderLots);
order.close(orderLots);
} else {
order.close();
}
partialsDropdown.setSelectedItem("100%");
} catch (JFException ex) {
ex.printStackTrace();
}
}
// SL2BE BUTTON
if (e.getSource() == sl2beButton && selectedRow != null) {
try {
IOrder order = myEngine.getOrderById(selectedRow);
double entryPrice = order.getOpenPrice();
order.setStopLossPrice(entryPrice);
} catch (JFException ex) {
ex.printStackTrace();
}
}
// UPDATE SL/TP BUTTON
if (e.getSource() == updateSLTPButton && selectedRow != null) {
try {
IOrder order = myEngine.getOrderById(selectedRow);
String direction = order.getOrderCommand().toString().toLowerCase().contains("buy") ? "BUY"
: "SELL";
double orderEntryPrice = order.getOpenPrice();
validateFields(direction, orderEntryPrice);
order.setTakeProfitPrice(myTakeProfit);
order.setStopLossPrice(myStopLoss);
myConsole.getOut().println("TP and SL Updated");
myConsole.getOut().println(myTakeProfit);
myConsole.getOut().println(myStopLoss);
} catch (JFException ex) {
ex.printStackTrace();
}
}
// PAUSE EVERY BUTTON
if (e.getSource() == pauseEveryDropdown) {
String value = pauseEveryDropdown.getSelectedItem().toString();
if (value.equals("None")) {
pauseEvery = null;
} else if (value.equals("1m")) {
pauseEvery = Period.ONE_MIN;
} else if (value.equals("5m")) {
pauseEvery = Period.FIVE_MINS;
} else if (value.equals("15m")) {
pauseEvery = Period.FIFTEEN_MINS;
} else if (value.equals("30m")) {
pauseEvery = Period.THIRTY_MINS;
} else if (value.equals("1hr")) {
pauseEvery = Period.ONE_HOUR;
} else if (value.equals("4hr")) {
pauseEvery = Period.FOUR_HOURS;
} else if (value.equals("1d")) {
pauseEvery = Period.DAILY;
}
}
}// end actionPerformed
public double round(double num, int digits) {
// epsilon correction
double n = Double.longBitsToDouble(Double.doubleToLongBits(num) + 1);
double p = Math.pow(10, digits);
return Math.round(n * p) / p;
}
public void updatePrices() {
if (entryDropdown.getSelectedItem().toString().equals("Market")) {
buyButton.setText("<html>BUY<br />" + Double.toString(askPrice) + "</html>");
sellButton.setText("<html>SELL<br />" + Double.toString(bidPrice) + "</html>");
spreadButton.setText("<html>Spread:<br />" + Double.toString(round(spreadDiff, 2)) + "</html>");
// myConsole.getOut().println(askPrice - bidPrice);
}
}// end updatePrices
// Update Table
public void updateTableOrders() {
try {
// get orders
List<IOrder> myAllOrders = myEngine.getOrders();
if (myAllOrders.size() > 0) {
tableData = new Object[myAllOrders.size()][7];
int counter = 0;
// if any order update the values of the table
for (IOrder order : myAllOrders) {
if (order != null) {
double profitLossInUSD = order.getProfitLossInUSD();
double orderEntryPrice = order.getOpenPrice();
double orderStopLoss = order.getStopLossPrice();
double orderTakeProfit = order.getTakeProfitPrice();
double orderLots = order.getAmount();
String orderState = order.getState().toString();
String orderID = order.getId();
String orderDirection = order.getOrderCommand().toString();
tableData[counter][0] = orderID;
tableData[counter][1] = orderDirection;
tableData[counter][2] = orderLots * 10;
tableData[counter][3] = orderEntryPrice;
tableData[counter][4] = orderStopLoss;
tableData[counter][5] = orderTakeProfit;
tableData[counter][6] = profitLossInUSD;
counter++;
}
}
tradesTableModel = new DefaultTableModel(tableData, tableHeaders);
tradesTableModel.fireTableDataChanged();
tradesTable.setModel(tradesTableModel);
} else {
DefaultTableModel dtm = (DefaultTableModel) tradesTable.getModel();
dtm.setRowCount(0);
}
} catch (Exception e) {
myConsole.getOut().println(e.getMessage());
}
}// end updateTableOrder
public void printOrders() {
try {
myConsole.getOut().println("Active orders: " + myEngine.getOrders());
} catch (JFException e) {
Logger.getLogger("Error!!!");
}
}
// Validate fields
private OrderCommand getOrderCommand(String direction) {
try {
String entryType = entryDropdown.getSelectedItem().toString();
String entryPrice = entryField.getText();
// ORDER COMMAND - DIRECTION
if (direction.equals("BUY")) {
if (entryType.equals("Market")) {
myOrderCommand = OrderCommand.BUY;
} else {
if (Double.parseDouble(entryPrice) > bidPrice) {
myOrderCommand = OrderCommand.BUYSTOP;
} else {
myOrderCommand = OrderCommand.BUYLIMIT;
}
}
} else {
if (entryType.equals("Market")) {
myOrderCommand = OrderCommand.SELL;
} else {
if (Double.parseDouble(entryPrice) > askPrice) {
myOrderCommand = OrderCommand.SELLLIMIT;
} else {
myOrderCommand = OrderCommand.SELLSTOP;
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in Order Command!", "Error in Order Command",
JOptionPane.WARNING_MESSAGE);
}
return myOrderCommand;
}
// Validate fields
private boolean validateFields(String direction, double entryPrice) {
// ENTRY Field
try {
if (entryPrice != -111) {
myEntry = entryPrice;
} else {
if (entryDropdown.getSelectedItem().toString().equals("Market")) {
myEntry = 0;
} else {
myEntry = Double.valueOf(entryField.getText());
}
if (myEntry < 0) {
JOptionPane.showMessageDialog(null, "Incorrect Entry value!", "Incorrect Entry value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect Entry value!", "Incorrect Entry value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
// Order Command
try {
myOrderCommand = getOrderCommand(direction);
if (myOrderCommand == null) {
JOptionPane.showMessageDialog(null, "Invalid Order Command", "Invalid Order Command",
JOptionPane.WARNING_MESSAGE);
return false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Invalid Order Command", "Invalid Order Command",
JOptionPane.WARNING_MESSAGE);
return false;
}
// SL Field
try {
myStopLoss = Double.valueOf(slField.getText());
if (myStopLoss < 0) {
JOptionPane.showMessageDialog(null, "Incorrect SL value!", "Incorrect SL value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
if (slDropdown.getSelectedItem().toString().equals("Pips")) {
myStopLossInPips = Double.valueOf(slField.getText());
} else {
if (entryDropdown.getSelectedItem().toString().equals("Market")) {
if (myOrderCommand.toString().contains("buy")) {
myStopLossInPips = Math.abs((bidPrice - myStopLoss) / myInstrument.getPipValue());
} else {
myStopLossInPips = Math.abs((myStopLoss - askPrice) / myInstrument.getPipValue());
}
} else {
if (myOrderCommand.toString().contains("buy")) {
myStopLossInPips = Math.abs((myEntry - myStopLoss) / myInstrument.getPipValue());
} else {
myStopLossInPips = Math.abs((myStopLoss - myEntry) / myInstrument.getPipValue());
}
}
}
myConsole.getOut().println("SL in pips: " + myStopLossInPips);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect SL value!", "Incorrect SL value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
// TP Field
try {
myTakeProfit = Double.valueOf(tpField.getText());
if (myTakeProfit < 0) {
JOptionPane.showMessageDialog(null, "Incorrect TP value!", "Incorrect TP value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect TP value!", "Incorrect TP value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
// SL/TP
try {
boolean orderCommandIsBuy = myOrderCommand.toString().toLowerCase().contains("buy");
setTpSl(orderCommandIsBuy);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect SLTP value!", "Incorrect SLTP value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
return false;
}
// LOTS and AMOUNT
try {
// If empty lots field
if (lotsField.getText() == null) {
JOptionPane.showMessageDialog(null, "Incorrect Lots/Risk value!", "Incorrect Lots/Risk value...",
JOptionPane.WARNING_MESSAGE);
lotsField.requestFocusInWindow();
return false;
}
// If lots = FIXED LOT
if (lotsDropdown.getSelectedItem().toString().equals("Fixed Lots")) {
myAmount = Double.valueOf(lotsField.getText()) / 10;
if (myAmount < 0.001) {
JOptionPane.showMessageDialog(null, "Incorrect lots value!", "Incorrect lots value...",
JOptionPane.WARNING_MESSAGE);
lotsField.requestFocusInWindow();
return false;
}
}
// If lots = Balance %
else {
double riskPercentage = Double.valueOf(lotsField.getText());
myAmount = getPositionSize(myStopLossInPips, riskPercentage);
myConsole.getOut().println("Amount: " + myAmount);
}
if (myAmount <= 0) {
JOptionPane.showMessageDialog(null, "Incorrect amount value!", "Incorrect amount value...",
JOptionPane.WARNING_MESSAGE);
lotsField.requestFocusInWindow();
return false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect amount value!", "Incorrect amount value...",
JOptionPane.WARNING_MESSAGE);
lotsField.requestFocusInWindow();
return false;
}
return true;
}// end validateprices
// Validate fields
double getPositionSize(double stopLossPips, double riskPercentage) throws JFException {
double lotSize = 0;
double tickValue = myInstrument.getTickScale();
double accountBalance = myAccount.getBalance();
double amountToRiskInUSD = accountBalance * (riskPercentage / 100);
double pipValue = myInstrument.getPipValue();
double pairExchangeRate = bidPrice;
// init symbols
String accountCurrency = myContext.getAccount().getCurrency().getCurrencyCode();
String primaryCurrency = myInstrument.getPrimaryCurrency().getCurrencyCode();
String secondaryCurrency = myInstrument.getSecondaryCurrency().getCurrencyCode();
// calc currency/pip value
// double pairExchangeRate;
// if (myOrderCommand == OrderCommand.BUY)
// pairExchangeRate = askPrice;
// else
// pairExchangeRate = bidPrice;
if (tickValue == 3) { // 0.001
pipValue = pipValue * 1000;
} else if (tickValue == 5) { // 0.00001
pipValue = pipValue * 100000;
}
lotSize = (amountToRiskInUSD / (stopLossPips * pipValue)) / 10;
lotSize = round(lotSize, 2);
return lotSize;
}
/**
* Submits the orders
*
* @param orderType direction of the order
* @throws JFException
*/
private void placeOrder(String orderType) throws JFException {
try {
myOrder = myEngine.submitOrder(orderType + myOrderCounter, myInstrument, myOrderCommand, myAmount,
myEntry, mySlippage, myStopLoss, myTakeProfit);
myConsole.getOut().println(myOrder);
myOrderCounter++;
} catch (JFException ex) {
myConsole.getOut().println("ERROR IN PLACEORDER");
}
}// end placeOrder
/**
* Sets the Stop Loss and take profit of any order provided
*
* @param order to change SL and TP
* @throws JFException
*/
public void setTpSl(boolean isBuy) throws JFException {
String slType = slDropdown.getSelectedItem().toString();
String tpType = tpDropdown.getSelectedItem().toString();
double orderSL;
double orderTP;
double openPrice = 0.00;
if (myEntry > 0) {
openPrice = myEntry;
} else {
if (isBuy) {
openPrice = bidPrice;
} else {
openPrice = askPrice;
}
}
// SL Field
try {
if (myStopLoss > 0) {
// If SL = Price
if (slType.equals("Price")) {
orderSL = Double.parseDouble(slField.getText());
myStopLoss = orderSL;
// order.setStopLossPrice(orderSL);
}
// If SL = Pips
else if (slType.equals("Pips")) {
// If Lots = Fixed (convert pips to price)
if (isBuy) {
orderSL = openPrice - myStopLoss * myPipValue;
} else {
orderSL = openPrice + myStopLoss * myPipValue;
}
myStopLoss = orderSL;
}
}
} catch (Exception e) {
myConsole.getOut().println(e.getMessage());
myConsole.getOut().println(e.getStackTrace()[0].getLineNumber());
JOptionPane.showMessageDialog(null, "Incorrect SL 2 value!", "Incorrect SL 2 value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
}
try {
if (myTakeProfit > 0) {
// If TP = Price
if (tpType.equals("Price")) {
orderTP = Double.parseDouble(tpField.getText());
myTakeProfit = orderTP;
// order.setTakeProfitPrice(orderTP);
}
// If TP = Pips
else if (tpType.equals("Pips")) {
// Convert pips to price
if (isBuy) {
orderTP = openPrice + myTakeProfit * myPipValue;
} else {
orderTP = openPrice - myTakeProfit * myPipValue;
}
myTakeProfit = orderTP;
// order.setTakeProfitPrice(orderTP);
}
// If TP = RR
else {
if (myStopLoss > 0) {
double tpPips = myStopLossInPips * myTakeProfit;
// Convert pips to price
if (isBuy) {
orderTP = openPrice + tpPips * myPipValue;
} else {
orderTP = openPrice - tpPips * myPipValue;
}
myTakeProfit = orderTP;
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Incorrect TP 2 value!", "Incorrect TP 2 value...",
JOptionPane.WARNING_MESSAGE);
slField.requestFocusInWindow();
}
}// end setTpSl
}
}Editor is loading...