|
JFOREX SDK - How to send HTTPS GET request to www server ssl connection with server side php and mysql files |
zix
|
Post subject: JFOREX SDK - How to send HTTPS GET request to www server ssl connection with server side php and mysql files |
Post rating: 1
|
Posted: Mon 24 Mar, 2014, 14:31
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
Hi All This send opened positions from jforex to www server via HTTPS(SSL) save update delete in database java file package singlejartest;
import com.dukascopy.api.system.ISystemListener; import com.dukascopy.api.system.IClient; import com.dukascopy.api.system.ClientFactory; import com.dukascopy.api.*;
import java.awt.Color; import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Array; import java.net.URL; import java.nio.file.Files; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set;
import javax.net.ssl.HttpsURLConnection; import javax.swing.JFrame;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
//import singlejartest.JavaHttpsExample;
public class sss {
private static final Logger LOGGER = LoggerFactory.getLogger(sss.class); private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp"; private static String userName = "DEMOAC03MQajo"; private static String password = "MQajo";
//static String[] columns = {"Open Time", "Id", "Label", "Comment", "Instrument", "Side", "Amount", "Original Amount", "Open Price", "Stop Loss", "Take Profit", "Profit (Pips)", "Profit Currency", "Profit in USD", "Commission", "Commission USD"}; static String[] columns = {"Id", "Instrument", "Side", "Amount", "Open Price", "Stop Loss", "Take Profit"}; //static String[][] data = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
//static String[][] data = new String[10][10]; static String[][] out = new String[10][10]; //static String[][] data = null; //static JFrame jf = new JFrame();
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface final IClient client = ClientFactory.getDefaultInstance(); //set the listener that will receive system events client.setSystemListener(new ISystemListener() { private int lightReconnects = 3;
public void onStart(long procid) { //IConsole console = context.getConsole(); LOGGER.info("Strategy started: "); }
public void onStop(long processId) { LOGGER.info("Strategy stopped: " + processId); if (client.getStartedStrategies().size() == 0) { System.exit(0); } }
@Override public void onConnect() { LOGGER.info("Connected"); lightReconnects = 3; }
@Override public void onDisconnect() { LOGGER.warn("Disconnected"); if (lightReconnects > 0) { LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects); client.reconnect(); --lightReconnects; } else { try { //sleep for 10 seconds before attempting to reconnect Thread.sleep(10000); } catch (InterruptedException e) { //ignore } try { client.connect(jnlpUrl, userName, password); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } } });
LOGGER.info("Connecting..."); //connect to the server using jnlp, user name and password client.connect(jnlpUrl, userName, password);
//wait for it to connect int i = 10; //wait max ten seconds while (i > 0 && !client.isConnected()) { Thread.sleep(1000); i--; } if (!client.isConnected()) { LOGGER.error("Failed to connect Dukascopy servers"); System.exit(1); }
//subscribe to the instruments Set<Instrument> instruments = new HashSet<Instrument>(); instruments.add(Instrument.EURUSD); LOGGER.info("Subscribing instruments..."); client.setSubscribedInstruments(instruments);
//start the strategy LOGGER.info("Starting strategy"); final long strategyId = client.startStrategy(new IStrategy(){ public Instrument instrument = Instrument.EURUSD; private IConsole console; private IEngine engine;
public void onStart(IContext context) throws JFException { console = context.getConsole(); engine = context.getEngine();
} public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException { if ( instrument == this.instrument){ //console.getOut().println(" bar: " + period + " " + askBar); }
}
public void onTick(Instrument instrument, ITick tick) throws JFException { String[][] data = new String[10][10]; try {
int xx = 0; //data[0][1] = "1"; for(IOrder o : engine.getOrders()){ if(o.getProfitLossInUSD() != 987654231){ console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Copy orders to array //String userHash = ""+ xx; String positionOpenTime = "" + o.getFillTime(); String positionId = "" + o.getId(); String positionInstrument = "" + o.getInstrument(); String positionIsbuy = "" + o.getOrderCommand().isLong(); String positionVolume = "" + o.getAmount(); String positionOpen = "" + o.getOpenPrice(); String positionSl = "" + o.getStopLossPrice(); String positionTp = "" + o.getTakeProfitPrice(); String positionComment = "" + o.getComment(); String positionLabel = "" + o.getLabel();
//data[xx][0] = userHash; data[xx][0] = positionOpenTime; data[xx][1] = positionId; data[xx][2] = positionInstrument; data[xx][3] = positionIsbuy; data[xx][4] = positionVolume; data[xx][5] = positionOpen; data[xx][6] = positionSl; data[xx][7] = positionTp; data[xx][8] = positionLabel; data[xx][9] = positionComment; xx++; } } xx=0;
console.getOut().println("=====================================================================================" );
if (Arrays.deepEquals(data, out)) System.out.println("Same"); else{ System.out.println("Not same"); out = new String[10][10]; } console.getOut().println("=====================================================================================" ); // convert array to string String line = ""; int k = 0; for(int i =0; i< 10; i++){ for(int j =0; j< 10; j++){ if(data[i][j] != null){ line += data[i][j] + ","; }else{k = 1;} } if(k == 0){ line += "ZZZ"; } } //line = "START"+line+"STOP"; System.out.println(line); System.out.println(Arrays.deepToString(data)); console.getOut().println("=====================================================================================" ); if (!Arrays.deepEquals(data, out)){ //=================================================================== send get == need commerciall ssl like startssl.com and serveralias and servername in virtualhost URL hp = new URL("https://breakermind.com/send.php?line="+line+"&user=USERNSME&pass=USERPASS"); HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
boolean isProxy = hpCon.usingProxy(); System.out.println("is using proxy " + isProxy); InputStream obj = hpCon.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(obj));
console.getOut().println("=====================================================================================" ); // convert string to array String s = ""; while ((s = br.readLine()) != null) {
String[] xline = line.split("ZZZ");
int ss = 0; for (String str : xline) { out[ss] = (String[]) str.split(","); ss++; }
break; } System.out.println(s); System.out.println(Arrays.deepToString(out)); } console.getOut().println("=====================================================================================" );
} catch (Exception e) { console.getErr().println(e.getMessage()); e.printStackTrace(console.getErr()); // context.stop(); }
//console.getOut().println("=====================================================================================" );
} public void onMessage(IMessage message) throws JFException { } public void onAccount(IAccount account) throws JFException { } public void onStop() throws JFException { } }); //now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy Thread thread = new Thread(new Runnable() { @Override public void run() {
Scanner s = new Scanner(System.in); while(true){ while(s.hasNext()){ String str = s.next(); if(str.equalsIgnoreCase("stop")){ System.out.println("Strategy stop by console command."); client.stopStrategy(strategyId); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread.start();
} }
server side php and mysql files send.php save/update/delete opened positions from jForex account <?php include('functions.php'); // line example // START1395336294584,59923886,GBP/JPY,true,1.0,169.199,167.195,171.195,jf1nikmw1,null,ZZZ1395336294584,59923886,GBP/JPY,true,1.0,169.199,167.195,171.195,jf1nikmw1,null,ZZZEND
//======================================================================================= connect mysql $mysqlcon = isConnect('localhost','root', 'toor');
//======================================================================================= get input strings $user_ip = $_SERVER['REMOTE_ADDR']; $user_time = time(); $user = md5($_GET['user']); $pass = md5($_GET['pass']); $line = htmlspecialchars($_GET['line'], ENT_QUOTES, 'UTF-8'); echo "<pre>"; echo $line; echo "</pre>"; $userID = 0; $out = ""; $positions[] = 0;
//======================================================================================= if user and password correct $q = mysql_query("SELECT * FROM users WHERE user_email_hash='$user' AND user_pass='$pass'"); $userExist = mysql_num_rows($q);
// user istnieje pobierz rekord z bazy (id usera) if($userExist != 0){ while ($row = mysql_fetch_assoc($q)){ //echo "user id: " . $userID = $row['user_id']; $userID = $row['user_id']; } }
if($line == "STARTEND"){ $q5 = mysql_query("UPDATE positionsTest1 SET pos_close='$user_time' WHERE pos_close = 0 AND user_id =".$userID) or die( "#ERROR-1#" . mysql_error()); die($line); }
//========================================================================================== preg_match for correct positions settings
$isLineOK = preg_match("/^START([0-9]{1,99},[0-9]{1,99},[A-Z0-9\/]{1,10},[A-Z]{1,6},[0-9]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[a-zA-Z0-9]{1,100},[a-zA-Z0-9]{1,100},ZZZ)+END$/", $line);
//======================================================================================== sprawdzenie danych wejściowych if(isPositionString($line) && isAllowedChar($line) && $userExist == 1 && $userID != 0 && $isLineOK == 1){ $cutline = isPositionStringCut($line);
$posLines = explode('ZZZ', $cutline);
$i = 0; foreach ($posLines as $line1){ $positions[$i] = explode(',', substr($line1, 0, -3)); $i++; }
$positionsExists = ""; $z =0; foreach ($positions as $value) { $positionsExists = $positionsExists.$userID.$positions[$z][1].","; $positionsExists = $positionsExists."0"; //echo "==".$positionsExists."++"; $z++; }
$j =0; foreach ($positions as $value) { $pos_id = $userID.$positions[$j][1]; $pos_currency = $positions[$j][2]; $pos_volume = $positions[$j][4]; $pos_stoploss = (float)$positions[$j][6]; $pos_takeprofit = (float)$positions[$j][7]; $pos_isLong = $positions[$j][3]; $pos_open = $positions[$j][0]; $pos_open_price = (float)$positions[$j][5]; $pos_label = $positions[$j][8]; $pos_comment = $positions[$j][9]; if($pos_volume = $positions[$j][4] <= 10000){ $pos_volume = 10000; }
// INSERT INTO table (primarykeycol,col1,col2) VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=0, col2=col2+1
//$q2 = mysql_query("DELETE FROM positionsTest WHERE pos_id NOT IN ( $positionsExists)"); $q4 = mysql_query("UPDATE positionsTest1 SET pos_close='$user_time' WHERE pos_close = 0 AND user_id =".$userID." AND pos_id NOT IN (".$positionsExists.")") or die( "#ERROR-1#" . mysql_error());
//$q3 = mysql_query("UPDATE positionsTest SET pos_currency='$pos_currency',pos_volume='$pos_volume',pos_stoploss='$pos_stoploss',pos_takeprofit='$pos_takeprofit',pos_isLong='$pos_isLong',pos_open='$pos_open',pos_open_price='$pos_open_price',pos_label='$pos_label',pos_comment='$pos_comment', user_ip='$user_ip', user_time='$user_time' WHERE pos_id = '$pos_id'"); $q1 = mysql_query("INSERT INTO positionsTest1(pos_id,pos_currency,pos_volume,pos_stoploss,pos_takeprofit,pos_isLong,pos_open,pos_open_price,pos_label,pos_comment, user_id, user_ip, user_time) VALUES('$pos_id','$pos_currency','$pos_volume','$pos_stoploss','$pos_takeprofit','$pos_isLong','$pos_open','$pos_open_price','$pos_label','$pos_comment', '$userID', '$user_ip', '$user_time') ON DUPLICATE KEY UPDATE pos_currency='$pos_currency',pos_volume='$pos_volume',pos_stoploss='$pos_stoploss',pos_takeprofit='$pos_takeprofit',pos_isLong='$pos_isLong',pos_label='$pos_label',pos_comment='$pos_comment', user_ip='$user_ip', user_time='$user_time'") or die( "#ERROR-1#" . mysql_error()); $j++; }
//echo microtime(); //$nanotime = system('date +%s%N'); //function microtime_float() //{ // list($usec, $sec) = explode(" ", microtime()); // return ((float)$usec + (float)$sec); //} //echo microtime_float(); if (!empty($_GET)) { //echo "<br>"; //echo $user."<br>"; //echo $pass."<br>"; //echo $line."<br>"; } $out = $line; }else{$out = '##SEND##CORRECT##DATA##';} mysql_close($mysqlcon);
//========================================================================================= send output string //echo $out; echo $out; ?>
functions.php file <?php
function isConnect($host, $user, $password, $db = 'db'){ $link = mysql_connect($host, $user, $password) or die('Not connected : ' . mysql_error());
// make foo the current db $db_selected = mysql_select_db($db, $link) or die ('Can\'t use foo : ' . mysql_error()); mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); mysql_query("SET NAMES utf8"); mysql_query("SET CHARACTER SET utf8"); mysql_query("SET collation_connection = utf8_generali_ci");
return $link; }
function isAllowedChar($line){ if (preg_match("#^[a-zA-Z0-9\.\,\/]+$#", $line)) { return 1;} else { return 0;} }
function isPositionString($string){ // start end check if(substr($string, 0, 5) == "START" && substr($string, -3) == "END"){return 1;}else{return 0;} }
function isPositionStringCut($string){ // start end check $string = substr($string, 5); $string = substr($string, 0, -6); return $string; }
// clean input from $_GET $_POST USE: $_CLEAN['GET'] = cleanInput($_GET); function cleanInput($elem) { if(!is_array($elem)) $elem = htmlentities($elem, ENT_QUOTES,"UTF-8"); else{ foreach ($elem as $key => $value){ $elem[$key] = cleanInput($value); } } return $elem; }
//$isLineOK = preg_match("/^START([0-9]{1,99}AAA[0-9]{1,99}AAA[A-Z0-9\/]{1,10}AAA[A-Z]{1,6}AAA[0-9]{5,30}AAA[0-9\.]{5,30}AAA[0-9\.]{5,30}AAA[0-9\.]{5,30}AAA[a-zA-Z0-9]{1,100}AAA[a-zA-Z0-9]{1,100}AAAZZZ)+END$/", $line); ?>
and mysql databases ## mysql database
CREATE DATABASE db CHARACTER SET utf8 COLLATE utf8_general_ci;
# CREATE DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci; # GRANT ALL ON `mydb`.* TO `username`@localhost IDENTIFIED BY 'password'; # FLUSH PRIVILEGES; # `user_time` TIMESTAMP DEFAULT NOW(),
USE db;
## create table users CREATE TABLE `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_alias` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_email` varchar(200) CHARACTER SET utf8 collate utf8_general_ci , `user_email_hash` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_pass` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_ip` text CHARACTER SET utf8 collate utf8_general_ci, `user_time` int(21), `user_code` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_active` char(1) CHARACTER SET utf8 collate utf8_general_ci DEFAULT '0', PRIMARY KEY (`user_id`), UNIQUE (`user_email` , `user_alias`) )ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
insert into users VALUES('','zix','xx#email.com', md5('[email protected]'), md5('pass'),null,null,null,0);
## create table users_all CREATE TABLE `users_all` ( `user_id` bigint(21) NOT NULL AUTO_INCREMENT, `user_alias` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_email` varchar(200) CHARACTER SET utf8 collate utf8_general_ci , `user_email_hash` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_pass` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_ip` text CHARACTER SET utf8 collate utf8_general_ci, `user_time` int(21), `user_code` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_active` char(1) CHARACTER SET utf8 collate utf8_general_ci DEFAULT '0', `user_firstname` char(2) CHARACTER SET utf8 collate utf8_general_ci , `user_lastname` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_country` char(2) CHARACTER SET utf8 collate utf8_general_ci , `user_town` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_gender` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_dofb` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_mobile` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_startbalance` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_descripion` text CHARACTER SET utf8 collate utf8_general_ci, `user_ip_mask` varchar(200) CHARACTER SET utf8 collate utf8_general_ci , PRIMARY KEY (`user_id`), UNIQUE (`user_email` , `user_alias`) )ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
CREATE TABLE `positionsTest1` ( `pos_id` varchar(200) CHARACTER SET utf8 collate utf8_general_ci , `pos_currency` varchar(25) CHARACTER SET utf8 collate utf8_general_ci , `pos_volume` bigint(21) DEFAULT 10000, `pos_stoploss` float, `pos_takeprofit` float, `pos_isLong` char(5) NOT NULL DEFAULT 0, `pos_open` bigint(21) NOT NULL DEFAULT 0, `pos_open_price` float, `pos_close` int(11) NOT NULL DEFAULT 0, `pos_close_price` float DEFAULT 0, `pos_label` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `pos_comment` varchar(100) CHARACTER SET utf8 collate utf8_general_ci , `user_id` bigint(21) DEFAULT 0, `user_ip` text CHARACTER SET utf8 collate utf8_general_ci, `user_time` text CHARACTER SET utf8 collate utf8_general_ci, `user_microtime` text CHARACTER SET utf8 collate utf8_general_ci, `user_nanotime` text CHARACTER SET utf8 collate utf8_general_ci, PRIMARY KEY (`pos_id`), UNIQUE (`pos_id`) )ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;
maybe useful for someone ... Have nice dayzix bye.
|
|
|
|
 |
zix
|
Post subject: Re: JFOREX SDK - How to send HTTPS GET request to www server ssl connection with server side php and mysql files |
Post rating: 0
|
Posted: Mon 24 Mar, 2014, 14:53
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
|
|
|
 |
zix
|
Post subject: Re: JFOREX SDK - How to send HTTPS GET request to www server ssl connection with server side php and mysql files |
Post rating: 0
|
Posted: Wed 02 Apr, 2014, 08:24
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
Hi all, Why is displayed in console: 2014-04-02 07:16:58.324 INFO sss - Connecting... 2014-04-02 07:17:00.311 INFO AuthorizationClient - Selecting the best server... 2014-04-02 07:17:00.989 INFO AuthorizationClient - retry count = 1, properties request time = 2014-04-02 07:17:00 2014-04-02 07:17:01.582 INFO AuthorizationClient - retry count = 1, properties response time = 2014-04-02 07:17:01 2014-04-02 07:17:03.993 WARN WLabelData - White Label Image is not received 2014-04-02 07:17:04.147 INFO sss - Connected 2014-04-02 07:17:05.014 INFO sss - Subscribing instruments... 2014-04-02 07:17:05.018 INFO sss - Starting strategy 2014-04-02 07:17:07.525 ERROR LoadOrdersAction - com/dukascopy/dds4/common/Bits$BitsSerializable : Unsupported major.minor version 51.0 java.lang.UnsupportedClassVersionError: com/dukascopy/dds4/common/Bits$BitsSerializable : Unsupported major.minor version 51.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at java.net.URLClassLoader.access$000(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:212) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at java.net.URLClassLoader.access$000(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:212) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at com.dukascopy.transport.common.msg.datafeed.OrderGroupsBinaryMessage.getOrderGroups(OrderGroupsBinaryMessage.java:74) at com.dukascopy.charts.data.datacache.CurvesJsonProtocolHandler.loadOrders(CurvesJsonProtocolHandler.java:772) at com.dukascopy.charts.data.datacache.CurvesDataLoader.loadAndSaveOrdersChunk(CurvesDataLoader.java:556) at com.dukascopy.charts.data.datacache.CurvesDataLoader.loadOrders(CurvesDataLoader.java:504) at com.dukascopy.charts.data.datacache.LoadOrdersAction.run(LoadOrdersAction.java:100) at com.dukascopy.charts.data.datacache.FeedDataProvider.loadOrdersHistoricalDataSynched(FeedDataProvider.java:1980) at com.dukascopy.api.impl.HistoryOrderProvider.getOrdersHistory(HistoryOrderProvider.java:46) at com.dukascopy.api.impl.History$17.run(History.java:780) at com.dukascopy.api.impl.History$17.run(History.java:777) at java.security.AccessController.doPrivileged(Native Method) at com.dukascopy.api.impl.History.getOrdersHistory(History.java:777) at com.dukascopy.api.impl.connect.JForexTaskManager.initExistingOrders(JForexTaskManager.java:297) at com.dukascopy.api.impl.connect.JForexTaskManager.access$500(JForexTaskManager.java:100) at com.dukascopy.api.impl.connect.JForexTaskManager$1.call(JForexTaskManager.java:624) at com.dukascopy.api.impl.connect.JForexTaskManager$1.call(JForexTaskManager.java:613) at com.dukascopy.api.impl.execution.TaskCustom.call(TaskCustom.java:34) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at com.dukascopy.api.impl.execution.ScienceThreadPoolExecutor$Worker.runTask(ScienceThreadPoolExecutor.java:904) at com.dukascopy.api.impl.execution.ScienceThreadPoolExecutor$Worker.run(ScienceThreadPoolExecutor.java:926) at java.lang.Thread.run(Thread.java:679) Strategy "" Strategy ID: 70E524F8310A772903F53D3525C1906C is started at 2014-04-02 07:17:07.622 GMT on the local computer with no parameters 2014-04-02 07:17:07.633 INFO sss - Strategy started: Order: GBP/JPY 12.9 BUY ===================================================================================== Not same ===================================================================================== 1396417910458,60210010,GBP/JPY,true,1.0,172.598,172.094,174.594,jf1h5y751,null,ZZZ [[1396417910458, 60210010, GBP/JPY, true, 1.0, 172.598, 172.094, 174.594, jf1h5y751, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null], [null, null, null, null, null, null, null, null, null, null]] ===================================================================================== is using proxy false
Thx
|
|
|
|
 |
zix
|
Post subject: Re: JFOREX SDK - getAmount() |
Post rating: 0
|
Posted: Wed 02 Apr, 2014, 09:06
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
Hi,
How to get open order amount in base currency ?
|
|
|
|
 |
hebasto
|
Post subject: Re: JFOREX SDK - getAmount() |
Post rating: 0
|
Posted: Wed 02 Apr, 2014, 09:19
|
|
User rating: 96
Joined: Mon 09 Sep, 2013, 07:09 Posts: 287 Location: Ukraine, SHostka
|
zix wrote: Hi,
How to get open order amount in base currency ? Something like this: IHistory history; IOrder order; ... double amountInBaseCurrency = order.getAmount() * history.getLastTick(order.getInstrument()).getAsk();
|
|
|
|
 |
zix
|
Post subject: Re: JFOREX SDK - How to send HTTPS GET request to www server ssl connection with server side php and mysql files |
Post rating: 0
|
Posted: Wed 02 Apr, 2014, 12:58
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
thx why this code generate error: 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:/x/pool.jar;c:/x/dbcp.jar;c:/x/mysql.jar") public class TestMySQLAccess 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://breakermind.com/db"); properties.put("username", "root"); properties.put("password", "toor"); 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 { } }
error: 11:46:32 BasicDataSource cannot be resolved to a type
second question: There is somewhere an example how to load from mysql databas to jforex strategies It is possible?? thx
|
|
|
|
 |
zix
|
Post subject: how to send a http request from strategies |
Post rating: 0
|
Posted: Thu 03 Apr, 2014, 07:00
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
Hi all,
how to send a http request to www server from strategies. It is possible that the platform does not provide such JForex cap ability ?
|
|
|
|
 |
zix
|
Post subject: Re: JFOREX SDK - get open positions and save to file and read from strategies |
Post rating: 0
|
Posted: Fri 04 Apr, 2014, 13:56
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
get positions from www server and save to file package breakermind;
import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL;
import javax.net.ssl.HttpsURLConnection; import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1000000000L; // constants and variables public static final int WIDTH = 50; public static final int HEIGHT = WIDTH/12*9; public static final int SCALE = 3; public static final String NAME = "db breakermind.com"; public boolean running = false; public int tickCount = 0; public String Username = ""; public String Password = ""; public String Line = ""; //private BufferedImage img = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //int[] pixels = (img.getRaster().getDataBuffer()).getNumBanks(); private JFrame f; // construktor public Game(){ setMinimumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE)); setMaximumSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE)); setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE)); f = new JFrame("db"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new BorderLayout()); f.add(this, BorderLayout.CENTER); f.pack(); f.setResizable(false); f.setLocationRelativeTo(null); f.setVisible(true); /* // add button with action listener JButton button = new JButton("START CONNECTION"); ActionListener printAction = new ActionListener() { public void actionPerformed(ActionEvent e) { try { //table.print(); // show dialog box with pass and user JOptionPane.showMessageDialog(f, "Start connection for User: "); } catch (Exception pe) { System.err.println("Error printing: " + pe.getMessage()); } } }; button.addActionListener(printAction); f.add(button, BorderLayout.SOUTH); */ // load username BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:\\x\\username.txt")); while ((Username = br.readLine()) != null) { System.out.println(Username); break; } } catch (IOException e) { e.printStackTrace(); } // load password BufferedReader br1 = null; try { br1 = new BufferedReader(new FileReader("C:\\x\\password.txt")); while ((Password = br1.readLine()) != null) { System.out.println(Password); break; } } catch (IOException e) { e.printStackTrace(); } }// Game
// start public synchronized void start() { running = true; new Thread(this).start(); }
// stop public synchronized void stop() { running = false; } // run main loop for the game public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D/60D; int ticks = 0; int frames = 0; long lastTimer = System.currentTimeMillis(); double delta = 0; while(running){ long now = System.nanoTime(); delta += (now - lastTime)/nsPerTick; lastTime = now; boolean shouldRender = false; while(delta >= 1){ ticks++; tick(); delta -= 1; shouldRender = true; } try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } if(shouldRender){ frames++; try { render(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
paint(getGraphics()); } if(System.currentTimeMillis() - lastTimer >= 1000){ lastTimer+= 1000; //System.out.println(frames + " " + ticks); frames = 0; ticks = 0; } } } // update the game public void tick(){ tickCount++; }
public void paint(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); //g.drawRect(10, 10, 100, 100); g.setColor(Color.blue); g.drawString("Copier working ... "+tickCount, 5, 20); g.dispose();
} // =============================================================================== print this == connect to www server and get data from https write to file and refresh public void render() throws IOException{ System.out.println("Render " + tickCount); System.out.println(Username); System.out.println(Password); System.out.println("Render " + tickCount); System.out.println(Username); System.out.println(Password); System.out.println("=====================================================================================" ); URL hp; try { //hp = new URL("https://breakermind.com/s.php?line=" + Line + "&user=" + Username + "&pass=" + Password); hp = new URL("https://google.pl"); HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection(); boolean isProxy = hpCon.usingProxy(); System.out.println("is using proxy " + isProxy); InputStream obj = hpCon.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(obj)); System.out.println(br.readLine()); //File myFile = new File("c:\\positions.txt"); PrintWriter writer = new PrintWriter("D:\\positions.txt", "UTF-8"); writer.println("The first line"); writer.println("The second line"); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
System.out.println("=====================================================================================" );
//================================================================================ } // manin public static void main(String[] args){ new Game().start(); }
}
and then load from strategies 
|
|
|
|
 |
zix
|
Post subject: Strategy JForex Platform - Send open positions to www server |
Post rating: 0
|
Posted: Tue 15 Apr, 2014, 10:44
|
|
User rating: 6
Joined: Tue 11 Feb, 2014, 11:38 Posts: 60 Location: PolandPoland
|
Hi, Strategy -------- Send open positions to www server and log to file (onMessage): package jforex;
import java.util.*; import java.awt.Color; import java.awt.List; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Array; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.net.MalformedURLException; import java.io.IOException; import java.io.*; import java.sql.Timestamp; import java.util.Date; import javax.swing.JFrame; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable;
import com.dukascopy.api.*;
@RequiresFullAccess public class Copyhttp implements IStrategy { private final String USER_AGENT = "Mozilla/5.0"; public String logFilePath = "/root/Pulpit/jfxlog.db"; public String pathToServerFile = "https://breakermind.com/z.php"; private IEngine engine; private IConsole console; private IHistory history; private IContext context; private IIndicators indicators; private IUserInterface userInterface; static String[][] out = new String[100][10]; public String line = ""; public void onStart(IContext context) throws JFException { this.engine = context.getEngine(); this.console = context.getConsole(); this.history = context.getHistory(); this.context = context; this.indicators = context.getIndicators(); this.userInterface = context.getUserInterface(); console.getOut().println("========================================================"); console.getOut().println("Robot start ..."); console.getOut().println("========================================================"); }
public void onAccount(IAccount account) throws JFException { } @Override public void onMessage(IMessage message) throws JFException {
String[][] data = new String[100][10]; try { int xx = 0; //data[0][1] = "1"; for(IOrder o : engine.getOrders()){ if(o.getProfitLossInUSD() != 987654231){ // open orders console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand()); // Copy orders to array String positionOpenTime = "" + o.getFillTime(); String positionId = "" + o.getId(); String positionInstrument = "" + o.getInstrument(); String positionIsbuy = "" + o.getOrderCommand().isLong(); String positionVolume = "" + o.getAmount(); String positionOpen = "" + o.getOpenPrice(); String positionSl = "" + o.getStopLossPrice(); String positionTp = "" + o.getTakeProfitPrice(); String positionComment = "" + o.getComment(); String positionLabel = "" + o.getLabel(); data[xx][0] = positionOpenTime; data[xx][1] = positionId; data[xx][2] = positionInstrument; data[xx][3] = positionIsbuy; data[xx][4] = positionVolume; data[xx][5] = positionOpen; data[xx][6] = positionSl; data[xx][7] = positionTp; data[xx][8] = positionLabel; data[xx][9] = positionComment; xx++; } } xx=0; // convert array to string line = ""; int k = 0; for(int i =0; i< 100; i++){ for(int j =0; j< 10; j++){ if(data[i][j] != null){ line += data[i][j] + ","; }else{k = 1;} } if(k == 0){ line += "ZZZ"; } } line = "START"+line+"STOP"; console.getOut().println("========================================================"); sendPost("line="+line+"&dd=hsdjkahdkjashk"); console.getOut().println("\nSend positions to server: "+ line); console.getOut().println("========================================================");
line="";
} catch (Exception e) { console.getOut().println(e.getMessage()); // context.stop(); } }
public void onStop() throws JFException { console.getOut().println("========================================================"); console.getOut().println("Robot stop!"); console.getOut().println("========================================================"); }
public void onTick(Instrument instrument, ITick tick) throws JFException {
} public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException { } // SENT HTTP POST request and log to file private void sendPost(String txt){ try{ String url = pathToServerFile; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header boolean isProxy = con.usingProxy(); if(isProxy){ System.out.println("System using proxy: " + isProxy); } con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = txt; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); //console.getOut().println("\nSending 'POST' request to URL : " + url); //console.getOut().println("Post parameters : " + urlParameters); //console.getOut().println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); // read one line break; } in.close();
// log file operation get timestamp java.util.Date date= new java.util.Date(); //System.out.println(new Timestamp(date.getTime())); // time to string String time = new Timestamp(date.getTime()).toString(); // log file catch all response PrintWriter log = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, true))); log.println("Copyhttp: " + time + " " + response.toString()); log.close(); //print result console.getOut().println("Server response: " + response.toString()); }catch(Exception spi) { /// } } }
Regards
|
|
|
|
 |
|
Pages: [
1
]
|
|
|
|
|