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.

JFOREX SDK - Send position to www server ssl
 Post subject: JFOREX SDK - Send position to www server ssl Post rating: 0   New post Posted: Thu 08 May, 2014, 11:53 
User avatar

User rating: 6
Joined: Tue 11 Feb, 2014, 11:38
Posts: 60
Location: PolandPoland
Hi,


Unfortunately, it was gone :
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.util.HashSet;
import java.util.Scanner;
import java.util.Set;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.awt.EventQueue;
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;

/**
 * This small program demonstrates how to initialize Dukascopy client and start a strategy
 */
public class MainStopFromConsole {
   
    private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
    private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
    private static String userName = "DEMOAC05uFQYX";
    private static String password = "uFQYX";
   
    static String[][] out = new String[100][10];

    public static void main(String[] args) throws Exception {
        //new Okno();
        //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;

           @Override
           public void onStart(long processId) {
                LOGGER.info("Strategy started: " + processId);
           }

         @Override
         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 final String USER_AGENT = "Mozilla/5.0";
            public String logFilePath = "/root/Pulpit/jfxlog.db";
            public String pathToServerFile = "https://breakermind.com/set.php";
            private IEngine engine;
            private IHistory history;
            private IContext context;
            private IIndicators indicators;
            private IUserInterface userInterface;
            public String line = "";

            public void onStart(IContext context) throws JFException {       
                console = context.getConsole();   
                engine = context.getEngine();
                history = context.getHistory();
                indicators = context.getIndicators();
                userInterface = context.getUserInterface();
                console.getOut().println("========================================================");
                console.getOut().println("Robot start ...");
                console.getOut().println("========================================================");
            }
            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 {    }
            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 = "BUY";
                if(o.getOrderCommand().isLong()){
                    positionIsbuy = "BUY";
                }else{
                    positionIsbuy = "SELL";
                }
                String positionVolume = "" + o.getAmount();
                String positionOpen = "" + o.getOpenPrice();
                String positionSl = "" + o.getStopLossPrice();
                String positionTp = "" + o.getTakeProfitPrice();
                String positionComment = "" + o.getComment();
                String positionLabel = "" + o.getLabel();
                   

                double vol = Double.parseDouble(positionVolume) * 1000000;
                data[xx][0] = positionId;
                data[xx][1] = positionInstrument;
                data[xx][2] = positionIsbuy;
                data[xx][3] = Double.toString(vol);
                data[xx][4] = positionOpen;
                data[xx][5] = positionSl;
                data[xx][6] = positionTp;
                data[xx][7] = positionOpenTime;
                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< 8; j++){
                if(data[i][j] != null){
                line += data[i][j] + ";";
                }else{k = 1;}
                }
                if(k == 0){
                line += "|";
                }
                }
                line = "[GO]"+line+"[OG]";
                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 onAccount(IAccount account) throws JFException {    }
            public void onStop() throws JFException {    }
           
                // SENT HTTP POST request and log to file
                private void sendPost(String txt){
                try{
                String url = pathToServerFile;
                URL obj = new URL(url);
                HttpsURLConnection con = (HttpsURLConnection) 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);
                console.getOut().println("Server response: " + response.toString());
                // 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 ss)
                {
                ///
                }}
        });
        //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();
       
    }
}



Regards
zix


 
 Post subject: Re: JFOREX SDK - Send position to www server ssl Post rating: 0   New post Posted: Thu 08 May, 2014, 13:35 
User avatar

User rating: 6
Joined: Tue 11 Feb, 2014, 11:38
Posts: 60
Location: PolandPoland
Hi
i have got Exception (code above):

------------------------------------------------------------------------
Building JForex-SDK 2.33.3
------------------------------------------------------------------------

--- exec-maven-plugin:1.2.1:exec (default-cli) @ JForex-SDK ---
2014-05-08 14:28:47.337 INFO  MainStopFromConsole - Connecting...
2014-05-08 14:28:49.273 INFO  AuthorizationClient - Selecting the best server...
2014-05-08 14:28:50.187 INFO  AuthorizationClient - retry count = 1, properties request time = 2014-05-08 14:28:50
2014-05-08 14:28:50.969 INFO  AuthorizationClient - retry count = 1, properties response time = 2014-05-08 14:28:50
2014-05-08 14:29:02.606 WARN  WLabelData - White Label Image is not received
2014-05-08 14:29:02.758 INFO  MainStopFromConsole - Connected
2014-05-08 14:29:03.609 INFO  MainStopFromConsole - Subscribing instruments...
2014-05-08 14:29:03.614 INFO  MainStopFromConsole - Starting strategy
Strategy "" Strategy ID: A8443C59250F4C9E4FD45DD695F09178 is started at 2014-05-08 12:29:06.623 GMT on the local computer with no parameters
========================================================
Robot start ...
========================================================
2014-05-08 14:29:06.685 INFO  MainStopFromConsole - Strategy started: 40
Order: GBP/USD 14.1 SELL
Order: EUR/USD -1.8 SELL
========================================================

Send positions to server (convert): line=[GO]61144529;GBP/USD;SELL;1000000,0;1,69627;1,70143;1,69143;1399542456191;|61144450;EUR/USD;SELL;5000000,0;1,39441888;1,39944;1,38944;1399542388065;|[OG]&dd=hsdjkahdkjashk

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target



How to improve my code?


 

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