Dukascopy
 
 
Wiki JStore Search Login

Attention! Read the forum rules carefully before posting a topic.

    Try to find an answer in Wiki before asking a question.
    Submit programming questions in this forum only.
    Off topics are strictly forbidden.

Any topics which do not satisfy these rules will be deleted.

DataBase access
 Post subject: DataBase access Post rating: 0   Post Posted: Thu 23 Oct, 2008, 10:26 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Example that writes ticks to the database:
package jforex;

import com.dukascopy.api.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import org.apache.commons.dbcp.*;

/**
 * commons-pool can be downloaded here - https://commons.apache.org/pool/
 * commons-dbcp can be downloaded here - https://commons.apache.org/dbcp/
 * mysql java connection can be downloaded here - https://dev.mysql.com/downloads/connector/j/5.1.html
 */
@RequiresFullAccess
@Library("c:/fullpathtolib/commons-pool-1.4.jar;c:/fullpathtolib/commons-dbcp-1.2.2.jar;c:/fullpathtolib/mysql-connector-java-5.1.7-bin.jar")
public class TestMySQLAccess implements IStrategy {
   private IContext context;
   private IConsole console;
   private DataSource dataSource;
   private Calendar gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
   
   public void onStart(IContext context) throws JFException {
      this.context = context;
      console = context.getConsole();
      try {
           Properties properties = new Properties();
           properties.put("driverClassName", "com.mysql.jdbc.Driver");
           properties.put("url", "jdbc:mysql://localhost/test");
           properties.put("username", "test");
           properties.put("password", "test");
           properties.put("poolPreparedStatements", "true");

           dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
           console.getErr().println(e);
        }
   }

   public void onAccount(IAccount account) throws JFException {
   }

   public void onMessage(IMessage message) throws JFException {
   }

   public void onStop() throws JFException {
      try {
         ((BasicDataSource) dataSource).close();
      } catch (SQLException e) {
         console.getErr().println(e);
      }
   }

   public void onTick(Instrument instrument, ITick tick) throws JFException {
      try {
         Connection connection = dataSource.getConnection();
         try {
            PreparedStatement statement = connection.prepareStatement("insert into ticks(instrument, tick_time, ask, bid, askVol, bidVol) values (?, ?, ?, ?, ?, ?)");
            try {
               statement.setString(1, instrument.toString());
               statement.setTimestamp(2, new Timestamp(tick.getTime()), gmtCalendar);
               statement.setDouble(3, tick.getAsk());
               statement.setDouble(4, tick.getBid());
               statement.setDouble(5, tick.getAskVolume());
               statement.setDouble(6, tick.getBidVolume());
               statement.execute();
            } finally {
               statement.close();
            }
         } finally {
            connection.close();
         }
      } catch (SQLException e) {
         console.getErr().println(e);
      }
   }
   
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
    }
}


Attachments:
TestMySQLAccess.java [2.59 KiB]
Downloaded 821 times
DISCLAIMER: Dukascopy Bank SA's waiver of responsability - Documents, data or information available on this webpage may be posted by third parties without Dukascopy Bank SA being obliged to make any control on their content. Anyone accessing this webpage and downloading or otherwise making use of any document, data or information found on this webpage shall do it on his/her own risks without any recourse against Dukascopy Bank SA in relation thereto or for any consequences arising to him/her or any third party from the use and/or reliance on any document, data or information found on this webpage.
 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 20 May, 2010, 08:06 

User rating: -
i can't compile

2010-05-20 06:56:44 The type Properties is ambiguous
2010-05-20 06:56:44 ^^^^^^^^^^
2010-05-20 06:56:44 Properties properties = new Properties();
2010-05-20 06:56:44 2. ERROR in C:\DOCUME~1\user\LOCALS~1\Temp\jfxide\tmp\TestMySQLAccess.java (at line 28)


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Fri 21 May, 2010, 08:17 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Please, make sure that you are using proper libraries:
  • commons-pool-1.4.jar;
  • commons-dbcp-1.2.2.jar;
  • mysql-connector-java-5.1.7-bin.jar;


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Mon 24 May, 2010, 11:03 

User rating: -
I compile but this error pops up every time in the journal:

08:39:53 The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
08:39:53 org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure

What should I do??


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Tue 25 May, 2010, 07:47 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Hi,
please consider this link https://forums.sun.com/thread.jspa?threadID=5392136
If it isn't the problem, please send us a full stacktrace form the java console.


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 10 Jun, 2010, 22:57 

User rating: 0
Joined: Mon 24 May, 2010, 07:48
Posts: 3
Thanks for the example :D

How would we implement the same functionality but have the method record the price every 10 seconds exactly? :!:


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 10 Jun, 2010, 23:18 

User rating: 0
Joined: Mon 24 May, 2010, 07:48
Posts: 3
I should probably be more specific.. i know that i can use the thread.sleep method, but this will not give me accurate timing, as there will still be some time between the thread calls. In practice, my timing will drift 1-4 seconds per minute, which is quite a lot.

So i am assuming the correct implementation would be to check the time and record the price when the time is at or after +10 seconds of the previous time. Is there a quick and easy way to do that? 8-)


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Mon 14 Jun, 2010, 09:07 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Hi,
The IHistory interface have method getTimeOfLastTick(instrument) (also even simple way is System.currentTimeMillis()). You could put this check in an onTick method.


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Fri 02 Jul, 2010, 18:38 

User rating: 0
Joined: Fri 07 May, 2010, 02:59
Posts: 61
Support wrote:
Hi,
The IHistory interface have method getTimeOfLastTick(instrument) (also even simple way is System.currentTimeMillis()). You could put this check in an onTick method.


I would strongly suggest you use Support's previous suggestion of getting the date/time from the system instead of using System.currentTimeMillis(). If for no other reason, this will give you the time when the strategy executes. If you're running live you probably wouldn't notice a difference of more than a few milliseconds. But in backtesting you'll see a wildly different timestamp.

-Brian


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Mon 26 Jul, 2010, 20:39 

User rating: 0
Joined: Mon 24 May, 2010, 07:48
Posts: 3
Thank you Support, Brian :)

I will put the first method into test soon!

Phantal wrote:
Support wrote:
Hi,
The IHistory interface have method getTimeOfLastTick(instrument) (also even simple way is System.currentTimeMillis()). You could put this check in an onTick method.


I would strongly suggest you use Support's previous suggestion of getting the date/time from the system instead of using System.currentTimeMillis(). If for no other reason, this will give you the time when the strategy executes. If you're running live you probably wouldn't notice a difference of more than a few milliseconds. But in backtesting you'll see a wildly different timestamp.

-Brian


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 26 Aug, 2010, 12:58 

User rating: 0
Joined: Mon 09 Aug, 2010, 10:23
Posts: 5
Can you please post an updated version?

I have replaced the library files with the updated ones (the ones you mention no longer exist), and replaced the @Library directive with the following:
@Library("c:/Documents and Settings/User/My Documents/JForex/Strategies/files/commons-pool-1.5.4.jar;c:/Documents and Settings/User/My Documents/JForex/Strategies/files/commons-dbcp-1.4.jar;c:/Documents and Settings/User/My Documents/JForex/Strategies/files/mysql-connector-java-5.1.13-bin.jar")

I'm not sure what I'm doing wrong but I'm getting the following compilation error messages (re The type Properties at line 30):
10:11:32 The type Properties is ambiguous
10:11:32 Properties properties = new Properties();

Thanks in advance


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Mon 30 Aug, 2010, 09:52 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Hi,
try providing the full class name in the declaration as follows: java.util.Properties properties = new java.util.Properties();


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 09 Jun, 2011, 08:02 

User rating: 0
Joined: Thu 09 Jun, 2011, 07:49
Posts: 4
Location: France, Nice
This version can save either ALL the market depth or just the best bid / best ask (and volume) , to mysql database of your choice.

To get this up and running , you just need to import the mysql script in mysql Workbench , launch them and the databases will be auto created.

Works fine with net beans , though to get this up and running on the platform you will need to locate the .jar (mysql connectors , and the 2 others)...In net beans you can just remove the lines with require full access , and don't have to locate the .jar (net beans does it for you).

If you need help setting it up , my email is in the programmer list in dukascopy (Olivier. [email protected] )

Cheers



package singlejartest;

//~--- non-JDK imports --------------------------------------------------------

import com.dukascopy.api.*;

//~--- JDK imports ------------------------------------------------------------

import java.sql.*;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import java.util.*;



/**
* commons-pool can be downloaded here - https://commons.apache.org/pool/
* commons-dbcp can be downloaded here - https://commons.apache.org/dbcp/
* mysql java connection can be downloaded here - https://dev.mysql.com/downloads/connector/j/5.1.html
*/
@RequiresFullAccess
@Library("c:/fullpathtolib/commons-pool-1.4.jar;c:/fullpathtolib/commons-dbcp-1.2.2.jar;c:/fullpathtolib/mysql-connector-java-5.1.7-bin.jar")
public class TestMySQLTicks implements IStrategy {
    double[]                               askVolumes  = new double[10];
    double[]                               asks        = new double[10];
    double[]                               bidVolumes  = new double[10];
    double[]                               bids        = new double[10];
    Connection                             conn        = GetCon();
    String                                 dbIp        = "x.x.x.x";
    ResultSet                              rs          = null;
    Statement                              stmt        = null;
    private Calendar                       gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    private IConsole                       console;
    private IContext                       context;
   

    public Connection GetCon() {
        try {
            conn = DriverManager.getConnection("jdbc:mysql://" + dbIp + ":3306/ticks"
                                               + "?user=root&password=mypassword&pooling=true");    // Do something with the Connection
        } catch (SQLException ex) {
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());

            return null;
        }

        return conn;
    }

    public void onStart(IContext context) throws JFException {
        this.context = context;
        console      = context.getConsole();
        console.getOut().println("In on start trying to register eurousd");

        // set instruments that will be used in testing
        Set<Instrument> instruments = new HashSet<Instrument>();

        instruments.add(Instrument.EURUSD);
    }

    public void onAccount(IAccount account) throws JFException {}

    public void onMessage(IMessage message) throws JFException {}

    public void onStop() throws JFException {
        try {
            if (!GetCon().isClosed()) {
                GetCon().close();
            }
        } catch (SQLException ex) {
            console.getErr();
        }
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {
       // InsertTicks(instrument.toString(), tick);

        InsertMyTicksDepth(instrument.toString(),tick);
    }

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}

   

    private void InsertTicks(String instrument, ITick tick) {
        try {
            CallableStatement callproc = GetCon().prepareCall("call `ticks`.InsertTicks(?,?,?,?,?,?,?)");

            // Lets send the procedure.
            callproc.setString(1, instrument.toString());
            callproc.setString(2, String.valueOf(tick.getTime()));
            callproc.setTimestamp(3, new Timestamp(tick.getTime()), gmtCalendar);
            callproc.setDouble(4, tick.getBid());
            callproc.setDouble(5, tick.getAsk());
            callproc.setDouble(6, tick.getAskVolume());
            callproc.setDouble(7, tick.getBidVolume());
            callproc.execute();
            callproc.close();
        } catch (SQLException ex) {
            console.getOut().print("Error writing to the mysql db:" + ex.getLocalizedMessage());
            console.getOut().print("Error writing to the mysql db:" + ex.getMessage());
            console.getOut().print("Error writing to the mysql db:" + ex.getSQLState());
        } finally {
            console.getOut().print("Wrote a tick to file?");
        }
    }

    private void InsertMyTicksDepth(String instrument, ITick tick) {
        try {
            CallableStatement callproc =
                GetCon().prepareCall("call `ticks`.InsertTicksWithDepth(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

            asks       = tick.getAsks();
            bids       = tick.getBids();
            bidVolumes = tick.getBidVolumes();
            askVolumes = tick.getAskVolumes();
            FillProcFields(callproc, instrument, tick);
       
            callproc.execute();
            callproc.close();
        } catch (SQLException ex) {
            console.getOut().print("Error writing to the mysql db:" + ex.getLocalizedMessage());
            console.getOut().print("Error writing to the mysql db:" + ex.getMessage());
            console.getOut().print("Error writing to the mysql db:" + ex.getSQLState());
        } finally {
            console.getOut().print("Wrote a tick to file?");
        }
    }

 
   
     private void FillProcFields(CallableStatement callproc, String instrument, ITick tick) throws SQLException {
        // Lets send the procedure.
        callproc.setString(1, instrument.toString());
        callproc.setString(2, String.valueOf(tick.getTime()));
        callproc.setTimestamp(3, new Timestamp(tick.getTime()), gmtCalendar);
        callproc.setDouble(4, bids[0]);
        callproc.setDouble(5, asks[0]);
        callproc.setDouble(6, bidVolumes[0]);
        callproc.setDouble(7, askVolumes[0]);
        callproc.setDouble(8, bids[1]);
        callproc.setDouble(9, bids[2]);
        callproc.setDouble(10, bids[3]);
        callproc.setDouble(11, bids[4]);
        callproc.setDouble(12, bids[5]);
        callproc.setDouble(13, bids[6]);
        callproc.setDouble(14, bids[7]);
        callproc.setDouble(15, bids[8]);
        callproc.setDouble(16, bids[9]);
        callproc.setDouble(17, asks[1]);
        callproc.setDouble(18, asks[2]);
        callproc.setDouble(19, asks[3]);
        callproc.setDouble(20, asks[4]);
        callproc.setDouble(21, asks[5]);
        callproc.setDouble(22, asks[6]);
        callproc.setDouble(23, asks[7]);
        callproc.setDouble(24, asks[8]);
        callproc.setDouble(25, asks[9]);
        callproc.setDouble(26, bidVolumes[1]);
        callproc.setDouble(27, bidVolumes[2]);
        callproc.setDouble(28, bidVolumes[3]);
        callproc.setDouble(29, bidVolumes[4]);
        callproc.setDouble(30, bidVolumes[5]);
        callproc.setDouble(31, bidVolumes[6]);
        callproc.setDouble(32, bidVolumes[7]);
        callproc.setDouble(33, bidVolumes[8]);
        callproc.setDouble(34, bidVolumes[9]);           
        callproc.setDouble(35, askVolumes[1]);
        callproc.setDouble(36, askVolumes[2]);
        callproc.setDouble(37, askVolumes[3]);
        callproc.setDouble(38, askVolumes[4]);
        callproc.setDouble(39, askVolumes[5]);
        callproc.setDouble(40, askVolumes[6]);
        callproc.setDouble(41, askVolumes[7]);
        callproc.setDouble(42, askVolumes[8]);
        callproc.setDouble(43, askVolumes[9]);
    }
}




The database itself :
-- MySQL dump 10.13  Distrib 5.6.2-m5, for Win64 (x86)
--
-- Host: localhost    Database: ticks
-- ------------------------------------------------------
-- Server version   5.6.2-m5

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `dukasticks`
--

DROP TABLE IF EXISTS `dukasticks`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dukasticks` (
  `idDukasticks` int(11) NOT NULL AUTO_INCREMENT,
  `Instrument` varchar(45) NOT NULL,
  `TickTime` varchar(80) DEFAULT NULL,
  `theDate` timestamp NULL DEFAULT NULL,
  `bid` double NOT NULL,
  `ask` double NOT NULL,
  `bidvolume` double DEFAULT NULL,
  `askvolume` double DEFAULT NULL,
  `bid1` double DEFAULT NULL,
  `bid2` double DEFAULT NULL,
  `bid3` double DEFAULT NULL,
  `bid4` double DEFAULT NULL,
  `bid5` double DEFAULT NULL,
  `bid6` double DEFAULT NULL,
  `bid7` double DEFAULT NULL,
  `bid8` double DEFAULT NULL,
  `bid9` double DEFAULT NULL,
  `ask1` double DEFAULT NULL,
  `ask2` double DEFAULT NULL,
  `ask3` double DEFAULT NULL,
  `ask4` double DEFAULT NULL,
  `ask5` double DEFAULT NULL,
  `ask6` double DEFAULT NULL,
  `ask7` double DEFAULT NULL,
  `ask8` double DEFAULT NULL,
  `ask9` double DEFAULT NULL,
  `bidvolume1` double DEFAULT NULL,
  `bidvolume2` double DEFAULT NULL,
  `bidvolume3` double DEFAULT NULL,
  `bidvolume4` double DEFAULT NULL,
  `bidvolume5` double DEFAULT NULL,
  `bidvolume6` double DEFAULT NULL,
  `bidvolume7` double DEFAULT NULL,
  `bidvolume8` double DEFAULT NULL,
  `bidvolume9` double DEFAULT NULL,
  `askvolume1` double DEFAULT NULL,
  `askvolume2` double DEFAULT NULL,
  `askvolume3` double DEFAULT NULL,
  `askvolume4` double DEFAULT NULL,
  `askvolume5` double DEFAULT NULL,
  `askvolume6` double DEFAULT NULL,
  `askvolume7` double DEFAULT NULL,
  `askvolume8` double DEFAULT NULL,
  `askvolume9` double DEFAULT NULL,
  PRIMARY KEY (`idDukasticks`)
) ENGINE=InnoDB AUTO_INCREMENT=469 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `dukasticks`
--

LOCK TABLES `dukasticks` WRITE;
/*!40000 ALTER TABLE `dukasticks` DISABLE KEYS */;
/*!40000 ALTER TABLE `dukasticks` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2011-06-09  8:19:54



The procedures (the one that writes only best bid/best ask):
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `InsertTicks`(in instrument varchar(20),in ticktime varchar(80) ,in theDate TimeStamp,in bid double ,in ask double ,in bidVol double ,in AskVol double)
begin

INSERT into `Ticks`.`dukasticks`(Instrument,TickTime,theDate,bid,ask,bidvolume,askvolume) values (instrument,ticktime,theDate,bid,ask,bidVol,AskVol);

   
END



the procedure that writes ALL of the market depth (10 bids / 10 asks and the volumes for each bid/ask):
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `InsertTicksWithDepth`(in instrument varchar(20),in ticktime varchar(80) ,in theDate TimeStamp,in bid double ,in ask double ,
in bidVol double ,in AskVol double,in bid1 double,in bid2 double,in bid3 double,in bid4 double,in bid5 double,in bid6 double,in bid7 double,in bid8 double,in bid9 double,
in ask1 double,in ask2 double,in ask3 double,in ask4 double,in ask5 double,in ask6 double,in ask7 double,in ask8 double,in ask9 double, in bidvol1 double,
in bidvol2 double,in bidvol3 double, in bidvol4 double,in bidvol5 double,in bidvol6 double,in bidvol7 double,in bidvol8 double,in bidvol9 double,in askvol1 double,
 in askvol2 double, in askvol3 double,in askvol4 double
,in askvol5 double,in askvol6 double,in askvol7 double,in askvol8 double,in askvol9 double)
begin

INSERT into `Ticks`.`dukasticks`(Instrument,TickTime,theDate,bid,ask,bidvolume,askvolume,
bid1,bid2,bid3,bid4,bid5,bid6,bid7,bid8,bid9,
ask1,ask2,ask3,ask4,ask5,ask6,ask7,ask8,ask9,
bidvolume1,bidvolume2,bidvolume3,bidvolume4,bidvolume5,bidvolume6,bidvolume7,bidvolume8,bidvolume9,
askvolume1,askvolume2,askvolume3,askvolume4,askvolume5,askvolume6,askvolume7,askvolume8,askvolume9)

values (instrument,ticktime,theDate,bid,ask,
bidVol,AskVol,
bid1,bid2,bid3,bid4,bid5,bid6,bid7,bid8,bid9,
ask1,ask2,ask3,ask4,ask5,ask6,ask7,ask8,ask9,
bidvol1,bidvol2,bidvol3,bidvol4,bidvol5,bidvol6,bidvol7,bidvol8,bidvol9,
askvol1,askvol2,askvol3q,askvol4,askvol5,askvol6,askvol7,askvol8,askvol9);

   
END



 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Thu 26 Apr, 2012, 16:18 

User rating: 0
Joined: Thu 26 Apr, 2012, 14:41
Posts: 7
Hello,

I'm new to programming in Java and JForex. I used the first code listed earlier in the thread successfully, see below. However, how would the code be altered to get OHLC, time, volume, and date data for EURUSD 1 minute bar instead of ticks as in the below example? Any help is greatly appreciated! I have no idea where to start!

Cheers,

RMG

package jforex;

import com.dukascopy.api.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import org.apache.commons.dbcp.*;

/**
 * commons-pool can be downloaded here - https://commons.apache.org/pool/
 * commons-dbcp can be downloaded here - https://commons.apache.org/dbcp/
 * mysql java connector can be downloaded here - https://dev.mysql.com/downloads/connector/j/5.1.html
 *
 * @author Dmitry Shohov
 */
@RequiresFullAccess
@Library("c:/lib/commons-pool-1.5.4.jar;c:/lib/commons-dbcp-1.4.jar;c:/lib/mysql-connector-java-5.1.13-bin.jar")
public class GCMQFXFTestMySQLAccess implements IStrategy {   
    private IConsole console;
    private DataSource dataSource;
    private Calendar gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
   
    public void onStart(IContext context) throws JFException {       
        console = context.getConsole();
        try {
            java.util.Properties properties = new java.util.Properties();
            properties.put("driverClassName", "com.mysql.jdbc.Driver");
            properties.put("url", "jdbc:mysql://localhost/test");
            properties.put("username", "root");
            properties.put("password", "root");
            properties.put("poolPreparedStatements", "true");

            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            console.getErr().println(e);
        }
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
        try {
            ((BasicDataSource) dataSource).close();
        } catch (SQLException e) {
            console.getErr().println(e);
        }
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        try {
            Connection connection = dataSource.getConnection();
            try {
                PreparedStatement statement = connection.prepareStatement("insert into ticks(instrument, tickID, tick_time, ask, bid, askVol, bidVol) values (?, ?, ?, ?, ?, ?, ?)");
                try {
                    statement.setString(1, instrument.toString());
                    statement.setString(2, String.valueOf(tick.getTime()));
                    statement.setTimestamp(3, new Timestamp(tick.getTime()), gmtCalendar);
                    statement.setDouble(4, tick.getAsk());
                    statement.setDouble(5, tick.getBid());
                    statement.setDouble(6, tick.getAskVolume());
                    statement.setDouble(7, tick.getBidVolume());
                    statement.execute();
                } finally {
                    statement.close();
                }
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            console.getErr().println(e);
        }
    }
   
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
    }
}


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Fri 27 Apr, 2012, 16:09 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Assuming that you have a corresponding database table you would do something like this:
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
       
       //filter unused bars
       if(instrument != Instrument.EURUSD || period != Period.ONE_MIN){
          return;
       }
       console.getOut().println("Will try to write bar: " + askBar);
        try {
            Connection connection = dataSource.getConnection();
            try {
                PreparedStatement statement = connection.prepareStatement("insert into bars(instrument, barTime, O, H, L, C) values (?, ?, ?, ?, ?, ?)");
                try {
                    statement.setString(1, instrument.toString());
                    statement.setLong(2, askBar.getTime());
                    statement.setDouble(3, askBar.getOpen());
                    statement.setDouble(4, askBar.getHigh());
                    statement.setDouble(5, askBar.getLow());
                    statement.setDouble(6, askBar.getClose());
                    statement.execute();
                } finally {
                    statement.close();
                }
            } finally {
                connection.close();
            }
        } catch (SQLException e) {
            console.getErr().println(e);
        }
    }


 
 Post subject: Re: DataBase access Post rating: 0   Post Posted: Fri 28 Sep, 2012, 06:07 

User rating: 0
Joined: Thu 26 Apr, 2012, 14:41
Posts: 7
Thanks! 8-)


 

Jump to:  

cron
  © 1998-2025 Dukascopy® Bank SA
On-line Currency forex trading with Swiss Forex Broker - ECN Forex Brokerage,
Managed Forex Accounts, introducing forex brokers, Currency Forex Data Feed and News
Currency Forex Trading Platform provided on-line by Dukascopy.com