From 25e8aa449596028411bb35e04e9af9c83163d6a9 Mon Sep 17 00:00:00 2001 From: 7u83 <7u83@maiol.ru> Date: Tue, 31 Jan 2017 08:04:11 +0100 Subject: [PATCH] File Save is possible --- src/main/java/chart/Chart.java | 25 +-- src/main/java/gui/AskBook.java | 2 +- src/main/java/gui/EditExchangeDialog.form | 117 ++++++++++++++ src/main/java/gui/EditExchangeDialog.java | 177 ++++++++++++++++++++++ src/main/java/gui/Globals.java | 26 +++- src/main/java/gui/NewMDIApplication.form | 32 ++-- src/main/java/gui/NewMDIApplication.java | 96 ++++++++---- src/main/java/gui/OrderBook.java | 17 ++- src/main/java/sesim/Exchange.java | 92 ++++++----- src/main/java/traders/RandomTrader.java | 4 +- src/test/java/sesim/Test.java | 29 ++-- 11 files changed, 498 insertions(+), 119 deletions(-) create mode 100644 src/main/java/gui/EditExchangeDialog.form create mode 100644 src/main/java/gui/EditExchangeDialog.java diff --git a/src/main/java/chart/Chart.java b/src/main/java/chart/Chart.java index edc3c5f..b1ab11e 100644 --- a/src/main/java/chart/Chart.java +++ b/src/main/java/chart/Chart.java @@ -35,7 +35,7 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab protected int num_bars = 4000; protected Rectangle clip_bounds = new Rectangle(); - protected Dimension dim; + protected Dimension gdim; protected int first_bar, last_bar; @@ -185,7 +185,7 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab float m = c_mm.max/c_mm.min; - System.out.printf("Min: %f Max: %f M: %f\n",c_mm.min,c_mm.max,m); + //System.out.printf("Min: %f Max: %f M: %f\n",c_mm.min,c_mm.max,m); //float fac = (float) c_rect.height /(float) Math.log(c_mm.max * c_yscaling); @@ -195,7 +195,7 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab float fmin = c_rect.height - ((float) Math.log((y / c_mm.min)) * fac); - System.out.printf("Fac: %f fmin: %f\n", fac, fmin); + //System.out.printf("Fac: %f fmin: %f\n", fac, fmin); return fmin; //return c_rect.height - ((float) Math.log((y - c_mm.min) * c_yscaling) * fac); @@ -291,7 +291,7 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab g.drawLine(dim.width + dim.x - yw, 0, dim.width + dim.x - yw, dim.height); -// float yscale = dim.height / c_mm.getDiff(); +// float yscale = gdim.height / c_mm.getDiff(); c_yscaling = c_rect.height / c_mm.getDiff(); // System.out.printf("yscale %f\n", c_yscaling); @@ -309,7 +309,7 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab // g.drawLine(0,(int)getYc(c_mm.min), 1000, (int)getYc(c_mm.min)); //g.setColor(Color.green); //g.drawRect(c_rect.x, c_rect.y, c_rect.width, c_rect.height); - // System.out.printf("Size: %d %d\n",dim.width,dim.height); + // System.out.printf("Size: %d %d\n",gdim.width,gdim.height); // System.exit(0); } @@ -343,15 +343,16 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab //this.getSize(); int pwidth = em_width * num_bars; int phight = 400; + // phight=this.getVisibleRect().height; - this.setPreferredSize(new Dimension(pwidth, dim.height)); + this.setPreferredSize(new Dimension(pwidth, gdim.height)); this.revalidate(); - Rectangle r = new Rectangle(0, 0, pwidth, dim.height - 6 * em_width); + Rectangle r = new Rectangle(0, 0, pwidth, gdim.height - 6 * em_width); c_rect = r; this.drawYLegend(g); - // Dimension dim = this.getSize(); + // Dimension gdim = this.getSize(); // Iterator<OHLCDataItem> it = data.iterator(); OHLCDataItem prev = null; // int myi = 0; @@ -405,10 +406,14 @@ public class Chart extends javax.swing.JPanel implements QuoteReceiver, Scrollab super.paintComponent(g); this.initEmSize(g); - this.dim = this.getSize(dim); + this.gdim = this.getParent().getSize(gdim); + this.getParent().setPreferredSize(gdim); + + + this.clip_bounds = g.getClipBounds(this.clip_bounds); -// System.out.printf("X:%d %d\n",dim.width,dim.height); +// System.out.printf("X:%d %d\n",gdim.width,gdim.height); first_bar = (int) (clip_bounds.x / (this.bar_width * this.em_size)); last_bar = 1 + (int) ((clip_bounds.x + clip_bounds.width - (this.y_legend_width * em_size)) / (this.bar_width * this.em_size)); diff --git a/src/main/java/gui/AskBook.java b/src/main/java/gui/AskBook.java index 6533601..c86ffe8 100644 --- a/src/main/java/gui/AskBook.java +++ b/src/main/java/gui/AskBook.java @@ -41,7 +41,7 @@ public class AskBook extends OrderBook { @Override boolean getDesc(){ - return true; + return false; } public AskBook(){ diff --git a/src/main/java/gui/EditExchangeDialog.form b/src/main/java/gui/EditExchangeDialog.form new file mode 100644 index 0000000..2abfd62 --- /dev/null +++ b/src/main/java/gui/EditExchangeDialog.form @@ -0,0 +1,117 @@ +<?xml version="1.0" encoding="UTF-8" ?> + +<Form version="1.5" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JDialogFormInfo"> + <Properties> + <Property name="defaultCloseOperation" type="int" value="2"/> + <Property name="title" type="java.lang.String" value="SeSim ExchangeSettings"/> + <Property name="minimumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor"> + <Dimension value="[300, 142]"/> + </Property> + <Property name="modal" type="boolean" value="true"/> + </Properties> + <SyntheticProperties> + <SyntheticProperty name="formSizePolicy" type="int" value="1"/> + <SyntheticProperty name="generateCenter" type="boolean" value="false"/> + </SyntheticProperties> + <AuxValues> + <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/> + <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/> + <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/> + <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/> + <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/> + </AuxValues> + + <Layout> + <DimensionLayout dim="0"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" attributes="0"> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="1" attributes="0"> + <EmptySpace min="0" pref="0" max="32767" attributes="0"/> + <Component id="jButton2" min="-2" max="-2" attributes="0"/> + <EmptySpace max="-2" attributes="0"/> + <Component id="jButton1" min="-2" max="-2" attributes="0"/> + </Group> + <Group type="102" alignment="1" attributes="0"> + <Group type="103" groupAlignment="1" attributes="0"> + <Component id="jLabel1" pref="212" max="32767" attributes="0"/> + <Component id="jLabel2" max="32767" attributes="0"/> + </Group> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="0" attributes="0"> + <Component id="jSpinner2" alignment="1" min="-2" pref="70" max="-2" attributes="0"/> + <Component id="jSpinner1" alignment="1" min="-2" pref="70" max="-2" attributes="0"/> + </Group> + </Group> + </Group> + <EmptySpace max="-2" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + <DimensionLayout dim="1"> + <Group type="103" groupAlignment="0" attributes="0"> + <Group type="102" alignment="0" attributes="0"> + <EmptySpace min="-2" pref="15" max="-2" attributes="0"/> + <Group type="103" groupAlignment="3" attributes="0"> + <Component id="jSpinner1" alignment="3" min="-2" pref="28" max="-2" attributes="0"/> + <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/> + </Group> + <EmptySpace max="-2" attributes="0"/> + <Group type="103" groupAlignment="3" attributes="0"> + <Component id="jSpinner2" alignment="3" min="-2" pref="28" max="-2" attributes="0"/> + <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/> + </Group> + <EmptySpace pref="32" max="32767" attributes="0"/> + <Group type="103" groupAlignment="3" attributes="0"> + <Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/> + <Component id="jButton2" alignment="3" min="-2" max="-2" attributes="0"/> + </Group> + <EmptySpace max="-2" attributes="0"/> + </Group> + </Group> + </DimensionLayout> + </Layout> + <SubComponents> + <Component class="javax.swing.JSpinner" name="jSpinner1"> + <Properties> + <Property name="model" type="javax.swing.SpinnerModel" editor="org.netbeans.modules.form.editors2.SpinnerModelEditor"> + <SpinnerModel initial="0" maximum="10" minimum="0" numberType="java.lang.Integer" stepSize="1" type="number"/> + </Property> + </Properties> + </Component> + <Component class="javax.swing.JLabel" name="jLabel1"> + <Properties> + <Property name="text" type="java.lang.String" value="Number of decimals for shares:"/> + </Properties> + </Component> + <Component class="javax.swing.JSpinner" name="jSpinner2"> + <Properties> + <Property name="model" type="javax.swing.SpinnerModel" editor="org.netbeans.modules.form.editors2.SpinnerModelEditor"> + <SpinnerModel initial="2" maximum="10" minimum="0" numberType="java.lang.Integer" stepSize="1" type="number"/> + </Property> + </Properties> + </Component> + <Component class="javax.swing.JLabel" name="jLabel2"> + <Properties> + <Property name="text" type="java.lang.String" value="Number of decimals for money:"/> + </Properties> + </Component> + <Component class="javax.swing.JButton" name="jButton1"> + <Properties> + <Property name="mnemonic" type="int" value="99"/> + <Property name="text" type="java.lang.String" value="Cancel"/> + </Properties> + </Component> + <Component class="javax.swing.JButton" name="jButton2"> + <Properties> + <Property name="mnemonic" type="int" value="111"/> + <Property name="text" type="java.lang.String" value="Ok"/> + </Properties> + </Component> + </SubComponents> +</Form> diff --git a/src/main/java/gui/EditExchangeDialog.java b/src/main/java/gui/EditExchangeDialog.java new file mode 100644 index 0000000..ac3745d --- /dev/null +++ b/src/main/java/gui/EditExchangeDialog.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2017, 7u83 <7u83@mail.ru> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +package gui; + +/** + * + * @author 7u83 <7u83@mail.ru> + */ +public class EditExchangeDialog extends javax.swing.JDialog { + + /** + * Creates new form EditExchnageDialog + */ + public EditExchangeDialog(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + this.setLocationRelativeTo(parent); + } + + int showdialog(){ + this.setVisible(true); + return 3; + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents + private void initComponents() { + + jSpinner1 = new javax.swing.JSpinner(); + jLabel1 = new javax.swing.JLabel(); + jSpinner2 = new javax.swing.JSpinner(); + jLabel2 = new javax.swing.JLabel(); + jButton1 = new javax.swing.JButton(); + jButton2 = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle("SeSim ExchangeSettings"); + setMinimumSize(new java.awt.Dimension(300, 142)); + setModal(true); + + jSpinner1.setModel(new javax.swing.SpinnerNumberModel(0, 0, 10, 1)); + + jLabel1.setText("Number of decimals for shares:"); + + jSpinner2.setModel(new javax.swing.SpinnerNumberModel(2, 0, 10, 1)); + + jLabel2.setText("Number of decimals for money:"); + + jButton1.setMnemonic('c'); + jButton1.setText("Cancel"); + + jButton2.setMnemonic('o'); + jButton2.setText("Ok"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(jButton2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE) + .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jSpinner2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jSpinner1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addGap(15, 15, 15) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel2)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jButton1) + .addComponent(jButton2)) + .addContainerGap()) + ); + + pack(); + }// </editor-fold>//GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(EditExchangeDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(EditExchangeDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(EditExchangeDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(EditExchangeDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + //</editor-fold> + //</editor-fold> + + /* Create and display the dialog */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + EditExchangeDialog dialog = new EditExchangeDialog(new javax.swing.JFrame(), true); + dialog.addWindowListener(new java.awt.event.WindowAdapter() { + @Override + public void windowClosing(java.awt.event.WindowEvent e) { + System.exit(0); + } + }); + dialog.setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JSpinner jSpinner1; + private javax.swing.JSpinner jSpinner2; + // End of variables declaration//GEN-END:variables +} diff --git a/src/main/java/gui/Globals.java b/src/main/java/gui/Globals.java index dae6de7..e763de2 100644 --- a/src/main/java/gui/Globals.java +++ b/src/main/java/gui/Globals.java @@ -25,9 +25,12 @@ */ package gui; - +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; import java.util.Iterator; import java.util.TreeMap; +import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.swing.JComboBox; @@ -88,8 +91,8 @@ public class Globals { JSONObject cfgs = new JSONObject(cfglist); return cfgs; } - - static public JSONObject getStrategy(String name){ + + static public JSONObject getStrategy(String name) { return getStrategies().getJSONObject(name); } @@ -123,4 +126,21 @@ public class Globals { prefs.put(STRATEGYPREFS, cfgs.toString()); } + static void saveFile(File f) { + + JSONObject sobj = new JSONObject(); + JSONArray traders = getTraders(); + JSONObject strategies = getStrategies(); + sobj.put("strategies", strategies); + sobj.put("traders", traders); + try { + PrintWriter out = new PrintWriter(f.getAbsolutePath()); + out.print(sobj.toString(4)); + out.close(); + } catch (FileNotFoundException ex) { + Logger.getLogger(Globals.class.getName()).log(Level.SEVERE, null, ex); + } + + } + } diff --git a/src/main/java/gui/NewMDIApplication.form b/src/main/java/gui/NewMDIApplication.form index db0f1a9..6472f5d 100644 --- a/src/main/java/gui/NewMDIApplication.form +++ b/src/main/java/gui/NewMDIApplication.form @@ -31,6 +31,9 @@ <Property name="mnemonic" type="int" value="111"/> <Property name="text" type="java.lang.String" value="Open"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="openMenuItemActionPerformed"/> + </Events> </MenuItem> <MenuItem class="javax.swing.JMenuItem" name="saveMenuItem"> <Properties> @@ -44,6 +47,9 @@ <Property name="text" type="java.lang.String" value="Save As ..."/> <Property name="displayedMnemonicIndex" type="int" value="5"/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveAsMenuItemActionPerformed"/> + </Events> </MenuItem> <MenuItem class="javax.swing.JMenuItem" name="exitMenuItem"> <Properties> @@ -54,15 +60,6 @@ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="exitMenuItemActionPerformed"/> </Events> </MenuItem> - <MenuItem class="javax.swing.JMenuItem" name="jMenuItem1"> - <Properties> - <Property name="text" type="java.lang.String" value="Run"/> - <Property name="hideActionText" type="boolean" value="true"/> - </Properties> - <Events> - <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jMenuItem1ActionPerformed"/> - </Events> - </MenuItem> </SubComponents> </Menu> <Menu class="javax.swing.JMenu" name="editMenu"> @@ -71,17 +68,14 @@ <Property name="text" type="java.lang.String" value="Edit"/> </Properties> <SubComponents> - <MenuItem class="javax.swing.JMenuItem" name="cutMenuItem"> - <Properties> - <Property name="mnemonic" type="int" value="116"/> - <Property name="text" type="java.lang.String" value="Cut"/> - </Properties> - </MenuItem> - <MenuItem class="javax.swing.JMenuItem" name="copyMenuItem"> + <MenuItem class="javax.swing.JMenuItem" name="editExchangeMenuItem"> <Properties> <Property name="mnemonic" type="int" value="121"/> - <Property name="text" type="java.lang.String" value="Copy"/> + <Property name="text" type="java.lang.String" value="Exchange ..."/> </Properties> + <Events> + <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="editExchangeMenuItemActionPerformed"/> + </Events> </MenuItem> <MenuItem class="javax.swing.JPopupMenu$Separator" name="jSeparator1"> </MenuItem> @@ -194,10 +188,10 @@ <Layout> <DimensionLayout dim="0"> <Group type="103" groupAlignment="0" attributes="0"> - <Component id="jToolBar1" pref="797" max="32767" attributes="0"/> + <Component id="jToolBar1" pref="798" max="32767" attributes="0"/> <Group type="102" attributes="0"> <EmptySpace max="-2" attributes="0"/> - <Component id="orderBookPanel1" min="-2" max="-2" attributes="0"/> + <Component id="orderBookPanel1" min="-2" pref="233" max="-2" attributes="0"/> <EmptySpace max="-2" attributes="0"/> <Component id="jScrollPane1" max="32767" attributes="0"/> <EmptySpace max="-2" attributes="0"/> diff --git a/src/main/java/gui/NewMDIApplication.java b/src/main/java/gui/NewMDIApplication.java index 16bf6a9..b34a147 100644 --- a/src/main/java/gui/NewMDIApplication.java +++ b/src/main/java/gui/NewMDIApplication.java @@ -26,6 +26,7 @@ package gui; import java.awt.Dialog; +import java.awt.Frame; import java.io.File; import java.util.ArrayList; import java.util.logging.Handler; @@ -34,6 +35,7 @@ import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.swing.JFileChooser; import javax.swing.UIManager; +import javax.swing.filechooser.FileNameExtensionFilter; import org.json.JSONArray; import org.json.JSONObject; import sesim.AutoTrader; @@ -137,10 +139,8 @@ public class NewMDIApplication extends javax.swing.JFrame { saveMenuItem = new javax.swing.JMenuItem(); saveAsMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); - jMenuItem1 = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); - cutMenuItem = new javax.swing.JMenuItem(); - copyMenuItem = new javax.swing.JMenuItem(); + editExchangeMenuItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); pasteMenuItem = new javax.swing.JMenuItem(); deleteMenuItem = new javax.swing.JMenuItem(); @@ -208,6 +208,11 @@ public class NewMDIApplication extends javax.swing.JFrame { openMenuItem.setMnemonic('o'); openMenuItem.setText("Open"); + openMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + openMenuItemActionPerformed(evt); + } + }); fileMenu.add(openMenuItem); saveMenuItem.setMnemonic('s'); @@ -217,6 +222,11 @@ public class NewMDIApplication extends javax.swing.JFrame { saveAsMenuItem.setMnemonic('a'); saveAsMenuItem.setText("Save As ..."); saveAsMenuItem.setDisplayedMnemonicIndex(5); + saveAsMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + saveAsMenuItemActionPerformed(evt); + } + }); fileMenu.add(saveAsMenuItem); exitMenuItem.setMnemonic('x'); @@ -228,27 +238,19 @@ public class NewMDIApplication extends javax.swing.JFrame { }); fileMenu.add(exitMenuItem); - jMenuItem1.setText("Run"); - jMenuItem1.setHideActionText(true); - jMenuItem1.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent evt) { - jMenuItem1ActionPerformed(evt); - } - }); - fileMenu.add(jMenuItem1); - menuBar.add(fileMenu); editMenu.setMnemonic('e'); editMenu.setText("Edit"); - cutMenuItem.setMnemonic('t'); - cutMenuItem.setText("Cut"); - editMenu.add(cutMenuItem); - - copyMenuItem.setMnemonic('y'); - copyMenuItem.setText("Copy"); - editMenu.add(copyMenuItem); + editExchangeMenuItem.setMnemonic('y'); + editExchangeMenuItem.setText("Exchange ..."); + editExchangeMenuItem.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + editExchangeMenuItemActionPerformed(evt); + } + }); + editMenu.add(editExchangeMenuItem); editMenu.add(jSeparator1); pasteMenuItem.setMnemonic('s'); @@ -325,10 +327,10 @@ public class NewMDIApplication extends javax.swing.JFrame { getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 797, Short.MAX_VALUE) + .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 798, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() - .addComponent(orderBookPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(orderBookPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1) .addContainerGap()) @@ -369,10 +371,6 @@ public class NewMDIApplication extends javax.swing.JFrame { d.setVisible(rootPaneCheckingEnabled); }//GEN-LAST:event_editPreferencesActionPerformed - private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed - // TODO add your handling code here: - }//GEN-LAST:event_jMenuItem1ActionPerformed - private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed TraderListDialog d = new TraderListDialog(this, false); d.setVisible(rootPaneCheckingEnabled); @@ -407,6 +405,50 @@ public class NewMDIApplication extends javax.swing.JFrame { }//GEN-LAST:event_jMenuItem3ActionPerformed + private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed + + }//GEN-LAST:event_openMenuItemActionPerformed + + private void saveAsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveAsMenuItemActionPerformed + JFileChooser fc = new JFileChooser(); + + FileNameExtensionFilter filter = new FileNameExtensionFilter("SeSim Files","sesim"); + fc.setFileFilter(filter); + + if (fc.showSaveDialog(this.getParent()) != JFileChooser.APPROVE_OPTION){ + return; + } + + + File f = fc.getSelectedFile(); + + String [] e = ((FileNameExtensionFilter)fc.getFileFilter()).getExtensions(); + + System.out.printf("Abs: %s\n", f.getAbsoluteFile()); + + String fn=f.getAbsolutePath(); + + + if (!f.getAbsolutePath().endsWith(e[0])){ + f = new File(f.getAbsolutePath()+"."+e[0]); + } + + + Globals.saveFile(f); + + + System.out.printf("Sel File: %s \n",f.getAbsolutePath()); + + + }//GEN-LAST:event_saveAsMenuItemActionPerformed + + private void editExchangeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editExchangeMenuItemActionPerformed + EditExchangeDialog ed=new EditExchangeDialog((Frame) this.getParent(),true); + int rc = ed.showdialog(); + // System.out.printf("EDRET: %d\n",rc); + + }//GEN-LAST:event_editExchangeMenuItemActionPerformed + /** * @param args the command line arguments * @throws java.lang.IllegalAccessException @@ -460,9 +502,8 @@ public class NewMDIApplication extends javax.swing.JFrame { private javax.swing.JMenuItem aboutMenuItem; private chart.Chart chart1; private javax.swing.JMenuItem contentMenuItem; - private javax.swing.JMenuItem copyMenuItem; - private javax.swing.JMenuItem cutMenuItem; private javax.swing.JMenuItem deleteMenuItem; + private javax.swing.JMenuItem editExchangeMenuItem; private javax.swing.JMenu editMenu; private javax.swing.JMenuItem editPreferences; private javax.swing.JMenuItem exitMenuItem; @@ -470,7 +511,6 @@ public class NewMDIApplication extends javax.swing.JFrame { private javax.swing.JMenu helpMenu; private javax.swing.JButton jButton2; private javax.swing.JMenu jMenu1; - private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JButton jRunButton; diff --git a/src/main/java/gui/OrderBook.java b/src/main/java/gui/OrderBook.java index e1939ad..89601df 100644 --- a/src/main/java/gui/OrderBook.java +++ b/src/main/java/gui/OrderBook.java @@ -33,6 +33,7 @@ import javax.swing.table.AbstractTableModel; import javax.swing.table.JTableHeader; import javax.swing.SwingUtilities; import java.awt.*; +import java.text.DecimalFormat; import javax.swing.*; import javax.swing.table.*; @@ -85,7 +86,11 @@ public abstract class OrderBook extends javax.swing.JPanel implements Exchange.B } ArrayList newlist = getOrderBook(); + //this.orderBookScroller.scrollRectToVisible(this.orderBookList.getCellRect(this.orderBookList.getRowCount()-1, 0, true)); SwingUtilities.invokeLater(new Updater(this.model,newlist)); + + //this.scrollRectToVisible(this.getCellRect(rowIndex, vColIndex, false)); + } @@ -144,8 +149,13 @@ public abstract class OrderBook extends javax.swing.JPanel implements Exchange.B return 3; } + DecimalFormat dfm = new DecimalFormat("0.00#"); + DecimalFormat dfv = new DecimalFormat("0.#"); + @Override public Object getValueAt(int r, int c) { + + Order o; int s = list.size(); @@ -162,9 +172,12 @@ public abstract class OrderBook extends javax.swing.JPanel implements Exchange.B return String.format("#%06x", o.getID()); case 1: - return String.format("%.4f",o.getLimit()); + //return String.format("%.f",o.getLimit()); + return dfm.format((double)o.getLimit()); + case 2: - return String.format("%.4f", o.getVolume()); + return dfv.format((double)o.getVolume()); + //return String.format("%f", o.getVolume()); } return ""; } diff --git a/src/main/java/sesim/Exchange.java b/src/main/java/sesim/Exchange.java index ee6ea61..33984ac 100644 --- a/src/main/java/sesim/Exchange.java +++ b/src/main/java/sesim/Exchange.java @@ -6,23 +6,46 @@ import java.util.concurrent.CopyOnWriteArrayList; import org.json.JSONArray; import org.json.JSONObject; - /** * * @author tube */ public class Exchange { //extends Thread { + private double money_df = 10000; + private double shares_df = 1; + + public void setMoneyDecimals(int n) { + money_df = Math.pow(10, n); + } + + public void setSharesDecimals(int n) { + shares_df = Math.pow(10, n); + } + + public double roundToDecimals(double val,double f){ + return Math.floor(val*f)/f; + } + + public double roundShares(double shares){ + return roundToDecimals(shares,shares_df); + } + public double roundMoney(double money){ + return roundToDecimals(money,money_df); + } + + + public enum OrderType { BID, ASK } IDGenerator account_id = new IDGenerator(); //public static Timer timer = new Timer(); - + public Scheduler timer = new Scheduler(); //public AutoTraderList traders = new AutoTraderList(); - public ArrayList <AutoTrader> traders = new ArrayList(); + public ArrayList<AutoTrader> traders = new ArrayList(); /** * Implements a trading account @@ -61,16 +84,13 @@ public class Exchange { //extends Thread { } } - - - public void createTraders(JSONArray traderdefs){ - for (int i=0; i<traderdefs.length(); i++){ + + public void createTraders(JSONArray traderdefs) { + for (int i = 0; i < traderdefs.length(); i++) { JSONObject o = traderdefs.getJSONObject(i); - - + } - - + // this.traders.add(randt); // randt.setName("Bob"); // randt.start(); @@ -111,6 +131,11 @@ public class Exchange { //extends Thread { if (d != 0) { return d > 0 ? 1 : -1; } + + d=right.initial_volume-left.initial_volume; + if (d!=0){ + return d > 0 ? 1 : -1; + } if (left.id < right.id) { return -1; @@ -126,7 +151,6 @@ public class Exchange { //extends Thread { } - HashMap<OrderType, SortedSet<Order>> order_books = new HashMap(); IDGenerator order_id = new IDGenerator(); @@ -145,9 +169,9 @@ public class Exchange { //extends Thread { id = order_id.getNext(); this.account = account; this.type = type; - this.limit = limit; - this.volume = volume; - this.initial_volume = volume; + this.limit = roundMoney(limit); + this.volume = roundShares(volume); + this.initial_volume = this.volume; this.created = System.currentTimeMillis(); } @@ -194,23 +218,17 @@ public class Exchange { //extends Thread { //SortedSet b = new TreeSet(new OrderComparator(type)); order_books.put(type, new TreeSet(new OrderComparator(type))); } - } - - - - - /*public interface TimerEvent { + + /*public interface TimerEvent { long timerEvent(); } - */ - - void start(){ + */ + void start() { timer.start(); } - class BidBook extends TreeSet { @@ -274,7 +292,6 @@ public class Exchange { //extends Thread { } - // Class to describe an executed order // QuoteReceiver has to be implemented by objects that wants // to receive quote updates @@ -318,7 +335,7 @@ public class Exchange { //extends Thread { while (i.hasNext()) { i.next().UpdateOrderBook(); } - + } // Here we store the list of quote receivers @@ -347,13 +364,8 @@ public class Exchange { //extends Thread { double lastprice = 100.0; long lastsvolume; - - private final Locker tradelock = new Locker(); - - - public ArrayList<Order> getOrderBook(OrderType type, int depth) { SortedSet<Order> book = order_books.get(type); @@ -376,9 +388,6 @@ public class Exchange { //extends Thread { return this.quoteHistory.last(); } - - - private void transferMoneyAndShares(Account src, Account dst, double money, double shares) { src.money -= money; dst.money += money; @@ -417,21 +426,19 @@ public class Exchange { //extends Thread { * * @param o */ - - - long nextQuoteId = 0; private void removeOrderIfExecuted(Order o) { if (o.volume != 0) { return; } + o.account.orders.remove(o.id); SortedSet book = order_books.get(o.type); + book.remove(book.first()); - //pollFirst(); } /** @@ -450,6 +457,9 @@ public class Exchange { //extends Thread { Order b = bid.first(); Order a = ask.first(); + //System.out.printf("In %f (%f) < %f (%f)\n",b.limit,b.volume,a.limit,a.volume); + + if (b.limit < a.limit) { break; } @@ -457,6 +467,8 @@ public class Exchange { //extends Thread { // There is a match, calculate price and volume double price = b.id < a.id ? b.limit : a.limit; double volume = b.volume >= a.volume ? a.volume : b.volume; + + //System.out.printf("Price %f Vol %f\n", price,volume); // Transfer money and shares transferMoneyAndShares(b.account, a.account, volume * price, -volume); @@ -465,6 +477,8 @@ public class Exchange { //extends Thread { b.volume -= volume; a.volume -= volume; + //System.out.printf("In %f (%f) < %f (%f)\n",b.limit,b.volume,a.limit,a.volume); + volume_total += volume; money_total += price * volume; diff --git a/src/main/java/traders/RandomTrader.java b/src/main/java/traders/RandomTrader.java index 82617b3..decd34e 100644 --- a/src/main/java/traders/RandomTrader.java +++ b/src/main/java/traders/RandomTrader.java @@ -66,7 +66,7 @@ public class RandomTrader extends AutoTrader { public long timerTask() { sesim.Exchange.Account a = se.getAccount(account_id); long rc = this.doTrade(); - return rc /1; + return rc /100; // return this.event(); } @@ -84,7 +84,7 @@ public class RandomTrader extends AutoTrader { } - double start = 1.1; + double start = 0.1; //Timer timer = new Timer(); @Override diff --git a/src/test/java/sesim/Test.java b/src/test/java/sesim/Test.java index 1ce0b01..3e626cf 100644 --- a/src/test/java/sesim/Test.java +++ b/src/test/java/sesim/Test.java @@ -98,21 +98,20 @@ public class Test { */ public static void main(String[] args) throws InterruptedException, MalformedURLException, InstantiationException, IllegalAccessException, IOException { - Float x0; - x0 = 3.1f; - - int x1; // = new Integer(0); - - x1 = 4; - - //x1 = (Integer)(Number)x0; - Double z = 0.99; - // to(x0,z); - - System.out.printf("Erg: %f\n", x0); - - System.out.printf("Hello world\n", ""); - System.exit(0); + Double x = 3.1415926; + + Double r = Math.floor(x*100.0)/100.0; + + + + System.out.print(r); + System.out.println(); + + Double p = Math.pow(10, 5); + System.out.print(p); + + + }