Better RandomTrader + Chart (still just a demo chart)

This commit is contained in:
7u83 2016-12-30 04:50:00 +01:00
parent 811cc0636d
commit 7025647166
21 changed files with 703 additions and 361 deletions

View File

@ -5,26 +5,30 @@
<group>
<file>file:/home/tube/NetBeansProjects/SeSim/additional/README.txt</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/Trader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/TraderRun.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/MTrader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/build.xml</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/Order.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/ControlPanel.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/OrderBookPanel.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/MainWin.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/OrderBook.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/manifest.mf</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Traders/RandomTrader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/TraderConfig.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/Account.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/Exchange.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/NewPanel.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/Chart.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Traders/RandomTraderConfig.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/TraderRunner.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/AskBook.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/AutoTrader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/BidBook.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/build.xml</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/OrderBookPanel.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Traders/RandomTrader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/AutoTraderLIst.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/BuyOrder.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Traders/ManTrader.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/README.md</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/AskBook.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/CandlestickDemo.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/Logger.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/Gui/BidBook.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/src/SeSim/SellOrder.java</file>
<file>file:/home/tube/NetBeansProjects/SeSim/LICENSE</file>
</group>

View File

@ -46,6 +46,9 @@ public class AskBook extends OrderBook {
}
public AskBook(){
if (MainWin.se == null) {
return;
}
MainWin.se.addBookReceiver(OrderType.ask, this);
}

View File

@ -37,11 +37,13 @@ public class BidBook extends OrderBook {
@Override
ArrayList getOrderBook() {
return MainWin.se.getOrderBook(OrderType.bid,40);
return MainWin.se.getOrderBook(OrderType.bid, 40);
}
BidBook(){
MainWin.se.addBookReceiver(OrderType.bid,this);
BidBook() {
if (MainWin.se == null) {
return;
}
MainWin.se.addBookReceiver(OrderType.bid, this);
}
}

View File

@ -0,0 +1,99 @@
package Gui;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;
import java.util.List;
public class CandlestickDemo extends JFrame {
public CandlestickDemo(String stockSymbol) {
super("CandlestickDemo");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
CandlestickRenderer renderer = new CandlestickRenderer();
XYDataset dataset = getDataSet(stockSymbol);
XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);
//Do some setting up, see the API Doc
renderer.setSeriesPaint(0, Color.BLACK);
renderer.setDrawVolume(false);
rangeAxis.setAutoRangeIncludesZero(false);
domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );
//Now create the chart and chart panel
JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(600, 300));
this.add(chartPanel);
this.pack();
}
protected AbstractXYDataset getDataSet(String stockSymbol) {
//This is the dataset we are going to create
DefaultOHLCDataset result = null;
//This is the data needed for the dataset
OHLCDataItem[] data;
//This is where we go get the data, replace with your own data source
data = getData(stockSymbol);
//Create a dataset, an Open, High, Low, Close dataset
result = new DefaultOHLCDataset(stockSymbol, data);
return result;
}
//This method uses yahoo finance to get the OHLC data
protected OHLCDataItem[] getData(String stockSymbol) {
List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
try {
String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
URL url = new URL(strUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
DateFormat df = new SimpleDateFormat("y-M-d");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse( st.nextToken() );
double open = Double.parseDouble( st.nextToken() );
double high = Double.parseDouble( st.nextToken() );
double low = Double.parseDouble( st.nextToken() );
double close = Double.parseDouble( st.nextToken() );
double volume = Double.parseDouble( st.nextToken() );
double adjClose = Double.parseDouble( st.nextToken() );
OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
dataItems.add(item);
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
//Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
Collections.reverse(dataItems);
//Convert the list into an array
OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
return data;
}
public static void main(String[] args) {
new CandlestickDemo("MSFT").setVisible(true);
}
}

View File

@ -1,11 +1,6 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
<Properties>
<Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
<Dimension value="[300, 300]"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
@ -16,18 +11,20 @@
<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"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="400" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="300" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Component class="javax.swing.JToggleButton" name="jToggleButton2">
<Properties>
<Property name="text" type="java.lang.String" value="jToggleButton2"/>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Form>

View File

@ -25,125 +25,127 @@
*/
package Gui;
import java.awt.Color;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.jfree.chart.plot.PlotOrientation;
import java.util.Collections;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import java.util.List;
import java.util.StringTokenizer;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.SegmentedTimeline;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.DefaultHighLowDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.chart.plot.PlotOrientation;
import SeSim.Exchange;
import SeSim.Exchange.*;
/**
*
* @author 7u83 <7u83@mail.ru>
*/
public class Chart extends javax.swing.JPanel implements Exchange.QuoteReceiver {
SeSim.Exchange se;
private DefaultHighLowDataset createDataset() {
// System.out.print("Making Data");
int s = se.quoteHistory.size();
// System.out.print(("SIZE"));
// System.out.println(s);
int serice = 115;
Date[] date = new Date[serice];
double[] high = new double[serice];
double[] low = new double[serice];
double[] open = new double[serice];
double[] close = new double[serice];
double[] volume = new double[serice];
Calendar calendar = Calendar.getInstance();
calendar.set(2008, 5, 1);
for (int i = 0; i < serice; i++) {
date[i] = createData(2008, 8, i + 1);
high[i] = 30 + Math.round(10) + new Double(Math.random() * 20.0);
low[i] = 30 + Math.round(10) + new Double(Math.random() * 20.0);
open[i] = 10 + Math.round(10) + new Double(Math.random() * 20.0);
close[i] = 10 + Math.round(10) + new Double(Math.random() * 20.0);
volume[i] = 10.0 + new Double(Math.random() * 20.0);
}
DefaultHighLowDataset data = new DefaultHighLowDataset("", date, high,
low, open, close, volume);
return data;
}
private Date createData(int year, int month, int date) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, date);
return calendar.getTime();
}
private JFreeChart createChart(final DefaultHighLowDataset dataset) {
// final JFreeChart chart = ChartFactory.createCandlestickChart(
//"Candlestick Demo", "Time", "Price", dataset, false);
// final JFreeChart chart = ChartFactory.createCandlestickChart(
// "Candlestick Demo", "Time", "Price", dataset, false);
final JFreeChart chart = ChartFactory.createXYLineChart(
"The Chart", "X axis ", "Y axis", dataset,
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls;
);
//"Candlestick Demo", "Time", "Price", dataset, false);
return chart;
}
public class Chart extends javax.swing.JPanel implements QuoteReceiver{
/**
* Creates new form Chart
*/
public Chart() {
initComponents();
this.se = MainWin.se;
if (this.se == null) {
String stockSymbol = "MSFT";
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
CandlestickRenderer renderer = new CandlestickRenderer();
XYDataset dataset = getDataSet(stockSymbol);
XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);
//Do some setting up, see the API Doc
renderer.setSeriesPaint(0, Color.BLACK);
renderer.setDrawVolume(false);
rangeAxis.setAutoRangeIncludesZero(false);
domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );
//Now create the chart and chart panel
JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 270));
add(chartPanel);
System.out.print("Hallo Welt\n");
if (MainWin.se == null)
return;
}
final DefaultHighLowDataset dataset = createDataset();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(800, 350));
// setContentPane(chartPanel);
initChart(chartPanel);
MainWin.se.addQuoteReceiver(this);
}
protected AbstractXYDataset getDataSet(String stockSymbol) {
//This is the dataset we are going to create
DefaultOHLCDataset result = null;
//This is the data needed for the dataset
OHLCDataItem[] data;
private void initChart(ChartPanel chart) {
//This is where we go get the data, replace with your own data source
data = getData(stockSymbol);
// orderBook1 = new Gui.OrderBook();
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chart, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(chart, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(16, Short.MAX_VALUE))
);
//Create a dataset, an Open, High, Low, Close dataset
result = new DefaultOHLCDataset(stockSymbol, data);
return result;
}
//This method uses yahoo finance to get the OHLC data
protected OHLCDataItem[] getData(String stockSymbol) {
List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
try {
String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
URL url = new URL(strUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
DateFormat df = new SimpleDateFormat("y-M-d");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse( st.nextToken() );
double open = Double.parseDouble( st.nextToken() );
double high = Double.parseDouble( st.nextToken() );
double low = Double.parseDouble( st.nextToken() );
double close = Double.parseDouble( st.nextToken() );
double volume = Double.parseDouble( st.nextToken() );
double adjClose = Double.parseDouble( st.nextToken() );
OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
dataItems.add(item);
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
//Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
Collections.reverse(dataItems);
//Convert the list into an array
OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
return data;
}
/**
@ -155,28 +157,22 @@ public class Chart extends javax.swing.JPanel implements Exchange.QuoteReceiver
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setPreferredSize(new java.awt.Dimension(300, 300));
jToggleButton2 = new javax.swing.JToggleButton();
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setLayout(new java.awt.BorderLayout());
jToggleButton2.setText("jToggleButton2");
add(jToggleButton2, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
@Override
public void UpdateQuote(Exchange.Quote q) {
System.out.print("Quote received");
System.out.println(q.price);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton jToggleButton2;
// End of variables declaration//GEN-END:variables
@Override
public void UpdateQuote(Quote q) {
q.print();
}
}

View File

@ -94,25 +94,12 @@
</Constraint>
</Constraints>
</Component>
<Container class="Gui.Chart" name="chart2">
<Component class="Gui.Chart" name="zZChart1">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="287" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="582" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
</Container>
</Component>
</SubComponents>
</Form>
</Form>

View File

@ -67,7 +67,7 @@ public class MainWin extends javax.swing.JFrame {
jMenuItem1 = new javax.swing.JMenuItem();
controlPanel2 = new Gui.ControlPanel();
orderBookPanel1 = new Gui.OrderBookPanel();
chart2 = new Gui.Chart();
zZChart1 = new Gui.Chart();
MainMenu = new javax.swing.JMenuBar();
FileMenu = new javax.swing.JMenu();
FileNew = new javax.swing.JMenuItem();
@ -87,19 +87,7 @@ public class MainWin extends javax.swing.JFrame {
setMinimumSize(new java.awt.Dimension(640, 480));
getContentPane().add(controlPanel2, java.awt.BorderLayout.LINE_END);
getContentPane().add(orderBookPanel1, java.awt.BorderLayout.LINE_START);
javax.swing.GroupLayout chart2Layout = new javax.swing.GroupLayout(chart2);
chart2.setLayout(chart2Layout);
chart2Layout.setHorizontalGroup(
chart2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 287, Short.MAX_VALUE)
);
chart2Layout.setVerticalGroup(
chart2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 582, Short.MAX_VALUE)
);
getContentPane().add(chart2, java.awt.BorderLayout.CENTER);
getContentPane().add(zZChart1, java.awt.BorderLayout.CENTER);
FileMenu.setBackground(new java.awt.Color(254, 203, 1));
FileMenu.setText("File");
@ -166,9 +154,9 @@ public class MainWin extends javax.swing.JFrame {
tr.start();
*/
AutoTraders at = new AutoTraders();
AutoTraderLIst at = new AutoTraderLIst();
RandomTraderConfig rcfg = new RandomTraderConfig();
at.add(1000, rcfg, se, 1000, 10000);
at.add(500, rcfg, se, 1000, 10000);
// at.add(10, rcfg, se, 1000000, 0);
@ -217,11 +205,11 @@ public class MainWin extends javax.swing.JFrame {
private javax.swing.JMenuItem FileNew;
private javax.swing.JMenuItem FileRun;
private javax.swing.JMenuBar MainMenu;
private Gui.Chart chart2;
private Gui.ControlPanel controlPanel2;
private javax.swing.JButton jButton1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuItem jMenuItem1;
private Gui.OrderBookPanel orderBookPanel1;
private Gui.Chart zZChart1;
// End of variables declaration//GEN-END:variables
}

18
src/Gui/NewPanel.form Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.2" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.PanelFormInfo">
<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"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
</Form>

128
src/Gui/NewPanel.java Normal file
View File

@ -0,0 +1,128 @@
/*
* Copyright (c) 2016, 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;
//import static Gui.SimpleJFreeDemo.createDemoPanel;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.function.Function2D;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
/**
*
* @author 7u83 <7u83@mail.ru>
*/
public class NewPanel extends javax.swing.JPanel {
/**
* Creates new form NewPanel
*/
public NewPanel() {
initComponents();
initComponents();
JPanel chartPanel = createDemoPanel();
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
add(chartPanel);
}
private static JFreeChart createChart(XYDataset dataset) {
// create the chart...
JFreeChart chart = ChartFactory.createXYLineChart(
"Function2DDemo1 ", // chart title
"X", // x axis label
"Y", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
XYPlot plot = (XYPlot) chart.getPlot();
plot.getDomainAxis().setLowerMargin(0.0);
plot.getDomainAxis().setUpperMargin(0.0);
return chart;
}
/**
* Creates a sample dataset.
*
* @return A sample dataset.
*/
public static XYDataset createDataset() {
XYDataset result = DatasetUtilities.sampleFunction2D(new X2(),
-4.0, 4.0, 40, "f(x)");
return result;
}
/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public static JPanel createDemoPanel() {
JFreeChart chart = createChart(createDataset());
return new ChartPanel(chart);
}
/**
* A simple function.
*/
static class X2 implements Function2D {
/* (non-Javadoc)
* @see org.jfree.data.function.Function2D#getValue(double)
*/
public double getValue(double x) {
return x * x + 2;
}
}
/**
* 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.BorderLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}

View File

@ -53,6 +53,19 @@ final public class Account {
}
public boolean isRuined(){
/* System.out.print(
"Account: "
+money
+" / "
+shares
+"\n"
);
*/
return this.money<=se.lastprice && this.shares<=0;
}
public Order sell(long volume, double limit) {
SellOrder o = new SellOrder();

47
src/SeSim/AutoTrader.java Normal file
View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2016, 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 SeSim;
import static java.lang.Thread.sleep;
/**
*
* @author 7u83 <7u83@mail.ru>
*/
public abstract class AutoTrader extends Trader implements Runnable {
public AutoTrader(Account account, TraderConfig config) {
super(account, config);
}
protected void doSleep(int seconds) {
try {
sleep(seconds*1000);
} catch (InterruptedException e) {
}
}
}

View File

@ -29,12 +29,12 @@ package SeSim;
*
* @author 7u83 <7u83@mail.ru>
*/
public class AutoTraders {
public class AutoTraderLIst {
public void add(int n, TraderConfig config, Exchange se, long shares, double money) {
for (int i = 0; i < n; i++) {
Trader trader = config.createTrader(se, shares, money);
AutoTrader trader = config.createTrader(se, shares, money);
TraderRunner tr = new TraderRunner(trader);
tr.start();
}

View File

@ -23,7 +23,7 @@ public class Exchange extends Thread {
public Exchange() {
this.ask = new TreeSet<>();
this.bid = new TreeSet<>();
this.qrlist = new TreeSet<>();
this.qrlist = new ArrayList<>();
this.quoteHistory = new ArrayList<>();
}
@ -31,13 +31,27 @@ public class Exchange extends Thread {
public class Quote {
double bid;
double bid_size;
double bid_volume;
double ask;
double ask_size;
double ask_volume;
public double price;
public long size;
public long volume;
public long time;
public void print(){
System.out.print("Quite ("
+time
+") :"
+price
+" / "
+volume
+"\n"
);
}
}
// QuoteReceiver has to be implemented by objects that wants
@ -92,7 +106,7 @@ public class Exchange extends Thread {
}
// Here we store the list of quote receivers
private final TreeSet<QuoteReceiver> qrlist;
private final ArrayList<QuoteReceiver> qrlist;
/**
*
@ -297,7 +311,7 @@ public class Exchange extends Thread {
Quote q = new Quote();
q.size = volume;
q.volume = volume;
q.price = price;
q.time = System.currentTimeMillis();
@ -305,13 +319,14 @@ public class Exchange extends Thread {
this.updateBookReceivers(OrderType.bid);
this.updateBookReceivers(OrderType.ask);
System.out.print(
/* System.out.print(
"Executed: "
+ q.price
+ " / "
+ q.size
+ q.volume
+ "\n"
);
*/
//quoteHistory.add(q);
continue;

View File

@ -1,87 +0,0 @@
package SeSim;
import java.util.Random;
public class MTrader extends Trader {
Exchange ex;
Random rand;
public MTrader(Account account,TraderConfig config) {
super(account,config);
}
/* public MTrader(Exchange ex1, long shares, double money) {
account.money = money;
account.shares = shares;
this.ex = ex;
rand = new Random();
}
*/
public void DoBuy() {
// System.out.println("AAA");
if (account.orderpending) {
return;
}
if (account.money <= 0) {
return;
}
double perc = rand.nextDouble() * 1.0;
double lp = ex.lastprice;
double limit = lp / 100 * perc + lp;
// System.out.println("HW");
long size = (int) (account.money / limit);
account.buy(size, limit);
}
public void DoSell() {
// System.out.println("SoSell");
if (account.orderpending) {
return;
}
if (account.shares <= 0) {
return;
}
double perc = rand.nextDouble() * 1.0;
double lp = ex.lastprice;
double limit = lp - lp / 100 * perc;
long size = (int) (account.shares);
account.sell(size, limit);
return;
}
public void trade() {
// What to do?
int action = rand.nextInt(3);
// System.out.print("Action");
// System.out.println(action);
if (action == 0) {
return;
}
if (action == 1) {
DoBuy();
return;
}
if (action == 2) {
DoSell();
return;
}
//System.out.printf("MyPrice: %.2f\n",theprice);
}
}

View File

@ -25,11 +25,13 @@
*/
package SeSim;
import static java.lang.Thread.sleep;
public abstract class Trader {
public String name = null;
public abstract void trade();
public Account account;
public TraderConfig config;
@ -59,6 +61,9 @@ public abstract class Trader {
public Trader(Account account){
this(account,null);
}
};

View File

@ -32,5 +32,5 @@ package SeSim;
public abstract class TraderConfig{
String name;
public abstract Trader createTrader(Exchange se, long shares, double money);
public abstract AutoTrader createTrader(Exchange se, long shares, double money);
}

View File

@ -4,21 +4,15 @@ public class TraderRunner extends Thread {
protected long sleeptime = 1000;
Trader trader;
AutoTrader trader;
public TraderRunner(Trader trader){
public TraderRunner(AutoTrader trader){
this.trader=trader;
}
public void run() {
while (true) {
try {
sleep(sleeptime);
} catch (InterruptedException e) {
System.out.println("Interrupted");
return;
}
trader.trade();
}
trader.run();
}
}

View File

@ -45,7 +45,7 @@ public class ManTrader extends Trader{
@Override
public void trade(){
BuyOrder o = new BuyOrder();

View File

@ -1,75 +1,134 @@
/*
* Copyright (c) 2016, 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 Traders;
import SeSim.Account;
import SeSim.Order;
import java.util.Random;
import SeSim.Trader;
import SeSim.AutoTrader;
import SeSim.TraderConfig;
public class RandomTrader extends Trader {
public TraderConfig getTraderConfig(){
return new RandomTraderConfig();
}
private RandomTraderConfig myconfig;
public class RandomTrader extends AutoTrader {
Random rand = new Random();
// config for this trader
final private RandomTraderConfig myconfig;
// my current order
//private Order myorder = null;
public RandomTrader(Account account,TraderConfig config) {
super(account,config);
if (config==null){
// object to generate random numbers
final private Random rand = new Random();
public RandomTrader(Account account, TraderConfig config) {
super(account, config);
if (config == null) {
config = new RandomTraderConfig();
}
myconfig = (RandomTraderConfig)config;
myconfig = (RandomTraderConfig) config;
}
public void doBuy() {
if (account.money <= 0) {
return;
}
double perc = 5.0-rand.nextDouble() * 10.0;
double lp = account.se.getlastprice();
double limit = lp / 100 * perc + lp;
long volume = (int) (account.money / (limit * 1));
if (volume ==0 ){
System.out.print("Can't buy shares = 0 my money="+account.money+" shares="+account.shares+"\n");
return;
}
buy(volume, limit);
return;
/**
* Get a (long) random number between min an max
*
* @param min minimum value
* @param max maximeum value
* @return the number
*/
protected double getRandom(double min, double max) {
double r = rand.nextDouble();
return (max - min) * r + min;
}
public void doSell() {
if (account.shares <= 0) {
return;
}
double perc = 5.0-rand.nextDouble() * 10.0;
double lp = account.se.getlastprice();
double limit = lp - lp / 100 * perc;
long size = (int) (account.shares);
sell(size, limit);
protected int getRandom(int[] minmax){
return (int)Math.round(getRandom(minmax[0],minmax[1]));
}
private boolean monitorTrades() {
int numpending = account.pending.size();
/**
*
* @param val
* @param minmax
* @return
*/
protected double getRandomAmmount(double val, float[] minmax) {
double min = val * minmax[0] / 100.0;
double max = val * minmax[1] / 100.0;
return getRandom(min, max);
}
public boolean waitForOrder(long seconds){
// System.out.print("RT: Monitoring trades - Pending: "+numpending+"\n");
for (int i=0; (i<seconds) && (0!=account.pending.size());i++ ){
doSleep(1);
}
if (account.pending.size()!=0){
Order o=account.pending.get(0);
account.se.CancelOrder(o);
return false;
}
return true;
}
public boolean doBuy() {
double money = getRandomAmmount(account.money,myconfig.sell_volume);
double lp = account.se.getlastprice();
double limit;
limit = lp + getRandomAmmount(lp, myconfig.buy_limit);
long volume = (int) (money / (limit * 1));
if (volume<=0)
return false;
buy(volume, limit);
return waitForOrder(getRandom(myconfig.buy_order_wait));
}
public boolean doSell() {
long volume;
volume = (long) Math.round(getRandomAmmount(account.shares, myconfig.sell_volume));
double lp = account.se.getlastprice();
double limit;
limit = lp + getRandomAmmount(lp, myconfig.sell_limit);
sell(volume, limit);
return waitForOrder(getRandom(myconfig.sell_order_wait));
}
/* private boolean monitorTrades() {
int numpending = account.pending.size();
if (numpending == 0) {
// System.out.print("RT: pending = 0 - return false\n");
return false;
@ -77,37 +136,45 @@ public class RandomTrader extends Trader {
Order o = account.pending.get(0);
long age = o.getAge();
// System.out.print("RT: age is: "+age+"\n");
// System.out.print("RT: age is: "+age+"\n");
if (age > myconfig.maxage) {
// System.out.print("MaxAge is"+myconfig.maxage+"\n");
// System.out.print("MaxAge is"+myconfig.maxage+"\n");
account.se.CancelOrder(o);
// System.out.print("Age reached - canel return false\n");
return false;
}
//System.out.print("RT: monitor return true\n");
return true;
}
*/
public void trade() {
// System.out.print("RT: Now trading\n");
float am[] = {-10, 200};
double x = Math.round(this.getRandomAmmount(1000, am));
/* System.out.print(
"Random:"
+ x
+ "\n"
);
*/
/*
// System.out.print("RT: Now trading\n");
if (monitorTrades()) {
return;
}
// What next to do?
int action = rand.nextInt(5);
if (account.money<10 && account.shares<5){
if (account.money < 10 && account.shares < 5) {
System.out.print("I'm almost ruined\n");
}
if (action == 1) {
doBuy();
return;
@ -117,8 +184,57 @@ public class RandomTrader extends Trader {
doSell();
return;
}
*/
}
@Override
public void run() {
// System.out.print("Starting Random Trader\n");
while (true) {
// What next to do? (0=sell, 1=buy)
int action = rand.nextInt(2);
if (account.isRuined()){
// System.out.print("I'm ruined\n");
// System.exit(0);
}
boolean rc;
// action=1;
switch(action){
case 0: //sell
if(account.shares<=0){
// we have no shares
continue;
}
// System.out.print("Sell\n");
rc = doSell();
if (!rc)
continue;
// System.out.print("Sold\n");
doSleep(getRandom(myconfig.wait_after_sell));
// System.out.print("Next\n");
break;
case 1: //sell
if(account.money<=0){
// we have no money
continue;
}
// System.out.print("Sell\n");
rc = doBuy();
if (!rc)
continue;
// System.out.print("Bought\n");
doSleep(getRandom(myconfig.wait_after_buy));
// System.out.print("Next\n");
break;
}
// doSleep(1);
}
}
}

View File

@ -33,17 +33,34 @@ import SeSim.*;
*/
public class RandomTraderConfig extends TraderConfig {
public long maxage = 1000 * 10 * 1;
//public long maxage = 1000 * 10 * 1;
/*public long hold_shares_min = 10;
public long hold_shares_max = 30;
public float buy_volume_min = 10;
*/
/**
*
* @param se
* @param shares
* @param money
* @return
* If shares are selled, this specifies
* the minimum and maximum volume to be selled
*/
public float[] sell_volume= {100,100};
public float[] sell_limit = {-15,100};
public int[] sell_order_wait = {5,33};
public int[] wait_after_sell = {20,33};
public float[] buy_volume={100,100};
public float[] buy_limit = {-50,5};
public int[] buy_order_wait = {5,33};
public int[] wait_after_buy = {20,33};
@Override
public Trader createTrader(Exchange se, long shares, double money) {
public AutoTrader createTrader(Exchange se, long shares, double money) {
Account a = new Account(se, shares, money);
return new RandomTrader(a, this);
}